I have quite a simple question really.
I wrote a servlet for suppliers to upload XML-files to.
These files get written to a location on the server.
All the files get renamed with a timestamp.
Is there a risk of concurrency problems with the code below?
I ask because we receive files from a supplier, that look like
they have content from 2 different XML-files
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}// </editor-fold>
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
File dirToUse;
boolean mountExists = this.getDirmount().exists();
if (!mountExists) {
this.log("MOUNT " + this.getDirmount() + " does not exist!");
dirToUse = this.getDiras400();
} else {
dirToUse = this.getDirmount();
}
boolean useSimpleRead = true;
if (request.getMethod().equalsIgnoreCase("POST")) {
useSimpleRead = !ServletFileUpload.isMultipartContent(request);
}
if (useSimpleRead) {
this.log("Handle simple request.");
handleSimpleRequest(request, response, dirToUse);
} else {
this.log("Handle Multpart Post request.");
handleMultipart(request, response, dirToUse);
}
}
protected void handleMultipart(HttpServletRequest request,
HttpServletResponse response, File dir) throws IOException,
ServletException {
try {
FileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
List<FileItem> items = upload.parseRequest(request);
if (items.isEmpty()) {
this.log("No content to read in request.");
throw new IOException("No content to read in request.");
}
boolean savedToDisk = true;
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
getFilename(request);
File diskFile = new File(dir, this.getFilename(request));
item.write(diskFile);
if (!diskFile.exists()) {
savedToDisk = false;
}
}
if (!savedToDisk) {
throw new IOException("Data not saved to disk.");
}
} catch (FileUploadException fue) {
throw new ServletException(fue);
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
protected void handleSimpleRequest(HttpServletRequest request,
HttpServletResponse response, File dir) throws IOException {
// READINPUT DATA TO STRINGBUFFER
InputStream in = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String line = reader.readLine();
while (line != null) {
sb.append(line + "\r\n");
line = reader.readLine();
}
if (sb.length() == 0) {
this.log("No content to read in request.");
throw new IOException("No content to read in request.");
}
//Get new Filename
String newFilename = getFilename(request);
File diskFile = new File(dir, newFilename);
saveDataToFile(sb, diskFile);
if (!diskFile.exists()) {
throw new IOException("Data not saved to disk.");
}
}
protected abstract String getFilename(HttpServletRequest request);
protected void saveDataToFile(StringBuffer sb, File diskFile) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter(diskFile));
out.write(sb.toString());
out.flush();
out.close();
}
getFileName implementation:
#Override
protected String getFilename(HttpServletRequest request) {
Calendar current = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
long currentTimeMillis = current.getTimeInMillis();
System.out.println(currentTimeMillis);
return "disp_" + request.getRemoteHost() + "_" + currentTimeMillis + ".xml";
}
Anyway, thanks in advance!
There would not be synchronization problems but there can be race conditions, for example, two threads might return the same file name using the method getFileName()
Related
I've a error thrown I can't figure out how it happens. It doesn't occur all the time but once in a while. The error message thrown is "Java.lang.nullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference". I've used connectionRequest for parsing the json data. When the error is thrown I've checked if there's problem in url but it gives the proper json data as always. After trying few times, the error is solved automatically.
if (!regNOField.getText().equals("") && !newPasswordField.getText().equals("")) {
ArrayList<Map<String, String>> argumentsArrayList = new ArrayList<>();
Map argumentMap1 = new HashMap();
argumentMap1.put("argument", "reg_no");
argumentMap1.put("value", regNOField.getText().trim());
argumentsArrayList.add(argumentMap1);
Map argumentMap2 = new HashMap();
argumentMap2.put("argument", "token");
argumentMap2.put("value", newPasswordField.getText().trim());
argumentsArrayList.add(argumentMap2);
CommonMethod.connectionMethod(res, true, url, "Verification", argumentsArrayList, true, null);
}
CommonMethod.connectionMethod:
public static void connectionMethod(Resources res, Boolean postBoolean, String urlString, String form, ArrayList<Map<String, String>> arguments,
Boolean ipFlag, String extraData) {
ConnectionRequest cr = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jp = new JSONParser();
parser = jp.parseJSON(new InputStreamReader(input));
response = null;
if (parser != null && !parser.isEmpty()) {
if (parser.get("status").equals("true")) {
message = (String) parser.get("data");
ToastBar.getInstance().setPosition(Component.TOP);
ToastBar.showErrorMessage(message, 5000);
if (form.equals("Verification")) {
if (d != null) {
d.dispose();
}
new LoginAndSignUp(res, message).show();
}
}
}
}
#Override
protected void handleErrorResponseCode(int code, String message) {
System.out.println("login ErrorResponseCode " + code + "msg: " + message);
}
#Override
protected void handleException(Exception err) {
System.out.println("login Exception " + err);
}
#Override
protected void handleIOException(IOException err) {
System.out.println("login IOException " + err);
}
#Override
protected void handleRuntimeException(RuntimeException err) {
System.out.println("RuntimeException " + err);
}
};
cr.setPost(postBoolean);
cr.setUrl(urlString);
cr.setTimeout(80000);
if (arguments != null && !postBoolean.equals(false)) {
for (Map<String, String> entrySet : arguments) {
String argument1 = (String) entrySet.get("argument");
String value1 = (String) entrySet.get("value");
cr.addArgument(argument1, value1);
}
}
InfiniteProgress ip = new InfiniteProgress();
d = ip.showInifiniteBlocking();
cr.setDisposeOnCompletion(d);
cr.addRequestHeader("accept", "application/json");
NetworkManager.getInstance().addToQueueAndWait(cr);
}
Error msg:
I've a year & a half old app to update. It was written in statemachine. Now I added a few things but the connectionRequest doesn't seem to work in iOS (which was built for iOS debug). I built it in android and it works very well.
public void connectionForLogin(String username, String password) {
ConnectionRequest cr = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jSONParser = new JSONParser();
Map<String, Object> parsedData = jSONParser.parseJSON(new InputStreamReader(input));
ArrayList<Map<String, Object>> response = (ArrayList<Map<String, Object>>) parsedData.get("root");
if (response != null) {
for (Map<String, Object> element : response) {
success = (String) element.get("login");
msg = (String) element.get("msg");
ArrayList<Map<String, Object>> userInfoArray = (ArrayList) element.get("user_info");
Storage.getInstance().writeObject("userInfo", userInfoArray);
}
}
}
#Override
protected void postResponse() {
super.postResponse();
}
#Override
protected void handleErrorResponseCode(int code, String message) {
}
#Override
protected void handleException(Exception err) {
}
#Override
protected void handleIOException(IOException err) {
}
#Override
protected void handleRuntimeException(RuntimeException err) {
}
};
cr.setPost(true);
cr.setDuplicateSupported(true);
cr.setTimeout(30000);
AllUrl au = new AllUrl();
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
cr.setDisposeOnCompletion(d);
cr.setUrl(http://zzz.com/api/logins/match? + "username=" + username + "&password=" + password);
NetworkManager.getInstance().addToQueueAndWait(cr);
}
This may be due to new Apple regulations that prevents apps from fetching data from non secure URL http. You can fix this temporarily by adding below build hint:
ios.plistInject=<key>NSAppTransportSecurity</key><dict><key>NSAllowsArbitraryLoads</key><true/></dict><key>CFBundleURLTypes</key><array><dict><key>CFBundleURLName</key><string>com.mycompany.myapp</string></dict><dict><key>CFBundleURLSchemes</key><array><string>MyApp</string></array></dict></array>
Note that your app may be rejected if connected to a non secure URL.
I am Using GCM (Google Cloud Messaging).In that what i want i want to send J Son from the server side .On Client side I want to receive that for simple message i have done but i am stucked how could i pass J Son from the server side to the client side.
Please help me to resolve this.
This is my Server side code
public class GCMBroadcast extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String SENDER_ID = "";
private static final String ANDROID_DEVICE = "";
private List<String> androidTargets = new ArrayList<String>();
public GCMBroadcast() {
super();
androidTargets.add(ANDROID_DEVICE);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String collapseKey = "";
String userMessage = "";
try {
userMessage = request.getParameter("Message");
collapseKey = request.getParameter("CollapseKey");
} catch (Exception e) {
e.printStackTrace();
return;
}
Sender sender = new Sender(SENDER_ID);
Message message = new Message.Builder()
.collapseKey(collapseKey)
.addData("message", userMessage)
.build();
try {
MulticastResult result = sender.send(message, androidTargets, 1);
System.out.println("Response: " + result.getResults().toString());
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
System.out.println("response " +canonicalRegId );
}
} else {
int error = result.getFailure();
System.out.println("Broadcast failure: " + error);
}
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("CollapseKey", collapseKey);
request.setAttribute("Message", userMessage);
request.getRequestDispatcher("XX.jsp").forward(request, response);
}
}
Your payload (added to the Message by calls to addData) can only be name/value pairs. If you want to send a JSON, you can put a JSON string in the value of such name/value pair. Then you'll have to parse that JSON yourself in the client side.
For example :
.addData("message","{\"some_json_key\":\"some_json_value\"}")
Hi i am trying to implement OAuth1.0 following this tutorial in this tutorial there is a heading OAuthGetRequestToken
in which for getting request token we have to send a post request to URL
www.google.com/accounts/OAuthGetRequestToken
i am sending a post request in my code in google app engine my code is:
public class HelloWorldServlet extends HttpServlet {
#SuppressWarnings({ "unchecked", "unchecked" })
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
resp.getWriter().println("<html><head> <meta name=\"google-site-verification\" content=\"OBFeK6hFEbTkNdcYc-SQNH9tCTpcht-HkUdj6IgCaLg\" </head>");
resp.getWriter().println("<body>Hello, world");
//String post="key=AIzaSyBgmwbZaW3-1uaVOQ9UqlyHAUxvQtHe7X0&oauth_consumer_key=iriteshmehandiratta.appspot.com";
//String param= "&oauth_callback=\"https://www.iriteshmehandiratta.appspot.com\"&scope=\"http://www.google.com/calendar/feeds\"";
//URL url=new URL("https://www.googleapis.com/prediction/v1.5/trainedmodels/10/predict?");
TreeMap<String,String> tree=new TreeMap<String,String>();
tree.put("oauth_version","1.0");
tree.put("oauth_nonce", System.currentTimeMillis()+"");
tree.put("oauth_timestamp",System.currentTimeMillis()/1000+"");
tree.put("oauth_consumer_key", "imehandirattaritesh.appspot.com");
tree.put("oauth_signature_method", "RSA-SHA1");
ServletContext context = getServletContext();
PrivateKey privKey = getPrivateKey(context,"/myrsakey11.pk8");
tree.put("oauth_callback", "https://imehandirattaritesh.appspot.com/authsub");
tree.put("scope", "https://www.google.com/calendar/feeds");
Set set = tree.entrySet();
Iterator<Map.Entry<String, String>> i = set.iterator();
String datastring="";
Map.Entry me=(Map.Entry)i.next();
datastring=me.getKey()+"=";
datastring+=me.getValue();
while(i.hasNext()) {
me = (Map.Entry)i.next();
datastring+="&"+me.getKey()+"=";
datastring+=(me.getValue());
}
String data_string="GET&https://www.google.com/accounts/OAuthGetRequestToken&"+datastring;
byte[] xx11;
String str = null;
try {
xx11 = sign(privKey,data_string);
str=new String(xx11);
resp.getWriter().println(str);
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URL url=new URL("https://www.google.com/accounts/OAuthGetRequestToken?"+str);
// resp.getWriter().println(""+datastring);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Authorization", " OAuth");
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
resp.getWriter().println( urlConnection.getResponseCode());
String xx="";
String xx1="";
while((xx1=in.readLine()) != null)
{
xx+=xx1;
}
resp.getWriter().println("response");
resp.getWriter().println(xx);
resp.getWriter().println("</body></html>");
}
public static PrivateKey getPrivateKey(ServletContext context,String privKeyFileName) throws IOException {
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/myrsakey11.pk8");
// FileInputStream fis = new FileInputStream(privKeyFile);
DataInputStream dis = new DataInputStream(resourceContent);
#SuppressWarnings("deprecation")
String str="";
String str1="";
while((str=dis.readLine())!=null)
{
str1+=str;
}
String BEGIN = "-----BEGIN PRIVATE KEY-----";
String END = "-----END PRIVATE KEY-----";
// String str = new String(privKeyBytes);
if (str1.contains(BEGIN) && str1.contains(END)) {
str1 = str1.substring(BEGIN.length(), str1.lastIndexOf(END));
}
KeyFactory fac;
try {
fac = KeyFactory.getInstance("RSA");
EncodedKeySpec privKeySpec= new PKCS8EncodedKeySpec(Base64.decode(str1));
return fac.generatePrivate(privKeySpec);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Base64DecoderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
byte[] sign(PrivateKey key, String data) throws GeneralSecurityException {
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(key);
signature.update(data.getBytes());
return signature.sign();
}
}
first i generate data_string then sign it using my private key i get an encrypted string like this
F????T???&??$????????l:v????x???}??U-'?"?????U?[?kr^?G?(? ???qT0??]??j???5??`??$??AD??T??#<t?,#:`V????????????
then i concatenate it with
url : https://www.google.com/accounts/OAuthGetRequestToken?
and i get 400 error obviously it is not a valid uri format so i get this error.i post a query on stackoverflow a person suggest me to use sign method and after signing data_string i will get oauth_signature embedded in the return string which is variable str but in place of oauth_signature included i am getting an encrypted string can any one please tell me how to sign this data_string and what mistake i am doing ??
I would suggest you use an existing Java library for doing the OAuth. It will be much easier in the long term and you won't have to worry about debugging the protocol.
is it possible to load jsf 2 page from database, not from xhtml file?
Eg., the request comes for /faces/foo.xhtml, FacesServet intercepts request and VieHanlder creates view foo.xhtml by loading foo.xhtml from a DB, not from the server?
Thanks
It is in theory possible if you put it from the database into the public webcontent exactly there where the FacesServlet expect it to be, before it kicks in. A Filter is suitable for the job.
Here's a kickoff example:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String rootPath = req.getSession().getServletContext().getRealPath("/");
String fileName = req.getServletPath().substring(1);
File file = new File(rootPath, fileName);
if (!file.exists()) {
InputStream input = null;
OutputStream output = null;
try {
input = yourDAO.find(fileName);
output = response.getOutputStream();
byte[] buffer = new byte[10240];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException ignore) {}
if (input != null) try { input.close(); } catch (IOException ignore) {}
}
}
chain.doFilter(request, response);
}
Map this on the <servlet-name> of the FacesServlet.