API Connections only working once - java

I am creating an application that makes calls to the Hitbox API. I am trying to get the game name (listed as category_name from a list.
Thus far, I have managed to get the game name one time during the programs running stage, however when I change where to get the game name from, the program doesn't do anything. I am at a loss as to what could cause it not to send another request to the server.
public void apiConnect(){
String channel = text.getText();
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://api.hitbox.tv/media/live/" + channel);
HttpResponse response = null;
try {
response = client.execute(request);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Get the response
BufferedReader rd = null;
try {
rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
} catch (UnsupportedOperationException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line = "";
try {
while ((line = rd.readLine()) != null) {
hitbox.append(line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileUtils.writeStringToFile(new File("hitbox.json"), hitbox.getText());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String game = null;
FileInputStream fileHitbox = null;
try {
fileHitbox = new FileInputStream(new File("hitbox.json"));
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String strHitbox = null;
try {
strHitbox = IOUtils.toString(fileHitbox, "UTF-8");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject obj = new JSONObject(strHitbox);
JSONArray ar = obj.getJSONArray("livestream");
for (int i = 0; i < ar.length(); i++)
{
game = ar.getJSONObject(i).getString("category_name");
nameOf.setText("Game Name: " + game);
}
File hb = new File("hitbox.json");
if(hb.exists()){
hb.delete();
}
}
The above sample is the defined function, and the Get Game Name button code is below:
btnGetGameName.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
apiConnect();
}
});
Could anyone suggest what is causing it to not work after the first request, and if possible suggest a solution?
EDIT: I have found the issue. The reading of the data from the API is appended to the hitbox variable. I have thus added a snippet that clears what "hitbox" variable has when the button is pressed, thus meaning the code works without issues.

Try to consume your response after your read it to release the resource :
rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
response.getEntity().consumeContent();
//Or if you have EntityUtils
EntityUtils.consume(response.getEntity());
source

Related

Python output not displayed in jar file

I have created a java gui which takes values from the user send it to python file for processing and then displays the output from the python file onto the java gui. This is working perfectly on eclipse but when i exported it into a jar file the output is not displayed. I've seen a bunch of other questions like this but they do not give a solution that would help me.
This is how i connect my python script to java.
public void connection(String name)
{
ProcessBuilder pb= new ProcessBuilder("python","recomold.py","--movie_name",name);
///System.out.println("running file");
Process process = null;
try {
process = pb.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int err = 0;
try {
err = process.waitFor();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("any errors?"+(err==0 ? "no" : "yes"));
/* try {
System.out.println("python output "+ output(process.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
try {
matches.setText(output(process.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String output(InputStream inputStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try{
br= new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
//descp.setText("<html><br/><html>");
//sb.append("\n");
}
}
finally
{
br.close();
}
return sb.toString();
}

mocking url.openStream() should return InputStream

My actual class accepting URL as input and calling url.openStream(),this should return InputStream.
public static Map<String, Object> parseA(URL url) throws Exception {
byte[] readData = new byte[25*1024*1024];
// Here url.openStream() returning null
InputStream is = url.openStream();
while((readLength = is.read(readData, 0, 25*1024*1024)) != -1){
br = new BufferedReader(new InputStreamReader(new
ByteArrayInputStream(readData)));
// All CW_* strings are collected first
}
My test class is
#Rule
public TemporaryFolder folder= new TemporaryFolder();
#Test(enabled = true)
public void parseATest() {
File file=null;
try {
file =folder.newFile("testingData.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final URLConnection mockConnection = EasyMock.createMock(URLConnection.class);
final URLStreamHandler handler = new URLStreamHandler() {
#Override
protected URLConnection openConnection(final URL arg0)
throws IOException {
return mockConnection;
}
};
URL url=null;
try {
url = new URL("http://foo.bar", "foo.bar", 80, "", handler);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream is=null;
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
EasyMock.expect(url.openStream()).andReturn(is).anyTimes();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
// imageHeaderParser is object of actual class
imageHeaderParser.parseA(url);
} catch (IfmSwimParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here TemporaryFolder used to create temp file.And I dont want URL to go network.It can be just dummy URL and when i call url.openStream(),it should return stream of temp file i mentioned.
A file can be converted to an URL, so just do that :
Url testUrl = Paths.get("folder",("testingData.txt").toUri().toURL();
Map<String, Object> map = parseA(testUrl);
// assert map content
Besides you don't need any mock if you want to test with the file processing behavior.

Can't download html

I'm trying to download this html
I'm using this code:
Document doc = null;
try {
doc =Jsoup.connect(link).userAgent("Mozilla").get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i ("html", doc.toString());
UPDATED:
ASLO tried to use it:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(link);
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
//
e1.printStackTrace();
} catch (IOException e1) {
//
e1.printStackTrace();
}
InputStream in = null;
try {
in = response.getEntity().getContent();
} catch (IllegalStateException e1) {
//
e1.printStackTrace();
} catch (IOException e1) {
//
e1.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
} catch (UnsupportedEncodingException e) {
//
e.printStackTrace();
}
StringBuilder str = new StringBuilder();
String line = null;
try {
while((line = reader.readLine()) != null)
{
str.append(line);
}
} catch (IOException e1) {
//
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
//
e1.printStackTrace();
}
String html = str.toString();
Log.e("html", html);
again responce like this one:
<html>
<body>
<script>document.cookie="BPC=f563534535121d5a1ba5bd1e153b";
document.location.href="http://...link.../all?attempt=1";</script>
</body>
</html>
I can't find any solution... Page can not be downloaded maybe because haven't cookie ... or what?
In the script tag, you have this statement :
document.location.href="....link..../all?attempt=1";
Normally it forces the browser to reload the page with the location. I think it's the page "....link...?attempt=1" that you want to download in fact.
It is not sure that it will work anyway if you don't use the cookie defined in the script but it deserves a try.

Java - Jackson to a file

I have a JSON file like this:
{
"Product":
{
"ID": "08-17-96-71-D9-68",
"Licences":
{
"total": 40,
"used": 0,
"remain": 40
}
}
}
I used jackson to convert it to a Java Object and I get all the values (so far, so good).
My problem is that I want to change these values and re-write the JSON file but when I do that, the result is like this:
"{\"Product\":{\"IaD\": \"08-17-96-71-D9-68\",\"Licences\":{\"total\": 40,\"used\": 1,\"remain\": 39}}}"
So when I tried to read it again it gives me an error because it cannot read the first and last character (") and also it reads the \ character.
This is my code:
public class UsingJason {
String theJsonString = "";
ObjectMapper mapper = new ObjectMapper();
public class Product{
Licences lic;
public class Licences{
int total;
int used;
int remain;
}
}
public void readJson(){
if(new File("asset/testJson.json").exists()){
theJsonString = "";
try {
BufferedReader in = new BufferedReader(new FileReader("asset/testJson.json"));
String line;
while ((line = in.readLine()) != null){
theJsonString += line;
}
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("JSON String: "+ theJsonString);
}else{
System.out.println("NO FILE FOUND");
}
JsonNode rootNode = null;
try {
rootNode = mapper.readValue(theJsonString, JsonNode.class);
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JsonNode totalNode = rootNode.get("Product").get("Licences").get("total");
JsonNode usedNode = rootNode.get("Product").get("Licences").get("used");
JsonNode remainNode = rootNode.get("Product").get("Licences").get("remain");
JsonNode idStringNode = rootNode.get("Product").get("ID");
// Parse it into a Java object.
try {
int totalObject = mapper.readValue(totalNode, Integer.class);
System.out.println("INTEGER? HAS TO BE... 40: "+totalObject);
String idString = mapper.readValue(idStringNode, String.class);
System.out.println("String? Has to be 08-17-96-71-D9-68: "+idString + " True? "
+ idString.equals("08-17-96-71-D9-68") );
int usedObject = mapper.readValue(usedNode, int.class);
int remainObject = mapper.readValue(remainNode, int.class);
System.out.println("Going to rest 1");
usedObject ++;
remainObject = totalObject - usedObject;
String toJackson = "{\"Product\":{\"I\\D\": \"08-17-96-71-D9-68\",\"Licences\":{\"total\": "+totalObject+",\"used\": "+usedObject+",\"remain\": "+remainObject+"}}}";
System.out.println("String created: " +toJackson);
// THIS toJackson String returns the string without \ and without the "
// IT PRINT THIS: {"Product":{"ID": "08-17-96-71-D9-68","Licences":{"total": 40,"used": 1,"remain": 39}}}
// EXACTLY WHAT I WANT TO Write in the Json file but it writes the \ ..
mapper.writeValue(new File("asset/testJson.json"), toJackson);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can anyone tell me what I am doing wrong?
In your code here:
mapper.writeValue(new File("asset/testJson.json"), toJackson);
You are serializing not an object, but the string to the file. I suppose this is the reason why it gets escaped, like any string.
The input value should be an object with your structure.
Something like this:
// Initialize an object
Product myProduct = new Product();
myProduct.lic = new Procuct.Licences();
myProduct.lic.total = totalObject;
myProduct.lic.used = usedObject;
myProduct.lic.remain = remainObject;
// Serialize the object into JSON
mapper.writeValue(new File("asset/testJson.json"), myProduct);

How to append listview items from the Internet

I'm still struggling to find an answer to my question. I want to download 3 strings for each item in the listview to the phone. I know how to get all the data from the server, just not how to append the data to the litview, I'm really annoyed and this problem is dragging me down.
My Code:
public class ChatService extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatservice);
try {
ContactsandIm();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CheckLogin();
private void CheckLogin() {
// TODO Auto-generated method stub
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Execute HTTP Post Request
Log.w("HttpPost", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost", "TRUE");
try {Thread.sleep(250);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//put intent here(21/3/12);
} else {
Log.w("HttpPost", "FALSE");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
private void ContactsandIm() throws URISyntaxException, ClientProtocolException, IOException {
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
HttpClient get = new DefaultHttpClient();
URI website = new URI("http://www.gta5news.com/test.php");
HttpGet webget = new HttpGet();
webget.setURI(website);
HttpResponse response = get.execute(webget);
Log.w("HttpPost", "Execute HTTP Post Request");
in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
//now we'll return the data that the PHP set from the MySQL Database.
if (in.equals("True")); {
Toast.makeText(this,"yay", Toast.LENGTH_LONG).show();
}
}
// end bracket for "ContactsandIm"
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
Use an ArrayAdapter on your list, and add items to this adapter, then call notifyDatasetChanged on it, and zou
First of all when we connect to Server using the Network Threads, then you should go for AsyncTask or Handlers. Which is specially used for handling such Threads.
ListView can be created by using default Listview ans also the Custom Listview where we can design our own Row design in the Row.xml and the same design will be used for all the rows.
If you want move forward or go for some advanced Listview then even we can use 'n' number of designs for different rows.
Here in your case, You should use a AsyncTask for fetching the data and use the Listview for displaying rows.
You can get more information from the below link.
https://docs.google.com/leaf?id=0B2qCFbmeiTFxN2ViZjVlOTUtNmY3ZS00NThhLTg3N2UtYjVkYjgyM2Y4MWUy&hl=en&authkey=COeP8JYN

Categories