I am trying to send json object through volley in android studio to a server (mvc spring project in eclipse + tomcat is listening) but the app crashes. I'm new to the volley library. Also, the json object is made up of the data gotten from user inputs in combo box and textviews.
Login Activity:
package com.example.mujtaba.quizzer;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.StringRequest;
import com.example.mujtaba.quizzer.Activity.QuizMaking;
import com.example.mujtaba.quizzer.Activity.QuizTaking;
import org.w3c.dom.Text;
import java.util.HashMap;
import java.util.Map;
public class Login extends AppCompatActivity {
private Button button;
private TextView username;
private TextView password;
private Spinner role;
private String url = "http://localhost:8080/users/signup";
private RequestQueue queue;
private ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username=(TextView) findViewById(R.id.username);
password=(TextView) findViewById(R.id.password);
button=(Button) findViewById(R.id.button);
role = (Spinner) findViewById(R.id.role);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.role_spinner, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
role.setAdapter(adapter);
}
public void Quiz(View v) { //select a new activity on the basis of role
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
queue = new RequestQueue(cache, network);
// Start the queue
queue.start();
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String,String>();
MyData.put("Username", username.getText().toString() ); //Add the data you'd like to send to the server.
MyData.put("Password",password.getText().toString());
MyData.put("Role",role.getSelectedItem().toString());
MyData.put("Score","0");
return MyData;
}
};
queue.add(MyStringRequest);
}
}
Logcat error:
*3430-3440/com.android.dialer E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:57)
at android.os.Binder.execTransact(Binder.java:446)*
Related
Is there a way to set programmatically the contextName of a Logger in LogBack? I could then use the contextName to distinguish different instances of my Service class.
I see that we can set the contextName in the logback.xml, but this file is static in my project while the configuration of my application can change depending where my application is run from.
I'm searching a way to create dynamically contextNames and associate them to different instances of loggers.
The logback API can be called to implement the above functions, but not with dynamic contextNames. The following simple example
LoggerBuilder.java
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.ConsoleAppender;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
public class LoggerBuilder {
private static final Map<String,Logger> container = new HashMap<>();
private static final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
public Logger getLogger(String name) {
Logger logger = container.get(name);
return logger;
}
public void buildLogger(String name,String pattern) {
Logger logger = context.getLogger(name);
logger.setAdditive(false);
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(context);
encoder.setPattern(pattern);
encoder.start();
ConsoleAppender consoleAppender = new ConsoleAppender();
consoleAppender.setContext(context);
consoleAppender.setEncoder(encoder);
consoleAppender.start();
logger.addAppender(consoleAppender);
container.put(name,logger);
}
}
Test.java
import org.slf4j.Logger;
public class Test {
public static void main(String[] args) throws Exception {
LoggerBuilder loggerBuilder = new LoggerBuilder();
loggerBuilder.buildLogger("logger","%d %p (%file:%line\\)- %msg%n");
loggerBuilder.buildLogger("logger2","%d %p (%file:%line\\)%n");
Logger logger = loggerBuilder.getLogger("logger");
Logger logger2 = loggerBuilder.getLogger("logger2");
logger.info("1111");
logger2.info("2222");
}
}
I am setting a web application with embedded jetty and jersey .As i am fairly new with concepts, it is difficult to load a sample webpage index.html. When i target it as localhost:8989/myServlet i see the code flow through my servlet . But request dispatcher always returns null.
Please let me know with this:
Main class:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class MainApp {
public static void main(String[] args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(8989);
jettyServer.setHandler(context);
ServletHandler handler =new ServletHandler();
handler.addServletWithMapping(MyServletHandler.class,"/myServlet");
jettyServer.setHandler(handler);
ServletHolder jerseyServlet = context.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter(
"jersey.config.server.provider.classnames",
Entry.class.getCanonicalName());
try {
jettyServer.start();
jettyServer.join();
} finally {
jettyServer.destroy();
}
}
}
Myservlet class:
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyServletHandler extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Control is in servlet");
RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.html"); // this returns null. hence i am unable to request dispatch to view the html webpage.
}
}
I use Maven to build the application and i have placed index.html in src/main/resources directory
This works, but you'll have to properly setup the ServletContext so that the request.getRequestDispatcher() can do something.
For starters, your ServletContextHandler MUST have a Resource Base setup.
You'll have to setup a DefaultServlet so that the request dispatcher can be returned properly.
You'll also have to use embedded-jetty properly, don't use ServletHandler directly like that. Use the ServletHolder if you must, but otherwise just use the ServletContextHandler directly.
Here's an example of this behavior.
Run with a System Property of baseResource pointing to a directory where you have a index.html.
package jetty.dispatching;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.resource.Resource;
import static java.nio.charset.StandardCharsets.UTF_8;
public class DispatchingToDefaultServletDemo
{
public static void main(String[] args) throws Exception
{
DispatchingToDefaultServletDemo demo = new DispatchingToDefaultServletDemo();
try
{
demo.startServer();
demo.makeRequests();
}
finally
{
demo.stopServer();
}
}
private Server server;
public void startServer() throws Exception
{
server = new Server(8989);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
// Must have Resource Base for proper ServletContext (even if it points to an empty URI directory in a JAR file)
context.setBaseResource(getBaseResource());
// Don't use ServletHandler directly!
context.addServlet(MyServletHandler.class, "/myServlet");
// Add DefaultServlet last on ServletContextHandler to be able to serve content from resource base.
// It must be named "default" (per servlet spec)
ServletHolder defaultHolder = new ServletHolder("default", DefaultServlet.class);
defaultHolder.setInitParameter("dirAllowed", "true");
context.addServlet(defaultHolder, "/"); // this is the default url-pattern
HandlerList handlers = new HandlerList();
handlers.addHandler(context);
handlers.addHandler(new DefaultHandler()); // always last in handler tree
server.setHandler(handlers);
server.start();
}
public Resource getBaseResource() throws IOException
{
String baseResourceLocation = System.getProperty("baseResource");
if (baseResourceLocation == null)
{
baseResourceLocation = System.getProperty("user.dir");
}
Resource resource = Resource.newResource(baseResourceLocation);
System.out.println("Base Resource is " + resource);
return resource;
}
private void stopServer() throws Exception
{
server.stop(); // use .stop() NOT .destroy()
}
private void makeRequests()
{
performGET("/myServlet");
performGET("/");
}
private void performGET(String requestPath)
{
try
{
URI uri = server.getURI().resolve(requestPath);
System.out.println("Requesting GET on " + uri);
HttpURLConnection http = (HttpURLConnection) uri.toURL().openConnection();
System.out.println(" Response Status code = " + http.getResponseCode());
try (InputStream in = http.getInputStream())
{
System.out.println(" Response Body: " + IO.toString(in, UTF_8));
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static class MyServletHandler extends HttpServlet
{
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/index.html");
System.out.println("request Dispatcher = " + requestDispatcher);
requestDispatcher.forward(request, response);
}
}
}
The output ...
$ java -DbaseResource=/home/joakim/code/jetty/bases/listing-base/rez/welcomish/ -classpath <..snip..> jetty.dispatching.DispatchingToDefaultServletDemo
2019-04-18 15:15:15.595:INFO::main: Logging initialized #180ms to org.eclipse.jetty.util.log.StdErrLog
Base Resource is file:///home/joakim/code/jetty/bases/listing-base/rez/welcomish/
2019-04-18 15:15:15.678:INFO:oejs.Server:main: jetty-9.4.15.v20190215; built: 2019-02-15T16:53:49.381Z; git: eb70b240169fcf1abbd86af36482d1c49826fa0b; jvm 1.8.0_192-b12
2019-04-18 15:15:15.725:INFO:oejs.session:main: DefaultSessionIdManager workerName=node0
2019-04-18 15:15:15.726:INFO:oejs.session:main: No SessionScavenger set, using defaults
2019-04-18 15:15:15.727:INFO:oejs.session:main: node0 Scavenging every 660000ms
2019-04-18 15:15:15.736:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler#482f8f11{/,file:///home/joakim/code/jetty/bases/listing-base/rez/welcomish/,AVAILABLE}
2019-04-18 15:15:15.747:INFO:oejs.AbstractConnector:main: Started ServerConnector#3ffc5af1{HTTP/1.1,[http/1.1]}{0.0.0.0:8989}
2019-04-18 15:15:15.747:INFO:oejs.Server:main: Started #333ms
Requesting GET on http://127.0.1.1:8989/myServlet
request Dispatcher = Dispatcher#0x5d8c6ff2{null,/index.html}
Response Status code = 200
Response Body: <h1>My welcomish HTML</h1>
Requesting GET on http://127.0.1.1:8989/
Response Status code = 200
Response Body: <h1>My welcomish HTML</h1>
2019-04-18 15:15:15.827:INFO:oejs.AbstractConnector:main: Stopped ServerConnector#3ffc5af1{HTTP/1.1,[http/1.1]}{0.0.0.0:8989}
2019-04-18 15:15:15.827:INFO:oejs.session:main: node0 Stopped scavenging
2019-04-18 15:15:15.829:INFO:oejsh.ContextHandler:main: Stopped o.e.j.s.ServletContextHandler#482f8f11{/,file:///home/joakim/code/jetty/bases/listing-base/rez/welcomish/,UNAVAILABLE}
Process finished with exit code 0
I want to collect metrics for particular REST API
Suppose I have a URL like /company/{companyName}/person/{id}
Is it possible to collect metrics across
/company/test/person/{id}
/compaby/test2/person/{id}
There's no out-of-the-box support for it but you can provide your own WebMvcTagsProvider to implement it via a Spring bean.
Note that it could lead to tag explosion and end up with OOM if there's any possibility to companyName path variable explosion by a mistake or attack.
In case you are using Spring and RestTemplate for http call, you can register MetricsClientHttpRequestInterceptor with your RestTemplate .
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
import org.springframework.boot.actuate.metrics.web.client.MetricsRestTemplateCustomizer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
#Component
#AutoConfigureAfter({MetricsAutoConfiguration.class})
public class RestClientMetricConfiguration {
private final ApplicationContext applicationContext;
#Autowired
public RestClientMetricConfiguration(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
#PostConstruct
public void init() {
MetricsRestTemplateCustomizer restTemplateCustomizer =
applicationContext.getBean(MetricsRestTemplateCustomizer.class);
applicationContext.getBeansOfType(RestTemplate.class).values().forEach(restTemplateCustomizer::customize);
}
}
And use Below method provided by spring RestTemplate to make http call.
public <T> ResponseEntity<T> exchange(String url, HttpMethod method, #Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
Type type = responseType.getType();
RequestCallback requestCallback = this.httpEntityCallback(requestEntity, type);
ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(type);
return (ResponseEntity)nonNull(this.execute(url, method, requestCallback, responseExtractor, uriVariables));
}
I'm getting a Null pointer exception in two lines with three stars as shown in the code. Please see to it. I'm a beginnner in android. Thanks in advance. I tried instantiating tiles JSONarray but even that won't work.
package pack.assignment; ***
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.IOException;
import android.widget.ImageView;
import java.net.MalformedURLException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.app.ProgressDialog;
public class Landing extends Activity {
// url to make request
private static String url = "http://playup-jo.s3.amazonaws.com/dev/config.json";
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
// tiles JSONArray
JSONArray tiles=null;
ImageView img;
// JSON Node names
private static final String TAG_TILES = "tiles";
private static final String TAG_IMAGE = "image";
private static final String TAG_URL = "url";
private static final String TAG_MDPI = "mdpi";
private static final String TAG_NAME = "name";
// Intent go = new Intent(this, Google.class);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Loading JSON in Background Thread
new LoadJSON().execute();
img = (ImageView)findViewById(R.id.image);
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
}
/**
* Background Async Task to Load all INBOX messages by making HTTP Request
* */
class LoadJSON extends AsyncTask<String, String, Bitmap> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Landing.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting JSON
* */
protected Bitmap doInBackground(String... args) {
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
Bitmap bitmap=null;
// Check your log cat for JSON reponse
// Log.d("JSONNN: ", json.toString());
try {
// Getting Array of Tiles
tiles= new JSONArray();
tiles = json.getJSONArray(TAG_TILES); ***
// looping through All Tiles
for(int i = 0; i < 1; i++){
JSONObject c = tiles.getJSONObject(i);
// Storing json item in variable
String name = c.getString(TAG_NAME);
// mdpi is again JSONObject
JSONObject mdpi= c.getJSONObject(TAG_MDPI);
String image=mdpi.getString(TAG_IMAGE);
String url=mdpi.getString(TAG_URL);
// Using the variable to get the bitmap
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(image).getContent());
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
return bitmap;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(final Bitmap result) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data
* */
img.setImageBitmap(result); // Rule:2 Always access UI toolkit for UI thread not worker thread
MyEventHandler myEvHandler = new MyEventHandler();
// making the downloaded image clickable
img.setOnClickListener(myEvHandler);
}
});
}
}
class MyEventHandler implements OnClickListener
{
public void onClick(View v)
{
if (v instanceof ImageView)
{
// startActivity(go);
}
}
}
}
The error was in JSONParser class, I was using httpPost and getting a status code of 405 and not 200. I used httpGet and it got resolved.
I would like to drag and drop from my application into a system folder, so that when I drop an item, it shows up as a new file that represents the object I dragged.
What DataFlavor should I use?
I figured it out myself. You just need to use DataFlavor.javaFileListFlavor and create a temporary file somewhere, and it all works well. Here's what worked for me:
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class FileTransferable implements Transferable
{
final private List<File> files;
final private DataFlavor[] flavors;
/**
* A drag-and-drop object for transfering a file.
* #param file file to transfer -- this file should already exist,
* otherwise it may not be accepted by drag targets.
*/
public FileTransferable(Collection<File> files) {
this.files = Collections.unmodifiableList(
new ArrayList<File>(files));
this.flavors = new DataFlavor[]
{ DataFlavor.javaFileListFlavor };
}
static FileTransferable createFileInTempDirectory(String filename)
throws IOException
{
File dir = new File(System.getProperty("java.io.tmpdir"));
File f = new File(dir, filename);
f.createNewFile();
return new FileTransferable(Collections.singletonList(f));
}
public List<File> getFiles() { return this.files; }
#Override public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException
{
if (isDataFlavorSupported(flavor))
return this.files;
else
return null;
}
#Override public DataFlavor[] getTransferDataFlavors() {
return this.flavors;
}
#Override public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.javaFileListFlavor.equals(flavor);
}
}