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:org.eclipse.mylyn.internal.gerrit.core.client.GerritClient28.java
@Override public ChangeDetail cherryPick(String reviewId, int patchSetId, final String message, final String destBranch, IProgressMonitor monitor) throws GerritException { final PatchSet.Id id = new PatchSet.Id(new Change.Id(id(reviewId)), patchSetId); String url = "/changes/" + id.getParentKey() + "/revisions/" + id.get() + "/cherrypick"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ CherryPickInput input = new CherryPickInput(message, destBranch); ChangeInfo result = executePostRestRequest(url, input, ChangeInfo.class, new ErrorHandler() { @Override// w ww .j a va2s . c o m public void handleError(HttpMethodBase method) throws GerritException { String errorMsg = getResponseBodyAsString(method); if (isNotPermitted(method, errorMsg)) { errorMsg = NLS.bind("Cannot cherry pick: {0}", errorMsg); //$NON-NLS-1$ } else if (isConflict(method)) { errorMsg = NLS.bind("Request Conflict: {0}", errorMsg); //$NON-NLS-1$ } else if (isBadRequest(method)) { errorMsg = NLS.bind("Bad Request: {0}", errorMsg); //$NON-NLS-1$ } throw new GerritException(errorMsg); } private String getResponseBodyAsString(HttpMethodBase method) { try { return method.getResponseBodyAsString(); } catch (IOException e) { return null; } } private boolean isNotPermitted(HttpMethodBase method, String msg) { return method.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN && msg.toLowerCase().startsWith("cherry pick not permitted"); //$NON-NLS-1$ } private boolean isConflict(HttpMethodBase method) { return method.getStatusCode() == HttpURLConnection.HTTP_CONFLICT; } private boolean isBadRequest(HttpMethodBase method) { return method.getStatusCode() == HttpURLConnection.HTTP_BAD_REQUEST; } }, monitor); return getChangeDetail(result.getNumber(), monitor); }
From source file:rapture.kernel.DecisionApiImpl.java
@Override public void addStep(CallingContext context, String workflowURI, Step step) { Workflow workflow = getWorkflowNotNull(context, workflowURI); List<Step> steps = workflow.getSteps(); for (Step currStep : steps) { if (currStep.getName().equals(step.getName())) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, String.format("Trying to add step that already exists: Step name '%s'", step.getName())); }//from w w w . j av a 2 s. c om } steps.add(step); WorkflowStorage.add(new RaptureURI(workflow.getWorkflowURI(), Scheme.WORKFLOW), workflow, context.getUser(), "Add step"); }
From source file:i5.las2peer.services.gamificationAchievementService.GamificationAchievementService.java
/** * Post a new achievement// w w w.j a v a 2s .c om * @param appId applicationId * @param formData form data * @param contentType content type * @return HttpResponse returned as JSON object */ @POST @Path("/{appId}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Achievement upload success ( (achievementid) )\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (achievementid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the achievement. Achievement ID already exist!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Achievement ID cannot be null!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (achievementid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (achievementid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Achievement upload success ( (achievementid) )}") }) @ApiOperation(value = "createNewAchievement", notes = "A method to store a new achievement with details (achievement ID, achievement name, achievement description, achievement point value, achievement point id, achievement badge id") public HttpResponse createNewAchievement( @ApiParam(value = "Application ID to store a new achievement", required = true) @PathParam("appId") String appId, @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType, @ApiParam(value = "Achievement detail in multiple/form-data type", required = true) @ContentParam byte[] formData) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/achievements/" + appId); long randomLong = new Random().nextLong(); //To be able to match // parse given multipart form data JSONObject objResponse = new JSONObject(); String achievementid = null; String achievementname = null; String achievementdesc = null; int achievementpointvalue = 0; String achievementbadgeid = null; boolean achievementnotifcheck = false; String achievementnotifmessage = null; Connection conn = null; UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); if (name.equals("anonymous")) { return unauthorizedMessage(); } try { conn = dbm.getConnection(); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_14, "" + randomLong); try { if (!achievementAccess.isAppIdExist(conn, appId)) { logger.info("App not found >> "); objResponse.put("message", "Cannot create achievement. App not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } } catch (SQLException e1) { e1.printStackTrace(); objResponse.put("message", "Cannot create achievement. Cannot check whether application ID exist or not. Database error. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType); FormDataPart partAchievementID = parts.get("achievementid"); if (partAchievementID != null) { achievementid = partAchievementID.getContent(); if (achievementAccess.isAchievementIdExist(conn, appId, achievementid)) { // Achievement id already exist objResponse.put("message", "Cannot create achievement. Failed to add the achievement. achievement ID already exist!"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } FormDataPart partAchievementName = parts.get("achievementname"); if (partAchievementName != null) { achievementname = partAchievementName.getContent(); } FormDataPart partAchievementDesc = parts.get("achievementdesc"); if (partAchievementDesc != null) { // optional description text input form element achievementdesc = partAchievementDesc.getContent(); } FormDataPart partAchievementPV = parts.get("achievementpointvalue"); if (partAchievementPV != null) { // optional description text input form element achievementpointvalue = Integer.parseInt(partAchievementPV.getContent()); } FormDataPart partAchievementBID = parts.get("achievementbadgeid"); System.out.println("BADGE In Ach : " + partAchievementBID); System.out.println("BADGE In Ach : " + partAchievementBID.getContent()); if (partAchievementBID != null) { // optional description text input form element achievementbadgeid = partAchievementBID.getContent(); } if (achievementbadgeid.equals("")) { achievementbadgeid = null; } FormDataPart partNotificationCheck = parts.get("achievementnotificationcheck"); if (partNotificationCheck != null) { // checkbox is checked achievementnotifcheck = true; } else { achievementnotifcheck = false; } FormDataPart partNotificationMsg = parts.get("achievementnotificationmessage"); if (partNotificationMsg != null) { achievementnotifmessage = partNotificationMsg.getContent(); } else { achievementnotifmessage = ""; } AchievementModel achievement = new AchievementModel(achievementid, achievementname, achievementdesc, achievementpointvalue, achievementbadgeid, achievementnotifcheck, achievementnotifmessage); try { achievementAccess.addNewAchievement(conn, appId, achievement); objResponse.put("message", "Achievement upload success (" + achievementid + ")"); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_15, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24, "" + name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_25, "" + appId); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } else { objResponse.put("message", "Cannot create achievement. Achievement ID cannot be null!"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } catch (MalformedStreamException e) { // the stream failed to follow required syntax objResponse.put("message", "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } catch (IOException e) { // a read or write error occurred objResponse.put("message", "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (NullPointerException e) { e.printStackTrace(); objResponse.put("message", "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // always close connections finally { try { conn.close(); } catch (SQLException e) { logger.printStackTrace(e); } } }
From source file:org.jboss.narayana.rts.TransactionAwareResource.java
@PUT @Path("{wId}/terminator") public Response terminate(@PathParam("wId") @DefaultValue("") String wId, String content) { // System.out.println("Service: PUT request to terminate url: wId=" + wId + ", status:=" + content); TxStatus status = TxSupport.toTxStatus(content); if (log.isTraceEnabled()) log.tracef("terminate workId %s enlist%n", wId); if (status.isCommit()) { commitCnt.incrementAndGet();//w ww.j a v a 2s . c om } else if (!status.isPrepare() && !status.isAbort()) { return Response.status(HttpURLConnection.HTTP_BAD_REQUEST).build(); } if (log.isTraceEnabled()) log.tracef("terminated workId %s enlist%n", wId); return Response.ok(TxSupport.toStatusContent(status.name())).build(); }
From source file:rapture.kernel.AdminApiImpl.java
@Override public void addNamedUser(CallingContext context, String userName, String description, String hashPassword, String email, String realName) { checkParameter("User", userName); //$NON-NLS-1$ // Does the user already exist? RaptureUser usr = getUser(context, userName); if (usr == null) { String iAm = context.getUser(); // High-level audit log message. Kernel.getAudit().writeAuditEntry(context, RaptureConstants.DEFAULT_AUDIT_URI, "admin", 2, "New user " + userName + " added by " + iAm); usr = new RaptureUser(); usr.setUsername(userName);/*from w ww. j av a 2s . c om*/ usr.setUserId(realName); usr.setDescription(description); usr.setHashPassword(hashPassword); usr.setEmailAddress(email); RaptureUserHelper.validateSalt(usr); usr.setInactive(false); RaptureUserStorage.add(usr, context.getUser(), adminMessageCatalog.getMessage("AddedUser", userName).toString()); //$NON-NLS-1$ } else { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, Messages.getMessage("Admin", "UserAlreadyExists", null, null)); //$NON-NLS-1$ } }
From source file:i5.las2peer.services.gamificationActionService.GamificationActionService.java
/** * Post a new action/* w w w. j av a2 s.c om*/ * @param appId applicationId * @param formData form data * @param contentType content type * @return HttpResponse returned as JSON object */ @POST @Path("/{appId}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Action upload success ( (actionid) )\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (actionid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the action. Action ID already exist!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Action ID cannot be null!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (actionid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (actionid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Action upload success ( (actionid) )}") }) @ApiOperation(value = "createNewAction", notes = "A method to store a new action with details (action ID, action name, action description,action point value") public HttpResponse createNewAction( @ApiParam(value = "Application ID to store a new action", required = true) @PathParam("appId") String appId, @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType, @ApiParam(value = "Action detail in multiple/form-data type", required = true) @ContentParam byte[] formData) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/actions/" + appId); long randomLong = new Random().nextLong(); //To be able to match // parse given multipart form data JSONObject objResponse = new JSONObject(); String actionid = null; String actionname = null; String actiondesc = null; int actionpointvalue = 0; boolean actionnotifcheck = false; String actionnotifmessage = null; Connection conn = null; UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); if (name.equals("anonymous")) { return unauthorizedMessage(); } try { conn = dbm.getConnection(); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_14, "" + randomLong); try { if (!actionAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot create action. App not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } } catch (SQLException e1) { e1.printStackTrace(); objResponse.put("message", "Cannot create action. Cannot check whether application ID exist or not. Database error. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType); FormDataPart partID = parts.get("actionid"); if (partID != null) { actionid = partID.getContent(); if (actionAccess.isActionIdExist(conn, appId, actionid)) { objResponse.put("message", "Cannot create action. Failed to add the action. action ID already exist!"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } FormDataPart partName = parts.get("actionname"); if (partName != null) { actionname = partName.getContent(); } FormDataPart partDesc = parts.get("actiondesc"); if (partDesc != null) { // optional description text input form element actiondesc = partDesc.getContent(); } FormDataPart partPV = parts.get("actionpointvalue"); if (partPV != null) { // optional description text input form element actionpointvalue = Integer.parseInt(partPV.getContent()); } FormDataPart partNotificationCheck = parts.get("actionnotificationcheck"); if (partNotificationCheck != null) { // checkbox is checked actionnotifcheck = true; } else { actionnotifcheck = false; } FormDataPart partNotificationMsg = parts.get("actionnotificationmessage"); if (partNotificationMsg != null) { actionnotifmessage = partNotificationMsg.getContent(); } else { actionnotifmessage = ""; } ActionModel action = new ActionModel(actionid, actionname, actiondesc, actionpointvalue, actionnotifcheck, actionnotifmessage); try { actionAccess.addNewAction(conn, appId, action); objResponse.put("message", "Action upload success (" + actionid + ")"); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_15, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24, "" + name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_25, "" + appId); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } else { objResponse.put("message", "Cannot create action. Action ID cannot be null!"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } catch (MalformedStreamException e) { // the stream failed to follow required syntax objResponse.put("message", "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } catch (IOException e) { // a read or write error occurred objResponse.put("message", "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (NullPointerException e) { e.printStackTrace(); objResponse.put("message", "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // always close connections finally { try { conn.close(); } catch (SQLException e) { logger.printStackTrace(e); } } }
From source file:rapture.sheet.file.FileSheetStore.java
private void writeSheet(String name, Collection<RaptureSheetCell> cells, boolean append) { File sheetFile = FileRepoUtils.makeGenericFile(parentDir, name); if (sheetFile.exists() && !sheetFile.isFile()) throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "Cannot write to sheet " + sheetFile.getName() + " - not a file"); try {// ww w .j av a 2 s. c o m sheetFile.getParentFile().mkdirs(); try (PrintStream out = new PrintStream(new FileOutputStream(sheetFile, append))) { appendCells(out, cells); } } catch (SecurityException | IOException e) { // Very unlikely throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "Cannot write to sheet " + sheetFile.getName(), e); } return; }
From source file:rapture.plugin.install.PluginSandbox.java
public void readConfig() { String s = PluginUtil.getFileAsString(new File(rootDir, "plugin.txt")); PluginConfig config = null;// ww w. j a v a 2 s .com try { config = JacksonUtil.objectFromJson(s, PluginConfig.class); } catch (Exception ex) { throw RaptureExceptionFactory.create("The plugin.txt file has been corrupted.", ex); } if (!config.getPlugin().equals(pluginName)) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "Config mismatch: " + config.getPlugin()); } setConfig(config); }
From source file:i5.las2peer.services.gamificationLevelService.GamificationLevelService.java
/** * Post a new level//from w w w.j a v a2s. c o m * @param appId applicationId * @param formData form data * @param contentType content type * @return HttpResponse with the returnString */ @POST @Path("/{appId}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Level upload success ( (levelnum) )\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (levelnum)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the level. levelnum already exist!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Level number cannot be null!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (levelnum)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (levelnum)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Level upload success ( (levelnum) )}") }) @ApiOperation(value = "createLevel", notes = "A method to store a new level with details (Level number, level name, level point value, level point id)") public HttpResponse createLevel( @ApiParam(value = "Application ID to store a new level", required = true) @PathParam("appId") String appId, @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType, @ApiParam(value = "Level detail in multiple/form-data type", required = true) @ContentParam byte[] formData) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/levels/" + appId); long randomLong = new Random().nextLong(); //To be able to match // parse given multipart form data JSONObject objResponse = new JSONObject(); int levelnum = 0; String levelname = null; int levelpointvalue = 0; boolean levelnotifcheck = false; String levelnotifmessage = null; Connection conn = null; UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); if (name.equals("anonymous")) { return unauthorizedMessage(); } try { conn = dbm.getConnection(); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_14, "" + randomLong); try { if (!levelAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot create level. App not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } } catch (SQLException e1) { e1.printStackTrace(); objResponse.put("message", "Cannot create level. Cannot check whether application ID exist or not. Database error. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType); FormDataPart partNum = parts.get("levelnum"); if (partNum != null) { levelnum = Integer.parseInt(partNum.getContent()); if (levelAccess.isLevelNumExist(conn, appId, levelnum)) { // level id already exist objResponse.put("message", "Cannot create level. Failed to add the level. levelnum already exist!"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } FormDataPart partName = parts.get("levelname"); if (partName != null) { levelname = partName.getContent(); } FormDataPart partPV = parts.get("levelpointvalue"); if (partPV != null) { // optional description text input form element levelpointvalue = Integer.parseInt(partPV.getContent()); } FormDataPart partNotificationCheck = parts.get("levelnotificationcheck"); if (partNotificationCheck != null) { // checkbox is checked levelnotifcheck = true; } else { levelnotifcheck = false; } FormDataPart partNotificationMsg = parts.get("levelnotificationmessage"); if (partNotificationMsg != null) { levelnotifmessage = partNotificationMsg.getContent(); } else { levelnotifmessage = ""; } LevelModel model = new LevelModel(levelnum, levelname, levelpointvalue, levelnotifcheck, levelnotifmessage); try { levelAccess.addNewLevel(conn, appId, model); objResponse.put("message", "Level upload success (" + levelnum + ")"); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_15, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24, "" + name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_25, "" + appId); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot create level. Failed to upload " + levelnum + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } else { objResponse.put("message", "Cannot create level. Level number cannot be null!"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } catch (MalformedStreamException e) { // the stream failed to follow required syntax objResponse.put("message", "Cannot create level. Failed to upload. " + levelnum + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } catch (IOException e) { // a read or write error occurred objResponse.put("message", "Cannot create level. Failed to upload " + levelnum + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot create level. Failed to upload " + levelnum + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (NullPointerException e) { e.printStackTrace(); objResponse.put("message", "Cannot create level. Failed to upload " + levelnum + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // always close connections finally { try { conn.close(); } catch (SQLException e) { logger.printStackTrace(e); } } }
From source file:org.eclipse.hono.service.registration.BaseRegistrationService.java
private Future<EventBusMessage> processDeregisterRequest(final EventBusMessage request) { final String tenantId = request.getTenant(); final String deviceId = request.getDeviceId(); if (tenantId == null || deviceId == null) { return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST)); } else {//from w w w . jav a 2 s .c om log.debug("deregistering device [{}] of tenant [{}]", deviceId, tenantId); final Future<RegistrationResult> result = Future.future(); removeDevice(tenantId, deviceId, result.completer()); return result.map(res -> { return request.getResponse(res.getStatus()).setDeviceId(deviceId) .setCacheDirective(res.getCacheDirective()); }); } }