Java Code Examples for javax.servlet.http.HttpServletResponse#SC_INTERNAL_SERVER_ERROR

The following examples show how to use javax.servlet.http.HttpServletResponse#SC_INTERNAL_SERVER_ERROR . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileAppenderHandler.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected boolean handleGet(HttpServletRequest request,
		HttpServletResponse response, ILogService logService, IPath path)
		throws ServletException {

	String appenderName = path.segment(0);
	String parts = request.getParameter("parts"); //$NON-NLS-1$
	boolean metadata = parts != null && "meta".equals(parts); //$NON-NLS-1$

	if (!metadata)
		return downloadLog(request, response, logService, appenderName);

	try {
		return TaskJobHandler.handleTaskJob(request, response,
				new FileAppenderJob(TaskJobHandler.getUserId(request),
						logService, getURI(request), appenderName),
				statusHandler);
	} catch (Exception e) {
		final ServerStatus error = new ServerStatus(IStatus.ERROR,
				HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
				"An error occured when looking for appenders.", e);

		LogHelper.log(error);
		return statusHandler.handleRequest(request, response, error);
	}
}
 
Example 2
Source File: CGIServlet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Parses the Status-Line and extracts the status code.
 *
 * @param line The HTTP Status-Line (RFC2616, section 6.1)
 * @return The extracted status code or the code representing an
 * internal error if a valid status code cannot be extracted.
 */
private int getSCFromHttpStatusLine(String line) {
    int statusStart = line.indexOf(' ') + 1;

    if (statusStart < 1 || line.length() < statusStart + 3) {
        // Not a valid HTTP Status-Line
        log.warn(sm.getString("cgiServlet.runInvalidStatus", line));
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    String status = line.substring(statusStart, statusStart + 3);

    int statusCode;
    try {
        statusCode = Integer.parseInt(status);
    } catch (NumberFormatException nfe) {
        // Not a valid status code
        log.warn(sm.getString("cgiServlet.runInvalidStatus", status));
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    return statusCode;
}
 
Example 3
Source File: AuthorizationService.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Adds the right for the given user to put, post, get, or delete the given URI.
 * @param userId The user name
 * @param uri The URI to grant access to
 * @throws CoreException If an error occurred persisting user rights.
 */
public static void addUserRight(String userId, String uri) throws CoreException {
	try {
		//TODO probably want caller to pass in UserInfo for performance
		UserInfo user = OrionConfiguration.getMetaStore().readUser(userId);
		JSONArray userRightArray = AuthorizationReader.getAuthorizationData(user);

		// adds all rights for the uri
		JSONObject userRight = createUserRight(uri);

		//check if we already have this right
		for (int i = 0; i < userRightArray.length(); i++) {
			if (userRight.toString().equals(userRightArray.get(i).toString()))
				return;
		}

		//add the new right
		userRightArray.put(userRight);

		AuthorizationReader.saveRights(user, userRightArray);
	} catch (Exception e) {
		String msg = "Error persisting user rights";
		throw new CoreException(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
	}
}
 
Example 4
Source File: RouterTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public int setErrorParameter(BeforeEnterEvent event,
        ErrorParameter<IllegalArgumentException> parameter) {
    events.add(event);
    if (parameter.hasCustomMessage()) {
        getElement().setText(parameter.getCustomMessage());
    } else {
        getElement().setText("Illegal argument exception.");
    }
    return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
 
Example 5
Source File: AdminFilter.java    From admin-template with MIT License 5 votes vote down vote up
/**
 * skips faces-resources, index, error or logon pages
 *
 * @param request
 * @return true if resource must be skipped by the filter false otherwise
 */
private boolean skipResource(HttpServletRequest request, HttpServletResponse response) {
    String path = request.getServletPath();
    if (path.contains(".")) {
        path = path.substring(0, path.lastIndexOf("."));
    }
    boolean skip = path.startsWith(FACES_RESOURCES) || shouldIgnoreResource(path) || response.getStatus() == HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    return skip;
}
 
Example 6
Source File: CreateRouteCommand.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected ServerStatus _doIt() {
	try {
		/* create cloud foundry application */
		URI targetURI = URIUtil.toURI(target.getUrl());
		URI routesURI = targetURI.resolve("/v2/routes"); //$NON-NLS-1$

		PostMethod createRouteMethod = new PostMethod(routesURI.toString());
		ServerStatus confStatus = HttpUtil.configureHttpMethod(createRouteMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;

		/* set request body */
		JSONObject routeRequest = new JSONObject();
		routeRequest.put(CFProtocolConstants.V2_KEY_SPACE_GUID, target.getSpace().getCFJSON().getJSONObject(CFProtocolConstants.V2_KEY_METADATA).getString(CFProtocolConstants.V2_KEY_GUID));
		routeRequest.put(CFProtocolConstants.V2_KEY_HOST, hostName);
		routeRequest.put(CFProtocolConstants.V2_KEY_DOMAIN_GUID, domain.getGuid());
		createRouteMethod.setRequestEntity(new StringRequestEntity(routeRequest.toString(), "application/json", "utf-8")); //$NON-NLS-1$//$NON-NLS-2$
		createRouteMethod.setQueryString("inline-relations-depth=1"); //$NON-NLS-1$

		ServerStatus createRouteStatus = HttpUtil.executeMethod(createRouteMethod);
		if (!createRouteStatus.isOK())
			return createRouteStatus;

		route = new Route().setCFJSON(createRouteStatus.getJsonData());

		return createRouteStatus;
	} catch (Exception e) {
		String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
		logger.error(msg, e);
		return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
	}
}
 
Example 7
Source File: EndpointsMethodHandlerTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void fail_findService() throws Exception {
  EndpointMethod method = systemService.resolveService("TestEndpoint", "simple");
  ApiMethodConfig methodConfig = new ApiMethodConfig(method, typeLoader,
      apiConfig.getApiClassConfig());
  systemService = SystemService.builder()
      .withDefaults(classLoader)
      .addService(ArrayEndpoint.class, new ArrayEndpoint())
      .build();
  TestMethodHandler handler = new TestMethodHandler(
      ServletInitializationParameters.builder().build(), method,
      methodConfig, systemService, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RESOURCE);
  handler.getRestHandler().handle(context);
}
 
Example 8
Source File: ArchivaDavResource.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Override
public void copy( DavResource destination, boolean shallow )
    throws DavException
{
    if ( !exists() )
    {
        throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
    }

    if ( shallow && isCollection() )
    {
        throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
    }

    try
    {
        ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
        if ( isCollection() )
        {
            repositoryStorage.copyAsset( asset, destination.getResourcePath() );

            triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
        }
        else
        {
            repositoryStorage.copyAsset( asset, destination.getResourcePath() );

            triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
        }

        log.debug( "{}{}' copied to '{}' (current user '{}')", ( isCollection() ? "Directory '" : "File '" ),
                   asset.getPath(), destination, this.principal );

    }
    catch ( IOException e )
    {
        throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
    }
}
 
Example 9
Source File: GetStackByNameCommand.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected ServerStatus _doIt() {
	try {
		URI targetURI = URIUtil.toURI(target.getUrl());
		URI servicesURI = targetURI.resolve("/v2/stacks"); //$NON-NLS-0$//$NON-NLS-1$

		GetMethod getStacksMethod = new GetMethod(servicesURI.toString());
		NameValuePair[] params = new NameValuePair[] { //
		new NameValuePair("q", "name:" + stackName), //$NON-NLS-0$ //$NON-NLS-1$
				new NameValuePair("inline-relations-depth", "1") //$NON-NLS-0$ //$NON-NLS-1$
		};
		getStacksMethod.setQueryString(params);

		ServerStatus confStatus = HttpUtil.configureHttpMethod(getStacksMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;

		ServerStatus getStacksStatus = HttpUtil.executeMethod(getStacksMethod);
		if (!getStacksStatus.isOK())
			return getStacksStatus;
		
		JSONObject stacksJSON = getStacksStatus.getJsonData();
		if (stacksJSON.getInt(CFProtocolConstants.V2_KEY_TOTAL_RESULTS) < 1) {
			return getStacksStatus;
		}

		JSONArray resources = stacksJSON.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES);
		JSONObject stackJSON = resources.getJSONObject(0);
		stack = new Stack().setCFJSON(stackJSON);

		return getStacksStatus;
	} catch (Exception e) {
		String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
		logger.error(msg, e);
		return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
	}
}
 
Example 10
Source File: StreamACP.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns an ACP file containing the nodes represented by the given list of NodeRefs.
 * 
 * @param params The parameters for the ACP exporter
 * @param extension The file extenstion to use for the ACP file
 * @param keepFolderStructure Determines whether the folder structure is maintained for
 *        the content inside the ACP file
 * @return File object representing the created ACP
 */
protected File createACP(ExporterCrawlerParameters params, String extension, boolean keepFolderStructure)
{
    try
    {
        // generate temp file and folder name
        File dataFile = new File(GUID.generate());
        File contentDir = new File(GUID.generate());
        
        // setup export package handler
        File acpFile = TempFileProvider.createTempFile(TEMP_FILE_PREFIX, "." + extension);
        ACPExportPackageHandler handler = new ACPExportPackageHandler(new FileOutputStream(acpFile), 
             dataFile, contentDir, this.mimetypeService);
        handler.setExportAsFolders(keepFolderStructure);
        handler.setNodeService(this.nodeService);

        // perform the actual export
        this.exporterService.exportView(handler, params, null);
        
        if (logger.isDebugEnabled())
            logger.debug("Created temporary archive: " + acpFile.getAbsolutePath());
        
        return acpFile;
    }
    catch (FileNotFoundException fnfe)
    {
        throw new WebScriptException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 
                    "Failed to create archive", fnfe);
    }
}
 
Example 11
Source File: CommonsEntityProvider.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@EntityCustomAction(action = "savePermissions", viewKey = EntityView.VIEW_NEW)
public String handleSavePermissions(EntityView view, Map<String, Object> params) {

    String userId = getCheckedUser();

    String siteId = (String) params.get("siteId");

    if (sakaiProxy.setPermissionsForSite(siteId, params)) {
        return "success";
    } else {
        throw new EntityException("Failed to set perms", "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
 
Example 12
Source File: OptionsEndpointFilter.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
void writeErrorResponse(HttpServletResponse httpServletResponse, RuntimeException e) throws IOException {
    Response errorResponse;
    int statusCode;
    if (e instanceof InsufficientAuthenticationException) {
        errorResponse = new ErrorResponse("Anonymous access is prohibited");
        statusCode = HttpServletResponse.SC_FORBIDDEN;
    } else {
        errorResponse = new ErrorResponse("The server encountered an internal error");
        statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }
    String errorResponseText = jsonConverter.writeValueAsString(errorResponse);
    httpServletResponse.setContentType("application/json");
    httpServletResponse.getWriter().print(errorResponseText);
    httpServletResponse.setStatus(statusCode);
}
 
Example 13
Source File: ArchivaDavResource.java    From archiva with Apache License 2.0 5 votes vote down vote up
private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
    throws DavException
{
    if ( !( resource instanceof ArchivaDavResource ) )
    {
        throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "DavResource is not instance of ArchivaDavResource" );
    }
    return (ArchivaDavResource) resource;
}
 
Example 14
Source File: SalesforceBulkRuntime.java    From components with Apache License 2.0 4 votes vote down vote up
/**
 * Creates and executes job for bulk query. Job must be finished in 2 minutes on Salesforce side.<br/>
 * From Salesforce documentation two scenarios are possible here:
 * <ul>
 * <li>simple bulk query. It should have status - {@link BatchStateEnum#Completed}.</li>
 * <li>primary key chunking bulk query. It should return first batch info with status - {@link BatchStateEnum#NotProcessed}.<br/>
 * Other batch info's should have status - {@link BatchStateEnum#Completed}</li>
 * </ul>
 *
 * @param moduleName - input module name.
 * @param queryStatement - to be executed.
 * @throws AsyncApiException
 * @throws InterruptedException
 * @throws ConnectionException
 */
public void doBulkQuery(String moduleName, String queryStatement)
        throws AsyncApiException, InterruptedException, ConnectionException {
    job = new JobInfo();
    job.setObject(moduleName);
    job.setOperation(OperationEnum.query);
    if (concurrencyMode != null) {
        job.setConcurrencyMode(concurrencyMode);
    }
    job.setContentType(ContentType.CSV);
    job = createJob(job);
    if (job.getId() == null) { // job creation failed
        throw new ComponentException(new DefaultErrorCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "failedBatch"),
                ExceptionContext.build().put("failedBatch", job));
    }

    ByteArrayInputStream bout = new ByteArrayInputStream(queryStatement.getBytes());
    BatchInfo info = createBatchFromStream(job, bout);
    int secToWait = 1;
    int tryCount = 0;
    while (true) {
        LOGGER.debug("Awaiting " + secToWait + " seconds for results ...\n" + info);
        Thread.sleep(secToWait * 1000);
        info = getBatchInfo(job.getId(), info.getId());

        if (info.getState() == BatchStateEnum.Completed
                || (BatchStateEnum.NotProcessed == info.getState() && 0 < chunkSize)) {
            break;
        } else if (info.getState() == BatchStateEnum.Failed) {
            throw new ComponentException(new DefaultErrorCode(HttpServletResponse.SC_BAD_REQUEST, "failedBatch"),
                    ExceptionContext.build().put("failedBatch", info));
        }
        tryCount++;
        if (tryCount % 3 == 0 && secToWait < 120) {// after 3 attempt to get the result we multiply the time to wait by 2
            secToWait = secToWait * 2; // if secToWait < 120 : don't increase exponentially, no need to sleep more than 128 seconds
        }

        // The user can specify a global timeout for the job processing to suites some bulk limits :
        // https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/asynch_api_concepts_limits.htm
        if(jobTimeOut > 0) { // if 0, timeout is disabled
            long processingTime = System.currentTimeMillis() - job.getCreatedDate().getTimeInMillis();
            if (processingTime > jobTimeOut) {
                throw new ComponentException(
                        new DefaultErrorCode(HttpServletResponse.SC_REQUEST_TIMEOUT, "failedBatch"),
                        ExceptionContext.build().put("failedBatch", info));
            }
        }
    }

    retrieveResultsOfQuery(info);
}
 
Example 15
Source File: InvalidUploadOffsetException.java    From tus-java-server with MIT License 4 votes vote down vote up
public InvalidUploadOffsetException(String message) {
    super(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
}
 
Example 16
Source File: GetAppByGuidCommand.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
public ServerStatus _doIt() {
	try {
		URI targetURI = URIUtil.toURI(getCloud().getUrl());

		// Get the app
		URI appsURI = targetURI.resolve("/v2/apps/" + appGuid);
		GetMethod getAppsMethod = new GetMethod(appsURI.toString());
		ServerStatus confStatus = HttpUtil.configureHttpMethod(getAppsMethod, getCloud());
		if (!confStatus.isOK())
			return confStatus;

		ServerStatus getStatus = HttpUtil.executeMethod(getAppsMethod);
		if (!getStatus.isOK())
			return getStatus;

		JSONObject app = getStatus.getJsonData();

		//			if (!apps.has("resources") || apps.getJSONArray("resources").length() == 0)
		//				return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "Application not found", null);

		// Get more details about the app
		JSONObject appJSON = app.getJSONObject("metadata");

		String summaryAppUrl = appJSON.getString("url") + "/summary";
		URI summaryAppURI = targetURI.resolve(summaryAppUrl);

		GetMethod getSummaryMethod = new GetMethod(summaryAppURI.toString());
		confStatus = HttpUtil.configureHttpMethod(getSummaryMethod, getCloud());
		if (!confStatus.isOK())
			return confStatus;

		getStatus = HttpUtil.executeMethod(getSummaryMethod);
		if (!getStatus.isOK())
			return getStatus;

		JSONObject summaryJSON = getStatus.getJsonData();

		this.app = new App();
		this.app.setAppJSON(appJSON);
		this.app.setSummaryJSON(summaryJSON);
		this.app.setGuid(appJSON.getString("guid"));
		this.app.setName(summaryJSON.getString("name"));

		return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, this.app.toJSON());
	} catch (Exception e) {
		String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
		logger.error(msg, e);
		return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
	}
}
 
Example 17
Source File: CreateApplicationCommand.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected ServerStatus _doIt() {
	try {
		// get stack object
		Object stackId = JSONObject.NULL;
		if (stack != null){
			GetStackByNameCommand getStackCommand = new GetStackByNameCommand(target, stack);
			ServerStatus getStackStatus = (ServerStatus) getStackCommand.doIt();
			if (!getStackStatus.isOK())
				return getStackStatus;
			if (getStackCommand.getStack() == null)
				return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, NLS.bind("Stack {0} not found", stack), null);
			stackId = getStackCommand.getStack().getGuid();
		}

		/* create cloud foundry application */
		URI targetURI = URIUtil.toURI(target.getUrl());
		URI appsURI = targetURI.resolve("/v2/apps"); //$NON-NLS-1$

		PostMethod createAppMethod = new PostMethod(appsURI.toString());
		ServerStatus confStatus = HttpUtil.configureHttpMethod(createAppMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;

		/* set request body */
		JSONObject createAppRequst = new JSONObject();
		createAppRequst.put(CFProtocolConstants.V2_KEY_SPACE_GUID, target.getSpace().getCFJSON().getJSONObject(CFProtocolConstants.V2_KEY_METADATA).getString(CFProtocolConstants.V2_KEY_GUID));
		createAppRequst.put(CFProtocolConstants.V2_KEY_NAME, appName);
		createAppRequst.put(CFProtocolConstants.V2_KEY_INSTANCES, appInstances);
		createAppRequst.put(CFProtocolConstants.V2_KEY_BUILDPACK, buildPack != null ? buildPack : JSONObject.NULL);
		createAppRequst.put(CFProtocolConstants.V2_KEY_COMMAND, appCommand);
		createAppRequst.put(CFProtocolConstants.V2_KEY_MEMORY, appMemory);
		createAppRequst.put(CFProtocolConstants.V2_KEY_STACK_GUID, stackId);
		createAppRequst.put(CFProtocolConstants.V2_KEY_ENVIRONMENT_JSON, env != null ? env : new JSONObject());

		createAppMethod.setRequestEntity(new StringRequestEntity(createAppRequst.toString(), "application/json", "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$

		ServerStatus status = HttpUtil.executeMethod(createAppMethod);
		if (!status.isOK())
			return status;

		/* extract application guid */
		JSONObject appResp = status.getJsonData();
		application.setGuid(appResp.getJSONObject(CFProtocolConstants.V2_KEY_METADATA).getString(CFProtocolConstants.V2_KEY_GUID));
		application.setName(appName);

		return status;

	} catch (Exception e) {
		String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
		logger.error(msg, e);
		return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
	}
}
 
Example 18
Source File: HiveException.java    From devicehive-java-server with Apache License 2.0 4 votes vote down vote up
public HiveException(String message, Throwable cause, Integer code) {
    super(message, cause);
    this.code = code != null ? code : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
 
Example 19
Source File: GetAppCommand.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
public ServerStatus _doIt() {
	try {
		List<Object> key = Arrays.asList(target, name);
		app = appCache.get(key);
		if (app != null) {
			return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, this.app.toJSON());
		}
		URI targetURI = URIUtil.toURI(target.getUrl());

		// Find the app
		String appsUrl = target.getSpace().getCFJSON().getJSONObject("entity").getString("apps_url");
		URI appsURI = targetURI.resolve(appsUrl);
		GetMethod getAppsMethod = new GetMethod(appsURI.toString());
		ServerStatus confStatus = HttpUtil.configureHttpMethod(getAppsMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;
		
		getAppsMethod.setQueryString("q=name:" + URLEncoder.encode(name, "UTF8") + "&inline-relations-depth=1");

		ServerStatus getStatus = HttpUtil.executeMethod(getAppsMethod);
		if (!getStatus.isOK())
			return getStatus;

		JSONObject apps = getStatus.getJsonData();

		if (!apps.has("resources") || apps.getJSONArray("resources").length() == 0)
			return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "Application not found", null);

		// Get more details about the app
		JSONObject appJSON = apps.getJSONArray("resources").getJSONObject(0).getJSONObject("metadata");

		String summaryAppUrl = appJSON.getString("url") + "/summary";
		URI summaryAppURI = targetURI.resolve(summaryAppUrl);

		GetMethod getSummaryMethod = new GetMethod(summaryAppURI.toString());
		confStatus = HttpUtil.configureHttpMethod(getSummaryMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;

		getStatus = HttpUtil.executeMethod(getSummaryMethod);
		if (!getStatus.isOK())
			return getStatus;

		JSONObject summaryJSON = getStatus.getJsonData();
		
		// instances
		String instancesUrl = appJSON.getString("url") + "/instances";
		URI instancesURI = targetURI.resolve(instancesUrl);

		GetMethod getInstancesMethod = new GetMethod(instancesURI.toString());
		confStatus = HttpUtil.configureHttpMethod(getInstancesMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;

		getStatus = HttpUtil.executeMethod(getInstancesMethod);
		JSONObject instancesJSON = getStatus.getJsonData();

		this.app = new App();
		this.app.setAppJSON(appJSON);
		this.app.setSummaryJSON(summaryJSON);
		this.app.setName(summaryJSON.getString("name"));
		this.app.setGuid(summaryJSON.getString("guid"));
		appCache.put(key, app);
		
		JSONObject result = this.app.toJSON();
		result.put("instances_details", instancesJSON);

		return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, this.app.toJSON());
	} catch (Exception e) {
		String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
		logger.error(msg, e);
		return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
	}
}
 
Example 20
Source File: ServerLogout.java    From aceql-http with GNU Lesser General Public License v2.1 2 votes vote down vote up
public static void logout(HttpServletRequest request, HttpServletResponse response,
    DatabaseConfigurator databaseConfigurator) throws IOException {

PrintWriter out = response.getWriter();

try {
    response.setContentType("text/html");

    String username = request.getParameter(HttpParameter.USERNAME);
    String sessionId = request.getParameter(HttpParameter.SESSION_ID);

    SessionConfigurator sessionConfigurator = ServerSqlManager.getSessionManagerConfigurator();
    sessionConfigurator.remove(sessionId);

    Set<Connection> connections = ConnectionStore.getAllConnections(username, sessionId);

    for (Connection connection : connections) {
	// ConnectionCloser.freeConnection(connection, databaseConfigurator);
	databaseConfigurator.close(connection);
    }

    ConnectionStore.removeAll(username, sessionId);

    deleteOldBlobFiles(databaseConfigurator, username);

    String jSonReturn = JsonOkReturn.build();

    if (DEBUG) {
	System.err.println("jSonReturn: " + jSonReturn);
	System.err.println(sessionId);
    }

    out.println(jSonReturn);

} catch (Exception e) {

    JsonErrorReturn errorReturn = new JsonErrorReturn(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
	    JsonErrorReturn.ERROR_ACEQL_FAILURE, e.getMessage(), ExceptionUtils.getStackTrace(e));
    out.println(errorReturn.build());

}
   }