What is strict mode policy violation in Android - android-permissions

public static void write(byte[] aInput, String aOutputFileName, String dirName) {
(new File(dirName)).mkdir();
try {
OutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(dirName + "/" + aOutputFileName));
output.write(aInput);
} finally {
output.close();
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
} catch (IOException ex) {
System.out.println(ex);
}
}
The code above is from a library i'm using and it is supposed to create an output file and write a byte array to it. I checked logcat and saw the Strict Mode Policy violation Write.toDisk. I understand what it is supposed to be for my questions are: (1) Does Strict mode prevent you from doing disk reads and write on the main thread? (2) Does that mean that the file or folder were not actually created? (3) How then would I go about creating a folder or file within my App that doesn't trigger this? (4) What is the recommended way to handle disk read / write off the main ui thread, a real world example would be appreciated
Thanks in Advance

(1) It turns out that Strict mode doesn't actually prevent you from making writes to the disk it just gives a warning. From Android Developer "StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them". https://developer.android.com/reference/android/os/StrictMode
(2) The files were actually being created it's just that I was just not familiar with writing and reading from disk
(3) There are numerous ways to go about creating files (i) first you get a hold of a file directory to write the file to:
context.getFilesDir()
(ii) then you get an outputstream writer (iii) then you write out the data with the writer
public void makeFile(String filename){
//Create temp file for filename
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(filename));
fos.write(filename.getBytes());//Write the contents of the file to app folder
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
(iv) finally you close the outputstream writer
(4) The recommended way is to use either an AsyncTask or some other background running class like FutureTask or to use Threads or Runnable:
public class DownloadFileThread implements Runnable{
public void run(){
//your code here
}
}

Related

Open powershell with java processbuilder and keep it opened

is there some way on how to open powershell with process builder in javafx and keep it opened to execute any command anytime?
Example code(executing only one command at a time):
try {
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "powershell -Command \"Add-Type -AssemblyName System.DirectoryServices.AccountManagement; [System.DirectoryServices.AccountManagement.UserPrincipal]::Current.DisplayName\"&&exit");
Process p = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.trim().isEmpty()) {
displayname = line;
}
}
reader.close();
p.waitFor();
p.destroy();
} catch (IOException | InterruptedException ex) {
Logger.getLogger(AccountStatus.class.getName()).log(Level.SEVERE, null, ex);
}
Reason to keep it opened: loading powershell takes maybe 3 seconds and loading for example active directory plugin takes another maybe 2 seconds everytime i want to execute some command. If there is some way on how to preload powershell and send command to processbuilder anytime it would be very helpfull, thanks for advices.
EDIT:
I have found solution here: Apache Commons exec PumpStreamHandler continuous input
Thanks to MichalVales!
With this quick sample i am able to open powershell, keep it opened, preload some module and execute any new command anytime without loading all again.
public class FXMLDocumentController implements Initializable {
private BufferedWriter writer;
#FXML
private void handleButtonAction(ActionEvent event) {
try {
writer.write("Import-Module ActiveDirectory -Cmdlet Get-ADUser\n");
writer.flush();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
#FXML
private void handleButtonAction2(ActionEvent event) {
try {
writer.write("Get-ADUser somenamehere -Properties * | Select-Object LockedOut\n");
writer.flush();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
ProcessBuilder builder = new ProcessBuilder("powershell.exe");
Process process;
try {
process = builder.start();
writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
StreamReader outputReader = new StreamReader(process.getInputStream(), System.out);
outputReader.start();
StreamReader err = new StreamReader(process.getErrorStream(), System.err);
err.start();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
StreamReader code can be found on link from MichalVales
EDIT2:
I was trying to pass czech characters with any writer, but without success. I think that its impossible to pass czech characters like "ěščřžýáíé" to powershell without changing system locale, but i dont want to do it. I have tried processbuilder, apache exec, all failed, but i have found super library which works and is really easy to use:
jPowerShell
So if you have problems with keeping powershell alive or problem with characters, this is the best solution.

Hibernate Search call to SearchFactory optimize does not invoke immediately

I'm trying to call SearchFactory optimize to run a scheduled index maintenance job (compacting segments - the application is a write intensive). But it does not seem to invoke immediately until I shutdown the Tomcat. My code is calling simply like this.
public synchronized void optimizeIndexes() {
getFullTextEntityManager().flushToIndexes(); //apply any changes before optimizing
getFullTextEntityManager().getSearchFactory().optimize();
logger.info("[Lucene] optimization has performed on all the indexes...");
}
I got it to work around by loaning IndexWriter from HSearch backend.
private synchronized void optimizeBareMetal() {
try {
LuceneBackendQueueProcessor backend = (LuceneBackendQueueProcessor) getIndexManager().getBackendQueueProcessor();
LuceneBackendResources resources = backend.getIndexResources();
AbstractWorkspaceImpl workspace = resources.getWorkspace();
IndexWriter indexWriter = workspace.getIndexWriter();
indexWriter.forceMerge(1, true);
indexWriter.commit();
} catch (LockObtainFailedException e) {
e.printStackTrace();
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private synchronized DirectoryBasedIndexManager getIndexManager() {
SearchFactoryImplementor searchFactory = (SearchFactoryImplementor) getFullTextEntityManager().getSearchFactory();
IndexManagerHolder indexManagerHolder = searchFactory.getIndexManagerHolder();
return (DirectoryBasedIndexManager) indexManagerHolder.getIndexManager(getEntityClass().getName());
}

Can't compile Lucene project with Eclipse

Here's my code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.apache.lucene.index.CorruptIndexException;
public class Main
{
public static void main()
{
//Index index = new Index();
String[] titleAndContent = parseFile("files/methode.txt");
Index index = new Index("files",null);
try
{
index.openIndex(true);
index.addDocument(titleAndContent[0], titleAndContent[1], "files/methode.txt");
}
catch (CorruptIndexException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String[] parseFile(String path)
{
String[] titleAndContent = new String[2];
File file = new File(path);
try
{
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = new String();
String content = new String();
try
{
while((line = br.readLine()) != null)
{
if (line.substring(0,min(6,line.length())).equals("title:"))
{
titleAndContent[0] = line.substring(6,line.length());
}
else
{
if (line.substring(0,min(8,line.length())).equals("content:"))
{
content += line.substring(8,line.length())+"\n";
}
else
{
content += line+"\n";
}
}
}
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
titleAndContent[1] = content;
try
{
fr.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return titleAndContent;
}
public static int max (int a, int b)
{
if (a<b)
{
return b;
}
return a;
}
public static int min (int a, int b)
{
if (a<b)
{
return a;
}
return b;
}
}
The problem is, I can't compile my Lucene projet under Eclipse. It keeps telling me:
ERROR: index path not specified
Usage: java org.apache.lucene.index.CheckIndex pathToIndex [-fix] [-segment X] [-segment Y]
-fix: actually write a new segments_N file, removing any problematic segments
-segment X: only check the specified segments. This can be specified multiple
times, to check more than one segment, eg '-segment _2 -segment _a'.
You can't use this with the -fix option
**WARNING**: -fix should only be used on an emergency basis as it will cause
documents (perhaps many) to be permanently removed from the index. Always make
a backup copy of your index before running this! Do not run this tool on an index
that is actively being written to. You have been warned!
Run without -fix, this tool will open the index, report version information
and report any exceptions it hits and what action it would take if -fix were
specified. With -fix, this tool will remove any segments that have issues and
write a new segments_N file. This means all documents contained in the affected
segments will be removed.
This tool exits with exit code 1 if the index cannot be opened or has any
corruption, else 0.
I tried everything to make it work, and as the whole web says, I used
-ea:org.apache.lucene... pathToIndex -fix
as argument of compilation. But whatever I put instead of pathToIndex, it keeps telling me
Unexpected argument pathToIndex (or whatever instead)
How can I get this f... project work?
Thank you in advance.
Edit: Of course I've imported all Lucene JARs.
Actually, I started the project over by creating a simple Main class and a main method inside it and tried to compile it immediately. And it worked fine, this time. Note you should show the Main class on your screen tab before compiling in Eclipse.

Dynamic file loading in jetty

As per our implementation we are dynamically creating some image files in the server side and sharing the URLs.
But we are unable to retrieve the image resources using the URLs if the file is created while the JETTY is running.
However we can retrieve it if we stop the jetty and start it again.
I would like to know if there is any configuration which will enable us to retrieve the resources without the jetty being stopped?
Is it necessary to persist the dynamic images? If not, you can just stream the dynamic image like this:
public void sendImage(RenderedImage image, String mimeType, String imageIOType, HttpServletResponse response)
{
if(image != null)
{
OutputStream output = null;
try
{
output = response.getOutputStream();
response.setContentType(mimeType);
ImageIO.write(image, imageIOType, output);
}
catch (IOException e)
{
e.printStackTrace();
}
if(output != null)
{
try
{
output.flush();
output.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
HTH

linking my applet to a server dirctory to recieve or save a file from there?

I' m looking for a code to save the files created in a applet normally text files i want to save them on a server directory how can i do so.
Here is an example of how to send a String. In fact any Object can be sent this method so long as it's serializable and the same version of the Object exists on both the applet and the servlet.
To send from the applet
public void sendSomeString(String someString) {
ObjectOutputStream request = null;
try {
URL servletURL = new URL(getCodeBase().getProtocol(),
getCodeBase().getHost(),
getCodeBase().getPort(),
"/servletName");
// open the connection
URLConnection con = servletURL.openConnection();
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/octet-stream");
// send the data
request =
new ObjectOutputStream(
new BufferedOutputStream(con.getOutputStream()));
request.writeObject(someString);
request.flush();
// performs the connection
new ObjectInputStream(new BufferedInputStream(con.getInputStream()));
} catch (Exception e) {
System.err.println("" + e);
} finally {
if (request != null) {
try {
request.close();
} catch (Exception e) {
System.err.println("" + e);
};
}
}
}
To retrieve on the server side
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
// get the input stream
ObjectInputStream inputStream = new ObjectInputStream(
new BufferedInputStream(request.getInputStream()));
String someString = (String)inputStream.readObject();
ObjectOutputStream oos = new ObjectOutputStream(
new BufferedOutputStream(response.getOutputStream()));
oos.flush();
// handle someString....
} catch (SocketException e) {
// ignored, occurs when connection is terminated
} catch (IOException e) {
// ignored, occurs when connection is terminated
} catch (Exception e) {
log.error("Exception", e);
}
}
No one is going to hand you this on a plate. You have to write code in your applet to make a socket connection back to your server and send the data. One way to approach this is to push the data via HTTP, and use a library such as commons-httpclient. That requires your server to handle the appropriate HTTP verb.
There are many other options, and the right one will depend on the fine details of the problem you are trying to solve.