Handle the Post Request from Android? - java

I am writing an application with the user of Android Java " Eclipse " + Jquery Mobile + CodeIgniter Framework
I almost finished everything but still can not proceed on the push notification issue
one big problem taken about 2 days till now from me till I have headache from such conflict :
I made the POST Request from the android and it's already sending the POST Array.
here is the php code to handle the post request...
function notification() {
if($_POST['registrationId']) {
$this->session->set_userdata('registrationId', $_POST['registrationId']);
echo 'registerationID : success'.$this->session->userdata('registrationId').'====';
}
it really echo the session userdata indeed .. but when I try to use it in any other function or pages .. it's not working ? !!! it's empty or not existed ? !!
even when I try to make the query within the function in order to store it in Database .. the session is not available like $this->session->userdata('emailid')
update 'user' set deviceid ... where emailid = $this->session->userdata('emailid')
... not working and the session is not available !!!!!
PLEASE ANYONE CAN HELP ME ? !! :(

you can ues a class to storing the post data
class PostData {
public static $registrationId = "";
}
//set data
function notification() {
if(isset($_POST['registrationId']) && empty($_POST['registrationId']) {
PostData::$registrationId = $_POST['registrationId'];
}
}
// use data
$post_registrationId = empty(PostData::$registrationId) ? PostData::$registrationId : "";

well i couldn't solve the problem through sessions .. therefore i used fopen and i have registered the registration ID in a file.txt to use it later after in the session then delete the file. hope it can help someone someday .. thank you for sharing and participating

Related

Using the NCDC's Climate Data Online API with Java

I have never used a RESTful API. I want to use this API to get historical weather data, but I can't find a simple tutorial taking me from end to end making an app that uses a RESTful API in Java. I'm not sure what steps I should take to get the data.
The steps listed on the getting started page are not Java specific, so I'm not sure how to use that info. I have requested a token and got it, so I'm good on that front.
What I need help with is getting a minimal example showing how, with just a token and formatted URL, you can get JSON data from the API.
Some things I've looked into are javax.ws.rs and jersey client, but I'm not sure how to use those either.
Thanks in advance :)
Using Fetch you can do:
fetch(url, {options})
.then(data => {
// Do some stuff here
})
.catch(err => {
// Catch and display errors
})
Where the url is the one from the getting started page.
And you can get whatever data you need from data.
Say you need to save just the name in a local var, then you do:
.then(data => {
name = data.name
})

Getting a null response when calling a php site function from java in android

I'm trying to call a php function on a site that I have from an android application.
I'm using this to get my response: https://github.com/koush/ion
Here is my php code which is located at : Link
It's used to connect to a database i have on that site.
The php file just returns all the entries in the database as HTML text shown under the php code (Not sure if this is the proper way to get data from a database).
The Database entries get their own tags so I can handle them later in the app.
<?php
include('dbconnect.php');
if (isset($_GET['Tabela'])) {
DobiPodatke($_GET['Tabela']);
} else {
ECHO '<error>Ni selekcije</error>';
}
function DobiPodatke($Tabela)
{
$sqlget = "SELECT * FROM " . $Tabela;
ZazeniQuery($Tabela, $sqlget);
}
function ZazeniQuery($Ime, $Query){
$sqldata = mysqli_query($GLOBALS['dbcon'], $Query) or die('<error>error with fetching data</error>');
ECHO '<' . $Ime . '>';
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
switch($Ime){
case 'Sola':
ECHO '<vnos><Kratka_Oznaka>' . $row['Kratka_Oznaka'] . '</Kratka_Oznaka><Ime>' . $row['Ime'] . '</Ime></vnos>';
break;
case 'Stroka':
ECHO '<vnos><Ime_Stroke>' . $row['Ime_Stroke'] . '</Ime_Stroke></vnos>';
break;
case 'Sola_Smer':
ECHO '<vnos><ID_Sole>' . $row['ID_Sole'] . '</ID_Sole><ID_Stroke>' . $row['ID_Stroke'] . '</ID_Stroke><Stevilo_mest>' . $row['Stevilo_mest'] . '</Stevilo_mest></vnos>';
break;
}
}
ECHO '</' . $Ime . '>';
}
?>
HTML Response:
HTML
Now in order for this to work I need to supply the php function parameter on which table i need infromation from so I call it like this:
https://illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=Sola
Tabela beeing the variable I need to pass in otherwise the php does a die()
In the example above I called the php file with "?Tabela=Sola" at the end to get all table entries in the table "Sola".
While this works in the browser, it does not in my application.
Now in my android application I use the Ion library/class to get my response from a website in pure HTML code. It works with a regular website since I can get the whole HTML code from the site.
It however does not work on my php site since i get a null result.
The link variable in the following code is:
https://illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=Sola
Java code that connects to the website and returns the result:
private static void ParseDBFront(String link, Context context){
Ion.with(context).load(link).setLogging("MyLogs", Log.DEBUG).asString().setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Log.i("LOG", "LOG: " + result);
}
});
}
And the response I get from the above code when running is:
I/LOG: LOG: null
All i need is for the java code to return the HTML code but I have no idea why it won't return the html code.
I'm guessing that i'm parsing my variable in the wrong way.
I appreciate any feedback or solutions to this problem.
Managed to figure it out myself.
There was no problems with the code as is, the problem was the way i wrote the URL of my php file.
Original link:
private static final String DBLink = "www.illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=";
And how I fixed it:
private static final String DBLink = "https://illegible-deflector.000webhostapp.com/Site3/dbtest.php?Tabela=";
That "www." / "https://" difference is all that caused my program to return a null response for some reason.
I don't know why but the problem is gone.

Java Twitter Bot tweets to another account but using my accessToken?

I wrote this simple code that works just fine :
//access the twitter API using your twitter4j.properties file
Twitter twitter = TwitterFactory.getSingleton();
//create a new search
Query query = new Query("\"your welcome\"");
//get the results from that search
QueryResult result = twitter.search(query);
//get the first tweet from those results
Status tweetResult = result.getTweets().get(0);
//reply to that tweet
StatusUpdate statusUpdate = new StatusUpdate(".#" + tweetResult.getUser().getScreenName() +" I believe you meant \"you're\" here?");
statusUpdate.inReplyToStatusId(tweetResult.getId());
Status status = twitter.updateStatus(statusUpdate);
The problem is, even using my own parametres (Acessstoken, Consumerkey,,) that I generated manually from app.twitter.com, the code still sends the tweet to this account : Twit4j . it seems that too many had tweeted through it too!
twitter4j.proprieties is set up correctly
libs are correctly integrated
anyone knows what could be wrong ?
The Problem were (I guess) in the class name! the package name+ my class name are "Twitter" and the Object name from the Twitter4j is "Twitter" too! think the IDE got confused maybe ?
anyway now it works just fine !

get all issues stored in jira

hi i want to get all issues stored in jira from java using jql or any othere way.
i try to use this code:
for(String name:getProjectsNames()){
String jqlRequest = "project = \""+name+"\"";
SearchResult result = restClient.getSearchClient().searchJql(
jqlRequest, 10000,0, pm);
final Iterable<BasicIssue> issues = result.getIssues();
for (BasicIssue is : issues) {
Issue issue = restClient.getIssueClient().getIssue(is.getKey(), pm);
...........
}
it give me the result but it take a very long time.
is there a query or a rest API URL or any other way that give me all issues?
please help me
The JIRA REST API will give you all the info from each issue at a rate of a few issues/second. The Inquisitor add-on at https://marketplace.atlassian.com/plugins/com.citrix.jira.inquisitor will give you thousands of issues per second but only the standard JIRA fields.
There is one other way. There is one table in JIRA database named "dbo.jiraissue". If you have access to that database then you can fetch all the ids of all issues. After fetching this data you can send this REST request "**localhost/rest/api/2/issue/issue_id" and get JSON response. Of course you have to write some code for this but this is one way I know to get all issues.

redirect from jsf?

I am working on application with jsp, jstl and jsf for my college project, thats being said, I am as well very new to jsf.
Everything is going great so far. However, I seems to have a problem figuring out how to do redirect from managed bean to page with dinamyc parameters.
For example article.jsp?article_id=2
Can somebody tell me how it is done ?
I been trying to use somethinng like
FacesContext.getCurrentInstance().getExternalContext().dispatch("faces/article.jsp2?article_id=" + articleId);
But get error:
javax.servlet.ServletException: #{postComment.postClick}: javax.faces.FacesException: javax.servlet.ServletException: javax.faces.component.UIViewRoot cannot be cast to com.sun.faces.application.StateManagerImpl$TreeNode
javax.faces.webapp.FacesServlet.service(FacesServlet.java:256)
I been trying to use
response.sendRedirect("faces/article.jsp2?article_id=" + articleId);
return;
But again getting an error.
javax.servlet.ServletException: Cannot forward after response has been committed
javax.faces.webapp.FacesServlet.service(FacesServlet.java:256)
Can somebody please tell me how do i redirect from managed java bean when working with jsf ?
Bellow is my code (maybe something wrong with that and thats why redirect not working).
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
String articleId = request.getSession().getAttribute("article_id").toString();
//String articleId = request.getParameter("article_id");
String authorName = request.getSession().getAttribute("user_name").toString();
java.util.Calendar calendar = java.util.Calendar.getInstance();
String commentDate = String.valueOf(calendar.get(java.util.Calendar.DAY_OF_MONTH)) + ".";
commentDate += String.valueOf(calendar.get(java.util.Calendar.MONTH)) + ".";
commentDate += String.valueOf(calendar.get(java.util.Calendar.YEAR));
ArrayList error = new ArrayList();
if(commentName.contains("<"))
{
error.add("Comment name contains illegal characters");
}
if(commentBody.isEmpty() && commentBody.contains("<script"))
{
error.add("Your message body contains illegal characters");
}
if(error.size() > 0)
{
request.getSession().setAttribute("error", error);
error.clear();
FacesContext.getCurrentInstance().getExternalContext().dispatch("article.jsp2?article_id=" + articleId);
}
else
{
Comment comment = new Comment();
comment.setCommentAuthor(authorName);
comment.setCommentBody(commentBody);
comment.setCommentDate(commentDate);
comment.setCommentName(commentName);
comment.setArticleId(articleId);
DisplayArticleIO addComment = new DisplayArticleIO();
addComment.postComment(comment);
// FacesContext.getCurrentInstance().getExternalContext().dispatch("faces/article.jsp2?article_id=" + articleId);
response.sendRedirect("faces/article.jsp2?article_id=" + articleId);
return;
}
Thank you in advance.
In case some one will run into same problem.
That's what solved my problem:
FacesContext.getCurrentInstance().getExternalContext().redirect("article.jsp?article_id=" + articleId);
Why are you using dispatch in one place and redirect in the other? This isn't the source of the problem - not returning after sending responses, however, is. Other then that, if you don't mind, I have a few friendly suggestions:
You can use DateFormat to return the comment date as you want it (it will be much cleaner).
If the errors ArrayList only contains Strings, use generics (ArrayList<String>).
What are you doing with the errors?
Your sanitation of the commentName is very dangerous. You should use whitelisting instead of blacklisting - define what you wish to accept in a comment and block everything else. Right now someone could insert an <img> tag with a src pointing to a cookie stealing page which would result in a session hijack.
After changing the dispatch to a redirect add a return below it (you should always do this. Not doing this could result in what you're seeing right now, which is that you've already sent a response somewhere else, but since you haven't returned you've reached a place where you're trying to send another).
Basically, something is already sending output to the client before you make the call to response.sendRedirect(). Once something has been sent to the browser you can't redirect or forward them to a different place.
In general, any scenarios that might result in a redirect or a forward should be handled as early as possible in the request context to insure the redirect happens before you send any data to the client. Are you doing something like calling this code via a tag in the view?
FacesContext.getCurrentInstance().getExternalContext().redirect("http://www.myUrl.com");
René

Categories

Resources