Logging on device to file - java

How to redirect logging on device to file?
My application is hang on device but works great on emulator - I want to see logging on my device without sdk and its tools.

Look at Android Log Collector.

I found excellent feature of Logcat. It can redirect output to file himself by using simple command parameter "-f ".
To use it you can write Logcat wrapper in your application aLogcat like. Obviously I made this :)
For using logcat at android I wrote this code:
Process proc = null;
try {
proc = Runtime.getRuntime().exec(new String[] { "logcat", <!parametes_here!> });
mReader = new BufferedReader(new InputStreamReader(proc.getInputStream()), 1024);
String line;
while ((line = mReader.readLine()) != null) {
if (line.length() == 0) {
continue;
}
mHandler.sendMessage(mHandler.obtainMessage(Logcat.MSG_READ_LINE, line));
}
} catch (IOException e) {
Log.e(TAG, "Cannot start process", e);
} finally {
if (mReader != null)
try {
mReader.close();
} catch (IOException e) {
Log.e(TAG, "Cannot close stream", e);
}
}

Microlog - A logging framework for Java ME and Android inspired by Log4j.
(c) http://en.wikipedia.org/wiki/Log4j
"Using Microlog for Logging on Android & Viewing the Logs in the Emulator" by Johan Karlsson
Newsflash! Microlog for Android - microlog4android

I am using the application aLogCat downloaded free from android market.
Works very good.

Logging frameworks like log4j already provide features like logging to a file. Using android-logging-log4j it is possible to log to a rotating log file and to logcat. Also see log4j support in Android.

Related

Using Microsoft Speech API text-to-speech in java for Android?

I am trying to use Microsoft Speech API text-to-speech, in my java project for Android. It's not working. Is it possible to use this API in java?
The speech-to-text is working, I found the Quickstart and had no problem using it.
However, there is no java example for text-to-speech, only in C#, C++ (Windows) and C++ (Linux).
I tried to adapt the code in java, but it's not working and I have no idea why.
public void onTextToSpeechButtonClicked(View v) {
TextView txt = (TextView) this.findViewById(R.id.texttospeech); // 'texttospeech' is the ID of my text view
try {
// THIS LINE ISN'T WORKING
com.microsoft.cognitiveservices.speech.internal.SpeechConfig config = com.microsoft.cognitiveservices.speech.internal.SpeechConfig.FromSubscription(speechSubscriptionKey, serviceRegion);
config.SetSpeechRecognitionLanguage("fr-FR");
assert(config != null);
// Creates a speech synthesizer using the default speaker as audio output
SpeechSynthesizer synthesizer = SpeechSynthesizer.FromConfig(config);
assert(synthesizer != null);
SpeechSynthesizer synthesizer1 = SpeechSynthesizer.FromConfig(config);
SpeechSynthesisResult result = synthesizer.SpeakTextAsync(txt.toString()).Get();
// Checks result
if (result.getReason().equals(ResultReason.SynthesizingAudioCompleted)){
txt.setText("The text has been said.");
}
else if (result.getReason().equals(ResultReason.Canceled)){
SpeechSynthesisCancellationDetails cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
txt.setText("CANCELED: Reason ="+cancellation.getReason());
if(cancellation.getReason().equals(CancellationReason.Error)){
txt.append("ErrorCode = "+cancellation.getErrorCode()+" / ErrorDetails = "+cancellation.getErrorDetails()+" / Did you update the subscription info ?");
}
}
synthesizer.delete();
} catch (Exception ex) {
Log.e("SpeechSDKDemo", "unexpected " + ex.getMessage());
assert(false);
}
}
What I have in the log is that:
E/ples.quickstar: No implementation found for void com.microsoft.cognitiveservices.speech.internal.carbon_javaJNI.swig_module_init() (tried Java_com_microsoft_cognitiveservices_speech_internal_carbon_1javaJNI_swig_1module_1init and Java_com_microsoft_cognitiveservices_speech_internal_carbon_1javaJNI_swig_1module_1init__)
D/AndroidRuntime: Shutting down VM
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.microsoft.cognitiveservices.speech.samples.quickstart, PID: 4106
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
at android.view.View.performClick(View.java:6597)
at...
Can someone help me?
I searched if Microsoft Speech API is compatible with Java and the answer is no. It also seems a little obvious because Microsoft = C++ / C# which is nothing similar to Java.
In addition, in your post you mentionned the Quickstart. This uses the Cognitive Services Speech SDK and not Microsoft SAPI.
However, there are native Java libraries allowing Text-To-Speech. Here is a post related to Text-To-Speech engines. Here is more information about it.
There are also libraries available for Android:
Using the Text-To-Speech engine
Android documentation
I would suggest an alternative. Why not try to use windows tts instead by sending the text to a powershell command which can be executed from java code:
String[] command = {"powershell.exe", "Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('" + message +"');"};
try {
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();
System.out.format("Process exit code: %d", process.waitFor());
ProcessInputOutput.readStdnOutput(process);
}
catch (Exception e){
e.printStackTrace();
}

JavaFX WebEngine - fail to load firebug-lite.js that is stored locally

I'm trying to make kind of wrapper class to create applications that use JavaFX WebView for their GUI (I called the class Application), that I can easily use in my other apps (I make a jar of my wrapper project, and then jar can be imported in any other project). I assumed that including some debug features in my wrapper is important, so I downloaded 'firebug-lite.js' and 'firebug-lite.css' version 1.2 to ./src/firebug/ directory in my project folder (so no internet required). After a number of tries I came to following code in Application.debug():
public void debug() {
// file is inside the jar, in ./firebug/ directory, so I use getResourceAsStream()
BufferedReader br = new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream("/firebug/firebug-lite.js")));
String line;
String wholeFirebugCode = "";
try {
// reading firebug-lite.js line-by-line, not including \n characters
while ((line = br.readLine()) != null) {
wholeFirebugCode += line;
}
if (wholeFirebugCode.isEmpty()) System.out.println("!");
else {
// everything is OK, file is read, so add firebug to our page
engine.executeScript("document.body.innerHTML += \""+
"<script type='text/javascript'>" +
wholeFirebugCode +
"</script>\"");
}
} catch (IOException e) {
printError(e, "during load of /firebug/firebug-lite.js from within jar (WebEngineApp.jar)");
}
}
So, I built a jar, checked whether it has ./firebug/firebug-lite.js (it does), included that jar in a sample project and tried with this code:
// constructor works fine
Application app = new Application("title of window", path_to_sample_html_page,
width, height, bridge);
app.run();
try {//we wait a few til page is fully loaded (just for sure)
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
printError(e, "");
}
// here I check if java-js connection is established and page is loaded. It is
Platform.runLater(app::test);
// here I run the code which cause problem
Platform.runLater(app::debug);
But this doesn't work. I use Java 8, if it makes any difference:
Exception in thread "JavaFX Application Thread" netscape.javascript.JSException: SyntaxError: Unexpected identifier 'css'
at com.sun.webkit.dom.JSObject.fwkMakeException(JSObject.java:146)
at com.sun.webkit.WebPage.twkExecuteScript(Native Method)
at com.sun.webkit.WebPage.executeScript(WebPage.java:1509)
at javafx.scene.web.WebEngine.executeScript(WebEngine.java:1005)
at emeshka.webengineapp.Application.debug(Application.java:157)
at Main.lambda$main$0(Main.java:41)
(... etc)
File seems to be read correctly, I've checked it by logging. Same thing happens if I try to use 'firebug-lite-compressed.js', and if I use this method of code including:
engine.executeScript(wholeFirebugCode);
I'm completely lost. It couldn't be that firebug is syntactically incorrect. Sample html page contains no js. How can I make firebug work?
I've tried to use these solutions, that require internet, but they just took no effect, and no errors were shown:
Html/Javascript debugging in JavaFX WebView
,
JAVAFX / WebView / WebEngine FireBugLite or Some other debugger?

How to trace the route of a host using Java? [duplicate]

Java does not have primitives for ICMPs and traceroute. How to overcome this? Basically I'm building code that should run in *nix and Windows, and need a piece of code that will run in both platforms.
Here's what I wrote today to "implement" the trace route command in Java. I've only tested in windows but it should work in Linux as well although there are several traceroute tools available for Linux so most likely there need to be some checks for the existence of those programs.
public class NetworkDiagnostics{
private final String os = System.getProperty("os.name").toLowerCase();
public String traceRoute(InetAddress address){
String route = "";
try {
Process traceRt;
if(os.contains("win")) traceRt = Runtime.getRuntime().exec("tracert " + address.getHostAddress());
else traceRt = Runtime.getRuntime().exec("traceroute " + address.getHostAddress());
// read the output from the command
route = convertStreamToString(traceRt.getInputStream());
// read any errors from the attempted command
String errors = convertStreamToString(traceRt.getErrorStream());
if(errors != "") LOGGER.error(errors);
}
catch (IOException e) {
LOGGER.error("error while performing trace route command", e);
}
return route;
}
You'll need the jpcap library (maybe the SourceForge jpcap is working too) and use the ICMPPacket class to implement the desired functionality.
Here is the Java traceroute implementation using the jpcap library .

why does Files.probeContentType return null

i am using java se7 on mac, the oracle preview.
My problem is that "Files.probeContentType" returns null...is it possible that its due to the early status of se7 for mac?
My code:
if(directory == null) return;
String content = null;
try {
content = Files.probeContentType(directory.toPath());
} catch (IOException e) {
JOptionPane.showMessageDialog(main, e.toString());
return;
}
if(content == null)
{
return;
}
else if(content.contains("image"))
{
main.pctviewer.setImage(directory);
}
the name of the file is:
"/Users/admin/Desktop/temp/q12/formulare/Bildschirmfoto 2012-09-11 um 17.57.59.png"
and in debug mode in eclipse if i hover above File "file path = Unis-path(id:145)" is red
I have reported the bug to oracle again, hoping they will backport the jdk8 solution (I don't have much hope but you never know).
In the meantime you can use my own backport of the FileTypeDetector available at https://github.com/jeantil/jdk7-mimeutils the maven project packages to a jar which can be added to your classpath to enable mime type detection. I also provide a mime.types file to put in your home folder for the detection to work correctly. I extracted the mime.types file from some version of apache so it's pretty complete.
I found that the FileTypeDetector is buggy on OS X: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7133484
Apparently this will be fixed in Java 8.
Use the below approach to get mime type of file in Java 8 :
String location = "/Users/user/Desktop/leaf.jpg";
File file = new File(location);
Path source = Paths.get(location);
MimetypesFileTypeMap m = new MimetypesFileTypeMap(source.toString());
System.out.println( m.getContentType(file) );
Output of the above code is : 'image/jpg'

Eclipse : Welcome page not getting displayed

I am working on an application which is built on top of Eclipse. Though everything is working fine on windows, Sles 32 and 64 bit, but on SLED 64 bit the Welcome page is not getting Displayed. When you try to open the welcome page it throws an MalformedUrl exception with
"Could not load Swt Style: content/shared.css" as error message.
When i checked on net, i discovered that several people seems to have encountered this problem but i couldn't find a solution. Please help me out guys.
That error message comes directly form the SharedStyleManager class.
try {
URL JavaDoc styleURL = new URL JavaDoc(style);
InputStream JavaDoc is = styleURL.openStream();
properties.load(is);
is.close();
context.path = new Path(style).removeLastSegments(1);
String JavaDoc t = (String JavaDoc)properties.get("theme"); //$NON-NLS-1$
if (t!=null && t.trim().equalsIgnoreCase("true")) //$NON-NLS-1$
context.inTheme = true;
} catch (Exception JavaDoc e) {
Log.error("Could not load SWT style: " + style, e); //$NON-NLS-1$
}
Do you have the exception bundle within the "Could not load SWT style" exception? (in your Error view)
Found the problem Source. I was using incompatible version of xulrunner. Changing this to version compatible with eclipse fixed the problem.

Categories