Android app to push updating data - java

I new to developing in android but I'm not in java. So I want to develop an app that checks for football match scores and as soon as new data is available the android app must push that data to the user in a notification fashion.
My question is the following:
Can I use a website's server that is not mine to get data from since I dont have a server to use. Therefore I cant use C2DM
If not what is the solution to this: TCP/IP connection or can I customize a webview to my liking?
Thanks in advance,
Roy

My experience with using internet data, however this may help you start.
This is the class that I use to download webpages and return them as a string, it should be possible to parse the page data to extract the data that you want. Something you should be careful is that it can be common for webpages to change their format which could break your parsing functionality, perhaps without you even realising.
Check this out for Java HTML parsers
package AppZappy.NIRailAndBus;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Simplifies downloading of files from the internet
*/
public class FileDownloading
{
/**
* Download a text file from the Internet
* #param targetUrl The URL of the file to download
* #return The string contents of the files OR NULL if error occurred
*/
public static String downloadFile(String targetUrl)
{
BufferedReader in = null;
try
{
// Create a URL for the desired page
URL url = new URL(targetUrl);
// Read all the text returned by the server
in = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder sb = new StringBuilder(16384); // 16kb
String str = in.readLine();
if (str != null)
{
sb.append(str);
str = in.readLine();
}
while (str != null)
{
// str is one line of text; readLine() strips the newline
// character(s)
sb.append(C.new_line());
sb.append(str);
str = in.readLine();
}
String output = sb.toString();
return output;
}
catch (MalformedURLException e)
{}
catch (IOException e)
{}
finally
{
try
{
if (in != null) in.close();
}
catch (IOException e)
{
}
}
return null;
}
private FileDownloading()
{}
}

Related

How to upload zip file through REST API Mule 4?

I'm trying to upload zip file to the url https://anypoint.mulesoft.com/designcenter/api-designer/projects/{projectId}/branches/master/import. Content-Type must be application/zip, cant change to multipart/form-data. In Mule 3, a java transform class is used (com.test.FileReader) with the FileReader.class is stored in lib. It worked in Mule 3.
I tried to use ReadFile component to read test.zip and set as payload but it's not working. Any suggestion how to upload zip file in Mule 4?
package com.test;
import org.mule.transformer.*;
import org.mule.api.*;
import org.mule.api.transformer.*;
import java.io.*;
public class PayloadFileReader extends AbstractMessageTransformer
{
public Object transformMessage(final MuleMessage message, final String outputEncoding) throws TransformerException {
byte[] result = null;
try {
result = this.readZipFile("test.zip");
}
catch (Exception e) {
e.printStackTrace();
}
message.setPayload((Object)result);
return message;
}
public String readFileTest(final String path) throws FileNotFoundException, IOException, Exception {
final ClassLoader classLoader = this.getClass().getClassLoader();
final File file = new File(classLoader.getResource(path).getFile());
final FileReader fileReader = new FileReader(file);
BufferedReader bufferReader = null;
final StringBuilder stringBuffer = new StringBuilder();
try {
bufferReader = new BufferedReader(fileReader);
String line;
while ((line = bufferReader.readLine()) != null) {
stringBuffer.append(line);
}
}
catch (IOException e) {
e.printStackTrace();
if (bufferReader != null) {
try {
bufferReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
finally {
if (bufferReader != null) {
try {
bufferReader.close();
}
catch (IOException e2) {
e2.printStackTrace();
}
}
}
return stringBuffer.toString();
}
public byte[] readZipFile(final String path) {
final ClassLoader classLoader = this.getClass().getClassLoader();
final File file = new File(classLoader.getResource(path).getFile());
final byte[] b = new byte[(int)file.length()];
try {
final FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
fileInputStream.close();
}
catch (FileNotFoundException e) {
System.out.println("Not Found.");
e.printStackTrace();
}
catch (IOException e2) {
System.out.println("Error");
e2.printStackTrace();
}
return b;
}
}
'
Assuming that your zip file corresponds to a valid API spec, in Mule 4, you don't need to use a custom java code to achieve what you want: you can read the file content using the File connector Read operation, and use an HTTP Request to upload it to Design Center using Design Center API. Your flow should look like:
For the Read operation, you only need to set the file location, in the File Path operation property.
No need to set content type in the HTTP Request (Mule 4 will configure the content type automatically based on the file content loaded by the Read operation).
You can't use Java code that depends on Mule 3 classes in Mule 4. Don't bother trying to adapt the code, it is not meant to work. Their architecture are just different.
While in Mule 4 you can use plain Java code or create a module with the SDK, there is no reason to do so for this problem and it would be counterproductive. My advise it to forget the Java code and resolve the problem with pure Mule 4 components.
In this case there doesn't seem a need to actually use Java code. The File connector read operation should read the file just fine as it doesn't appear the Java code is doing anything else than reading the file into the payload.
Sending through the HTTP Request connector should be straightforward. You didn't provide any details of the error, (where is it happening, complete error message, HTTP status error code, complete flow with the HTTP request in both versions, etc) and the API Designer REST API doesn't document an import endpoint so it is difficult to say if the request is correctly constructed.

Using Java to login into www.messenger.com

I am having trouble using code that I found to log into www.messenger.com. It seems like I am not able to write out form parameters because I do not have the right form names. I am having trouble finding the form name of the button and what to set it equal to. My end goal, is to get the html code after I log in.
Source: http://www.dreamincode.net/forums/blog/114/entry-2715-login-to-a-website-from-java/
import java.net.*;
import java.io.*;
private static URL URLObj;
private static URLConnection connect;
public static void main(String[] args) {
try {
// Establish a URL and open a connection to it. Set it to output mode.
URLObj = new URL("http://www.messenger.com/#");
connect = URLObj.openConnection();
connect.setDoOutput(true);
}
catch (MalformedURLException ex) {
System.out.println("The URL specified was unable to be parsed or uses an invalid protocol. Please try again.");
System.exit(1);
}
catch (Exception ex) {
System.out.println("An exception occurred. " + ex.getMessage());
System.exit(1);
}
try {
// Create a buffered writer to the URLConnection's output stream and write our forms parameters.
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream()));
writer.write("email=MyEmail&pass=MyPassword&submit=Sign In");
//writer.close();
// Now establish a buffered reader to read the URLConnection's input stream.
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String lineRead = "";
// Read all available lines of data from the URL and print them to screen.
while ((lineRead = reader.readLine()) != null) {
System.out.println(lineRead);
}
reader.close();
}
catch (Exception ex) {
System.out.println("There was an error reading or writing to the URL: " + ex.getMessage());
}
}
This are the post parameters, that are send by a browser, when you click login:
default_persistent=0
email=user
initial_request_id=A2NPA_SLbM3wAkFRM_Y0fLx
lgndim=eyJ3IjoxOTIwLCJoIjoxMjAwLCJhdyI6MTkyMCwiYWgiOjExNjAsImMiOjI0fQ==
lgnjs=n
lgnrnd=125813_Br9w
login=1
lsd=AVrsF9i0
pass=pass
timezone=-120
Maybe you need some of these to get a successfull login.
You can find these as hidden parameters in the form with the id "login_form".

Scanning and displaying every word from a website source code Java

I have been given a task to scan the contents of a website's source code, and use delimiters to extract all hyperlinks from the site and display them. After some looking around online this is what I have so far:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class HyperlinkMain {
public static void main(String[] args) {
try {
Scanner in = new Scanner (System.in);
String URL = in.next();
URL website = new URL(URL);
BufferedReader input = new BufferedReader(new InputStreamReader(website.openStream()));
String inputLine;
while ((inputLine = input.readLine()) != null) {
// Process each line.
System.out.println(inputLine);
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
}
}
So my program can extract each line from the source code of a website and display it, but realistically I want it to extract each WORD as such from the source code rather than every line. I don't really know how it's done because I keep getting errors when I use input.read();
There is lots of source code around to retrieve web pages. Look at the Pattern class to see how to regex text for hyperlinks. You can treat your homework assignment as two separate problems by working on the hyperlink extraction separately from the web page downloads.

How to uploaded and read text file in JSF and PrimeFaces?

I need to upload and read a text file with PrimeFaces and JSF. My question is that when I uploaded the text file, where is it stored?
Here is my .xhtml file:
<p:fileUpload value="#{send.file }" mode="simple" />
</h:form>
<p:commandButton actionListener="#{send.upload}" value="Send" ajax="false" />
And Java class:
public class Send {
private UploadedFile file;
public void upload() {
if (file != null) {
FacesMessage msg = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
I also found this example to read the file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
My other question is in this example "C:\\testing.txt" is given as a path? Which address I must give to read my uploaded file?
when I uploaded the text file, where is it stored?
This is actually none of your business and you should not be interested in that from inside your JSF backing bean code. It's stored (partial) in memory and/or (partial) in server's temporary storage location which will be wiped/cleaned at intervals. It's absolutely not intented as permanent storage location. You should in the action/listener method just read the uploaded file content and store it in the permanent storage location to your choice.
E.g.
private static final File LOCATION = new File("/path/to/all/uploads");
public void upload() throws IOException {
if (file != null) {
String prefix = FilenameUtils.getBaseName(file.getName());
String suffix = FilenameUtils.getExtension(file.getName());
File save = File.createTempFile(prefix + "-", "." + suffix, LOCATION);
Files.write(save.toPath(), file.getContents());
// Add success message here.
}
}
Note that the FilenameUtils is part of Apache Commons IO which you should already have installed as it's a required dependency of <p:fileUpload>. Also note that File#createTempFile() does in above example not exactly generate a temp file, but it's just been used to generate an unique filename. Otherwise, when someone else coincidentally uploads a file with exactly the same name as an existing one, it would be overwritten. Also note that Files#write() is part of Java 7. If you're still on Java 6 or older, grab Apache Commons IO IOUtils instead.
please take a look at this thread that is related to the same issue:
how to upload file to http remote server using java?.
Please if it does not help you, let me know, and I will go through. ;)
I red the file this way
private UploadedFile file;
public void upload() {
if (file != null && !"".equals(file.getFileName())) {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputstream(), "UTF-8"))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception ex) {
LOG.error("Error uploading the file", ex);
}
}
}

a method that returns a ip of machine that access web app

I have a jsp web application hosted on a machine hosted in localhost.
I can access this web application from another machine on LAN.
What I'm doing here is I created a bean class which has a method that returns a IP of machine that access web app.
But when i was accessing from another machine I got the IP of hosted machine itself .
Can anyone tell why it happens? Tell me how can I get the IP of another machine that accesses web app hosted in local host.
You can try
getRemoteAddr
method of ServletRequest. Refer to Documentation for more details.
You can't reliably do so, but if you can control the network between all clients and servers, and if you're willing to accept that malicious requests may feed you false information, then there are methods available like ServletRequest.getRemoteAddr() that will give you information of that sort. To reiterate, it's by no means guaranteed to be the address of the machine that originally sent the request, and it's also guaranteed to be authentic in any way. Given the right (or wrong?) network conditions, it's easy to spoof that piece of information.
this is using a web service to get you the IP address
take a look
package ipInfo;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class ExternalIp {
private static String URL = "http://api-sth01.exip.org/?call=ip";
public static void main(String[] args) {
ExternalIp ipGetter = new ExternalIp();
ipGetter.getExternalIp();
}
public void getExternalIp()
{
BufferedReader reader = null;
String line = "";
int tries = 0;
do {
try {
reader = read(URL);
/*while(reader.readLine() != null)
{
line = line + reader.readLine();
}*/
line = reader.readLine();
}
catch (FileNotFoundException fne) {
System.out.println("File not found for url: " + URL);
System.out.println("Check your typing");
System.out.println();
return;
}
catch (IOException ioe) {
System.out.println("Got IO Exception, tries = " + (tries + 1));
System.out.println("Message: " + ioe.getMessage());
tries++;
try {
Thread.currentThread().sleep(300000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
continue;
}
catch (Exception exc) {
exc.printStackTrace();
}
} while (reader == null && tries < 5);
if (line != null && line.length() > 0) {
System.out.println("Your external ip address is: " + line);
}
else {
System.out.println("Sorry, couldn't get your ip address");
}
}
public BufferedReader read(String url) throws Exception{
return new BufferedReader(
new InputStreamReader(
new URL(url).openStream()));
}
}

Categories