Copying asset files to SD Card (file not found)? - ocr

I'm trying to copy files for Tesseract to use and no matter how I try it keeps giving me filenot found exceptions. I don't understand why because I have them in the assets folder. I tried it one way by copying the specific tessdata folder which wasn't working so I tried putting them all under the general assets folder and copying each file in there into a new directory I created on the card called tessdata.
Here's an image of the files in the folder, the method for copying and the log errors that post:
And here's the code:
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
android.util.Log.e(TAG, "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
out = new FileOutputStream(tesspath+ "/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
android.util.Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
-I also tried using this method from an example which copied them from the tessdata folder within assets-
if (!(new File(tesspath + File.separator + lang + ".traineddata")).exists()) {
copyAssets();
/* try {
AssetManager assetManager = getAssets();
//open the asset manager and open the traineddata path
InputStream in = assetManager.open("tessdata/eng.traineddata");
android.util.Log.e(TAG, "OPENED SUCCESSFULLY IF NO ERROR BEFORE THIS");
OutputStream out = new FileOutputStream(tesspath + "/eng.traineddata");
android.util.Log.e(TAG, "WRITING NOW TO" + tesspath);
byte[] buf = new byte[8024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Was unable to copy " + lang
+ " traineddata " + e.toString());
android.util.Log.e(TAG, "IM PRINTING THE STACK TRACEs");
e.printStackTrace();
}
*/
} else {
processImage(STORAGE_PATH + File.separator + "savedAndroid.jpg");
}

have you checked the sdcard write perssion in manifest.xml ?
probably you will need this in the AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Related

Exception no longer being caught

The following code was working fine. I then transported the files to another location (another instance of VS2019 Community). Now, the exception doesn't get caught any more and the code breaks during debug. How can this be explained? Thanks
private List<string> getMembers(string objectName)
{
List<string> result = new List<string>();
List<string> listMembers = new List<string>();
try
{
PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain);
UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, objectName);
string groupList = "";
foreach (var group in up.GetGroups())
{
groupList += group.SamAccountName + "|";
}
result.Add(objectName + tab + groupList);
}
catch (Exception ex)
{
result.Add(objectName + tab + "Error: " + ex.Message);
}
return result;
}
Case of corrupted/missing pdb files. Nothing wrong with code.

LibGdx load Texture from SmbFile

I try to create a Gdx Texture with an image file located in a shared folder on my PC.
The code works well on desktop app (but it works as well without using SmbFile...), but crash on android app. I obtain "no such file or directory" error.
Does somebody knows how can we do that ?
Thank's !
public void create () {
Gdx.app.setLogLevel(Application.LOG_DEBUG);
batch = new SpriteBatch();
SmbFile file=null;
try {
file = new SmbFile("smb://***path to shared folder***/icon-152.png");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
FileHandle fileHandle;
fileHandle = new FileHandle(file.getUncPath());
img = new Texture(fileHandle); //***No such file or directory***
//img = new Texture(Gdx.files.external(file.getUncPath())); //***No such file or directory***
}
Add on :
I tried to copy the File in assets before to load it as a Texture. Still working fine on desktop app, but Stil having an error on android app : Java.io.FiliNotFound Exception.
public void create () {
Gdx.app.setLogLevel(Application.LOG_DEBUG);
batch = new SpriteBatch();
SmbFile file=null;
try {
file = new SmbFile("smb://***path to shared folder***/icon-152.png");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(file.getUncPath());
os = new FileOutputStream("test.png");
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.close();
}
catch(java.io.IOException e){
Gdx.app.log("", e.getMessage()); //***Java.io.FileNotFound Exception***
}
img = new Texture("test.png"); //***No such file or directory***
}
Yes Nicolas,
I finaly did it by first copying the file in local. It is working on both android and desktop app.
If somebody is interested, the two functions loadFile and saveFile :
loadFile( "//***path to shared folder***/icon-152.png","icon-152.png");
saveFile("icon-152.png", "//HP2285/***path to shared folder***/icon-152.png");
}
public void loadFile(String smbFilePath, String fileName){
try {
SmbFile file = new SmbFile("smb:"+smbFilePath);
InputStream is = new SmbFileInputStream(file);
FileHandle fhd = Gdx.files.local(fileName);
OutputStream os = fhd.write(false);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.close();
}
catch(Exception e){
}
}
public void saveFile(String fileName, String smbFilePath){
try {
SmbFile file = new SmbFile("smb:"+smbFilePath);
OutputStream os = new SmbFileOutputStream(file);
FileHandle fhs = Gdx.files.local(fileName);
InputStream is = fhs.read();
byte[] buffer = new byte[1024];
int length;
while ((length = is.read (buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.close();
}
catch(Exception e){
}
}

How to work around jsch.addIdentity() in Junit test?

I use apache mina sshd to set up a mocked ssh server for Junit testing purpose. Since the documentation for apache mina is quite unclear, I cannot figure out how to deal with authentication problem in testing.
Code I would like to test, basically using Jsch to transfer file from local to remote.
public static void scpTo(String rfilePath, String lfilePath, String user, String host, String keyPath, int port) {
FileInputStream fis=null;
try {
while(true) {
String rfile = rfilePath;
String lfile = lfilePath;
JSch jsch = new JSch();
jsch.addIdentity(keyPath);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
Session session = jsch.getSession(user, host, port);
session.setConfig(config);
session.connect();
// exec 'scp -t rfile' remotely
String command = "scp " + " -t " + rfile;
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
if (checkAck(in) != 0) {
System.exit(0);
}
File _lfile = new File(lfile);
if(!_lfile.exists()) {
System.err.println("Local file not existing");
}
//check file existing
File _rfile = new File(rfile);
if (_rfile.exists()) {
System.out.println("Remote file already existed");
break;
}
// send "C0644 filesize filename", where filename should not include '/'
long filesize = _lfile.length();
command = "C0644 " + filesize + " ";
if (lfile.lastIndexOf('/') > 0) {
command += lfile.substring(lfile.lastIndexOf('/') + 1);
} else {
command += lfile;
}
command += "\n";
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
System.exit(0);
}
// send a content of lfile
fis = new FileInputStream(lfile);
byte[] buf = new byte[1024];
while (true) {
int len = fis.read(buf, 0, buf.length);
if (len <= 0) break;
out.write(buf, 0, len); //out.flush();
}
fis.close();
fis = null;
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
if (checkAck(in) != 0) {
System.exit(0);
}
out.close();
channel.disconnect();
session.disconnect();
//System.exit(0);
Thread.sleep(2000);
}
} catch (Exception e) {
System.out.println(e);
try {
if (fis != null) fis.close();
} catch (Exception ee) {
}
}
}
And the setUp used for testing. If I would like to authenticate all the user & host pairs by using a given key file in my resource folder, what should I do for setUp? For the current setUp, it will have Auth fail error.
#Before
public void setup() {
user = "siyangli";
host = "localhost";
//pick a port not occupied for tesing
port = 22998;
sshd = SshServer.setUpDefaultServer();
sshd.setPort(port);
keyPath = "/Users/siyangli/.ssh/id_rsa";
//it will change the key file??? do not know why, how to work around the authentication key??
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[]{"/Users/siyangli/.ssh/id_rsa"}));
//sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(keyPath));
sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
public boolean authenticate(String username, String password, ServerSession session) {
return true;
}
});
sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
#Override
public boolean authenticate(String username, PublicKey key, ServerSession session) {
return true;
}
});
CommandFactory myCommandFactory = new CommandFactory() {
public Command createCommand(String command) {
System.out.println("Command: " + command);
return null;
}
};
sshd.setCommandFactory(new ScpCommandFactory(myCommandFactory));
List<NamedFactory<UserAuth>> userAuthFactories = new ArrayList<NamedFactory<UserAuth>>();
userAuthFactories.add(new UserAuthPassword.Factory());
sshd.setUserAuthFactories(userAuthFactories);
List<NamedFactory<Command>> namedFactoryList = new ArrayList<NamedFactory<Command>>();
namedFactoryList.add(new SftpSubsystem.Factory()); sshd.setSubsystemFactories(namedFactoryList);
try {
sshd.start();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println("Finished setup !!! ");
}
You need to change this line:
userAuthFactories.add(new UserAuthPassword.Factory());
to
userAuthFactories.add(new UserAuthPublicKey.Factory());

how to download file form Google Drive asp.net

I am trying to download files from google drive below is my code
private static IAuthenticator CreateAuthenticator()
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = ClientCredentials.CLIENT_ID;
provider.ClientSecret = ClientCredentials.CLIENT_SECRET;
return new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
}
public static System.IO.Stream DownloadFile(
IAuthenticator authenticator, Google.Apis.Drive.v2.Data.File file)
{
if (!String.IsNullOrEmpty(file.DownloadUrl))
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
new Uri(file.DownloadUrl));
authenticator.ApplyAuthenticationToRequest(request);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
return response.GetResponseStream();
}
else
{
Console.WriteLine(
"An error occurred: " + response.StatusDescription);
return null;
}
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else
{
// The file doesn't have any content stored on Drive.
return null;
}
}
in .aspx page code
{
System.IO.Stream stream = Utilities.DownloadFile(CreateAuthenticator(), FIle);
//Convert the stream to an array of bytes.
System.IO.BinaryReader br = new System.IO.BinaryReader(stream);
Byte[] byteArray = br.ReadBytes((int)stream.Length);
its showing This stream does not support seek operations.
where is error
thank u....
You do not have to seek the file if you are trying just to download the file. What you should do is just to read the stream i.e. through the DownloadFile API method and pass it to the browser. I have enable it through the following code:
public FileResult DownloadFile(string fileId)
{
DriveService service = Session["service"] as DriveService;
Google.Apis.Drive.v2.Data.File file = service.Files.Get(fileId).Fetch();
System.IO.Stream data = new GDriveRepository(Utils.ReturnIAuth((GoogleAuthenticator)Session["Gauthenticator"])).DownloadFile(file.DownloadUrl);
return File(data, System.Net.Mime.MediaTypeNames.Application.Octet, file.Title);
}

Running pig local, UDF program cannot write files/folder: PriviledgedActionException

Newbie with Pig/hadoop..
Running pig at local.
java -Xmx512m -Xmx1024m -cp $PIGDIR/pig.jar org.apache.pig.Main -Dpig.temp.dir=/tmp/$USER/$RANDOM -stop_on_failure -x local script-buzz.pig
with my script.pig:
(...)
buzz = FOREACH files GENERATE chiron.buzz.Honey(file, id) as buzz_file, id;
Trying to write a folder/file with my UDF raise:
[JobControl] ERROR org.apache.hadoop.security.UserGroupInformation - PriviledgedActionException as:felipehorta cause:org.apache.pig.backend.executionengine.ExecException: ERROR 2118: Input path does not exist: file:/Users/felipehorta/dev/ufrj/pig/pig-buzz/output
the following code must (!) writes files that are consumed at the next LOAD.
jar works fine with: $ java -jar Pgm.jar *
(...)
public String exec(Tuple input) throws IOException {
try{
System.out.println(input.get(0).toString());
BumbleBee b = new BumbleBee(input.get(0).toString());
return b.writeRelation(input.get(1).toString());
} catch(Exception e){
System.err.println("Failed to process input; error - " + e.getMessage());
return null;
}
}
public String writeRelation(String folder) throws IOException {
try {
// writing file!
File output = new File("output/ERelation_" + folder + ".txt");
output.getParentFile().mkdirs();
FileWriter fw = new FileWriter(output);
String line = System.getProperty("line.separator");
fw.append("YEAR;WORD;COUNT" + line);
for (Integer year : buzzCandidates.keySet()) {
Map<String, Long> wordCounts = buzzCandidates.get(year);
for (String word : wordCounts.keySet()) {
long value = wordCounts.get(word);
if (value >= 3) {
fw.append(year + ";" + word.replace(" ", "_") + ";" + String.valueOf(value) + line);
}
}
}
fw.flush();
fw.close();
return output.getAbsolutePath();
} catch (Exception e) {
System.out.println(">>> ERROR!!\t" + e.getMessage());
return "ERROR";
}
}
I think it is about permission writing files with UDF, but I dont know where set permissions. Any help?
Thanks in advance, fellows!
Error reads Input path does not exist: file:/Users/felipehorta/dev/ufrj/pig/pig-buzz/output Please check the pig script as to how the load is used.
relation = load '/Users/felipehorta/dev/ufrj/pig/pig-buzz/output' using ...
would be the correct way of doing it.
Not sure if this could be the exact reason. Would be great if you could post the scripts.