List of usage examples for java.net HttpURLConnection HTTP_UNAUTHORIZED
int HTTP_UNAUTHORIZED
To view the source code for java.net HttpURLConnection HTTP_UNAUTHORIZED.
Click Source Link
From source file:org.openmrs.module.odkconnector.serialization.processor.HttpProcessor.java
/** * Process any stream connection to this module * * @param inputStream the input stream//from w w w .j a v a 2 s. c o m * @param outputStream the output stream * @throws Exception when the stream processing failed */ @Override public void process(final InputStream inputStream, final OutputStream outputStream) throws Exception { GZIPInputStream gzipInputStream = new GZIPInputStream(new BufferedInputStream(inputStream)); DataInputStream dataInputStream = new DataInputStream(gzipInputStream); String username = dataInputStream.readUTF(); String password = dataInputStream.readUTF(); Boolean savedSearch = dataInputStream.readBoolean(); Integer cohortId = 0; Integer programId = 0; if (StringUtils.equalsIgnoreCase(getAction(), HttpProcessor.PROCESS_PATIENTS)) { cohortId = dataInputStream.readInt(); programId = dataInputStream.readInt(); } dataInputStream.close(); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(new BufferedOutputStream(outputStream)); DataOutputStream dataOutputStream = new DataOutputStream(gzipOutputStream); try { Context.openSession(); Context.authenticate(username, password); dataOutputStream.writeInt(HttpURLConnection.HTTP_OK); dataOutputStream.flush(); if (log.isDebugEnabled()) { log.debug("Saved Search Value: " + savedSearch); log.debug("Cohort ID: " + cohortId); log.debug("Program ID: " + programId); } Serializer serializer = HandlerUtil.getPreferredHandler(Serializer.class, List.class); if (StringUtils.equalsIgnoreCase(getAction(), HttpProcessor.PROCESS_PATIENTS)) { ConnectorService connectorService = Context.getService(ConnectorService.class); Cohort cohort = new Cohort(); if (savedSearch) { CohortSearchHistory history = new CohortSearchHistory(); PatientSearchReportObject patientSearchReportObject = (PatientSearchReportObject) Context .getReportObjectService().getReportObject(cohortId); if (patientSearchReportObject != null) { if (log.isDebugEnabled()) { log.debug("Object Class: " + patientSearchReportObject.getClass()); log.debug("Object Name: " + patientSearchReportObject.getName()); log.debug("Object Subtype: " + patientSearchReportObject.getSubType()); log.debug("Object Type: " + patientSearchReportObject.getType()); } history.addSearchItem(PatientSearch.createSavedSearchReference(cohortId)); cohort = history.getPatientSet(0, null); } } else { cohort = Context.getCohortService().getCohort(cohortId); } if (log.isDebugEnabled()) log.debug("Cohort data: " + cohort.getMemberIds()); log.info("Streaming patients information!"); serializer.write(dataOutputStream, connectorService.getCohortPatients(cohort)); // check the concept list Collection<Concept> concepts = null; ConceptConfiguration conceptConfiguration = connectorService.getConceptConfiguration(programId); if (conceptConfiguration != null) { if (log.isDebugEnabled()) log.debug("Printing concept configuration information: " + conceptConfiguration); concepts = ConnectorUtils.getConcepts(conceptConfiguration.getConfiguredConcepts()); } log.info("Streaming observations information!"); serializer.write(dataOutputStream, connectorService.getCohortObservations(cohort, concepts)); // evaluate and get the applicable form for the patients CohortDefinitionService cohortDefinitionService = Context.getService(CohortDefinitionService.class); ReportingConnectorService reportingService = Context.getService(ReportingConnectorService.class); List<ExtendedDefinition> definitions = reportingService.getAllExtendedDefinition(); EvaluationContext context = new EvaluationContext(); context.setBaseCohort(cohort); Collection intersectedMemberIds = Collections.emptyList(); List<SerializedForm> serializedForms = new ArrayList<SerializedForm>(); for (ExtendedDefinition definition : definitions) { if (definition.containsProperty(ExtendedDefinition.DEFINITION_PROPERTY_FORM)) { if (log.isDebugEnabled()) log.debug("Evaluating: " + definition.getCohortDefinition().getName()); EvaluatedCohort evaluatedCohort = cohortDefinitionService .evaluate(definition.getCohortDefinition(), context); // the cohort could be null, so we don't want to get exception during the intersection process if (cohort != null) intersectedMemberIds = CollectionUtils.intersection(cohort.getMemberIds(), evaluatedCohort.getMemberIds()); if (log.isDebugEnabled()) log.debug("Cohort data after intersection: " + intersectedMemberIds); for (DefinitionProperty definitionProperty : definition.getProperties()) { // skip retired definition property if (definitionProperty.isRetired()) continue; Integer formId = NumberUtils.toInt(definitionProperty.getPropertyValue()); for (Object patientId : intersectedMemberIds) serializedForms.add( new SerializedForm(NumberUtils.toInt(String.valueOf(patientId)), formId)); } } } if (log.isDebugEnabled()) log.debug("Serialized form informations:" + serializedForms); log.info("Streaming forms information!"); serializer.write(dataOutputStream, serializedForms); } else { if (savedSearch) { List<SerializedCohort> serializedCohorts = new ArrayList<SerializedCohort>(); List<AbstractReportObject> objects = Context.getReportObjectService() .getReportObjectsByType(OpenmrsConstants.REPORT_OBJECT_TYPE_PATIENTSEARCH); for (AbstractReportObject object : objects) { SerializedCohort serializedCohort = new SerializedCohort(); serializedCohort.setId(object.getReportObjectId()); serializedCohort.setName(object.getName()); serializedCohorts.add(serializedCohort); } serializer.write(dataOutputStream, serializedCohorts); } else { serializer.write(dataOutputStream, Context.getCohortService().getAllCohorts()); } } dataOutputStream.close(); } catch (Exception e) { log.error("Processing stream failed!", e); dataOutputStream.writeInt(HttpURLConnection.HTTP_UNAUTHORIZED); dataOutputStream.close(); } finally { Context.closeSession(); } }
From source file:org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientFileSystemBrowser.java
protected void runRequest() throws Exception { Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, this.getClass(), "runRequest"); //$NON-NLS-1$ setupProxies();//from w ww . j a v a2 s. c o m // set timeout initHttpClientConnectionManager(); String urlString = directoryOrFile.toString(); CredentialsProvider credProvider = new HttpClientProxyCredentialProvider() { protected Proxy getECFProxy() { return getProxy(); } protected Credentials getNTLMCredentials(Proxy lp) { if (hasForceNTLMProxyOption()) return HttpClientRetrieveFileTransfer.createNTLMCredentials(lp); return null; } }; // setup authentication setupAuthentication(urlString); // setup https host and port setupHostAndPort(credProvider, urlString); headMethod = new HeadMethod(hostConfigHelper.getTargetRelativePath()); headMethod.setFollowRedirects(true); // Define a CredentialsProvider - found that possibility while debugging in org.apache.commons.httpclient.HttpMethodDirector.processProxyAuthChallenge(HttpMethod) // Seems to be another way to select the credentials. headMethod.getParams().setParameter(CredentialsProvider.PROVIDER, credProvider); // set max-age for cache control to 0 for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=249990 headMethod.addRequestHeader("Cache-Control", "max-age=0"); //$NON-NLS-1$//$NON-NLS-2$ headMethod.addRequestHeader("Connection", "Keep-Alive"); //$NON-NLS-1$ //$NON-NLS-2$ long lastModified = 0; long fileLength = -1; connectingSockets.clear(); int code = -1; try { Trace.trace(Activator.PLUGIN_ID, "browse=" + urlString); //$NON-NLS-1$ code = httpClient.executeMethod(getHostConfiguration(), headMethod); Trace.trace(Activator.PLUGIN_ID, "browse resp=" + code); //$NON-NLS-1$ // Check for NTLM proxy in response headers // This check is to deal with bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=252002 boolean ntlmProxyFound = NTLMProxyDetector.detectNTLMProxy(headMethod); if (ntlmProxyFound && !hasForceNTLMProxyOption()) throw new BrowseFileTransferException( "HttpClient Provider is not configured to support NTLM proxy authentication.", //$NON-NLS-1$ HttpClientOptions.NTLM_PROXY_RESPONSE_CODE); if (code == HttpURLConnection.HTTP_OK) { fileLength = headMethod.getResponseContentLength(); lastModified = getLastModifiedTimeFromHeader(); } else if (code == HttpURLConnection.HTTP_NOT_FOUND) { throw new BrowseFileTransferException(NLS.bind("File not found: {0}", urlString), code); //$NON-NLS-1$ } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new BrowseFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code); } else if (code == HttpURLConnection.HTTP_FORBIDDEN) { throw new BrowseFileTransferException("Forbidden", code); //$NON-NLS-1$ } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) { throw new BrowseFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required, code); } else { throw new BrowseFileTransferException( NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE, new Integer(code)), code); } remoteFiles = new IRemoteFile[1]; remoteFiles[0] = new URLRemoteFile(lastModified, fileLength, fileID); } catch (Exception e) { Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, this.getClass(), "runRequest", e); //$NON-NLS-1$ BrowseFileTransferException ex = (BrowseFileTransferException) ((e instanceof BrowseFileTransferException) ? e : new BrowseFileTransferException(NLS .bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT, urlString), e, code)); throw ex; } finally { headMethod.releaseConnection(); } }
From source file:org.eclipse.oomph.setup.internal.core.util.ECFURIHandlerImpl.java
@Override public InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException { if (TEST_IO_EXCEPTION) { File folder = new File(CACHE_FOLDER.toFileString()); if (folder.isDirectory()) { System.out.println("Deleting cache folder: " + folder); IOUtil.deleteBestEffort(folder); }//from ww w . j a va 2s. com throw new IOException("Simulated network problem"); } CacheHandling cacheHandling = getCacheHandling(options); URIConverter uriConverter = getURIConverter(options); URI cacheURI = getCacheFile(uri); String eTag = cacheHandling == CacheHandling.CACHE_IGNORE ? null : getETag(uriConverter, cacheURI); String expectedETag = cacheHandling == CacheHandling.CACHE_IGNORE ? null : getExpectedETag(uri); if (expectedETag != null || cacheHandling == CacheHandling.CACHE_ONLY || cacheHandling == CacheHandling.CACHE_WITHOUT_ETAG_CHECKING) { if (cacheHandling == CacheHandling.CACHE_ONLY || cacheHandling == CacheHandling.CACHE_WITHOUT_ETAG_CHECKING ? eTag != null : expectedETag.equals(eTag)) { try { setExpectedETag(uri, expectedETag); return uriConverter.createInputStream(cacheURI, options); } catch (IOException ex) { // Perhaps another JVM is busy writing this file. // Proceed as if it doesn't exit. } } } String username; String password; String uriString = uri.toString(); Proxy proxy = ProxySetupHelper.getProxy(uriString); if (proxy != null) { username = proxy.getUsername(); password = proxy.getPassword(); } else { username = null; password = null; } IContainer container = createContainer(); AuthorizationHandler authorizatonHandler = getAuthorizatonHandler(options); Authorization authorization = getAuthorizaton(options); int triedReauthorization = 0; for (int i = 0;; ++i) { IRetrieveFileTransferContainerAdapter fileTransfer = container .getAdapter(IRetrieveFileTransferContainerAdapter.class); if (proxy != null) { fileTransfer.setProxy(proxy); if (username != null) { fileTransfer.setConnectContextForAuthentication( ConnectContextFactory.createUsernamePasswordConnectContext(username, password)); } else if (password != null) { fileTransfer.setConnectContextForAuthentication( ConnectContextFactory.createPasswordConnectContext(password)); } } FileTransferListener transferListener = new FileTransferListener(eTag); try { FileTransferID fileTransferID = new FileTransferID(new FileTransferNamespace(), IOUtil.newURI(uriString)); Map<Object, Object> requestOptions = new HashMap<Object, Object>(); requestOptions.put(IRetrieveFileTransferOptions.CONNECT_TIMEOUT, CONNECT_TIMEOUT); requestOptions.put(IRetrieveFileTransferOptions.READ_TIMEOUT, READ_TIMEOUT); if (authorization != null && authorization.isAuthorized()) { requestOptions.put(IRetrieveFileTransferOptions.REQUEST_HEADERS, Collections.singletonMap("Authorization", authorization.getAuthorization())); } fileTransfer.sendRetrieveRequest(fileTransferID, transferListener, requestOptions); } catch (IncomingFileTransferException ex) { throw new IOExceptionWithCause(ex); } try { transferListener.receiveLatch.await(); } catch (InterruptedException ex) { throw new IOExceptionWithCause(ex); } if (transferListener.exception != null) { if (!(transferListener.exception instanceof UserCancelledException)) { if (transferListener.exception.getCause() instanceof SocketTimeoutException && i <= 2) { continue; } if (authorizatonHandler != null && transferListener.exception instanceof IncomingFileTransferException) { // We assume contents can be accessed via the github API https://developer.github.com/v3/repos/contents/#get-contents // That API, for security reasons, does not return HTTP_UNAUTHORIZED, so we need this special case for that host. IncomingFileTransferException incomingFileTransferException = (IncomingFileTransferException) transferListener.exception; int errorCode = incomingFileTransferException.getErrorCode(); if (errorCode == HttpURLConnection.HTTP_UNAUTHORIZED || API_GITHUB_HOST.equals(getHost(uri)) && errorCode == HttpURLConnection.HTTP_NOT_FOUND) { if (authorization == null) { authorization = authorizatonHandler.authorize(uri); if (authorization.isAuthorized()) { --i; continue; } } if (!authorization.isUnauthorizeable() && triedReauthorization++ < 3) { authorization = authorizatonHandler.reauthorize(uri, authorization); if (authorization.isAuthorized()) { --i; continue; } } } } } if (!CacheHandling.CACHE_IGNORE.equals(cacheHandling) && uriConverter.exists(cacheURI, options) && (!(transferListener.exception instanceof IncomingFileTransferException) || ((IncomingFileTransferException) transferListener.exception) .getErrorCode() != HttpURLConnection.HTTP_NOT_FOUND)) { setExpectedETag(uri, transferListener.eTag == null ? eTag : transferListener.eTag); return uriConverter.createInputStream(cacheURI, options); } throw new IOExceptionWithCause(transferListener.exception); } byte[] bytes = transferListener.out.toByteArray(); // In the case of the Github API, the bytes will be JSON that contains a "content" pair containing the Base64 encoding of the actual contents. if (API_GITHUB_HOST.equals(getHost(uri))) { // Find the start tag in the JSON value. String value = new String(bytes, "UTF-8"); int start = value.indexOf(CONTENT_TAG); if (start != -1) { // Find the ending quote of the encoded contents. start += CONTENT_TAG.length(); int end = value.indexOf('"', start); if (end != -1) { // The content is delimited by \n so split on that during the conversion. String content = value.substring(start, end); String[] split = content.split("\\\\n"); // Write the converted bytes to a new stream and process those bytes instead. ByteArrayOutputStream out = new ByteArrayOutputStream(); for (String line : split) { byte[] binary = XMLTypeFactory.eINSTANCE.createBase64Binary(line); out.write(binary); } out.close(); bytes = out.toByteArray(); } } } try { BaseUtil.writeFile(uriConverter, options, cacheURI, bytes); } catch (IORuntimeException ex) { // Ignore attempts to write out to the cache file. // This may collide with another JVM doing exactly the same thing. transferListener.eTag = null; } finally { setETag(uriConverter, cacheURI, transferListener.eTag); } setExpectedETag(uri, transferListener.eTag); Map<Object, Object> response = getResponse(options); if (response != null) { response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, transferListener.lastModified); } ETagMirror etagMirror = (ETagMirror) options.get(ETagMirror.OPTION_ETAG_MIRROR); if (etagMirror != null) { etagMirror.cacheUpdated(uri); } return new ByteArrayInputStream(bytes); } }
From source file:org.apache.hadoop.http.TestHttpServer.java
/** * Verify the administrator access for /logs, /stacks, /conf, /logLevel and * /metrics servlets./* w w w . ja v a 2 s . c o m*/ * * @throws Exception */ @Test public void testAuthorizationOfDefaultServlets() throws Exception { Configuration conf = new Configuration(); conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, true); conf.set(HttpServer.FILTER_INITIALIZER_PROPERTY, DummyFilterInitializer.class.getName()); conf.set(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING, MyGroupsProvider.class.getName()); Groups.getUserToGroupsMappingService(conf); MyGroupsProvider.clearMapping(); MyGroupsProvider.mapping.put("userA", Arrays.asList("groupA")); MyGroupsProvider.mapping.put("userB", Arrays.asList("groupB")); MyGroupsProvider.mapping.put("userC", Arrays.asList("groupC")); MyGroupsProvider.mapping.put("userD", Arrays.asList("groupD")); MyGroupsProvider.mapping.put("userE", Arrays.asList("groupE")); HttpServer myServer = new HttpServer("test", "0.0.0.0", 0, true, conf, new AccessControlList("userA,userB groupC,groupD")); myServer.setAttribute(HttpServer.CONF_CONTEXT_ATTRIBUTE, conf); myServer.start(); int port = myServer.getPort(); String serverURL = "http://localhost:" + port + "/"; for (String servlet : new String[] { "logs", "stacks", "logLevel" }) { for (String user : new String[] { "userA", "userB", "userC", "userD" }) { assertEquals(HttpURLConnection.HTTP_OK, getHttpStatusCode(serverURL + servlet, user)); } assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, getHttpStatusCode(serverURL + servlet, "userE")); } myServer.stop(); }
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 av a 2 s. 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:org.bibsonomy.rest.RestServlet.java
/** * @param request//ww w . j a v a 2 s. c o m * the servletrequest * @param response * the servletresponse * @param method * httpMethod to use, see {@link HttpMethod} * @throws IOException */ private void handle(final HttpServletRequest request, final HttpServletResponse response, final HttpMethod method) throws IOException { log.debug("Incoming Request: " + method.name() + " " + request.getRequestURL() + " from IP " + request.getHeader("x-forwarded-for")); final long start = System.currentTimeMillis(); try { // validate the requesting user's authorization final LogicInterface logic = validateAuthorization(request); // parse the request object to retrieve a list with all items of the // http request final MultiPartRequestParser parser = new MultiPartRequestParser(request); // choose rendering format (defaults to xml) final RenderingFormat renderingFormat = RESTUtils.getRenderingFormatForRequest( request.getParameterMap(), request.getHeader(HeaderUtils.HEADER_ACCEPT), request.getContentType()); // create Context final Reader reader = RESTUtils.getInputReaderForStream(request.getInputStream(), REQUEST_ENCODING); final Context context = new Context(method, getPathInfo(request), renderingFormat, this.urlRenderer, reader, parser.getList(), logic, request.getParameterMap(), additionalInfos); // validate request context.canAccess(); // set some response headers final String userAgent = request.getHeader(HeaderUtils.HEADER_USER_AGENT); log.debug("[USER-AGENT] " + userAgent); response.setContentType(context.getContentType(userAgent)); response.setCharacterEncoding(RESPONSE_ENCODING); // send answer if (method.equals(HttpMethod.POST)) { // if a POST request completes successfully this means that a // resource has been created response.setStatus(HttpServletResponse.SC_CREATED); } else { response.setStatus(HttpServletResponse.SC_OK); } // just define an ByteArrayOutputStream to store all outgoing data final ByteArrayOutputStream cachingStream = new ByteArrayOutputStream(); context.perform(cachingStream); /* * XXX: note: cachingStream.size() != * cachingStream.toString().length() !! the correct value is the * first one! */ response.setContentLength(cachingStream.size()); // some more logging log.debug("Size of output sent:" + cachingStream.size()); final long elapsed = System.currentTimeMillis() - start; log.debug("Processing time: " + elapsed + " ms"); cachingStream.writeTo(response.getOutputStream()); } catch (final AuthenticationException e) { log.warn(e.getMessage()); response.setHeader("WWW-Authenticate", "Basic realm=\"" + RestProperties.getInstance().getBasicRealm() + "\""); sendError(request, response, HttpURLConnection.HTTP_UNAUTHORIZED, e.getMessage()); } catch (final InternServerException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (final NoSuchResourceException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e.getMessage()); } catch (final BadRequestOrResponseException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (final AccessDeniedException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_FORBIDDEN, e.getMessage()); } catch (final ResourceMovedException e) { log.error(e.getMessage()); /* * sending new location TODO: add date using */ response.setHeader("Location", urlRenderer.createHrefForResource(e.getUserName(), e.getNewIntraHash())); sendError(request, response, HttpServletResponse.SC_MOVED_PERMANENTLY, e.getMessage()); } catch (final DatabaseException e) { final StringBuilder returnMessage = new StringBuilder(""); for (final String hash : e.getErrorMessages().keySet()) { for (final ErrorMessage em : e.getErrorMessages(hash)) { log.error(em.toString()); returnMessage.append(em.toString() + "\n "); } } sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, returnMessage.toString()); } catch (final Exception e) { log.error(e, e); // well, lets fetch each and every error... sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:com.flurry.proguard.UploadMapping.java
/** * Ensure that a response had an expected status * * @param response the API response/*from ww w. ja va 2 s .c om*/ * @param validStatuses the list of acceptable statuses */ private static void expectStatus(CloseableHttpResponse response, Integer... validStatuses) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { failWithError("The provided token is expired"); } if (!Arrays.asList(validStatuses).contains(statusCode)) { String responseString; try { responseString = "Response Body: " + EntityUtils.toString(response.getEntity()); } catch (IOException e) { responseString = "IO Exception while reading the response body."; } failWithError("Request failed: {} {}", statusCode, responseString); } }
From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java
/** * Post a new badge//from w w w. j a v a 2 s. c om * @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); } } }
From source file:org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerRestClient.java
public boolean download(String sessionId, String dataspacePath, String path, List<String> includes, List<String> excludes, File outputFile) throws Exception { StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL) .append(addSlashIfMissing(restEndpointURL)).append("data/").append(dataspacePath).append('/'); ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(providerFactory) .build();// w w w.jav a 2s .com ResteasyWebTarget target = client.target(uriTmpl.toString()).path(path); if (includes != null && !includes.isEmpty()) { target = target.queryParam("includes", includes.toArray(new Object[includes.size()])); } if (excludes != null && !excludes.isEmpty()) { target = target.queryParam("excludes", excludes.toArray(new Object[excludes.size()])); } Response response = null; try { response = target.request().header("sessionid", sessionId).acceptEncoding("*", "gzip", "zip").get(); if (response.getStatus() != HttpURLConnection.HTTP_OK) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("Cannot retrieve the file. Status code: %d", response.getStatus()), response); } } if (response.hasEntity()) { InputStream is = response.readEntity(InputStream.class); if (isGZipEncoded(response)) { if (outputFile.exists() && outputFile.isDirectory()) { outputFile = new File(outputFile, response.getHeaderString("x-pds-pathname")); } Zipper.GZIP.unzip(is, outputFile); } else if (isZipEncoded(response)) { Zipper.ZIP.unzip(is, outputFile); } else { File container = outputFile.getParentFile(); if (!container.exists()) { container.mkdirs(); } Files.asByteSink(outputFile).writeFrom(is); } } else { outputFile.createNewFile(); } } finally { if (response != null) { response.close(); } } return true; }