How to add a local file into a maven project? - file

Hi I'm trying to use the tokenizer in OpenNLP to develop a maven project. It needs to load a local file, but I don't know how to add it into the project so that even when I launched the project in other machine it still works. Like below, the project need to load this local file, how should I configure the file to be added into the project?
InputStream modelIn;
try {
modelIn = new FileInputStream("E:\\en-token.bin");
// Make sure the "en-token.bin" file is already in your local disk
TokenizerModel model = null;
try {
model = new TokenizerModel(modelIn);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (modelIn != null) {
try {
modelIn.close();
} catch (IOException e) {
}
}
}
Tokenizer tokenizer = new TokenizerME(model);
String tokens[] = tokenizer.tokenize(string);
List<String> tokenResult = Arrays.asList(tokens);
return tokenResult;
} catch (FileNotFoundException ex) {
return null;
}

Such kind of files should be put into src/main/resources folder which will be packaged into jar file.

Related

How do I select multiple images using cn1 file chooser

I am creating a mobile app where I need users to be able to select multiple images. I am using the cn1 lib file chooser but I am only able to select one Image. How can I select multiple images. Here is the code I use to select the image.
chooseImage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
animateImage.show();
if (FileChooser.isAvailable()){
FileChooser.showOpenDialog(".jpg,.png,.gif", e2->{
String file = (String)e2.getSource();
if (file == null){
animateImage.add("No File Was Selected");
animateImage.revalidate();
}else {
String extension = null;
if (file.lastIndexOf(".") > 0){
extension = file.substring(file.lastIndexOf(".")+1);
}
if ("txt".equals(extension)){
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
InputStream fis = fs.openInputStream(file);
animateImage.addComponent(new SpanLabel(Util.readToString(fis)));
} catch (Exception ex) {
Log.e(ex);
}
}else{
try{
Image image = URLImage.createImage((String)e2.getSource());
animateImage.add(image);
}catch (IOException e){
e.printStackTrace();
}
//animateImage.add("Selected file "+file);
}
}
animateImage.revalidate();
});
/*try{
Image image = URLImage.createImage((String)evt.getSource());
animateImage.add(image);
}catch (IOException e){
e.printStackTrace();
}*/
}
}
});
Thanks
There is no support for that in the cn1lib. You can fork the cn1lib and add support for it manually by changing the native code in the lib.
This isn't supported currently in the standard Codename One API, there is an RFE to add it here: https://github.com/codenameone/CodenameOne/issues/2383

Downloading Files added into database in Angularjs and Spring mvc

I am facing an issue while downloading the file added into the database. I am using AngularJS and Spring MVC architecture.
In a table I am displaying filenames I have added.
Here is my html
fee.html
<td><a href="./filedownload/{{fee.fileName}}/feespath">
{{fee.fileName}}</a></td>
Here is Spring Controller.java
#RequestMapping(value="/filedownload/{fileName:.+}/{path}",method=
{RequestMethod.GET,RequestMethod.POST})
public void filedownload(#PathVariable String
fileName,#PathVariable String path,HttpServletResponse response)
{
Path file = Paths.get(context.getRealPath("/"+path+"/"),
fileName);
if (Files.exists(file))
{
response.setContentType("*/*");
response.addHeader("Content-Disposition", "attachment;
filename="+fileName);
try
{
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
And while adding I am using "feespath" as the path name that I am using in my html. Here is how I am creating a path by name feespath
#RequestMapping(value="/uploadFeeFiles",method=
{RequestMethod.GET,RequestMethod.POST})
public #ResponseBody String uploadFeeFiles(HttpServletRequest
request,HttpServletResponse response,MultipartHttpServletRequest
mRequest,Principal principal)
{
String status="";
try
{
mRequest = (MultipartHttpServletRequest) request;
mRequest.getParameterMap();
Iterator<String> itr = mRequest.getFileNames();
while (itr.hasNext())
{
MultipartFile file = mRequest.getFile(itr.next());
String fileName =
uploadPathService.getFilesPath(file,"feespath");
status = fileName;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return status;
}
I am able to display file names correctly in the table but if I click on it it's redirecting to a blank page with url
http://localhost:8080/MyProject/filedownload/12802889_1263849593630301.jpg/feespath
So I am not able to figure it out. If anyone can introduce some ideas, I'll be very helpful.

Thucyides Test cases Queuing

Implemented A Thucydides(SERENITY) BDD Environment for automated testing of version 0.9.269. I have seen that the runner of test cases picks up the random test stories. Is there any way so that the stories can be queued?
The code for PortalTestSuit is as
public class PortalTestSuite extends ThucydidesJUnitStories {
private static final Logger LOGGER = LoggerFactory.getLogger(PortalTestSuite.class.getName());
/**
* Instantiates a new Portal test suite.
*/
public PortalTestSuite() {
/*Some Code to check the server is working or not*/
/* Do all stories */
findStoriesCalled("*.story");
}}
Here, the findStories will pick up the random stories from the directory and executes relative code... but please let me know the way to queue the Stories. Thanks.
Yes, we can maintain the order of story by overriding storyPaths() method of ThucydidesJUnitStories class.
#Override
public List<String> storyPaths() {
try {
File file = new File(System.getProperty("user.dir").concat("/src/test/resources/StoryContextTest.script"));
try (FileReader reader = new FileReader(file)) {
char[] buffer = new char[(int) file.length()];
reader.read(buffer);
String[] lines = new String(buffer).split("\n");
List<String> storiesList = new ArrayList<>(lines.length);
StoryFinder storyFinder = new StoryFinder();
for (String line : lines) {
if (!line.equals("") && !line.startsWith("#")) {
if (line.endsWith("*")) {
for (URL classpathRootUrl : allClasspathRoots()) {
storiesList.addAll(storyFinder.findPaths(classpathRootUrl, line.concat("*/*.story"), ""));
}
} else {
storiesList.add(line);
}
}
}
return storiesList;
}
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private List<URL> allClasspathRoots() {
try {
return Collections.list(getClassLoader().getResources("."));
} catch (IOException e) {
throw new IllegalArgumentException("Could not load the classpath roots when looking for story files",e);
}
}
The stories are being loaded from StoryContextTest.script as
################# Stories goes here #################
stories/authentication/authentication/authentication.story
stories/authentication/authentication/authentication1.story
(Or)
*/authentication/* (will get stories randomly)
This way you can serialize your stories as in Thucydides.

How to load XML file online and process?

I want to make an android app that is actually a RSS reader. This will load XML file from a particular link like http://kalaerkantho.com/rss.xml. After downloading I know how to parse it. But my question is how to download it first so that I can process the downloaded file.
Try this:
private static void downloadFile(String url, String filePath) {
try {
File outputFile = new File(filePath);
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return; // swallow a 404
} catch (IOException e) {
return; // swallow a 404
}
}
Adapted from this answer.

Sending SMS from BlackBerry Simulator

I'm developing a BlackBerry Application where I should send Text SMS from BlackBerry Device.
As I'm new to Blackberry, started few days back I'm unable to proceed.
Can anyone Help with providing code snippets for send SMS from BlackBerry Device or Simulator?
Thanks in Advance.
Suresh.
public static void sendSMS(final String no, final String msg) {
// try {
new Thread() {
public void run() {
boolean smsSuccess = false;
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
// / send successfully
smsSuccess = true;
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
smsSuccess = false;
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector
.open("sms://" + no);
TextMessage tmsg = (TextMessage) conn
.newMessage(MessageConnection.TEXT_MESSAGE);
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
conn.send(tmsg);
smsSuccess = true;
} catch (Exception e) {
smsSuccess = false;
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
if(smsSuccess)
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("success");
}
});
}else
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("failure");
}
});
}
}
}.start();
}
Check out the the above code function .... to send SMS from Blackberry
You haven't specified what language you are developing in, but if you are developing in java and, if you are using Eclipse for your development with the Blackberry Java plugins, you will find a wealth of sample applications in the plugins folder hierarchy. The actual location will depend on where you have installed Eclipse, but e.g. on my machine they are at: C:\Program Files\Eclipse\eclipse 3.6.2 BlackBerry\plugins\net.rim.ejde.componentpack7.0.0_7.0.0.33\components\samples\com\rim\samples\device for the OS7 samples. Similar samples will exist for the different OS plugins you have installed.
There is a long standing sample in most OS sample sets called smsdemo which should give you all the code you need. Even if you are not developing in java, this sample should give you an indication of the path you need to take to fulfil your requirement.

Resources