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:com.stackmob.example.TwilioSMS2.java
@Override public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) { int responseCode = 0; String responseBody = ""; LoggerService logger = serviceProvider.getLoggerService(TwilioSMS.class); // TO phonenumber should be YOUR cel phone String toPhoneNumber = request.getParams().get("tophonenumber"); // FROM phonenumber should be one create in the twilio dashboard at twilio.com String fromPhoneNumber = "18572541790"; // text message you want to send String message = request.getParams().get("message"); if (toPhoneNumber == null || toPhoneNumber.isEmpty()) { logger.error("Missing phone number"); }//ww w. j a va 2s.co m if (message == null || message.isEmpty()) { logger.error("Missing message"); } StringBuilder body = new StringBuilder(); body.append("To="); body.append(toPhoneNumber); body.append("&From="); body.append(fromPhoneNumber); body.append("&Body="); body.append(message); String url = "https://api.twilio.com/2010-04-01/Accounts/" + accountsid + "/SMS/Messages.json"; String pair = accountsid + ":" + accesstoken; // Base 64 Encode the accountsid/accesstoken String encodedString = new String("utf-8"); try { byte[] b = Base64.encodeBase64(pair.getBytes("utf-8")); encodedString = new String(b); } catch (Exception e) { logger.error(e.getMessage(), e); HashMap<String, String> errParams = new HashMap<String, String>(); errParams.put("error", "the auth header threw an exception: " + e.getMessage()); return new ResponseToProcess(HttpURLConnection.HTTP_BAD_REQUEST, errParams); // http 400 - bad request } Header accept = new Header("Accept-Charset", "utf-8"); Header auth = new Header("Authorization", "Basic " + encodedString); Header content = new Header("Content-Type", "application/x-www-form-urlencoded"); Set<Header> set = new HashSet(); set.add(accept); set.add(content); set.add(auth); try { HttpService http = serviceProvider.getHttpService(); PostRequest req = new PostRequest(url, set, body.toString()); HttpResponse resp = http.post(req); responseCode = resp.getCode(); responseBody = resp.getBody(); } catch (TimeoutException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_BAD_GATEWAY; responseBody = e.getMessage(); } catch (AccessDeniedException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; responseBody = e.getMessage(); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; responseBody = e.getMessage(); } catch (ServiceNotActivatedException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; responseBody = e.getMessage(); } Map<String, Object> map = new HashMap<String, Object>(); map.put("response_body", responseBody); return new ResponseToProcess(responseCode, map); }
From source file:com.netflix.genie.server.resources.JobResource.java
/** * Submit a new job.//from w ww . j av a 2 s. c om * * @param job request object containing job info element for new job * @return The submitted job * @throws GenieException For any error */ @POST @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Submit a job", notes = "Submit a new job to run to genie", response = Job.class) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Created", response = Job.class), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"), @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = "Job with ID already exists."), @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Precondition Failed"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") }) public Response submitJob(@ApiParam(value = "Job object to run.", required = true) final Job job) throws GenieException { if (job == null) { throw new GenieException(HttpURLConnection.HTTP_PRECON_FAILED, "No job entered. Unable to submit."); } LOG.info("Called to submit job: " + job); // get client's host from the context String clientHost = this.httpServletRequest.getHeader(FORWARDED_FOR_HEADER); if (clientHost != null) { clientHost = clientHost.split(",")[0]; } else { clientHost = this.httpServletRequest.getRemoteAddr(); } // set the clientHost, if it is not overridden already if (StringUtils.isNotBlank(clientHost)) { LOG.debug("called from: " + clientHost); job.setClientHost(clientHost); } final Job createdJob = this.executionService.submitJob(job); return Response.created(this.uriInfo.getAbsolutePathBuilder().path(createdJob.getId()).build()) .entity(createdJob).build(); }
From source file:com.stackmob.example.Stripe.java
@Override public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) { int responseCode = 0; String responseBody = ""; LoggerService logger = serviceProvider.getLoggerService(Stripe.class); // AMOUNT should be a whole integer - ie 100 is 1 US dollar String amount = request.getParams().get("amount"); // CURRENCY - should be one of the supported currencies, please check STRIPE documentation. String currency = "usd"; // TOKEN - is returned when you submit the credit card information to stripe using // the Stripe JavaScript library. String token = request.getParams().get("token"); // DESCRIPTION - the description of the transaction String description = request.getParams().get("description"); if (token == null || token.isEmpty()) { logger.error("Token is missing"); }/* www . j a v a2s. co m*/ if (amount == null || amount.isEmpty()) { logger.error("Amount is missing"); } StringBuilder body = new StringBuilder(); body.append("amount="); body.append(amount); body.append("¤cy="); body.append(currency); body.append("&card="); body.append(token); body.append("&description="); body.append(description); String url = "https://api.stripe.com/v1/charges"; String pair = secretKey; //Base 64 Encode the secretKey String encodedString = new String("utf-8"); try { byte[] b = Base64.encodeBase64(pair.getBytes("utf-8")); encodedString = new String(b); } catch (Exception e) { logger.error(e.getMessage(), e); HashMap<String, String> errParams = new HashMap<String, String>(); errParams.put("error", "the auth header threw an exception: " + e.getMessage()); return new ResponseToProcess(HttpURLConnection.HTTP_BAD_REQUEST, errParams); // http 400 - bad request } Header accept = new Header("Accept-Charset", "utf-8"); Header auth = new Header("Authorization", "Basic " + encodedString); Header content = new Header("Content-Type", "application/x-www-form-urlencoded"); Set<Header> set = new HashSet(); set.add(accept); set.add(content); set.add(auth); try { HttpService http = serviceProvider.getHttpService(); PostRequest req = new PostRequest(url, set, body.toString()); HttpResponse resp = http.post(req); responseCode = resp.getCode(); responseBody = resp.getBody(); } catch (TimeoutException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_BAD_GATEWAY; responseBody = e.getMessage(); } catch (AccessDeniedException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; responseBody = e.getMessage(); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; responseBody = e.getMessage(); } catch (ServiceNotActivatedException e) { logger.error(e.getMessage(), e); responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; responseBody = e.getMessage(); } Map<String, Object> map = new HashMap<String, Object>(); map.put("response_body", responseBody); return new ResponseToProcess(responseCode, map); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitCommitTest.java
@Test public void testCommitNoComment() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); String projectName = getMethodName(); JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString()); JSONObject testTxt = getChild(project, "test.txt"); modifyFile(testTxt, "change to commit"); JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); addFile(testTxt);//w w w .j a v a 2 s . c o m // commit with a null message WebRequest request = getPostGitCommitRequest(gitHeadUri /* all */, null, false); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); }
From source file:rapture.kernel.BlobApiImpl.java
@Override public void createBlobRepo(CallingContext context, String blobRepoUri, String config, String metaConfig) { checkParameter("Repository URI", blobRepoUri); checkParameter("Config", config); checkParameter("MetaConfig", metaConfig); RaptureURI interimUri = new RaptureURI(blobRepoUri, BLOB); String authority = interimUri.getAuthority(); if ((authority == null) || authority.isEmpty()) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("NoAuthority")); //$NON-NLS-1$ }/*from www. ja va 2s .c o m*/ if (interimUri.hasDocPath()) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("NoDocPath", blobRepoUri)); //$NON-NLS-1$ } if (blobRepoExists(context, blobRepoUri)) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("Exists", blobRepoUri)); //$NON-NLS-1$ } // store repo config BlobRepoConfig rbc = new BlobRepoConfig(); rbc.setConfig(config); rbc.setMetaConfig(metaConfig); rbc.setAuthority(interimUri.getAuthority()); BlobRepoConfigStorage.add(rbc, context.getUser(), "create repo"); // blob repo will be cached when it's accessed the first time logger.info("Creating Repository " + blobRepoUri); }
From source file:rapture.kernel.SeriesApiImpl.java
@Override public void createSeriesRepo(CallingContext context, String seriesURI, String config) { checkParameter("Repository URI", seriesURI); checkParameter("Config", config); RaptureURI internalURI = new RaptureURI(seriesURI, Scheme.SERIES); String authority = internalURI.getAuthority(); if ((authority == null) || authority.isEmpty()) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("NoAuthority")); //$NON-NLS-1$ }/*from www . j a v a 2 s .c om*/ if (internalURI.hasDocPath()) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("NoDocPath", seriesURI)); //$NON-NLS-1$ } try { ConfigValidatorService.validateConfig(config); } catch (InvalidConfigException | RecognitionException e) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("ConfigNotValid", config), e); //$NON-NLS-1$ } if (seriesRepoExists(context, seriesURI)) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("Exists", seriesURI)); //$NON-NLS-1$ } // Repo config SeriesRepoConfig series = new SeriesRepoConfig(); series.setAuthority(internalURI.getAuthority()); series.setConfig(config); SeriesRepoConfigStorage.add(series, context.getUser(), "Create series repo"); // series repo will be cached when accessed the first time }
From source file:com.stackmob.example.SendGrid.java
@Override public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) { int responseCode = 0; String responseBody = ""; String username = ""; String subject = ""; String text = ""; String from = ""; String to = ""; String toname = ""; String body = ""; String url = ""; LoggerService logger = serviceProvider.getLoggerService(SendGrid.class); //Log the JSON object passed to the StackMob Logs logger.debug(request.getBody());//from www.j a va2 s .c o m JSONParser parser = new JSONParser(); try { Object obj = parser.parse(request.getBody()); JSONObject jsonObject = (JSONObject) obj; //We use the username passed to query the StackMob datastore //and retrieve the user's name and email address username = (String) jsonObject.get("username"); // The following values could be static or dynamic subject = (String) jsonObject.get("subject"); text = (String) jsonObject.get("text"); from = (String) jsonObject.get("from"); } catch (ParseException e) { logger.error(e.getMessage(), e); responseCode = -1; responseBody = e.getMessage(); } if (username == null || username.isEmpty()) { HashMap<String, String> errParams = new HashMap<String, String>(); errParams.put("error", "the username passed was empty or null"); return new ResponseToProcess(HttpURLConnection.HTTP_BAD_REQUEST, errParams); // http 400 - bad request } // get the StackMob datastore service and assemble the query DataService dataService = serviceProvider.getDataService(); // build a query List<SMCondition> query = new ArrayList<SMCondition>(); query.add(new SMEquals("username", new SMString(username))); SMObject userObject; List<SMObject> result; try { // return results from user query result = dataService.readObjects("user", query); if (result != null && result.size() == 1) { userObject = result.get(0); to = userObject.getValue().get("email").toString(); toname = userObject.getValue().get("name").toString(); } else { HashMap<String, String> errMap = new HashMap<String, String>(); errMap.put("error", "no user found"); errMap.put("detail", "no matches for the username passed"); return new ResponseToProcess(HttpURLConnection.HTTP_OK, errMap); // http 500 - internal server error } } catch (InvalidSchemaException e) { HashMap<String, String> errMap = new HashMap<String, String>(); errMap.put("error", "invalid_schema"); errMap.put("detail", e.toString()); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error } catch (DatastoreException e) { HashMap<String, String> errMap = new HashMap<String, String>(); errMap.put("error", "datastore_exception"); errMap.put("detail", e.toString()); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error } catch (Exception e) { HashMap<String, String> errMap = new HashMap<String, String>(); errMap.put("error", "unknown"); errMap.put("detail", e.toString()); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error } if (subject == null || subject.equals("")) { logger.error("Subject is missing"); } //Encode any parameters that need encoding (i.e. subject, toname, text) try { subject = URLEncoder.encode(subject, "UTF-8"); text = URLEncoder.encode(text, "UTF-8"); toname = URLEncoder.encode(toname, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); } String queryParams = "api_user=" + API_USER + "&api_key=" + API_KEY + "&to=" + to + "&toname=" + toname + "&subject=" + subject + "&text=" + text + "&from=" + from; url = "https://www.sendgrid.com/api/mail.send.json?" + queryParams; Header accept = new Header("Accept-Charset", "utf-8"); Header content = new Header("Content-Type", "application/x-www-form-urlencoded"); Set<Header> set = new HashSet(); set.add(accept); set.add(content); try { HttpService http = serviceProvider.getHttpService(); PostRequest req = new PostRequest(url, set, body); HttpResponse resp = http.post(req); responseCode = resp.getCode(); responseBody = resp.getBody(); } catch (TimeoutException e) { logger.error(e.getMessage(), e); responseCode = -1; responseBody = e.getMessage(); } catch (AccessDeniedException e) { logger.error(e.getMessage(), e); responseCode = -1; responseBody = e.getMessage(); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); responseCode = -1; responseBody = e.getMessage(); } catch (ServiceNotActivatedException e) { logger.error(e.getMessage(), e); responseCode = -1; responseBody = e.getMessage(); } Map<String, Object> map = new HashMap<String, Object>(); map.put("response_body", responseBody); return new ResponseToProcess(responseCode, map); }
From source file:eu.codeplumbers.cosi.services.CosiNoteService.java
@Override protected void onHandleIntent(Intent intent) { // Do the task here Log.i(CosiNoteService.class.getName(), "Cosi Service running"); // Release the wake lock provided by the WakefulBroadcastReceiver. WakefulBroadcastReceiver.completeWakefulIntent(intent); Device device = Device.registeredDevice(); // delete all local notes new Delete().from(Note.class).execute(); // cozy register device url this.url = device.getUrl() + "/ds-api/request/note/cosiall/"; // concatenate username and password with colon for authentication final String credentials = device.getLogin() + ":" + device.getPassword(); authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); showNotification();//from ww w .j av a 2 s . c om if (isNetworkAvailable()) { try { URL 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) { for (int i = 0; i < jsonArray.length(); i++) { String version = "0"; if (jsonArray.getJSONObject(i).has("version")) { version = jsonArray.getJSONObject(i).getString("version"); } JSONObject noteJson = jsonArray.getJSONObject(i).getJSONObject("value"); Note note = Note.getByRemoteId(noteJson.get("_id").toString()); if (note == null) { note = new Note(noteJson); } else { boolean versionIncremented = note.getVersion() < Integer .valueOf(noteJson.getString("version")); int modifiedOnServer = DateUtils.compareDateStrings( Long.valueOf(note.getLastModificationValueOf()), noteJson.getLong("lastModificationValueOf")); if (versionIncremented || modifiedOnServer == -1) { note.setTitle(noteJson.getString("title")); note.setContent(noteJson.getString("content")); note.setCreationDate(noteJson.getString("creationDate")); note.setLastModificationDate(noteJson.getString("lastModificationDate")); note.setLastModificationValueOf(noteJson.getString("lastModificationValueOf")); note.setParentId(noteJson.getString("parent_id")); // TODO: 10/3/16 // handle note paths note.setPath(noteJson.getString("path")); note.setVersion(Integer.valueOf(version)); } } mBuilder.setProgress(jsonArray.length(), i, false); mBuilder.setContentText("Getting note : " + note.getTitle()); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new NoteSyncEvent(SYNC_MESSAGE, "Getting note : " + note.getTitle())); note.save(); } } else { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "Failed to parse API response")); } in.close(); conn.disconnect(); mNotifyManager.cancel(notification_id); EventBus.getDefault().post(new NoteSyncEvent(REFRESH, "Sync OK")); } catch (MalformedURLException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } } else { mSyncRunning = false; EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "No Internet connection")); mBuilder.setContentText("Sync failed because no Internet connection was available"); mNotifyManager.notify(notification_id, mBuilder.build()); } }
From source file:org.eclipse.orion.server.tests.servlets.site.SiteTest.java
@Test /**//w w w . j av a 2 s . co m * Attempt to create site with no name, expect 400 Bad Request */ public void testCreateSiteNoName() throws SAXException, IOException { final String siteName = "My great website"; final String hostHint = "mySite"; WebRequest request = getCreateSiteRequest(siteName, null, null, hostHint); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); }