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.languagetool.server.LanguageToolHttpHandler.java
@Override public void handle(HttpExchange httpExchange) throws IOException { long startTime = System.currentTimeMillis(); String remoteAddress = null;// w w w . j a v a 2 s .c o m Map<String, String> parameters = new HashMap<>(); int reqId = reqCounter.incrementRequestCount(); ServerMetricsCollector.getInstance().logRequest(); boolean incrementHandleCount = false; try { URI requestedUri = httpExchange.getRequestURI(); if (requestedUri.getRawPath().startsWith("/v2/")) { // healthcheck should come before other limit checks (requests per time etc.), to be sure it works: String pathWithoutVersion = requestedUri.getRawPath().substring("/v2/".length()); if (pathWithoutVersion.equals("healthcheck")) { if (workQueueFull(httpExchange, parameters, "Healthcheck failed: There are currently too many parallel requests.")) { ServerMetricsCollector.getInstance().logFailedHealthcheck(); return; } else { String ok = "OK"; httpExchange.getResponseHeaders().set("Content-Type", "text/plain"); httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, ok.getBytes(ENCODING).length); httpExchange.getResponseBody().write(ok.getBytes(ENCODING)); ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_OK); return; } } } String referrer = httpExchange.getRequestHeaders().getFirst("Referer"); String origin = httpExchange.getRequestHeaders().getFirst("Origin"); // Referer can be turned off with meta tags, so also check this for (String ref : config.getBlockedReferrers()) { String errorMessage = null; if (ref != null && !ref.isEmpty()) { if (referrer != null && siteMatches(referrer, ref)) { errorMessage = "Error: Access with referrer " + referrer + " denied."; } else if (origin != null && siteMatches(origin, ref)) { errorMessage = "Error: Access with origin " + origin + " denied."; } } if (errorMessage != null) { sendError(httpExchange, HttpURLConnection.HTTP_FORBIDDEN, errorMessage); logError(errorMessage, HttpURLConnection.HTTP_FORBIDDEN, parameters, httpExchange); ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_FORBIDDEN); return; } } String origAddress = httpExchange.getRemoteAddress().getAddress().getHostAddress(); String realAddressOrNull = getRealRemoteAddressOrNull(httpExchange); remoteAddress = realAddressOrNull != null ? realAddressOrNull : origAddress; reqCounter.incrementHandleCount(remoteAddress, reqId); incrementHandleCount = true; // According to the Javadoc, "Closing an exchange without consuming all of the request body is // not an error but may make the underlying TCP connection unusable for following exchanges.", // so we consume the request now, even before checking for request limits: parameters = getRequestQuery(httpExchange, requestedUri); if (requestLimiter != null) { try { requestLimiter.checkAccess(remoteAddress, parameters, httpExchange.getRequestHeaders()); } catch (TooManyRequestsException e) { String errorMessage = "Error: Access from " + remoteAddress + " denied: " + e.getMessage(); int code = HttpURLConnection.HTTP_FORBIDDEN; sendError(httpExchange, code, errorMessage); // already logged vai DatabaseAccessLimitLogEntry logError(errorMessage, code, parameters, httpExchange, false); return; } } if (errorRequestLimiter != null && !errorRequestLimiter.wouldAccessBeOkay(remoteAddress, parameters, httpExchange.getRequestHeaders())) { String textSizeMessage = getTextOrDataSizeMessage(parameters); String errorMessage = "Error: Access from " + remoteAddress + " denied - too many recent timeouts. " + textSizeMessage + " Allowed maximum timeouts: " + errorRequestLimiter.getRequestLimit() + " per " + errorRequestLimiter.getRequestLimitPeriodInSeconds() + " seconds"; int code = HttpURLConnection.HTTP_FORBIDDEN; sendError(httpExchange, code, errorMessage); logError(errorMessage, code, parameters, httpExchange); return; } if (workQueueFull(httpExchange, parameters, "Error: There are currently too many parallel requests. Please try again later.")) { ServerMetricsCollector.getInstance() .logRequestError(ServerMetricsCollector.RequestErrorType.QUEUE_FULL); return; } if (allowedIps == null || allowedIps.contains(origAddress)) { if (requestedUri.getRawPath().startsWith("/v2/")) { ApiV2 apiV2 = new ApiV2(textCheckerV2, config.getAllowOriginUrl()); String pathWithoutVersion = requestedUri.getRawPath().substring("/v2/".length()); apiV2.handleRequest(pathWithoutVersion, httpExchange, parameters, errorRequestLimiter, remoteAddress, config); } else if (requestedUri.getRawPath().endsWith("/Languages")) { throw new IllegalArgumentException( "You're using an old version of our API that's not supported anymore. Please see https://languagetool.org/http-api/migration.php"); } else if (requestedUri.getRawPath().equals("/")) { throw new IllegalArgumentException( "Missing arguments for LanguageTool API. Please see " + API_DOC_URL); } else if (requestedUri.getRawPath().contains("/v2/")) { throw new IllegalArgumentException( "You have '/v2/' in your path, but not at the root. Try an URL like 'http://server/v2/...' "); } else if (requestedUri.getRawPath().equals("/favicon.ico")) { sendError(httpExchange, HttpURLConnection.HTTP_NOT_FOUND, "Not found"); } else { throw new IllegalArgumentException( "This is the LanguageTool API. You have not specified any parameters. Please see " + API_DOC_URL); } } else { String errorMessage = "Error: Access from " + StringTools.escapeXML(origAddress) + " denied"; sendError(httpExchange, HttpURLConnection.HTTP_FORBIDDEN, errorMessage); throw new RuntimeException(errorMessage); } } catch (Exception e) { String response; int errorCode; boolean textLoggingAllowed = false; boolean logStacktrace = true; Throwable rootCause = ExceptionUtils.getRootCause(e); if (e instanceof TextTooLongException || rootCause instanceof TextTooLongException) { errorCode = HttpURLConnection.HTTP_ENTITY_TOO_LARGE; response = e.getMessage(); logStacktrace = false; } else if (e instanceof ErrorRateTooHighException || rootCause instanceof ErrorRateTooHighException) { errorCode = HttpURLConnection.HTTP_BAD_REQUEST; response = ExceptionUtils.getRootCause(e).getMessage(); logStacktrace = false; } else if (hasCause(e, AuthException.class)) { errorCode = HttpURLConnection.HTTP_FORBIDDEN; response = e.getMessage(); logStacktrace = false; } else if (e instanceof IllegalArgumentException || rootCause instanceof IllegalArgumentException) { errorCode = HttpURLConnection.HTTP_BAD_REQUEST; response = e.getMessage(); } else if (e instanceof PathNotFoundException || rootCause instanceof PathNotFoundException) { errorCode = HttpURLConnection.HTTP_NOT_FOUND; response = e.getMessage(); } else if (e instanceof TimeoutException || rootCause instanceof TimeoutException) { errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR; response = "Checking took longer than " + config.getMaxCheckTimeMillis() / 1000.0f + " seconds, which is this server's limit. " + "Please make sure you have selected the proper language or consider submitting a shorter text."; } else { response = "Internal Error: " + e.getMessage(); errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR; textLoggingAllowed = true; } long endTime = System.currentTimeMillis(); logError(remoteAddress, e, errorCode, httpExchange, parameters, textLoggingAllowed, logStacktrace, endTime - startTime); sendError(httpExchange, errorCode, "Error: " + response); } finally { httpExchange.close(); if (incrementHandleCount) { reqCounter.decrementHandleCount(reqId); } } }
From source file:net.ymate.module.webproxy.WebProxy.java
@SuppressWarnings("unchecked") public void transmission(HttpServletRequest request, HttpServletResponse response, String url, Type.HttpMethod method) throws Exception { StopWatch _consumeTime = null;// w ww . java 2 s.co m long _threadId = 0; if (_LOG.isDebugEnabled()) { _consumeTime = new StopWatch(); _consumeTime.start(); _threadId = Thread.currentThread().getId(); _LOG.debug("-------------------------------------------------"); _LOG.debug("--> [" + _threadId + "] URL: " + url); } // HttpURLConnection _conn = null; try { if (__moduleCfg.isUseProxy()) { _conn = (HttpURLConnection) new URL(url).openConnection(__moduleCfg.getProxy()); } else { _conn = (HttpURLConnection) new URL(url).openConnection(); } _conn.setUseCaches(__moduleCfg.isUseCaches()); _conn.setInstanceFollowRedirects(__moduleCfg.isInstanceFollowRedirects()); // boolean _postFlag = Type.HttpMethod.POST.equals(method); boolean _multipartFlag = _postFlag && StringUtils.contains(request.getContentType(), "multipart/"); if (_postFlag) { _conn.setDoOutput(true); _conn.setDoInput(true); _conn.setRequestMethod(method.name()); } if (__moduleCfg.getConnectTimeout() > 0) { _conn.setConnectTimeout(__moduleCfg.getConnectTimeout()); } if (__moduleCfg.getReadTimeout() > 0) { _conn.setReadTimeout(__moduleCfg.getReadTimeout()); } // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Method: " + method.name()); _LOG.debug("--> [" + _threadId + "] Request Headers: "); } // Enumeration _header = request.getHeaderNames(); while (_header.hasMoreElements()) { String _name = (String) _header.nextElement(); String _value = request.getHeader(_name); boolean _flag = false; if (_postFlag && StringUtils.equalsIgnoreCase(_name, "content-type") || __moduleCfg.isTransferHeaderEnabled() && (!__moduleCfg.getTransferHeaderBlackList().isEmpty() && !__moduleCfg.getTransferHeaderBlackList().contains(_name) || !__moduleCfg.getTransferHeaderWhiteList().isEmpty() && __moduleCfg.getTransferHeaderWhiteList().contains(_name))) { _conn.setRequestProperty(_name, _value); _flag = true; } // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _name + ": " + _value); } } _conn.connect(); // if (_postFlag) { DataOutputStream _output = new DataOutputStream(_conn.getOutputStream()); try { if (_multipartFlag) { if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Multipart: TRUE"); } IOUtils.copyLarge(request.getInputStream(), _output); } else { String _charset = request.getCharacterEncoding(); String _queryStr = ParamUtils.buildQueryParamStr(request.getParameterMap(), true, _charset); IOUtils.write(_queryStr, _output, _charset); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Request Parameters: "); Map<String, String> _paramsMap = ParamUtils.parseQueryParamStr(_queryStr, true, _charset); for (Map.Entry<String, String> _param : _paramsMap.entrySet()) { _LOG.debug("--> [" + _threadId + "] \t - " + _param.getKey() + ": " + _param.getValue()); } } } _output.flush(); } finally { IOUtils.closeQuietly(_output); } } // int _code = _conn.getResponseCode(); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Code: " + _code); _LOG.debug("--> [" + _threadId + "] Response Headers: "); } // Map<String, List<String>> _headers = _conn.getHeaderFields(); for (Map.Entry<String, List<String>> _entry : _headers.entrySet()) { if (_entry.getKey() != null) { boolean _flag = false; String _values = StringUtils.join(_entry.getValue(), ","); if (StringUtils.equalsIgnoreCase(_entry.getKey(), "content-type") || __moduleCfg.isTransferHeaderEnabled() && !__moduleCfg.getResponseHeaderWhileList().isEmpty() && __moduleCfg.getResponseHeaderWhileList().contains(_entry.getKey())) { response.setHeader(_entry.getKey(), _values); _flag = true; } if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _entry.getKey() + ": " + _values); } } } if (HttpURLConnection.HTTP_BAD_REQUEST <= _conn.getResponseCode()) { response.sendError(_code); } else { if (HttpURLConnection.HTTP_OK == _code) { InputStream _inputStream = _conn.getInputStream(); if (_inputStream != null) { if (!_multipartFlag) { byte[] _content = IOUtils.toByteArray(_inputStream); IOUtils.write(_content, response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody( _conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding())); } } else { IOUtils.copyLarge(_conn.getInputStream(), response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: MultipartBody"); } } } else if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: NULL"); } response.flushBuffer(); } else { InputStream _inputStream = _conn.getInputStream(); if (_inputStream != null) { byte[] _content = IOUtils.toByteArray(_inputStream); IOUtils.write(_content, response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody(_conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding())); } } else if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: NULL"); } response.setStatus(_code); response.flushBuffer(); } } } catch (Throwable e) { _LOG.warn("An exception occurred while processing request mapping '" + url + "': ", RuntimeUtils.unwrapThrow(e)); } finally { IOUtils.close(_conn); // if (_LOG.isDebugEnabled()) { if (_consumeTime != null) { _consumeTime.stop(); _LOG.debug("--> [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms"); } _LOG.debug("-------------------------------------------------"); } } }
From source file:fi.cosky.sdk.API.java
private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException { URL serverAddress;// ww w . j a v a 2s. com BufferedReader br; String result = ""; HttpURLConnection connection = null; String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri(); try { String method = l.getMethod(); String type = l.getType(); serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); boolean doOutput = doOutput(method); connection.setDoOutput(doOutput); connection.setRequestMethod(method); connection.setInstanceFollowRedirects(false); if (method.equals("GET") && useMimeTypes) if (type == null || type.equals("")) { addMimeTypeAcceptToRequest(object, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); } if (!useMimeTypes) connection.setRequestProperty("Accept", "application/json"); if (doOutput && useMimeTypes) { //this handles the case if the link is self made and the type field has not been set. if (type == null || type.equals("")) { addMimeTypeContentTypeToRequest(l, tClass, connection); addMimeTypeAcceptToRequest(l, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); connection.addRequestProperty("Content-Type", helper.getSupportedType(type)); } } if (!useMimeTypes) connection.setRequestProperty("Content-Type", "application/json"); if (tokenData != null) { connection.addRequestProperty("Authorization", tokenData.getTokenType() + " " + tokenData.getAccessToken()); } addVersionNumberToHeader(object, url, connection); if (method.equals("POST") || method.equals("PUT")) { String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object. connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + ""); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); osw.write(json); osw.flush(); osw.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) { ResponseData data = new ResponseData(); Link link = parseLocationLinkFromString(connection.getHeaderField("Location")); link.setType(type); data.setLocation(link); connection.disconnect(); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println( "Authentication expired " + connection.getResponseMessage() + " trying to reauthenticate"); if (retry && this.tokenData != null) { this.tokenData = null; retry = false; if (authenticate()) { System.out.println("Reauthentication success, will continue with " + l.getMethod() + " request on " + l.getRel()); return sendRequest(l, tClass, object); } } else throw new IOException( "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API"); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return (T) objectCache.getObject(url); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { return (T) new ResponseData(); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + method); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) { if (retry) { System.out.println("Request caused internal server error, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println("Requst caused internal server error, please contact dev@nfleet.fi"); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_GATEWAY) { if (retry) { System.out.println("Could not connect to NFleet-API, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println( "Could not connect to NFleet-API, please check service status from http://status.nfleet.fi and try again later."); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } catch (SecurityException e) { throw e; } catch (IllegalArgumentException e) { throw e; } finally { assert connection != null; connection.disconnect(); } Object newEntity = gson.fromJson(result, tClass); objectCache.addUri(url, newEntity); return (T) newEntity; }
From source file:org.eclipse.orion.server.tests.servlets.git.GitStatusTest.java
@Test public void testStatusWithPath() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); String projectName = getMethodName(); JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString()); JSONObject testTxt = getChild(project, "test.txt"); modifyFile(testTxt, "file change"); JSONObject folder = getChild(project, "folder"); JSONObject folderTxt = getChild(folder, "folder.txt"); modifyFile(folderTxt, "folder change"); JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT); String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS); // GET /git/status/file/{proj}/ assertStatus(new StatusResult().setModifiedNames("folder/folder.txt", "test.txt") .setModifiedPaths("folder/folder.txt", "test.txt"), gitStatusUri); // GET /git/status/file/{proj}/test.txt WebRequest request = getGetGitStatusRequest(gitStatusUri + "test.txt"); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); gitSection = folder.getJSONObject(GitConstants.KEY_GIT); gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS); // GET /git/status/file/{proj}/folder/ assertStatus(new StatusResult().setModifiedNames("folder/folder.txt", "test.txt") .setModifiedPaths("folder.txt", "../test.txt"), gitStatusUri); }
From source file:rapture.kernel.SearchApiImpl.java
/** * Return the {@link SearchRepository} for the given uri or throw a {@link RaptureException} with an error message * * @param uri//from w w w . ja v a2 s . c om * @return */ private SearchRepository getRepoOrFail(RaptureURI uri) { SearchRepository repo = getRepoFromCache(uri.getAuthority()); if (repo == null) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("NoSuchRepo", uri.toAuthString())); } else { return repo; } }
From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java
/** * Adds a tenant./*from w w w .j ava 2s . c om*/ * * @param tenantId The identifier of the tenant. * @param tenantSpec The information to register for the tenant. * @return The outcome of the operation indicating success or failure. * @throws NullPointerException if any of the parameters are {@code null}. */ public TenantResult<JsonObject> add(final String tenantId, final JsonObject tenantSpec) { Objects.requireNonNull(tenantId); Objects.requireNonNull(tenantSpec); if (tenants.containsKey(tenantId)) { return TenantResult.from(HttpURLConnection.HTTP_CONFLICT); } else { try { final TenantObject tenant = tenantSpec.mapTo(TenantObject.class); tenant.setTenantId(tenantId); final TenantObject conflictingTenant = getByCa(tenant.getTrustedCaSubjectDn()); if (conflictingTenant != null) { // we are trying to use the same CA as an already existing tenant return TenantResult.from(HttpURLConnection.HTTP_CONFLICT); } else { tenants.put(tenantId, tenant); dirty = true; return TenantResult.from(HttpURLConnection.HTTP_CREATED); } } catch (IllegalArgumentException e) { return TenantResult.from(HttpURLConnection.HTTP_BAD_REQUEST); } } }
From source file:rapture.kernel.UserApiImpl.java
@Override public void revokeApiKey(CallingContext context, String appKey, String apiKey) { String testKey = appKey + "/" + apiKey; RaptureUser user = RaptureUserStorage.readByFields(context.getUser()); if (user.getApiKeys().contains(testKey)) { user.getApiKeys().remove(testKey); RaptureUserStorage.add(user, context.getUser(), "Revoked api key"); APIKeyDefinitionStorage.deleteByFields(appKey, apiKey, context.getUser(), "Revoke api key"); } else {// ww w . j a va 2 s. com throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "No api key for this user"); } }
From source file:org.eclipse.orion.server.tests.servlets.users.BasicUsersTest.java
@Test public void testCreateUserEmailDifferentCase() throws IOException, SAXException { WebConversation webConversation = new WebConversation(); webConversation.setExceptionsThrownOnErrorStatus(false); // create user Map<String, String> params = new HashMap<String, String>(); params.put("login", "testCaseEmail"); params.put("Name", "username_testCreateUserDuplicateEmail"); params.put("password", "pass_" + System.currentTimeMillis()); params.put("email", "duplicateemail@example.com"); WebRequest request = getPostUsersRequest("", params, true); WebResponse response = webConversation.getResponse(request); assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode()); //try creating another user with same email address but different case params.put("email", "DUPLICATEEMAIL@example.com"); params.put("login", "testCaseEmail2"); request = getPostUsersRequest("", params, true); response = webConversation.getResponse(request); assertEquals(response.getText(), HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); }
From source file:org.betaconceptframework.astroboa.resourceapi.resource.TopicResource.java
@DELETE @Path("/{topicIdOrName: " + CmsConstants.UUID_OR_SYSTEM_NAME_REG_EXP_FOR_RESTEASY + "}") public Response deleteTopicResource(@PathParam("topicIdOrName") String topicIdOrName) { if (StringUtils.isEmpty(topicIdOrName)) { throw new WebApplicationException(Response.Status.BAD_REQUEST); }/* w w w. j a v a 2s . co m*/ try { boolean topicDeleted = astroboaClient.getTopicService().deleteTopicTree(topicIdOrName); return ContentApiUtils.createResponseForHTTPDelete(topicDeleted, topicIdOrName); } catch (CmsUnauthorizedAccessException e) { throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } catch (Exception e) { logger.error("", e); throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST); } }
From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java
/** * Post a new badge//from w w w. ja va 2 s . c o m * @param appId application id * @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\": \"Badge upload success ( (badgeid) )\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (badgeid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the badge. Badge ID already exist!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Badge ID cannot be null!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (badgeid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (badgeid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Badge upload success ( (badgeid) )}") }) @ApiOperation(value = "createNewBadge", notes = "A method to store a new badge with details (badge ID, badge name, badge description, and badge image") public HttpResponse createNewBadge( @ApiParam(value = "Application ID to store a new badge", required = true) @PathParam("appId") String appId, @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType, @ApiParam(value = "Badge detail in multiple/form-data type", required = true) @ContentParam byte[] formData) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/badges/" + appId); long randomLong = new Random().nextLong(); //To be able to match // parse given multipart form data JSONObject objResponse = new JSONObject(); String filename = null; byte[] filecontent = null; String mimeType = null; String badgeid = null; // Badge ID for the filesystem is appended with app id to make sure it is unique String badgename = null; String badgedescription = null; String badgeImageURI = null; boolean badgeusenotification = false; String badgenotificationmessage = 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 (!badgeAccess.isAppIdExist(conn, appId)) { logger.info("App not found >> "); objResponse.put("message", "Cannot create badge. 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(); logger.info( "Cannot check whether application ID exist or not. Database error. >> " + e1.getMessage()); objResponse.put("message", "Cannot create badge. 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 partBadgeID = parts.get("badgeid"); if (partBadgeID != null) { // these data belong to the (optional) file id text input form element badgeid = partBadgeID.getContent(); if (badgeAccess.isBadgeIdExist(conn, appId, badgeid)) { // Badge id already exist logger.info("Failed to add the badge. Badge ID already exist!"); objResponse.put("message", "Cannot create badge. Failed to add the badge. Badge ID already exist!."); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } FormDataPart partFilecontent = parts.get("badgeimageinput"); if (partFilecontent != null) { System.out.println(partFilecontent.getContent()); // these data belong to the file input form element filename = partFilecontent.getHeader(HEADER_CONTENT_DISPOSITION).getParameter("filename"); byte[] filecontentbefore = partFilecontent.getContentRaw(); // validate input if (filecontentbefore == null) { logger.info("File content null"); objResponse.put("message", "Cannot create badge. File content null. Failed to upload " + badgeid); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } // in unit test, resize image will turn the image into null BufferedImage // but, it works in web browser FormDataPart partDev = parts.get("dev"); if (partDev != null) { filecontent = filecontentbefore; } else { filecontent = resizeImage(filecontentbefore); } mimeType = partFilecontent.getContentType(); logger.info("upload request (" + filename + ") of mime type '" + mimeType + "' with content length " + filecontent.length); } FormDataPart partBadgeName = parts.get("badgename"); if (partBadgeName != null) { badgename = partBadgeName.getContent(); } FormDataPart partDescription = parts.get("badgedesc"); if (partDescription != null) { // optional description text input form element badgedescription = partDescription.getContent(); } FormDataPart partNotificationCheck = parts.get("badgenotificationcheck"); if (partNotificationCheck != null) { // checkbox is checked badgeusenotification = true; } else { badgeusenotification = false; } FormDataPart partNotificationMsg = parts.get("badgenotificationmessage"); if (partNotificationMsg != null) { badgenotificationmessage = partNotificationMsg.getContent(); } else { badgenotificationmessage = ""; } try { storeBadgeDataToSystem(appId, badgeid, filename, filecontent, mimeType, badgedescription); BadgeModel badge = new BadgeModel(badgeid, badgename, badgedescription, badgeusenotification, badgenotificationmessage); try { badgeAccess.addNewBadge(conn, appId, badge); objResponse.put("message", "Badge upload success (" + badgeid + ")"); 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 badge. Failed to upload " + badgeid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } catch (AgentNotKnownException | L2pServiceException | L2pSecurityException | InterruptedException | TimeoutException e) { e.printStackTrace(); objResponse.put("message", "Cannot create badge. Failed to upload " + badgeid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } else { logger.info("Badge ID cannot be null"); objResponse.put("message", "Cannot create badge. Badge 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 badge. Failed to upload " + badgeid + ". " + 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 badge. Failed to upload " + badgeid + ". " + 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 badge. Failed to upload " + badgeid + ". " + e.getMessage()); //L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); L2pLogger.logEvent(this, Event.AGENT_UPLOAD_FAILED, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (NullPointerException e) { e.printStackTrace(); objResponse.put("message", "Cannot create badge. Failed to upload " + badgeid + ". " + 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); } } }