how to fix file .json not found when it is there - java

I am trying here to consume the data from a json file:
DATA.json
[
{"Label"
:"USA",
"Adress":"This is the us",
"Lat":"36.9628066",
"Lng":"-122.0194722"
},
{ "Label" :"USA",
"Address":"2020",
"Lat":"36.9628066",
"Lng":"-122.0194722" }
]
Then applying it in my Mainclass:
using System.Collections.Generic;
using Xamarin.Forms.Maps;
using Xamarin.Forms;
using System.IO;
using Newtonsoft.Json;
using System;
namespace Orbage
{
class MapPage : ContentPage
{
public MapPage()
{
CustomMap customMap = new CustomMap
{
MapType = MapType.Street
};
// ...
Content = customMap;
var json = File.ReadAllText("File.json");
var places = JsonConvert.DeserializeObject<List<File>>(json);
foreach (var place in places)
{
CustomPin pin = new CustomPin
{
Type = PinType.Place,
Position = new Position(Double.Parse(place.Lat), Double.Parse(place.Lng)),
Label = place.Label,
Address = place.Address,
Name = "Xamarin",
Url = "http://xamarin.com/about/"
};
customMap.CustomPins = new List<CustomPin> { pin };
customMap.Pins.Add(pin);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
}
}
}
}
But when I put the file in there it says that it doesn't exist.
Error:
FilenotfoundException
Whats the fix for this.
I tried:
Changing the location of the file.
Its name
Instead of E:/-/- i even wrote file.json but I still get the same error.
Thanks alot!

Try to use the method below:
Put your File.json to your PCL project,and set its Build Action to EmbeddedResource.
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MapPage)).Assembly;
Stream stream = assembly.GetManifestResourceStream("Orbage.File.json");
string text = "";
using (var reader = new System.IO.StreamReader(stream))
{
text = reader.ReadToEnd();
}

Its better before reading the file, put check whether file exists in the location or not.
if (File.Exists("File.Json"))
With this you would become to know that your given path is correct or not.

Related

How to use Wordnet Synonyms with Hibernate Search?

I've been trying to figure out how to use WordNet synonyms with a search function I'm developing which uses Hibernate Search 5.6.1. At first, I thought about using Hibernate Search annotations:
#TokenFilterDef(factory = SynonymFilterFactory.class, params = {#Parameter(name = "ignoreCase", value = "true"),
#Parameter(name = "expand", value = "true"),#Parameter(name = "synonyms", value = "synonymsfile") })
However, this requires an actual file populated with synonyms. From WordNet I was only able to get ".pl" files. So I tried manually making a SynonymAnalyzer class which would read from the ".pl" file:
public class SynonymAnalyzer extends Analyzer {
#Override
protected TokenStreamComponents createComponents(String fieldName) {
final Tokenizer source = new StandardTokenizer();
TokenStream result = new StandardFilter(source);
result = new LowerCaseFilter(result);
SynonymMap wordnetSynonyms = null;
try {
wordnetSynonyms = loadSynonyms();
} catch (IOException e) {
e.printStackTrace();
}
result = new SynonymFilter(result, wordnetSynonyms, false);
result = new StopFilter(result, StopAnalyzer.ENGLISH_STOP_WORDS_SET);
return new TokenStreamComponents(source, result);
}
private SynonymMap loadSynonyms() throws IOException {
File file = new File("synonyms\\wn_s.pl");
InputStream stream = new FileInputStream(file);
Reader reader = new InputStreamReader(stream);
SynonymMap.Builder parser = null;
parser = new WordnetSynonymParser(true, true, new StandardAnalyzer(CharArraySet.EMPTY_SET));
try {
((WordnetSynonymParser) parser).parse(reader);
} catch (ParseException e) {
e.printStackTrace();
}
return parser.build();
}
}
The problem with this method is that I'm getting java.lang.OutOfMemoryError which I'm assuming is because there's too many synonyms or something? What is the proper way to do this, everywhere I've looked online has suggested using WordNet but I can't seem to find an example with Hibernate Search Annotations. Any help is appreciated, thanks!
The wordnet format is actually supported by SynonymFilterFactory. You're simply missing the "format" parameter in your annotation configuration; by default, the factory uses the Solr format.
Change your annotation to this:
#TokenFilterDef(
factory = SynonymFilterFactory.class,
params = {
#Parameter(name = "ignoreCase", value = "true"),
#Parameter(name = "expand", value = "true"),
#Parameter(name = "synonyms", value = "synonymsfile"),
#Parameter(name = "format", value = "wordnet") // Add this
}
)
Also, make sure that the value of the "synonyms" parameter is the path of a file in your classpath (e.g. "com/acme/synonyms.pl", or just "synonyms.pl" if the file is at the root of your "resources" directory).
In general when you have an issue with the parameters of a Lucene filter/tokenizer factory, your best bet is having a look at the source code of that factory, or having a look at this page.

Returning an exe file from server and downloading on client via browser

I am trying to send an exe file from the server to the client.
The file contents come in the form of byte array.
Then i am trying to recreate the .exe file on the client machine again.
On server side I am returning file contents as
'application/octet-stream', 'Content':bytearray
I am using an ajax call of following type to get file contents.
$.ajax({
type : 'POST',
url : 'https://myurl,
cache : false,
success : function(data) {
var myBlob = new Blob([data], { type: "application/octet-stream" });
var uri = (window.URL || window.webkitURL).createObjectURL(myBlob);
// var outputFile = window.prompt("Saving .log file of rows from different modalities") || 'export';
var outputFile = "utility"+ '.exe'
var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download =outputFile;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
cnt++;
/* }); */
},
error : (function(message) {
debugger;
console.log('message ' +message)
}),
statusCode : {
404 : function() {
alert("page not found");
}
}
});
But when the file gets downloaded the size of the file is big.
for ex original file 192kbs
downloaded file 320 kbs
Also I am getting the following exception after running the exe:
The version of file is not compatible with version of windows you are running on 32/64
Please if anybody can help resolve this issue
The following is the server side code to return exe file contents
//The context with which all SDK operations are performed.
Context context = Context.create();
String modelnumber = parameters.modelnumber;
String siteid=parameters.siteid;
def b;
try{
JSONArray arr=new JSONArray();
ModelFinder mf = new ModelFinder(context);
mf.setName(modelnumber)
Model m=mf.find();
if(m!=null)
{
DeviceFinder df = new DeviceFinder(context);
df.setModel(m)
df.setSerialNumber(siteid)
Device dev=df.find()
if(dev!=null)
{
UploadedFileFinder filefinder=new UploadedFileFinder(context)
filefinder.setDevice(dev)
filefinder.setFilename("/remote/notepad.exe")
UploadedFile temp=filefinder.find()
if(temp!=null)
{
File f=temp.extractFile();
arr[0]=f.text
b=f.getBytes()
}
}
}
return ['Content-Type': 'application/binary', 'Content':b];
}
catch(Exception e)
{ return ['Content-Type': 'application/text', 'Content':e.getMessage()];
}
I have solved the problem in following manner:
Server side code:
JSONArray arr=new JSONArray()
def bytes=file.getBytes()
arr.add(bytes)
return ['Content-Type': 'application/json', 'Content': arr];
}
> Client side code:
value3 comes from ajax which is a byte array
var arr =value3
var byteArray = new Uint8Array(arr);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/octet-stream' }));
a.download ="Utility.exe";
// Append anchor to body.
document.body.appendChild(a)
a.click();
// Remove anchor from body
document.body.removeChild(a)

How to read Nutch content from Java/Scala?

I'm using Nutch to crawl some websites (as a process that runs separate of everything else), while I want to use a Java (Scala) program to analyse the HTML data of websites using Jsoup.
I got Nutch to work by following the tutorial (without the script, only executing the individual instructions worked), and I think it's saving the websites' HTML in the crawl/segments/<time>/content/part-00000 directory.
The problem is that I cannot figure out how to actually read the website data (URLs and HTML) in a Java/Scala program. I read this document, but find it a bit overwhelming since I've never used Hadoop.
I tried to adapt the example code to my environment, and this is what I arrived at (mostly by guesswprk):
val reader = new MapFile.Reader(FileSystem.getLocal(new Configuration()), ".../apache-nutch-1.8/crawl/segments/20140711115438/content/part-00000", new Configuration())
var key = null
var value = null
reader.next(key, value) // test for a single value
println(key)
println(value)
However, I am getting this exception when I run it:
Exception in thread "main" java.lang.NullPointerException
at org.apache.hadoop.io.SequenceFile$Reader.next(SequenceFile.java:1873)
at org.apache.hadoop.io.MapFile$Reader.next(MapFile.java:517)
I am not sure how to work with a MapFile.Reader, specifically, what constructor parameters I am supposed to pass to it. What Configuration objects am I supposed to pass in? Is that the correct FileSystem? And is that the data file I'm interested in?
Scala:
val conf = NutchConfiguration.create()
val fs = FileSystem.get(conf)
val file = new Path(".../part-00000/data")
val reader = new SequenceFile.Reader(fs, file, conf)
val webdata = Stream.continually {
val key = new Text()
val content = new Content()
reader.next(key, content)
(key, content)
}
println(webdata.head)
Java:
public class ContentReader {
public static void main(String[] args) throws IOException {
Configuration conf = NutchConfiguration.create();
Options opts = new Options();
GenericOptionsParser parser = new GenericOptionsParser(conf, opts, args);
String[] remainingArgs = parser.getRemainingArgs();
FileSystem fs = FileSystem.get(conf);
String segment = remainingArgs[0];
Path file = new Path(segment, Content.DIR_NAME + "/part-00000/data");
SequenceFile.Reader reader = new SequenceFile.Reader(fs, file, conf);
Text key = new Text();
Content content = new Content();
// Loop through sequence files
while (reader.next(key, content)) {
try {
System.out.write(content.getContent(), 0,
content.getContent().length);
} catch (Exception e) {
}
}
}
}
Alternatively, you can use org.apache.nutch.segment.SegmentReader (example).

libgdx Json parsing

hi I'm trying to get all 'id' value from my json into my 'results' array.
I didn't really understood how the json class of libgdx works, but I know how json works itself.
Here is the json : http://pastebin.com/qu71EnMx
Here is my code :
Array<Integer> results = new Array<Integer>();
Json jsonObject = new Json(OutputType.json);
JsonReader jsonReader = new JsonReader();
JsonValue jv = null;
JsonValue jv_array = null;
//
try {
String str = jsonObject.toJson(jsonString);
jv = jsonReader.parse(str);
} catch (SerializationException e) {
//show error
}
//
try {
jv_array = jv.get("table");
} catch (SerializationException e) {
//show error
}
//
for (int i = 0; i < jv_array.size; i++) {
//
try {
jv_array.get(i).get("name").asString();
results.add(new sic_PlayerInfos(
jv_array.get(i).get("id").asInt()
));
} catch (SerializationException e) {
//show error
}
}
Here is the error I get : 'Nullpointer' on jv_array.size
Doing it this way will result in a very hacky, not maintainable code. Your JSON file looks very simple but your code is terrible if you parse the whole JSON file yourself. Just imagine how it will look like if you are having more than an id, which is probably going to happen.
The much more clean way is object oriented. Create an object structure, which resembles the structure of your JSON file. In your case this might look like the following:
public class Data {
public Array<TableEntry> table;
}
public class TableEntry {
public int id;
}
Now you can easily deserialize the JSON with libgdx without any custom serializers, because libgdx uses reflection to handle most standard cases.
Json json = new Json();
json.setTypeName(null);
json.setUsePrototypes(false);
json.setIgnoreUnknownFields(true);
json.setOutputType(OutputType.json);
// I'm using your file as a String here, but you can supply the file as well
Data data = json.fromJson(Data.class, "{\"table\": [{\"id\": 1},{\"id\": 2},{\"id\": 3},{\"id\": 4}]}");
Now you've got a plain old java object (POJO) which contains all the information you need and you can process it however you want.
Array<Integer> results = new Array<Integer>();
for (TableEntry entry : data.table) {
results.add(entry.id);
}
Done. Very clean code and easily extendable.

How to download a file from TestResource using JAVA OTA (COM4J)

Actually I need to download the XLS file from Test Resource using Resource ID in java
Can any one help me out Please
I tried with below pece of code but m missing something on it
IQCResourceFolderFactory rft = tdc.queryInterface(IQCResourceFolderFactory.class)​;
Com4jObject dfe = rft.item(3252);
IQCResourceFactory fds = dfe.queryInterface(IQCResourceFactory.class);
IList C = fds.newList("");
System.out.println(C.count());
above code throw me "Null pointer exception in Com4jObject dfe = rft.item(3252);
Please Help
Thanks in advance
Successfully downloaded the desired files from Test Resources by providing Resource Folder ID
Here is the working source code :
ITDConnection6 QCConnection = ClassFactory.createTDConnection();
QCConnection object should be declared with ITDConnection6 to access all QC attributes
IQCResourceFolderFactory resourceFolderFactory = QCConnection.qcResourceFolderFactory().queryInterface(IQCResourceFolderFactory.class);
IList folders = resourceFolderFactory.newList("");
for(Com4jObject rec : folders)
{
IQCResourceFolder resourceFolder = rec.queryInterface(IQCResourceFolder.class);
if(resourceFolder.id().toString().equals(properties.getProperty("ResourceFolderID")))
{
Com4jObject objResourceFactory = resourceFolder.qcResourceFactory();
IQCResourceFactory resourceFactory = objResourceFactory.queryInterface(IQCResourceFactory.class);
IList resources = resourceFactory.newList("");
for(Com4jObject objResource : resources)
{
IQCResource resource = objResource.queryInterface(IQCResource.class); ;
IResourceStorage resourceStorage = resource.queryInterface(IResourceStorage.class);
resourceStorage.downloadResource("D:\\", true);
}
}
}

Categories

Resources