Example usage for java.net HttpURLConnection HTTP_INTERNAL_ERROR

List of usage examples for java.net HttpURLConnection HTTP_INTERNAL_ERROR

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_INTERNAL_ERROR.

Prototype

int HTTP_INTERNAL_ERROR

To view the source code for java.net HttpURLConnection HTTP_INTERNAL_ERROR.

Click Source Link

Document

HTTP Status-Code 500: Internal Server Error.

Usage

From source file:com.netflix.genie.server.resources.ApplicationConfigResource.java

/**
 * Update the configuration files for a given application.
 *
 * @param id      The id of the application to update the configuration files
 *                for. Not null/empty/blank.
 * @param configs The configuration files to replace existing configuration
 *                files with. Not null/empty/blank.
 * @return The new set of application configurations.
 * @throws GenieException For any error// w w w .  ja  v  a 2 s. c om
 */
@PUT
@Path("/{id}/configs")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update configuration files for an application", notes = "Replace the existing configuration files for application with given id.", response = String.class, responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Application not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid ID supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Set<String> updateConfigsForApplication(
        @ApiParam(value = "Id of the application to update configurations for.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The configuration files to replace existing with.", required = true) final Set<String> configs)
        throws GenieException {
    LOG.info("Called with id " + id + " and configs " + configs);
    return this.applicationConfigService.updateConfigsForApplication(id, configs);
}

From source file:com.netflix.genie.server.resources.ClusterConfigResource.java

/**
 * Update the configuration files for a given cluster.
 *
 * @param id      The id of the cluster to update the configuration files for.
 *                Not null/empty/blank.//w  ww .  ja v a  2s.c o m
 * @param configs The configuration files to replace existing configuration
 *                files with. Not null/empty/blank.
 * @return The new set of cluster configurations.
 * @throws GenieException For any error
 */
@PUT
@Path("/{id}/configs")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update configuration files for an cluster", notes = "Replace the existing configuration files for cluster with given id.", response = String.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Cluster not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Set<String> updateConfigsForCluster(
        @ApiParam(value = "Id of the cluster to update configurations for.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The configuration files to replace existing with.", required = true) final Set<String> configs)
        throws GenieException {
    LOG.info("Called with id " + id + " and configs " + configs);
    return this.clusterConfigService.updateConfigsForCluster(id, configs);
}

From source file:i5.las2peer.services.gamificationActionService.GamificationActionService.java

/**
 * Get an action data with specific ID from database
 * @param appId applicationId//w  w  w.  ja  v  a2s.co  m
 * @param actionId action id
 * @return HttpResponse returned as JSON object
 */
@GET
@Path("/{appId}/{actionId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found an action"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "Find action for specific App ID and action ID", notes = "Returns a action", response = ActionModel.class, authorizations = @Authorization(value = "api_key"))
public HttpResponse getActionWithId(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Action ID") @PathParam("actionId") String actionId) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "GET " + "gamification/actions/" + appId + "/" + actionId);
    long randomLong = new Random().nextLong(); //To be able to match 

    ActionModel action = null;
    Connection conn = null;

    JSONObject objResponse = new JSONObject();
    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_16, "" + randomLong);

        try {

            try {
                if (!actionAccess.isAppIdExist(conn, appId)) {
                    objResponse.put("message", "Cannot get action. App not found");
                    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
                objResponse.put("message",
                        "Cannot get action. Cannot check whether application ID exist or not. Database error. "
                                + e1.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
            if (!actionAccess.isActionIdExist(conn, appId, actionId)) {
                objResponse.put("message", "Cannot get action. Action not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
            action = actionAccess.getActionWithId(conn, appId, actionId);
            if (action != null) {
                ObjectMapper objectMapper = new ObjectMapper();
                //Set pretty printing of json
                objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

                String actionString = objectMapper.writeValueAsString(action);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_17, "" + randomLong);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_26, "" + name);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_27, "" + appId);
                return new HttpResponse(actionString, HttpURLConnection.HTTP_OK);
            } else {
                objResponse.put("message", "Cannot get action. Cannot find badge with " + actionId);
                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 get action. DB Error. " + e.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

        }

    } catch (JsonProcessingException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get action. JSON processing error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get action. DB Error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

From source file:org.wso2.carbon.registry.app.RegistryResolver.java

/**
 * Method to identify the response target for the request.
 *
 * @param request the request.// w  ww  .  ja v a  2s  .  c  o m
 *
 * @return the response target.
 */
public Target resolve(Request request) {
    RequestContext context = (RequestContext) request;
    final ServletRequestContext requestContext;
    if (context instanceof ServletRequestContext) {
        requestContext = (ServletRequestContext) request;
    } else {
        requestContext = null;
    }
    if (embeddedRegistryService == null) {
        if (requestContext != null) {
            embeddedRegistryService = (EmbeddedRegistryService) requestContext.getRequest().getSession()
                    .getServletContext().getAttribute("registry");
        }
        if (embeddedRegistryService == null) {
            String msg = "Error in retrieving the embedded registry service.";
            log.error(msg);
        }
    }

    //TODO (reg-sep) 
    UserRegistry registry = null;
    String uri = context.getUri().toString();
    String loggedIn = null;
    if (requestContext != null) {
        loggedIn = ((ServletRequestContext) request).getRequest().getParameter("loggedIn");
    }
    if (loggedIn != null) {
        String loggedUser = (String) requestContext.getRequest().getSession().getServletContext()
                .getAttribute("logged-user");
        try {
            registry = embeddedRegistryService.getRegistry(loggedUser);
            uri = uri.substring(0, uri.lastIndexOf('?'));
        } catch (RegistryException e) {
            final StringResponseContext response = new StringResponseContext("Unauthorized",
                    HttpURLConnection.HTTP_UNAUTHORIZED);
            response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
            return new ResponseTarget(context, response);
        }
    }

    if (registry == null) {
        // Set up secure registry instance
        String authorizationString = request.getAuthorization();
        if (authorizationString != null) {
            // splitting the Authorization string "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
            String values[] = authorizationString.split("\\ ");
            if (values == null || values.length == 0) {
                final StringResponseContext response = new StringResponseContext("Unauthorized",
                        HttpURLConnection.HTTP_UNAUTHORIZED);
                response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
                return new ResponseTarget(context, response);
            } else if ("Basic".equals(values[0])) {
                try {
                    // Decode username/password
                    authorizationString = new String(Base64.decode(values[1]));
                    values = authorizationString.split("\\:");
                    String userName = values[0];
                    String password = values[1];
                    String tenantDomain = (String) ((ServletRequestContext) request).getRequest()
                            .getAttribute(MultitenantConstants.TENANT_DOMAIN);
                    int tenantId;
                    String userNameAlong;
                    if (tenantDomain == null
                            || MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                        tenantId = getTenantId(userName);
                        userNameAlong = getUserName(userName);
                    } else {
                        tenantId = getTenantIdFromDomain(tenantDomain);
                        userNameAlong = userName;
                    }
                    registry = embeddedRegistryService.getRegistry(userNameAlong, password, tenantId);
                } catch (Exception e) {
                    final StringResponseContext response = new StringResponseContext("Unauthorized",
                            HttpURLConnection.HTTP_UNAUTHORIZED);
                    response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
                    return new ResponseTarget(context, response);
                }
            } else {
                // TODO - return an ExceptionTarget which contains the authentication problem
                // return new ExceptionTarget(400, "Only basic authentication is supported!");
                return null;
            }
        } else {
            String tenantDomain = (String) requestContext.getRequest()
                    .getAttribute(MultitenantConstants.TENANT_DOMAIN);
            int calledTenantId = MultitenantConstants.SUPER_TENANT_ID;
            if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                if (RegistryContext.getBaseInstance().getRealmService() == null) {
                    String msg = "Error in getting the tenant manager. "
                            + "The realm service is not available.";
                    log.error(msg);
                    return new ResponseTarget(context, new EmptyResponseContext(400, msg));
                }
                TenantManager tenantManager = RegistryContext.getBaseInstance().getRealmService()
                        .getTenantManager();
                try {
                    calledTenantId = tenantManager.getTenantId(tenantDomain);
                } catch (org.wso2.carbon.user.api.UserStoreException e) {
                    String msg = "Error in converting tenant domain to the id for tenant domain: "
                            + tenantDomain + ".";
                    log.error(msg, e);
                    return new ResponseTarget(context, new EmptyResponseContext(400, msg));
                }
                try {
                    if (!tenantManager.isTenantActive(calledTenantId)) {
                        // the tenant is not active.
                        String msg = "The tenant is not active. tenant domain: " + tenantDomain + ".";
                        log.error(msg);
                        return new ResponseTarget(context, new EmptyResponseContext(400, msg));
                    }
                } catch (org.wso2.carbon.user.api.UserStoreException e) {
                    String msg = "Error in converting tenant domain to the id for tenant domain: "
                            + tenantDomain + ".";
                    log.error(msg, e);
                    return new ResponseTarget(context, new EmptyResponseContext(400, msg));
                }
                RegistryContext.getBaseInstance().getRealmService().getBootstrapRealmConfiguration();

            }
            String anonUser = CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME;
            try {
                registry = embeddedRegistryService.getRegistry(anonUser, calledTenantId);
            } catch (RegistryException e) {
                String msg = "Error in creating the registry.";
                log.error(msg, e);
                return new ResponseTarget(context, new EmptyResponseContext(400, msg));
            }
        }
    }

    // Squirrel this away so the adapter can get it later (after all that work we just did!)
    context.setAttribute("userRegistry", registry);

    final String method = context.getMethod();

    /*
    Following code moved further down
    try {
    uri = URLDecoder.decode(uri, "utf-8");
    } catch (UnsupportedEncodingException e) {
    log.error(e);
    return null;
    } */

    if (uri.startsWith(RegistryConstants.PATH_SEPARATOR + RegistryConstants.REGISTRY_INSTANCE
            + RegistryConstants.PATH_SEPARATOR + RegistryConstants.REGISTRY_INSTANCE)) {
        //if ROOT war is renamed to 'registry', uri will look like following,
        //'/registry/registry/foo/bar'
        //Hence,we need to remove the first 'registry'
        uri = uri.replaceFirst(RegistryConstants.PATH_SEPARATOR + RegistryConstants.REGISTRY_INSTANCE, "");
    }

    // URI will start with the baseURI, which we need to strip off.

    String[] excludeStartArr = { basePath + APPConstants.ATOM, basePath + APPConstants.RESOURCE,
            basePath + "/tags" };

    if (basePath == null) {
        log.error("Base path is null. Aborting the operation.");
        final StringResponseContext response = new StringResponseContext("Internal Server Error",
                HttpURLConnection.HTTP_INTERNAL_ERROR);
        return new ResponseTarget(context, response);

    } else if (!basePath.equals("")) {
        for (String excludeStartStr : excludeStartArr) {
            // URI will start with the baseURI, which we need to strip off.
            if (uri.indexOf(excludeStartStr) > -1
                    && uri.length() > uri.indexOf(excludeStartStr) + basePath.length()) {
                uri = uri.substring(uri.indexOf(excludeStartStr) + basePath.length());
                break;
            }
        }
    }

    if (!uri.startsWith(RegistryConstants.PATH_SEPARATOR + RegistryConstants.REGISTRY_INSTANCE)) {
        uri = uri.substring(uri.indexOf(RegistryConstants.PATH_SEPARATOR));
    }
    context.setAttribute("pathInfo", uri);
    String[] parts = splitPath(uri); // splits with "\;"
    boolean hasColon = false;
    TargetType type = null;

    // Let's just see if this is an import first - in which case we can just send it
    // on through.

    if (parts.length > 1) {
        String discriminator = parts[1];

        // If this is a version request, don't do anything special.  Otherwise process.
        if (discriminator.startsWith("version:")) {
            if (parts.length > 2) {
                // Make sure this is a restore.
                if (parts[2].equals("restore")) {
                    type = RESTORE_TYPE;
                    uri = parts[0] + RegistryConstants.URL_SEPARATOR + parts[1];
                } else if (parts[2].equals(APPConstants.ASSOCIATIONS)) {
                    type = ASSOCIATIONS_TYPE;
                    uri = parts[0] + RegistryConstants.URL_SEPARATOR + parts[1];
                } else {
                    // There's an extra semicolon here somewhere.
                    return null;
                }
            }
        } else {
            // Store the split URL for later
            context.setAttribute(APPConstants.PARAMETER_SPLIT_PATH, parts);
            int idx = discriminator.indexOf('?');
            if (idx > -1) {
                discriminator = discriminator.substring(0, idx);
            }

            String suffix = null;
            idx = discriminator.indexOf(':');
            if (idx > -1) {
                suffix = discriminator.substring(idx + 1, discriminator.length());
                discriminator = discriminator.substring(0, idx);
                hasColon = true;
            }

            if (discriminator.startsWith("aspect")) {
                type = ASPECT_TYPE;
            } else {
                type = types.get(discriminator);
            }

            if (discriminator.equals("tag") && method.equals("DELETE") && hasColon) {
                context.setAttribute("tagName", suffix);
                type = DELETE_TYPE;
            } else if (discriminator.equals("comment") && method.equals("DELETE") && hasColon) {
                context.setAttribute("commentId", suffix);
                type = DELETE_TYPE;
            } else if (discriminator.equals("ratings") && hasColon) {
                context.setAttribute("ratingUser", suffix);
                type = RATINGS_TYPE;
            }

            // If we have a discriminator that we don't understand, return a 404
            if (type == null) {
                return null;
            }

            // For the rest of this code, we'll want the "raw" resource URI
            if (!hasColon
                    || !(type.equals(COMMENTS_TYPE) || type.equals(RATINGS_TYPE) || type.equals(TAGS_TYPE))) {
                uri = parts[0];
            }
            if (hasColon && type.equals(TAGS_TYPE)) {
                type = null;
            }
        }
    }

    int idx = uri.indexOf('?');
    if (idx > -1) {
        String queryString = uri.substring(idx + 1, uri.length());
        context.setAttribute("queryString", queryString);
        uri = uri.substring(0, idx);
    }

    try {
        uri = URLDecoder.decode(uri, RegistryConstants.DEFAULT_CHARSET_ENCODING);
    } catch (UnsupportedEncodingException e) {
        log.error(e);
        return null;
    }

    boolean isMedia = false;
    if (uri.startsWith(APPConstants.RESOURCE)) {
        uri = uri.substring(APPConstants.RESOURCE.length());
        isMedia = true;
    } else if (uri.startsWith(APPConstants.ATOM)) {
        uri = uri.substring(APPConstants.ATOM.length());
    } else if (uri.startsWith("/tags") && (uri.length() == 5 || uri.charAt(5) == '/')) {
        return new SimpleTarget(TAG_URL_TYPE, context);
    } else {
        return null;
    }

    if (uri.length() == 0) {
        uri = "/";
    }

    // See if we're asking for a paginated collection
    String startParam = context.getParameter("start");
    String pageLenParam = context.getParameter("pageLen");
    int start = (startParam == null) ? -1 : Integer.parseInt(startParam);
    int pageLen = (pageLenParam == null) ? -1 : Integer.parseInt(pageLenParam);

    Resource resource = null;
    if (type != null && type.equals(DUMP_TYPE) && method != null && method.equals("POST")) {
        // for restoring a dump we don't need to have available resource
        // here we will create a fake resource to store the path

        resource = new ResourceImpl();
        ((ResourceImpl) resource).setPath(uri);
    } else {
        // in a restore, path don't need to exist.
        CurrentSession.setUserRealm(registry.getUserRealm());
        CurrentSession.setUser(registry.getUserName());
        try {
            if (!AuthorizationUtils.authorize(RegistryUtils.getAbsolutePath(registry.getRegistryContext(), uri),
                    ActionConstants.GET)) {
                final StringResponseContext response = new StringResponseContext("Unauthorized",
                        HttpURLConnection.HTTP_UNAUTHORIZED);
                response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
                return new ResponseTarget(context, response);
            } else if (start > -1 || pageLen > -1) {
                resource = registry.get(uri, start, pageLen);
            } else {
                resource = registry.get(uri);
            }
        } catch (AuthorizationFailedException e) {
            final StringResponseContext response = new StringResponseContext("Unauthorized",
                    HttpURLConnection.HTTP_UNAUTHORIZED);
            response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
            return new ResponseTarget(context, response);
        } catch (ResourceNotFoundException e) {
            // If this is a straight-ahead POST to a non-existent directory, create it?
            if (method.equals("POST") && parts.length == 1) {
                // Need to create it.
                try {
                    Collection c = registry.newCollection();
                    registry.put(uri, c);
                    resource = registry.get(uri);
                } catch (RegistryException e1) {
                    log.error(e1);
                    return null;
                }
            }
            if (resource == null) {
                return null;
            }
        } catch (RegistryException e) {
            return null; // return 404
        } finally {
            CurrentSession.removeUser();
            CurrentSession.removeUserRealm();
        }

        if (method.equals("GET")) {
            // eTag based conditional get
            String ifNonMatchValue = context.getHeader("if-none-match");
            if (ifNonMatchValue != null) {
                String currentETag = Utils.calculateEntityTag(resource);
                if (ifNonMatchValue.equals(currentETag)) {
                    /* the version is not modified */
                    ResponseContext response = new StringResponseContext("Not Modified",
                            HttpURLConnection.HTTP_NOT_MODIFIED);
                    return new ResponseTarget(context, response);
                }
            }

            // date based conditional get
            long ifModifiedSinceValue = 0;
            Date ifModifiedSince = context.getDateHeader("If-Modified-Since");
            if (ifModifiedSince != null) {
                ifModifiedSinceValue = ifModifiedSince.getTime();
            }

            if (ifModifiedSinceValue > 0) {
                long lastModifiedValue = resource.getLastModified().getTime();
                // convert the time values from milliseconds to seconds
                ifModifiedSinceValue /= 1000;
                lastModifiedValue /= 1000;

                /* condition to check we have latest updates in terms of dates */
                if (ifModifiedSinceValue >= lastModifiedValue) {
                    /* no need to response with data */
                    ResponseContext response = new StringResponseContext("Not Modified",
                            HttpURLConnection.HTTP_NOT_MODIFIED);
                    return new ResponseTarget(context, response);
                }
            }
        }
    }
    context.setAttribute("MyResolver", this);
    if (type == null) {
        if (method.equals("DELETE")) {
            // Unfortunately, deletions aren't quite handled the way we want them
            // in AbstractEntityCollectionProvider, so for now we're using an
            // extensionRequest to get it done.
            type = DELETE_TYPE;
        } else {
            if (resource instanceof Collection) {
                if (method.equals("HEAD") || method.equals("PUT")) {
                    // Abdera doesn't handle HEAD or PUT on collections yet. this should
                    // go away once that's fixed!
                    type = COLLECTION_CUSTOM_TYPE;
                } else {
                    type = TargetType.TYPE_COLLECTION;
                }
            } else {
                type = isMedia ? TargetType.TYPE_MEDIA : TargetType.TYPE_ENTRY;
            }
        }
    }

    return new ResourceTarget(type, context, resource);
}

From source file:com.netflix.genie.server.resources.JobResource.java

/**
 * Update the tags for a given job.//from  w ww . j a  v  a2s . co m
 *
 * @param id   The id of the job to update the tags for.
 *             Not null/empty/blank.
 * @param tags The tags to replace existing configuration
 *             files with. Not null/empty/blank.
 * @return The new set of job tags.
 * @throws GenieException For any error
 */
@PUT
@Path("/{id}/tags")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update tags for a job", notes = "Replace the existing tags for job with given id.", response = String.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Job for id does not exist."),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid id supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Set<String> updateTagsForJob(
        @ApiParam(value = "Id of the job to update tags for.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The tags to replace existing with.", required = true) final Set<String> tags)
        throws GenieException {
    LOG.info("Called with id " + id + " and tags " + tags);
    return this.jobService.updateTagsForJob(id, tags);
}

From source file:com.netflix.genie.server.services.impl.GenieExecutionServiceImpl.java

/** {@inheritDoc} */
@Override/*  ww  w .j ava 2 s.c o m*/
public JobStatusResponse killJob(String jobId) {
    logger.info("called for jobId: " + jobId);

    JobStatusResponse response;

    JobInfoElement jInfo;
    try {
        jInfo = pm.getEntity(jobId, JobInfoElement.class);
    } catch (Exception e) {
        logger.error("Failed to get job results from database: ", e);
        response = new JobStatusResponse(
                new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage()));
        return response;
    }

    // do some basic error handling
    if (jInfo == null) {
        String msg = "Job not found: " + jobId;
        logger.error(msg);
        response = new JobStatusResponse(new CloudServiceException(HttpURLConnection.HTTP_NOT_FOUND, msg));
        return response;
    }

    // check if it is done already
    if (jInfo.getStatus().equalsIgnoreCase("SUCCEEDED") || jInfo.getStatus().equalsIgnoreCase("KILLED")
            || jInfo.getStatus().equalsIgnoreCase("FAILED")) {
        // job already exited, return status to user
        response = new JobStatusResponse();
        response.setStatus(jInfo.getStatus());
        response.setMessage("Job " + jobId + " is already done");
        return response;
    } else if (jInfo.getStatus().equalsIgnoreCase("INIT") || (jInfo.getProcessHandle() == -1)) {
        // can't kill a job if it is still initializing
        String msg = "Unable to kill job as it is still initializing: " + jobId;
        logger.error(msg);
        response = new JobStatusResponse(new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, msg));
        return response;
    }

    // if we get here, job is still running - and can be killed

    // redirect to the right node if killURI points to a different node
    String killURI = jInfo.getKillURI();
    if (killURI == null) {
        String msg = "Failed to get killURI for jobID: " + jobId;
        logger.error(msg);
        response = new JobStatusResponse(new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, msg));
        return response;
    }
    String localURI;
    try {
        localURI = getEndPoint() + "/" + jobResourcePrefix + "/" + jobId;
    } catch (CloudServiceException e) {
        logger.error("Error while retrieving local hostname: " + e.getMessage(), e);
        response = new JobStatusResponse(e);
        return response;
    }
    if (!killURI.equals(localURI)) {
        logger.debug("forwarding kill request to: " + killURI);
        response = forwardJobKill(killURI);
        return response;
    }

    // if we get here, killURI == localURI, and job should be killed here
    logger.debug("killing job on same instance: " + jobId);
    try {
        JobManagerFactory.getJobManager(jInfo.getJobType()).kill(jInfo);
    } catch (Exception e) {
        logger.error("Failed to kill job: ", e);
        response = new JobStatusResponse(new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR,
                "Failed to kill job: " + e.getCause()));
        return response;
    }

    jInfo.setJobStatus(JobStatus.KILLED, "Job killed on user request");
    jInfo.setExitCode(SubprocessStatus.JOB_KILLED.code());

    // increment counter for killed jobs
    stats.incrGenieKilledJobs();

    // update final status in DB
    ReentrantReadWriteLock rwl = PersistenceManager.getDbLock();
    try {
        logger.debug("updating job status to KILLED for: " + jobId);
        // acquire write lock first, and then update status
        // if job status changed between when it was read and now,
        // this thread will simply overwrite it - final state will be KILLED
        rwl.writeLock().lock();
        jInfo.setUpdateTime(System.currentTimeMillis());
        if (!jInfo.getDisableLogArchival()) {
            jInfo.setArchiveLocation(NetUtil.getArchiveURI(jobId));
        }
        pm.updateEntity(jInfo);
        rwl.writeLock().unlock();
    } catch (Exception e) {
        logger.error("Failed to update job status in database: ", e);
        response = new JobStatusResponse(
                new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage()));

        // unlock before returning response
        if (rwl.writeLock().isHeldByCurrentThread()) {
            rwl.writeLock().unlock();
        }
        return response;
    }

    // all good - return results
    response = new JobStatusResponse();
    response.setStatus(jInfo.getStatus());
    response.setMessage("Successfully killed job: " + jobId);
    return response;
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitCloneTest.java

@Test
public void testCloneNotGitRepository() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = getWorkspaceId(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = new Path("file").append(workspaceId).append(project.getString(ProtocolConstants.KEY_NAME))
            .makeAbsolute();/* ww  w  . j  a  v a 2 s.c  o  m*/

    // clone
    IPath randomLocation = AllGitTests.getRandomLocation();
    assertNull(GitUtils.getGitDir(randomLocation.toFile()));
    WebRequest request = getPostGitCloneRequest(randomLocation.toFile().toURI().toString(), clonePath);
    WebResponse response = webConversation.getResponse(request);
    ServerStatus status = waitForTask(response);
    assertFalse(status.toString(), status.isOK());

    assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, status.getHttpCode());
    assertEquals("Error cloning git repository", status.getMessage());
    assertNotNull(status.getJsonData());
    assertEquals(status.toString(), "Invalid remote: origin", status.getException().getMessage());

    // we don't know ID of the clone that failed to be created, so we're checking if none has been added
    JSONArray clonesArray = listClones(workspaceId, null);
    assertEquals(0, clonesArray.length());
}

From source file:fi.cosky.sdk.API.java

private <T extends BaseData> T sendRequestWithAddedHeaders(Verb verb, String url, Class<T> tClass,
        Object object, HashMap<String, String> headers) throws IOException {
    URL serverAddress;/* w w  w.j ava2s. c  o  m*/
    HttpURLConnection connection;
    BufferedReader br;
    String result = "";
    try {
        serverAddress = new URL(url);
        connection = (HttpURLConnection) serverAddress.openConnection();
        connection.setInstanceFollowRedirects(false);
        boolean doOutput = doOutput(verb);
        connection.setDoOutput(doOutput);
        connection.setRequestMethod(method(verb));
        connection.setRequestProperty("Authorization", headers.get("authorization"));
        connection.addRequestProperty("Accept", "application/json");

        if (doOutput) {
            connection.addRequestProperty("Content-Length", "0");
            OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream());
            os.write("");
            os.flush();
            os.close();
        }
        connection.connect();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER
                || connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
            Link location = parseLocationLinkFromString(connection.getHeaderField("Location"));
            Link l = new Link("self", "/tokens", "GET", "", true);
            ArrayList<Link> links = new ArrayList<Link>();
            links.add(l);
            links.add(location);
            ResponseData data = new ResponseData();
            data.setLocation(location);
            data.setLinks(links);
            return (T) data;
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            System.out.println("Authentication expired: " + connection.getResponseMessage());
            if (retry && this.tokenData != null) {
                retry = false;
                this.tokenData = null;
                if (authenticate()) {
                    System.out.println(
                            "Reauthentication success, will continue with " + verb + " request on " + url);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                }
            } else
                throw new IOException(
                        "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API");
        }

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST
                && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) {
            System.out.println("ErrorCode: " + connection.getResponseCode() + " "
                    + connection.getResponseMessage() + " " + url + ", verb: " + verb);

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class);
        } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) {
            if (retry) {
                System.out.println("Server responded with internal server error, trying again in "
                        + RETRY_WAIT_TIME + " msec.");
                try {
                    retry = false;
                    Thread.sleep(RETRY_WAIT_TIME);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                } catch (InterruptedException e) {

                }
            } else {
                System.out.println("Server responded with internal server error, please contact dev@nfleet.fi");
            }

            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;
    }
    return (T) gson.fromJson(result, tClass);
}

From source file:com.netflix.genie.server.resources.CommandConfigResource.java

/**
 * Delete the all configuration files from a given command.
 *
 * @param id The id of the command to delete the configuration files from.
 *           Not null/empty/blank./*from   w  w w  .  ja va2s .  co  m*/
 * @return Empty set if successful
 * @throws GenieException For any error
 */
@DELETE
@Path("/{id}/configs")
@ApiOperation(value = "Remove all configuration files from an command", notes = "Remove all the configuration files from the command with given id.", response = String.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Command not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Set<String> removeAllConfigsForCommand(
        @ApiParam(value = "Id of the command to delete from.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called with id " + id);
    return this.commandConfigService.removeAllConfigsForCommand(id);
}

From source file:i5.las2peer.services.gamificationAchievementService.GamificationAchievementService.java

/**
 * Get an achievement data with specific ID from database
 * @param appId applicationId//from   w ww .  ja va  2s  .c  o  m
 * @param achievementId achievement id
 * @return HttpResponse returned as JSON object
 */
@GET
@Path("/{appId}/{achievementId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found an achievement"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getAchievementWithId", notes = "Get achievement data with specified ID", response = AchievementModel.class)
public HttpResponse getAchievementWithId(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Achievement ID") @PathParam("achievementId") String achievementId) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "GET " + "gamification/achievements/" + appId + "/" + achievementId);
    long randomLong = new Random().nextLong(); //To be able to match 

    AchievementModel achievement = null;
    Connection conn = null;

    JSONObject objResponse = new JSONObject();
    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_16, "" + randomLong);

        try {

            try {
                if (!achievementAccess.isAppIdExist(conn, appId)) {
                    objResponse.put("message", "Cannot get achievement detail. App not found");
                    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
                objResponse.put("message",
                        "Cannot get achievement detail. 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);
            }
            if (!achievementAccess.isAchievementIdExist(conn, appId, achievementId)) {
                objResponse.put("message", "Cannot get achievement detail. Achievement not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
            achievement = achievementAccess.getAchievementWithId(conn, appId, achievementId);
            if (achievement == null) {
                objResponse.put("message", "Achievement Null, Cannot find achievement with " + achievementId);
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
            ObjectMapper objectMapper = new ObjectMapper();
            //Set pretty printing of json
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

            String achievementString = objectMapper.writeValueAsString(achievement);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_17, "" + randomLong);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_26, "" + name);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_27, "" + appId);

            return new HttpResponse(achievementString, HttpURLConnection.HTTP_OK);
        } catch (SQLException e) {
            e.printStackTrace();
            objResponse.put("message", "Cannot get achievement detail. DB Error. " + e.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

        }

    } catch (JsonProcessingException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get achievement detail. JSON processing error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot get achievement. Failed to fetch " + achievementId + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    }
}