Where to put and how to read txt file - css

I am passing an app to CSS and I have not been able to read a flat file that I am using.
In the figure I show where I had it at the beginning and the folder where I placed it in the "maven" version.
What is the correct way and if it is necessary to change the CSS?
My Method:
public ListModel tomarDatosLocalizacion() {
Vector aL = new Vector();
try {
aL = leeArchivo("/localidades.txt");
} catch (IOException ex) {
Dialog.show(idioma.getError(), ex.getMessage(), idioma.getContinuar(), null);
}
ListModel localidad = new DefaultListModel(aL);
return localidad;
}
// Rutina que lee el archivo de subzonas en Texto y carga tabla de datos
private Vector leeArchivo(String nombreArchivo) throws IOException {
InputStream lectura = Display.getInstance().getResourceAsStream(getClass(), nombreArchivo);
String registro = null;
Vector datos = new Vector();
// Lee una un registro desde del archivo. null representa el EOF.
while ((registro = leeRegistro(lectura)) != null) {
Vector tmp = dividirCadena(registro, ",");
datos.addElement(new Localidades(Integer.parseInt(tmp.elementAt(0).toString()), tmp.elementAt(1).toString(), tmp.elementAt(2).toString()));
}
lectura.close();
return datos;
}

Open the Common project. Under the source hierarchy you can create a resources directory which is a special case in Maven. In it you can place arbitrary files and they will behave in the way you expect.

Related

Background location service stops working after a few minutes [closed]

Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 2 days ago.
Improve this question
Estoy realizando una app en xamarin forms y xamarin.android para el tracking de una servicio, ya tengo creado mi servicio y la peticion de la ubicacion, el problema radica en que el dispositivo deja de obtener la ubicacion luego de un tiempo cuando se encuentra suspendido o en segundo plano, esto me pasa solo en mi dispositivo fisico ya que con el emulador no se me presenta este error
Service
[Service]
public class AndroidLocationService : Service
{
CancellationTokenSource _cts;
public const int SERVICE_RUNNING_NOTIFICATION_ID = 10001;
public static string NAME = "com.swfactorygroup.bongoadm.WakefulIntentService";
private static volatile PowerManager.WakeLock lockStatic = null;
[MethodImpl(MethodImplOptions.Synchronized)]
private static PowerManager.WakeLock GetLock(Context context)
{
if (lockStatic == null)
{
PowerManager manager = (PowerManager)context.GetSystemService(Context.PowerService);
lockStatic = manager.NewWakeLock(WakeLockFlags.Partial, NAME);
lockStatic.SetReferenceCounted(false);
}
return (lockStatic);
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
_cts = new CancellationTokenSource();
Notification notification = new NotificationHelper().GetServiceStartedNotification();
StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
PowerManager.WakeLock wakeLock = GetLock(this.ApplicationContext);
wakeLock.Acquire();
Task.Run(() => {
try
{
var locShared = new GetLocationService();
locShared.Run(_cts.Token).Wait();
}
catch (Android.OS.OperationCanceledException)
{
}
finally
{
if (_cts.IsCancellationRequested)
{
var message = new StopServiceMessage();
Device.BeginInvokeOnMainThread(
() => MessagingCenter.Send(message, "ServiceStopped")
);
}
PowerManager.WakeLock wakeLock = GetLock(this.ApplicationContext);
if (wakeLock.IsHeld)
{
try
{
wakeLock.Release();
}
catch (Exception ex)
{
Log.Error(Class.SimpleName, "Exception when releasing wakelock", ex);
//Log exception when releasing wakelock
}
}
}
}, _cts.Token);
return StartCommandResult.Sticky;
}
public override void OnDestroy()
{
if (_cts != null)
{
_cts.Token.ThrowIfCancellationRequested();
_cts.Cancel();
}
base.OnDestroy();
}
}
public class GetLocationService
{
readonly bool stopping = false;
SQLiteHelper _bd = App.BDSQLite;
public GetLocationService()
{
}
public async Task Run(CancellationToken token)
{
await Task.Run(async () => {
while (!stopping)
{
token.ThrowIfCancellationRequested();
try
{
await Task.Delay(10000);
var request = new GeolocationRequest(GeolocationAccuracy.Best);
var location = await Geolocation.GetLocationAsync(request);
if (location != null)
{
var message = new LocationMessage
{
Latitude = location.Latitude,
Longitude = location.Longitude
};
Device.BeginInvokeOnMainThread(() =>
{
MessagingCenter.Send(message, "Location");
});
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
var errormessage = new LocationErrorMessage();
MessagingCenter.Send(errormessage, "LocationError");
});
}
}
return;
}, token);
}
}
I tried using a PowerManager.WakeLock, but it is not poorly implemented, it seems that the device will kill the process after a few minutes

Save data from combo box in database Javafx

I get an error from this code line:
prov = obtenerProveedor(productos_comboPROVEEDOR.getSelectionModel().getSelectedItem());
the method obtenerProveedor() is this:
public long obtenerProveedor(String s){
ConexionMySQL conexion = new ConexionMySQL();
Connection conn = conexion.conectar();
String query ="select id from proveedores where nombre = '"+s+"'";
Statement Squery;
try{
Squery = conn.createStatement();
ResultSet res = Squery.executeQuery(query);
res.next();
return res.getLong("id");
}catch(Exception e){
JOptionPane.showMessageDialog(null, "No se pudo obtener el proveedor");
}
return 0;
}
And I get the following error:
This one is the error but I can't put images yet
I'm not sure but I think that the problem is beause the method obtenerProveedor() asks for a String and I send it an object, but I don't know how to fix it
Try this
prov = Long.toString(obtenerProveedor(productos_comboPROVEEDOR.getSelectionModel().getSelectedItem()));

Using KeyEvent in javaFx

I'm using JavaFX for my application's GUI.
public void testUsername(KeyEvent ke) throws SQLException{
if (ke.getCode().equals(KeyCode.ENTER))
{
if(checkUsernameInDataBase(txtUsername.getText())==false)
{
Image image = new Image(getClass().getResourceAsStream("Z6if3PZ.png"));
lblImage.setGraphic(new ImageView(image));
}
}
}
public boolean checkUsernameInDataBase(String username) throws SQLException {
// verific daca username introdus este sau nu in baza de date
// daca este deja returnez true altfel returnez false
// daca e true nu se poate face signUp daca e false se poate
String usrCheckStr = String.format("select * from utilizatori where username = '" + username + "'");
ResultSet results = DBMain.getStatement().executeQuery(usrCheckStr);
if (!results.isBeforeFirst()) {
// results.isBeforeFirst verifica daca curosorul se afla inainte de
// primul rezultat
// si intoarce true daca este acolo sau false daca nu este
// daca intoarce false inseamna ca nu exista inregistrari
// deci username nu exista in baza de date
return false;
} else
return true;
}
Could someone tell me why i receive NullPointerException when i am using checkUserNameInDataBase method? This method looks in a DataBase if current Username exits. Ideea is that when i am using it in a main method, it works, but when i am trying to use it in the testUsername method, i receive error.
Thx!

Solr : Autolink on body from words dictionnary

I'm looking for to generate auto link in body result in solr. Words on link must be in a dictionnary.
For example :
a doc :
<doc>
[...]
<str name="title">Il faut, quand on gouverne, voir les hommes tels qu’ils sont, et les choses telles qu’elles devraient être.</str>
<str name="path">citation/faut-gouverne-voir-hommes-tels-choses-telles-devraient-etre-15.php</str>
<str name="ss_field_citation_keywords">#faut#gouverne#voir#hommes#tels#choses#telles#devraient#etre#</str>
[...]
</doc>
Body from title to display :
Il faut, quand on gouverne, voir les hommes tels qu’ils sont, et les choses telles qu’elles devraient être.
Links from ss_field_citation_keywords :
#faut#gouverne#voir#hommes#tels#choses#telles#devraient#etre#
Body must be display like this :
Il faut, quand on gouverne, voir les hommes tels qu’ils sont, et les choses telles qu’elles devraient être.
Il faut, quand on gouverne, voir les hommes tels qu’ils sont, et les choses telles qu’elles devraient être
Do you have any idea?
You have two phases here:
Identify the keywords. For this you want to build your analyzer chain properly. Whitespace tokenizer, lowercase filter and - that's the key part - KeepWordFilterFactory . This will make Solr keep only your keywords with offsets in the text.
Get those offsets. There is might be several ways, but one of them is to reuse Field Analyzer which you can experiment with in admin WebUI of latest (4+) Solr. Make sure to check the Verbose box. That uses /analysis/field end point and you can use it too (with verbose flag). The result is probably too verbose for you but good enough to start. Then you can look for better implementation or copy/reduce the one currently done.
a proposal for internal processing with velocity and a java class
public class autoLinkCitationDirective extends Directive{
public String getName() {
return "autolinkcitation";
}
public int getType() {
return LINE;
}
public boolean render(InternalContextAdapter context, Writer writer, Node node)
throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
String CitationMe = null;
String KeyWords = null;
String SchemaUrl = null;
//params
if (node.jjtGetChild(0) != null) {
CitationMe = String.valueOf(node.jjtGetChild(0).value(context));
}
if (node.jjtGetChild(1) != null) {
KeyWords = String.valueOf(node.jjtGetChild(1).value(context));
}
//schema url
if (node.jjtGetChild(2) != null) {
SchemaUrl = String.valueOf(node.jjtGetChild(2).value(context));
}
writer.write(autoLinkCitation(CitationMe, KeyWords, SchemaUrl));
return true;
}
public String autoLinkCitation(String CitationMe, String KeyWords, String SchemaUrl) {
if (CitationMe == null) {
return null;
}
List<String> tokens = new ArrayList<String>();
StringTokenizer stkKeyWords = new StringTokenizer(KeyWords, "#");
while ( stkKeyWords.hasMoreTokens() ) {
tokens.add(stkKeyWords.nextToken());
}
String patternString = "\\b(" + StringUtils.join(tokens, "|") + ")\\b";
Pattern pattern = Pattern.compile(patternString);
String strippedHtml = CitationMe.replaceAll("<(.|\n)*?>", "");
StringTokenizer st = new StringTokenizer(strippedHtml, ".,! ()[]");
while (st.hasMoreTokens())
{
String token = st.nextToken().trim();
if (token.length() > 3)
{
Matcher matcher = pattern.matcher(cleanString(token));
while (matcher.find()) {
if(CitationMe.indexOf( SchemaUrl + cleanString(token) + "'") == -1)
{
String tmpStringreplacement = "<a href='" + SchemaUrl + cleanString(token) + "'>"+token+"</a>";
CitationMe = CitationMe.replaceAll("\\b"+token+"\\b(?!/)",tmpStringreplacement);
}
}
}
}
return CitationMe;
}
public String cleanString(String CleanStringMe) {
if (CleanStringMe == null) {
return null;
}
CleanStringMe = Normalizer.normalize(CleanStringMe, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
CleanStringMe = CleanStringMe.toLowerCase();
CleanStringMe = CleanStringMe.replaceAll("[^A-Za-z0-9]", "-");
return CleanStringMe;
}
}
and to display:
#autolinkcitation($doc.getFieldValue('body'),$doc.getFieldValue('ss_field_citation_keywords'), '/citations/mot.php?mot=' )

How to pass the db connection information and query parameters from controller to JasperReportsMultiFormatView

I am prototyping a web application using Spring MVC 3.0 with JasperReports.
I have already done reporting applications using Spring + Jfreechart + iText + Apache POI and been able to use successfully the respective view classes provided by Spring to stream pdfs, xls and images.
This time I want to try to use JasperReports so that I can design my pdfs outside of the application and not have to worry about knowing the underlying api (be that jfreechart, itext, or poi).
Problem
I have a report1.jrxml file that contains a queryString tag with my query with two date parameters. When I test the report through iReport, it compiles and runs successfully. No problems here.
Now I am reading the JasperReports section from the following Spring documentation http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#view-jasper-reports
and I am trying to get the JasperReportsMultiFormatView to work properly, but there is one piece that I am not understanding:
How does JasperReportMultiFormatView know the database to connect to (Recall that I have the query embedded in the report itself) ?
The documentation states to use the reportDataKey property in the view, but I do not see how this is the solution to my problem.
How do you pass parameters?
What can be done
JaperReports provides with a set of xxxManager objects that are responsible for compiling, fiiling, and exporting the report. You could create a custom class that implements the Spring View interface and do something like this:
Connection connection;
ServletOutputStream servletOutputStream = response .getOutputStream();
InputStream reportStream = getServlet().getServletConfig().getServletContext().getResourceAsStream("/reports/report1.jasper");
response.setContentType("application/pdf");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:
3306/flightstats?user=user&password=secret");
JasperRunManager.runReportToPdfStream(reportStream,
servletOutputStream, new HashMap(), connection);
connection.close();
servletOutputStream.flush();
servletOutputStream.close();
What I need
I need to accomplish what the code above those leveraging the Spring classes such as JasperReportsPdfView, JasperReportsXlsView, or even better JasperReportsMultiFormatView
So in summary I need to be able to pass the following from my controller to the jasper report:
Parameters
Db connection information so that the queryString inside the jasper knows who to run against
This is what I have and the output is a blank PDF document, I am assuming because it does not know how to run the query
#RequestMapping("/reports/**")
#Controller
public class ReportsController {
#RequestMapping(value ="/reports/usage/report", method = RequestMethod.GET)
public ModelAndView handleSimpleReportMulti(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("Made it here");
Map model = new HashMap();
//model.put("format", "pdf");
model.put("START_DATE", new String("09-12-2011"));
model.put("END_DATE", new String("09-17-2011"));
return new ModelAndView("report1", model);
}
}
I found the answer to my question. I have changed my controller above to this:
#RequestMapping(value ="/reports/usage/report/{format}", method = RequestMethod.GET)
public ModelAndView handleSimpleReportMulti(ModelMap modelMap, #PathVariable("format") String format) throws Exception {
//Map model = new HashMap();
modelMap.put("format", format);
modelMap.put("REPORT_CONNECTION", dataSource.getConnection());
modelMap.put("START_DATE", new String("09-12-2011"));
modelMap.put("END_DATE", new String("09-17-2011"));
return new ModelAndView("report1", modelMap);
}
I have changed my view.properties to this:
#report1(class)=org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView
report1(class)=org.springframework.web.servlet.view.jasperreports.JasperReportsMultiFormatView
report1.url=/WEB-INF/reports/report1.jasper
I hope this helps.
Thanks
I found another way to pass the connection as a parameter, and then close it.
THE PROBLEM:
I implement the solution above an the problem was, that everytime I call a PDF, a new connection was created, so when the app gets to the max limit of open connections it crash.
ReportesDAOJDBC reportes;
public void setReportes(ReportesDAOJDBC reportes) {
this.reportes = reportes;
}
public ModelAndView leoTest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
Map < String, Object > model = new HashMap < String, Object >();
model.put("PARAMCONTRARECIBO", new Integer(1101));
model.put("PARAMDOCTOS", new Integer(1101));
model.put("REPORT_CONNECTION", reportes.getConexion());
return new ModelAndView("leoTest",model);
}
The parameter to pass a connection to a JasperReport is REPORT_CONNECTION, but as I said, doing this way, will cause a lot of trobubles.
MY SOLUTION:
ReportesDAOJDBC reportes;
public void setReportes(ReportesDAOJDBC reportes) {
this.reportes = reportes;
}
public ModelAndView leoTest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
Map < String, Object > model = new HashMap < String, Object >();
model.put("PARAMCONTRARECIBO", new Integer(1101));
model.put("PARAMDOCTOS", new Integer(1101));
model.put("OBJETO_CONEXION", reportes);
return new ModelAndView(new PdfView("leoTest"),model);
}
As you can see, I implement my own PdfView and I pass in the constructor the name of the key define in the view.properties file, and also I pass a reference to my DAO (reportes) as a parameter of the HashMap, the name of the parameter is "OBJETO_CONEXION". Here is the code for ReportesDAOJDBC:
public class ReportesDAOJDBC extends JdbcDaoSupport {
public Connection getConexion() {
Connection con ;
try {
con = getDataSource().getConnection();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
return con;
}
public void closeConecction(Connection con) {
try {
if (con != null) {
con.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Then the next step is to show you the code of my own PdfView implementation.
import java.io.File;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.Map;
import java.util.ResourceBundle;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mx.com.mexican.leinksy.dao.jdbc.ReportesDAOJDBC;
import mx.com.mexican.leinksy.utils.Utils;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
public class PdfView implements View {
private static final String CONTENT_TYPE = "application/pdf";
private String JASPER_URL;
public PdfView(String jasperUrl){
this.JASPER_URL = jasperUrl+".url";
}
#Override
public String getContentType() {
return CONTENT_TYPE;
}
#Override
public void render(Map model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println(Utils.getRealPath(request));
ResourceBundle rb = ResourceBundle.getBundle("view");/* Se lee el archivo view.properties*/
ReportesDAOJDBC reporte = (ReportesDAOJDBC)model.get("OBJETO_CONEXION");/* Se obtiene el objeto de conexion */
Connection con = reporte.getConexion();/* Se genera la conexion a la base de datos*/
String jasperFilePath = Utils.getRealPath(request) + rb.getString( JASPER_URL );/* Se obtiene la ruta fisica del archivo .jasper a ejectuar*/
JasperReport jasperReport = (JasperReport)JRLoader.loadObject(new File(jasperFilePath));/* Se carga el reporte ya compilado*/
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, model, con);/* Se llena el reporte con datos del modelo y con la conexion a la BD*/
try{
OutputStream out = response.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, out);/* Se manda el contenido a la salida estandar*/
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
reporte.closeConecction(con);/* Cierro la conexion a la base de datos para liberar el pool*/
}
}
As you can see, I read the view.properties file using the ResourceBoundle class to get the path and name of the .jasper file to load, Also notice that I dont compile the .jrxml file I just load the compiled file, I compile the jrxml with IREPORTS. Also I hava a utility to get the path of my .jasper file, here is the code if you dont have idea of how to do it.
public static String getRealPath(HttpServletRequest req) {
ServletContext context = req.getSession().getServletContext();
String path = context.getRealPath("/");
if (path != null) {
if (!path.endsWith(File.separator)) {
path += File.separator;
}
}
return path;
}
With this implementation I can control where to open an close connection, also I respect the MVC model of SPRING, and also I still using the view.properties.
And at this point, maybe you are asking WHAT CAN I DO IF I WANT AN EXCEL FILE, well, I also implement an XlsView, (Ajuuaaaa !!! ). Here is the code:
import java.io.File;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.Map;
import java.util.ResourceBundle;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mx.com.mexican.leinsky.dao.jdbc.ReportesDAOJDBC;
import mx.com.mexican.leinksy.utils.Utils;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
public class XlsView implements View {
private static final String CONTENT_TYPE = "application/vnd.ms-excel";
private String JASPER_URL;
private String FILE_NAME = "XLSFile";
public XlsView(String jasperUrl){
this.JASPER_URL = jasperUrl+".url";
}
#Override
public String getContentType() {
return CONTENT_TYPE;
}
#Override
public void render(Map model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
if(model.get("FILE_NAME")!=null){
this.FILE_NAME = model.get("FILE_NAME").toString();
}
ResourceBundle rb = ResourceBundle.getBundle("view");/* Se lee el archivo view.properties*/
ReportesDAOJDBC reporte = (ReportesDAOJDBC)model.get("OBJETO_CONEXION");/* Se obtiene el objeto de conexion */
Connection con = reporte.getConexion();/* Se genera la conexion a la base de datos*/
String jasperFilePath = Utils.getRealPath(request) + rb.getString( JASPER_URL );/* Se obtiene la ruta fisica del archivo .jasper a ejectuar*/
JasperReport jasperReport = (JasperReport)JRLoader.loadObject(new File(jasperFilePath));/* Se carga el reporte ya compilado*/
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, model, con);/* Se llena el reporte con datos del modelo y con la conexion a la BD*/
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment; filename=\""+FILE_NAME+".xls\"");
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 1);
try{
OutputStream out = response.getOutputStream();
JRXlsExporter exporterXLS = new JRXlsExporter();
exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT,jasperPrint);
exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM,out);
exporterXLS.exportReport();
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
reporte.closeConecction(con);/* Cierro la conexion a la base de datos para liberar el pool*/
}
}
So this is my solution, hope It helps !!!

Resources