List of usage examples for java.net HttpURLConnection HTTP_BAD_REQUEST
int HTTP_BAD_REQUEST
To view the source code for java.net HttpURLConnection HTTP_BAD_REQUEST.
Click Source Link
From source file:rapture.kernel.UserApiImpl.java
@Override public RaptureUser getWhoAmI(CallingContext context) { RaptureUser usr = Kernel.getAdmin().getTrusted().getUser(context, context.getUser()); if (usr != null) { return usr; } else {/*from w w w . j a v a 2s . c om*/ throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "Could not find this user"); } }
From source file:rapture.kernel.Login.java
public CallingContext checkLogin(String context, String username, String saltedPassword, ApiVersion clientApiVersion) {/*w w w.j ava 2s . c o m*/ long functionStartTime = System.currentTimeMillis(); String documentName = "session/" + context; String content; if (!ApiVersionComparator.INSTANCE.isCompatible(clientApiVersion)) { String message = String.format("Client API Version (%s) does not match server API Version (%s)", clientApiVersion, ServerApiVersion.getApiVersion()); throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, message); } content = getEphemeralRepo().getDocument(documentName); CallingContext savedContext = JacksonUtil.objectFromJson(content, CallingContext.class); RaptureUser userAccount = Kernel.getAdmin().getUser(ContextFactory.getKernelUser(), username); String userPassInvalid = String.format("username or password invalid (attempted username '%s')", username); if (userAccount == null) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_UNAUTHORIZED, userPassInvalid); } if (username.equals(savedContext.getUser())) { if (userAccount.getInactive()) { String message = "Cannot login as an inactive user"; throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_UNAUTHORIZED, message); } if (!userAccount.getVerified()) { String message = "This account has not yet been verified. Please check your email at " + userAccount.getEmailAddress() + " for the verification link.-"; throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_UNAUTHORIZED, message); } if (userAccount.getApiKey()) { savedContext.setValid(true); } else { String toHash = userAccount.getHashPassword() + ":" + savedContext.getSalt(); String testHash = MD5Utils.hash16(toHash); if (testHash.equals(saltedPassword)) { savedContext.setValid(true); String msg = "User " + username + " logged in"; log.info(msg); Kernel.writeComment(msg); } else { RaptureException raptException = RaptureExceptionFactory .create(HttpURLConnection.HTTP_UNAUTHORIZED, userPassInvalid); log.info( RaptureExceptionFormatter.getExceptionMessage(raptException, "Passwords do not match")); throw raptException; } } } getEphemeralRepo().addToStage(RaptureConstants.OFFICIAL_STAGE, documentName, JacksonUtil.jsonFromObject(savedContext), false); getEphemeralRepo().commitStage(RaptureConstants.OFFICIAL_STAGE, "admin", "session validation"); // user has successfully logged in, lets write it to the audit logs Kernel.getAudit().getTrusted().writeAuditEntry(savedContext, RaptureConstants.DEFAULT_AUDIT_URI, "login", 0, String.format("User [%s] has logged in", username)); long endFunctionTime = System.currentTimeMillis(); Kernel.getMetricsService().recordTimeDifference("apiMetrics.loginApi.checkLogin.fullFunctionTime.succeeded", (endFunctionTime - functionStartTime)); return savedContext; }
From source file:eu.codeplumbers.cosi.api.tasks.RegisterDeviceTask.java
@Override protected Device doInBackground(Void... voids) { URL urlO = null;//from ww w . java 2 s.co m try { urlO = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); os.write(deviceString.getBytes("UTF-8")); os.flush(); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONObject jsonObject = new JSONObject(result); if (jsonObject != null) { if (jsonObject.has("login")) { resultDevice = new Device(); resultDevice.setUrl(url.replace("/device/", "")); //Log.d(getClass().getName(), "Token="+jsonObject.getString("login")); resultDevice.setLogin(jsonObject.getString("login")); resultDevice.setPassword(jsonObject.getString("password")); resultDevice.setPermissions(jsonObject.getString("permissions")); resultDevice.setFirstSyncDone(false); resultDevice.setSyncCalls(false); resultDevice.setSyncContacts(false); resultDevice.setSyncFiles(false); resultDevice.setSyncNotes(false); resultDevice.save(); } else { errorMessage = jsonObject.getString("error"); } } in.close(); conn.disconnect(); } catch (MalformedURLException e) { errorMessage = e.getLocalizedMessage(); } catch (ProtocolException e) { errorMessage = e.getLocalizedMessage(); } catch (IOException e) { errorMessage = e.getLocalizedMessage(); } catch (JSONException e) { errorMessage = e.getLocalizedMessage(); } return resultDevice; }
From source file:rapture.mongodb.MongoDBFactory.java
private Mongo getMongoFromLocalConfig(String instanceName) { String mongoHost = MultiValueConfigLoader.getConfig("MONGODB-" + instanceName); log.info("Host is " + mongoHost); if (StringUtils.isBlank(mongoHost)) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, mongoMsgCatalog.getMessage("NoHost")); }/*www .j a v a 2 s .co m*/ MongoClientURI uri = new MongoClientURI(mongoHost); log.info("Username is " + uri.getUsername()); log.info("Host is " + uri.getHosts().toString()); log.info("DBName is " + uri.getDatabase()); log.info("Collection is " + uri.getCollection()); try { MongoClient mongo = new MongoClient(uri); mongoDBs.put(instanceName, mongo.getDB(uri.getDatabase())); mongoDatabases.put(instanceName, mongo.getDatabase(uri.getDatabase())); mongoInstances.put(instanceName, mongo); return mongo; } catch (MongoException e) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, new ExceptionToString(e)); } }
From source file:eu.codeplumbers.cosi.api.tasks.UnregisterDeviceTask.java
@Override protected String doInBackground(Void... voids) { URL urlO = null;//w ww . java 2s . com try { urlO = new URL(url + Device.registeredDevice().getLogin()); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoOutput(false); conn.setDoInput(true); conn.setRequestMethod("DELETE"); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); if (result == "") { Device.registeredDevice().delete(); new Delete().from(Call.class).execute(); new Delete().from(Note.class).execute(); new Delete().from(Sms.class).execute(); new Delete().from(Place.class).execute(); new Delete().from(File.class).execute(); errorMessage = ""; } else { errorMessage = result; } in.close(); conn.disconnect(); } catch (MalformedURLException e) { errorMessage = e.getLocalizedMessage(); } catch (ProtocolException e) { errorMessage = e.getLocalizedMessage(); } catch (IOException e) { errorMessage = e.getLocalizedMessage(); } return errorMessage; }
From source file:eu.codeplumbers.cosi.api.tasks.GetPlacesTask.java
@Override protected List<Place> doInBackground(Void... voids) { URL urlO = null;//from w ww . ja v a2 s .c o m try { urlO = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("POST"); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONArray jsonArray = new JSONArray(result); if (jsonArray != null) { if (jsonArray.length() > 0) { for (int i = 0; i < jsonArray.length(); i++) { String version = "0"; if (jsonArray.getJSONObject(i).has("version")) { version = jsonArray.getJSONObject(i).getString("version"); } JSONObject placeJson = jsonArray.getJSONObject(i).getJSONObject("value"); Place place = Place.getByLocation(placeJson.get("description").toString(), placeJson.get("latitude").toString(), placeJson.get("longitude").toString()); if (place == null) { place = new Place(placeJson); } else { place.setDeviceId(placeJson.getString("deviceId")); place.setAddress(placeJson.getString("address")); place.setDateAndTime(placeJson.getString("dateAndTime")); place.setLongitude(placeJson.getDouble("longitude")); place.setLatitude(placeJson.getDouble("latitude")); place.setRemoteId(placeJson.getString("_id")); } publishProgress("Saving place : " + place.getAddress()); place.save(); allPlaces.add(place); } } else { publishProgress("Your Cozy has no places stored."); return allPlaces; } } else { errorMessage = "Failed to parse API response"; } in.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); errorMessage = e.getLocalizedMessage(); } catch (ProtocolException e) { errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } catch (IOException e) { errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } catch (JSONException e) { errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } return allPlaces; }
From source file:org.eclipse.hono.service.http.AbstractHttpEndpoint.java
/** * Check the Content-Type of the request to be 'application/json' and extract the payload if this check was * successful.// w w w. java 2s. c o m * <p> * The payload is parsed to ensure it is valid JSON and is put to the RoutingContext ctx with the * key {@link #KEY_REQUEST_BODY}. * * @param ctx The routing context to retrieve the JSON request body from. */ protected void extractRequiredJsonPayload(final RoutingContext ctx) { final MIMEHeader contentType = ctx.parsedHeaders().contentType(); if (contentType == null) { ctx.response().setStatusMessage("Missing Content-Type header"); ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST); } else if (!HttpUtils.CONTENT_TYPE_JSON.equalsIgnoreCase(contentType.value())) { ctx.response().setStatusMessage("Unsupported Content-Type"); ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST); } else { try { if (ctx.getBody() != null) { ctx.put(KEY_REQUEST_BODY, ctx.getBodyAsJson()); ctx.next(); } else { ctx.response().setStatusMessage("Empty body"); ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST); } } catch (final DecodeException e) { ctx.response().setStatusMessage("Invalid JSON"); ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST); } } }
From source file:org.opendaylight.lispflowmapping.neutron.LispNeutronSubnetHandler.java
/** * Method to check whether new Subnet can be created by LISP implementation * of Neutron service API. Since we store the Cidr part of the subnet as the * main key to the Lisp mapping service, we do not support updates to * subnets that change it's cidr.//from w w w . ja v a 2 s . c om */ @Override public int canUpdateSubnet(NeutronSubnet delta, NeutronSubnet original) { if (delta == null || original == null) { LOG.error("Neutron canUpdateSubnet rejected: subnet objects were null"); return HttpURLConnection.HTTP_BAD_REQUEST; } LOG.info("Neutron canUpdateSubnet : Subnet name: " + original.getName() + " Subnet Cidr: " + original.getCidr()); LOG.debug("Lisp Neutron Subnet update: original : " + original.toString() + " delta : " + delta.toString()); // We do not accept a Subnet update that changes the cidr. If cider or // network UUID is changed, return error. if (!(original.getCidr().equals(delta.getCidr()))) { LOG.error("Neutron canUpdateSubnet rejected: Subnet name: " + original.getName() + " Subnet Cidr: " + original.getCidr()); return HttpURLConnection.HTTP_CONFLICT; } return HttpURLConnection.HTTP_OK; }
From source file:gov.nih.nci.nbia.servlet.DownloadServletV3.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // This servlet processes Manifest download related requests only. JNLP // download related requests are processed at DownloadServlet String numOfS = request.getParameter("numberOfSeries"); if (numOfS != null) { int numberOfSeries = Integer.parseInt(numOfS); List<String> seriesList = new ArrayList<String>(); for (int i = 1; i <= numberOfSeries; ++i) { String s = request.getParameter("series" + Integer.toString(i)); if (s != null) seriesList.add(s);/* w ww . j av a2 s . c o m*/ } //authenticate user if (numberOfSeries > 0) { String userId = request.getParameter("userId"); String password = request.getHeader("password"); if ((userId == null) || (password == null)) { userId = NCIAConfig.getGuestUsername(); } else if (!loggedIn(userId, password)) { response.sendError(CLIENT_LOGIN_FAILED, "Incorrect username and/or password. Please try it again."); return; } downloadManifestFile(seriesList, response, userId); } else { response.sendError(HttpURLConnection.HTTP_BAD_REQUEST, "The manifest file should include at least one series instance UID."); return; } } else { // individual download request String seriesUid = request.getParameter("seriesUid"); String userId = request.getParameter("userId"); String password = request.getHeader("password"); Boolean includeAnnotation = Boolean.valueOf(request.getParameter("includeAnnotation")); Boolean hasAnnotation = Boolean.valueOf(request.getParameter("hasAnnotation")); String sopUids = request.getParameter("sopUids"); if ((userId == null) || (userId.length() < 1)) { userId = NCIAConfig.getGuestUsername(); } logger.info("sopUids:" + sopUids); logger.info("seriesUid: " + seriesUid + " userId: " + userId + " includeAnnotation: " + includeAnnotation + " hasAnnotation: " + hasAnnotation); processRequest(response, seriesUid, userId, password, includeAnnotation, hasAnnotation, sopUids); } }
From source file:org.apache.sentry.api.service.thrift.TestSentryServerLogLevel.java
/** * Send class name and invalid log level via the HTTP interface and verify that it returns error response. * @throws Exception//from w ww. jav a 2 s . c o m */ @Test public void testInvalidLogLevel() throws Exception { final URL url = new URL("http://" + SERVER_HOST + ":" + webServerPort + "/admin/logLevel?log=" + CLASS_NAME + "&level=ABCD"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, conn.getResponseCode()); }