Example usage for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR

List of usage examples for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR.

Prototype

int SC_INTERNAL_SERVER_ERROR

To view the source code for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR.

Click Source Link

Document

Status code (500) indicating an error inside the HTTP server which prevented it from fulfilling the request.

Usage

From source file:de.unirostock.sems.cbarchive.web.servlet.DownloadServlet.java

private void downloadArchive(HttpServletRequest request, HttpServletResponse response, UserManager user,
        String archive) throws IOException {

    // filters for omex extension
    //      ( is just there for the browser to name the downloaded file correctly)
    if (archive.endsWith("." + COMBINEARCHIVE_FILE_EXT))
        // just removes the file extension -> we get the archiveId
        archive = archive.substring(0, archive.length() - (COMBINEARCHIVE_FILE_EXT.length() + 1));

    File archiveFile = null;//from  www  . jav  a2s .co  m
    String archiveName = null;
    try {
        archiveFile = user.getArchiveFile(archive);
        archiveName = user.getArchive(archive, false).getName();
    } catch (FileNotFoundException | CombineArchiveWebException e) {
        LOGGER.warn(e, MessageFormat.format(
                "FileNotFound Exception, while handling donwload request for Archive {1} in Workspace {0}",
                user.getWorkingDir(), archive));
        response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return;
    }

    // set MIME-Type to something downloadable
    response.setContentType("application/octet-stream");

    // set Content-Length
    response.setContentLength((int) archiveFile.length());

    // set the filename of the downloaded file
    response.addHeader("Content-Disposition",
            MessageFormat.format("inline; filename=\"{0}.{1}\"", archiveName, COMBINEARCHIVE_FILE_EXT));

    // print the file to the output stream
    try {
        OutputStream output = response.getOutputStream();
        InputStream input = new FileInputStream(archiveFile);

        // copy the streams
        IOUtils.copy(input, output);

        // flush'n'close
        output.flush();
        output.close();
        input.close();

        response.flushBuffer();
    } catch (IOException e) {
        LOGGER.error(e, MessageFormat.format(
                "IOException, while copying streams by handling donwload request for Archive {1} in Workspace {0}",
                user.getWorkingDir(), archive));
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IOException while sending the file.");
    }
}

From source file:es.logongas.ix3.web.util.ControllerHelper.java

public void exceptionToHttpResponse(Throwable throwable, HttpServletResponse httpServletResponse) {
    try {/* w  ww . j  a  v  a  2 s  .c om*/
        BusinessException businessException = ExceptionUtil.getBusinessExceptionFromThrowable(throwable);

        if (businessException != null) {

            if (businessException instanceof BusinessSecurityException) {
                BusinessSecurityException businessSecurityException = (BusinessSecurityException) businessException;
                Log log = LogFactory.getLog(ControllerHelper.class);
                log.info(businessSecurityException);

                httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                httpServletResponse.setContentType("text/plain; charset=UTF-8");
                if (businessSecurityException.getBusinessMessages().size() > 0) {
                    httpServletResponse.getWriter()
                            .println(businessSecurityException.getBusinessMessages().get(0).getMessage());
                }
            } else if (businessException instanceof BusinessException) {

                httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                httpServletResponse.setContentType("application/json; charset=UTF-8");
                httpServletResponse.getWriter()
                        .println(jsonFactory.getJsonWriter().toJson(businessException.getBusinessMessages()));
            } else {
                Log log = LogFactory.getLog(ControllerHelper.class);
                log.error("Es un tipo de businessException desconocida:", businessException);

                httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                httpServletResponse.setContentType("text/plain");
                businessException.printStackTrace(httpServletResponse.getWriter());
            }

        } else {
            Log log = LogFactory.getLog(ControllerHelper.class);
            log.error("Fall la llamada al servidor:", throwable);

            httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            httpServletResponse.setContentType("text/plain");
            throwable.printStackTrace(httpServletResponse.getWriter());
        }
    } catch (IOException ioException) {
        Log log = LogFactory.getLog(ControllerHelper.class);
        log.error("Fall al devolver la excepcin por la HttpResponse:", ioException);
        log.error("Excepcion original:", throwable);
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}

From source file:io.warp10.standalone.StandaloneDeleteHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    if (target.equals(Constants.API_ENDPOINT_DELETE)) {
        baseRequest.setHandled(true);//from w  w  w.j a  va 2  s.  c  o  m
    } else {
        return;
    }

    //
    // CORS header
    //

    response.setHeader("Access-Control-Allow-Origin", "*");

    long nano = System.nanoTime();

    //
    // Extract DatalogRequest if specified
    //

    String datalogHeader = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_DATALOG));

    DatalogRequest dr = null;

    boolean forwarded = false;

    if (null != datalogHeader) {
        byte[] bytes = OrderPreservingBase64.decode(datalogHeader.getBytes(Charsets.US_ASCII));

        if (null != datalogPSK) {
            bytes = CryptoUtils.unwrap(datalogPSK, bytes);
        }

        if (null == bytes) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid Datalog header.");
            return;
        }

        TDeserializer deser = new TDeserializer(new TCompactProtocol.Factory());

        try {
            dr = new DatalogRequest();
            deser.deserialize(dr, bytes);
        } catch (TException te) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.getMessage());
            return;
        }

        Map<String, String> labels = new HashMap<String, String>();
        labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
        labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
        Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_RECEIVED, labels, 1);

        //
        // Check that the request query string matches the QS in the datalog request
        //

        if (!request.getQueryString().equals(dr.getDeleteQueryString())) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid DatalogRequest.");
            return;
        }

        forwarded = true;
    }

    //
    // TODO(hbs): Extract producer/owner from token
    //

    String token = null != dr ? dr.getToken()
            : request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));

    if (null == token) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing token.");
        return;
    }

    WriteToken writeToken;

    try {
        writeToken = Tokens.extractWriteToken(token);
    } catch (WarpScriptException ee) {
        ee.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ee.getMessage());
        return;
    }

    String application = writeToken.getAppName();
    String producer = Tokens.getUUID(writeToken.getProducerId());
    String owner = Tokens.getUUID(writeToken.getOwnerId());

    //
    // For delete operations, producer and owner MUST be equal
    //

    if (!producer.equals(owner)) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid write token for deletion.");
        return;
    }

    Map<String, String> sensisionLabels = new HashMap<String, String>();
    sensisionLabels.put(SensisionConstants.SENSISION_LABEL_PRODUCER, producer);

    long count = 0;
    long gts = 0;

    Throwable t = null;
    StringBuilder metas = new StringBuilder();

    //
    // Extract start/end
    //

    String startstr = request.getParameter(Constants.HTTP_PARAM_START);
    String endstr = request.getParameter(Constants.HTTP_PARAM_END);

    //
    // Extract selector
    //

    String selector = request.getParameter(Constants.HTTP_PARAM_SELECTOR);

    String minage = request.getParameter(Constants.HTTP_PARAM_MINAGE);

    if (null != minage) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Standalone version does not support the '" + Constants.HTTP_PARAM_MINAGE
                        + "' parameter in delete requests.");
        return;
    }

    boolean dryrun = null != request.getParameter(Constants.HTTP_PARAM_DRYRUN);

    File loggingFile = null;
    PrintWriter loggingWriter = null;

    //
    // Open the logging file if logging is enabled
    //

    if (null != loggingDir) {
        long nanos = null != dr ? dr.getTimestamp() : TimeSource.getNanoTime();
        StringBuilder sb = new StringBuilder();
        sb.append(Long.toHexString(nanos));
        sb.insert(0, "0000000000000000", 0, 16 - sb.length());
        sb.append("-");
        if (null != dr) {
            sb.append(dr.getId());
        } else {
            sb.append(datalogId);
        }

        sb.append("-");
        sb.append(dtf.print(nanos / 1000000L));
        sb.append(Long.toString(1000000L + (nanos % 1000000L)).substring(1));
        sb.append("Z");

        if (null == dr) {
            dr = new DatalogRequest();
            dr.setTimestamp(nanos);
            dr.setType(Constants.DATALOG_DELETE);
            dr.setId(datalogId);
            dr.setToken(token);
            dr.setDeleteQueryString(request.getQueryString());
        }

        if (null != dr && (!forwarded || (forwarded && this.logforwarded))) {
            //
            // Serialize the request
            //

            TSerializer ser = new TSerializer(new TCompactProtocol.Factory());

            byte[] encoded;

            try {
                encoded = ser.serialize(dr);
            } catch (TException te) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.getMessage());
                return;
            }

            if (null != this.datalogPSK) {
                encoded = CryptoUtils.wrap(this.datalogPSK, encoded);
            }

            encoded = OrderPreservingBase64.encode(encoded);

            loggingFile = new File(loggingDir, sb.toString());
            loggingWriter = new PrintWriter(new FileWriterWithEncoding(loggingFile, Charsets.UTF_8));

            //
            // Write request
            //

            loggingWriter.println(new String(encoded, Charsets.US_ASCII));
        }
    }

    boolean validated = false;

    try {
        if (null == producer || null == owner) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
            return;
        }

        //
        // Build extra labels
        //

        Map<String, String> extraLabels = new HashMap<String, String>();
        //
        // Only set owner and potentially app, producer may vary
        //      
        extraLabels.put(Constants.OWNER_LABEL, owner);
        // FIXME(hbs): remove me
        if (null != application) {
            extraLabels.put(Constants.APPLICATION_LABEL, application);
            sensisionLabels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, application);
        }

        boolean hasRange = false;

        long start = Long.MIN_VALUE;
        long end = Long.MAX_VALUE;

        if (null != startstr) {
            if (null == endstr) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Both " + Constants.HTTP_PARAM_START + " and " + Constants.HTTP_PARAM_END
                                + " should be defined.");
                return;
            }
            if (startstr.contains("T")) {
                start = fmt.parseDateTime(startstr).getMillis() * Constants.TIME_UNITS_PER_MS;
            } else {
                start = Long.valueOf(startstr);
            }
        }

        if (null != endstr) {
            if (null == startstr) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Both " + Constants.HTTP_PARAM_START + " and " + Constants.HTTP_PARAM_END
                                + " should be defined.");
                return;
            }
            if (endstr.contains("T")) {
                end = fmt.parseDateTime(endstr).getMillis() * Constants.TIME_UNITS_PER_MS;
            } else {
                end = Long.valueOf(endstr);
            }
        }

        if (Long.MIN_VALUE == start && Long.MAX_VALUE == end
                && null == request.getParameter(Constants.HTTP_PARAM_DELETEALL)) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Parameter "
                    + Constants.HTTP_PARAM_DELETEALL + " should be set when deleting a full range.");
            return;
        }

        if (Long.MIN_VALUE != start || Long.MAX_VALUE != end) {
            hasRange = true;
        }

        if (start > end) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Invalid time range specification.");
            return;
        }

        //
        // Extract the class and labels selectors
        // The class selector and label selectors are supposed to have
        // values which use percent encoding, i.e. explicit percent encoding which
        // might have been re-encoded using percent encoding when passed as parameter
        //
        //

        Matcher m = EgressFetchHandler.SELECTOR_RE.matcher(selector);

        if (!m.matches()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        String classSelector = URLDecoder.decode(m.group(1), "UTF-8");
        String labelsSelection = m.group(2);

        Map<String, String> labelsSelectors;

        try {
            labelsSelectors = GTSHelper.parseLabelsSelectors(labelsSelection);
        } catch (ParseException pe) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, pe.getMessage());
            return;
        }

        validated = true;

        //
        // Force 'producer'/'owner'/'app' from token
        //

        labelsSelectors.putAll(extraLabels);

        List<Metadata> metadatas = null;

        List<String> clsSels = new ArrayList<String>();
        List<Map<String, String>> lblsSels = new ArrayList<Map<String, String>>();
        clsSels.add(classSelector);
        lblsSels.add(labelsSelectors);

        metadatas = directoryClient.find(clsSels, lblsSels);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/plain");

        PrintWriter pw = response.getWriter();
        StringBuilder sb = new StringBuilder();

        for (Metadata metadata : metadatas) {
            //
            // Remove from DB
            //

            if (!hasRange) {
                if (!dryrun) {
                    this.directoryClient.unregister(metadata);
                }
            }

            //
            // Remove data
            //

            long localCount = 0;

            if (!dryrun) {
                localCount = this.storeClient.delete(writeToken, metadata, start, end);
            }

            count += localCount;

            sb.setLength(0);
            GTSHelper.metadataToString(sb, metadata.getName(), metadata.getLabels());

            if (metadata.getAttributesSize() > 0) {
                GTSHelper.labelsToString(sb, metadata.getAttributes());
            } else {
                sb.append("{}");
            }

            pw.write(sb.toString());
            pw.write("\r\n");
            metas.append(sb);
            metas.append("\n");
            gts++;

            // Log detailed metrics for this GTS owner and app
            Map<String, String> labels = new HashMap<>();
            labels.put(SensisionConstants.SENSISION_LABEL_OWNER,
                    metadata.getLabels().get(Constants.OWNER_LABEL));
            labels.put(SensisionConstants.SENSISION_LABEL_APPLICATION,
                    metadata.getLabels().get(Constants.APPLICATION_LABEL));
            Sensision.update(
                    SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_DATAPOINTS_PEROWNERAPP,
                    labels, localCount);
        }
    } catch (Exception e) {
        t = e;
        throw e;
    } finally {
        if (null != loggingWriter) {
            Map<String, String> labels = new HashMap<String, String>();
            labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                    OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
            labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
            Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_LOGGED, labels, 1);

            loggingWriter.close();
            if (validated) {
                loggingFile.renameTo(new File(loggingFile.getAbsolutePath() + DatalogForwarder.DATALOG_SUFFIX));
            } else {
                loggingFile.delete();
            }
        }

        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_REQUESTS,
                sensisionLabels, 1);
        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_GTS, sensisionLabels,
                gts);
        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_DATAPOINTS,
                sensisionLabels, count);
        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_TIME_US,
                sensisionLabels, (System.nanoTime() - nano) / 1000);

        LoggingEvent event = LogUtil.setLoggingEventAttribute(null, LogUtil.DELETION_TOKEN, token);
        event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_SELECTOR, selector);
        event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_START, startstr);
        event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_END, endstr);
        event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_METADATA, metas.toString());
        event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_COUNT, Long.toString(count));
        event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_GTS, Long.toString(gts));

        LogUtil.addHttpHeaders(event, request);

        if (null != t) {
            LogUtil.setLoggingEventStackTrace(null, LogUtil.STACK_TRACE, t);
        }

        LOG.info(LogUtil.serializeLoggingEvent(this.keyStore, event));
    }

    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.google.gsa.valve.rootAuth.RootAuthenticationProcess.java

/**
 * This is the main method that drives the whole authentication 
 * process. It launches each individual authentication method declared in 
 * the configuration files. Those that includes the tag "checkauthN" set to 
 * false are not processed.//from w  w w .  j  a v  a 2 s  .  c  o m
 * <p>
 * The name of the authentication classes that need to be processed are included 
 * in a vector that is reused multiple times. Whenever a new authentication 
 * process needs to be relaunched, all these classes are processed and the 
 * individual authentication process is treated.
 * <p>
 * It returns the HTTP error code associated to the process result. If it was 
 * OK, this methods returns a 200 and 401 (unauthorized) otherwise.
 * <p>
 * There is a special repository named "root" that is treatly in a special way. 
 * If any repository is named as "root", it means this is the main authentication 
 * mechanim and that's why it's trated first. If it fails, the authentication 
 * process stops here and the return result is an error. If not, the whole 
 * processing continues.
 * <p>
 * If there is a "root" repository and the authentication process for this 
 * repository is OK, although any other repository would fail, the overall 
 * authentication method returns an OK. If there is not such a "root" 
 * repository, any authentication error will cause the authentication process 
 * to fail.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    // Initialize status code
    int rootStatusCode = HttpServletResponse.SC_UNAUTHORIZED;
    int repositoryAuthStatusCode = HttpServletResponse.SC_UNAUTHORIZED;
    //Check if authn is Ok in multiple repository
    boolean repositoryOKAuthN = false;

    //clear authCookies
    authCookies.clear();

    boolean rootAuthNDefined = false;
    logger.debug("AuthN authenticate [" + url + "]");

    //Read vars
    if (valveConf != null) {
        isKerberos = new Boolean(valveConf.getKrbConfig().isKerberos()).booleanValue();
        if (isKerberos) {
            isNegotiate = new Boolean(valveConf.getKrbConfig().isNegotiate()).booleanValue();
        }
        loginUrl = valveConf.getLoginUrl();
    } else {
        logger.error("Configuration error: Config file is not present");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Configuration error - Kerberos is not set properly");
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    //ValveHost: it's the same URL as the login page, without 
    String valveHost = loginUrl.substring(0, loginUrl.lastIndexOf("/") + 1);

    RE internal = new RE(valveHost, RE.MATCH_CASEINDEPENDENT);

    // The host and URL of the GSA for the search
    //TODO add support for multiple GSA's
    RE query = new RE("/search", RE.MATCH_CASEINDEPENDENT);

    //Request has come from the same host as the valve, so must be the login authenticate
    if (internal.match(url)) {

        //Authentication vars
        String repositoryID = null;
        AuthenticationProcessImpl authProcess = null;
        ValveRepositoryConfiguration repositoryConfig = null;

        int order = 1;
        int size = authenticationImplementationsOrder.size();
        if (authenticationImplementationsOrder == null) {
            order = 0;
            logger.error(
                    "No Authentication module has been defined. Please check and add those needed at config file");
        }

        while ((1 <= order) && (order <= size)) {

            //Get the repository ID
            logger.debug("###Processing repository # " + order + " ###");
            Integer orderInt = new Integer(order);
            if (authenticationImplementationsOrder.containsKey(orderInt)) {
                repositoryID = authenticationImplementationsOrder.get(orderInt);
            } else {
                logger.error("Error during processing authentication methods. Order is not valid");
                break;
            }

            //Get the Repository config and authentication class                                                    
            authProcess = authenticationImplementations.get(repositoryID);
            repositoryConfig = valveConf.getRepository(repositoryID);

            logger.debug("Authenticating ID: " + repositoryConfig.getId());
            if (repositoryConfig.getId().equals("root")) {
                //Root should be used for main authentication against an identity repository (LDAP, DB, ..)
                //and should not be used as a content repository that contains documents
                try {
                    //add support to cookie array
                    rootAuthCookies.clear();
                    rootStatusCode = authProcess.authenticate(request, response, rootAuthCookies, url, creds,
                            "root");
                    logger.info("Repository authentication - " + repositoryConfig.getId()
                            + " completed. Response was " + rootStatusCode);
                    if (rootStatusCode == HttpServletResponse.SC_UNAUTHORIZED) {
                        logger.error("Root AuthN failed");
                    } else {
                        //Support to cookie array
                        if (rootStatusCode == HttpServletResponse.SC_OK) {
                            logger.debug("Root AuthN is SC_OK (200)");
                            if (!rootAuthCookies.isEmpty()) {
                                logger.debug("Root AuthN returns cookies");
                                for (int j = 0; j < rootAuthCookies.size(); j++) {
                                    logger.debug("Root Cookie found: " + rootAuthCookies.elementAt(j).getName()
                                            + ":" + rootAuthCookies.elementAt(j).getValue());
                                    authCookies.add(rootAuthCookies.elementAt(j));
                                }
                            } else {
                                logger.debug("Root AuthN does NOT return cookies");
                            }
                        }
                    }

                    //If no repository is defined called root then rootStatusCode must be set to OK
                    // This flag is used to indicate that a root repository has been defined.
                    rootAuthNDefined = true;
                    //
                } catch (Exception e) {
                    logger.debug("Exception with authentication for ID: " + repositoryConfig.getId() + " - "
                            + e.getMessage());
                    rootAuthNDefined = true;
                }
            } else {
                try {

                    //add support to cookie array
                    repositoryAuthCookies.clear();

                    logger.debug("Let's do the authentication");

                    repositoryAuthStatusCode = authProcess.authenticate(request, response,
                            repositoryAuthCookies, url, creds, repositoryConfig.getId());

                    //add support to cookie array
                    if (repositoryAuthStatusCode == HttpServletResponse.SC_OK) {
                        logger.debug("Repository AuthN [" + repositoryConfig.getId() + "] is SC_OK (200)");
                        //check if multiple repository is set to valid
                        if (repositoryOKAuthN == false) {
                            repositoryOKAuthN = true;
                        }
                        //check if cookie array is not empty and consume it
                        if (!repositoryAuthCookies.isEmpty()) {
                            logger.debug("Repository AuthN [" + repositoryConfig.getId() + "] returns "
                                    + repositoryAuthCookies.size() + " cookies");
                            for (int j = 0; j < repositoryAuthCookies.size(); j++) {
                                logger.debug("Repository Cookie found: "
                                        + repositoryAuthCookies.elementAt(j).getName() + ":"
                                        + repositoryAuthCookies.elementAt(j).getValue());
                                authCookies.add(repositoryAuthCookies.elementAt(j));
                            }
                        } else {
                            logger.debug("Repository AuthN [" + repositoryConfig.getId()
                                    + "] does NOT return cookies");
                        }
                    }

                    //end Krb support
                    logger.info("Repository authentication - " + repositoryConfig.getId()
                            + " completed. Response was " + repositoryAuthStatusCode);
                } catch (Exception e) {
                    logger.debug("Exception with authentication for ID: " + repositoryConfig.getId() + " - "
                            + e.getMessage());
                }
            }

            //increase order
            order++;
        }
    } else if (query.match(url)) {

        logger.debug("Query pattern [" + url + "]");

        // Don't do anything in here
        rootStatusCode = HttpServletResponse.SC_OK;

    } else {

        logger.error("No pattern defined for URL: " + url + ". It should not have been possible to get here!");

        // Protection
        rootStatusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    //add support to multiple repositories
    if ((!rootAuthNDefined) && (repositoryOKAuthN)) {
        //If no root repository has been defined then rootStatusCode has to be set valid, to OK
        rootStatusCode = HttpServletResponse.SC_OK;
    }

    // Return status code
    logger.debug("RootAuthN Complete - Status Code: " + rootStatusCode);

    return rootStatusCode;

}

From source file:eu.smartfp7.EdgeNode.SocialNetworkFeed.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*  ww w  . j  av  a2  s. co m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String accept = request.getHeader("Accept");
    if (accept != null && accept.contains("application/json"))
        response.setContentType("application/json; charset=utf-8");
    else
        response.setContentType("text/plain; charset=utf-8");

    PrintWriter out = response.getWriter();

    String action = request.getParameter("action");
    String socialname = null;
    if (action == null) {
        try {
            response.sendRedirect("socialFeed.html");
        } catch (IOException e1) {
            System.err.println("doGet IOException: Can not redirect");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("{\"error\":\"action parameter not specified\"}");
        }
        return;
    }

    int res = -1;
    if (action.equals("start")) {
        // Read the keyword for the start action
        String keyword = request.getParameter("keyword");
        if (keyword == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("{\"error\":\"Start action requires the parameter 'keyword'\"}");
            return;
        }
        res = startSocial(keyword, out, request);
    } else if (action.equals("stop") || action.equals("delete")) {
        // Read the social network name for the other actions that need it
        socialname = request.getParameter("name");
        if (socialname == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("{\"error\":\"Stop and delete actions require the parameter 'name'\"}");
            return;
        }
        if (action.equals("stop"))
            res = stopSocial(socialname, out);
        else if (action.equals("delete"))
            res = deleteSocial(socialname, out);
    } else if (action.equals("list"))
        res = listRunningSocials(out);
    else if (action.equals("delete_all"))
        res = deleteAllSocials(out, request);
    else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.println(
                "{\"error\":\"Unknown action, should be one of: 'list', 'start', 'stop', 'delete', 'delete_all'\"}");
        return;
    }
    // error messages will be printed by the function
    if (res < 0) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } else if (res > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:eu.dasish.annotation.backend.rest.DebugResource.java

/**
 * /*w  w w  .  j av a  2  s . co  m*/
 * @param principalId the external UUID of a principal whose account type must be updated.
 * @param account the new account type (admin, developer, user). 
 * @return a message telling if the account has been updated or not.
 * @throws IOException if sending an error fails.
 */
@PUT
@Produces(MediaType.TEXT_XML)
@Path("/account/{principalId}/make/{account}")
@Transactional(readOnly = true)
public String updatePrincipalsAccount(@PathParam("principalId") String principalId,
        @PathParam("account") String account) throws IOException {
    Number remotePrincipalID = this.getPrincipalID();
    if (remotePrincipalID == null) {
        return " ";
    }
    String typeOfAccount = dbDispatcher.getTypeOfPrincipalAccount(remotePrincipalID);
    if (typeOfAccount.equals(admin)) {
        try {
            final boolean update = dbDispatcher.updateAccount(UUID.fromString(principalId), account);
            return (update ? "The account is updated" : "The account is not updated, see the log.");
        } catch (NotInDataBaseException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            return e.toString();
        }
    } else {
        this.ADMIN_RIGHTS_EXPECTED();
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        return "Coucou.";
    }

}

From source file:com.rmn.qa.servlet.BmpServlet.java

/**
 * Starts a new BrowserMobProxy. Note that either recordHar must be set to true or some credentials are provided or
 * a proxy will not be created.//w  w w  .  j  a  v  a  2 s.  c o  m
 *
 * Content should be a json object in the following form.
 * 
 * <pre>
{
  "uuid": "my-uuid",//required
  "recordHar" : "true",
  "credentials": [{
    "domain" : "",
    "username" : "",
    "password" : "",
  }]
}
 * </pre>
 * 
 * @return Responds with a 201 Created and the url ins the Location header if proxy is created.
 * 
 * @return Responds with a 400 Bad Request if the uuid is not specified or there is no reason to create the proxy
 *         (see above).
 * 
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // if (request.getContentType().equals("application/json"))
    try {
        JsonNode input = getNodeFromRequest(request);
        String uuid = getJsonString(input, "uuid");
        if (StringUtils.isBlank(uuid)) {
            log.error("uuid not  present");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "uuid must be specified in json");
            return;
        }

        JsonNode harRecording = input.get("recordHar");
        boolean recorrdingHar = harRecording != null && harRecording.asBoolean(false);
        BrowserMobProxy proxy = null;
        if (recorrdingHar) {
            proxy = new BrowserMobProxyServer();
            Set<CaptureType> set = new HashSet<CaptureType>(CaptureType.getRequestCaptureTypes());
            set.addAll(CaptureType.getResponseCaptureTypes());
            set.removeAll(CaptureType.getBinaryContentCaptureTypes());
            proxy.setHarCaptureTypes(set);
        }
        JsonNode creds = input.get("credentials");
        if (creds != null) {
            if (proxy == null) {
                proxy = new BrowserMobProxyServer();
            }
            if (creds.isArray()) {
                ArrayNode array = (ArrayNode) creds;
                Iterator<JsonNode> elements = array.elements();
                while (elements.hasNext()) {
                    JsonNode cred = elements.next();
                    addCredentials(proxy, cred);
                }
            } else {
                addCredentials(proxy, creds);
            }
        }
        if (proxy == null) {
            log.error("Nothing for proxy to do");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Har recording or credentials not specified. There is no reason to start a proxy.");
            return;
        } else {
            String localhostname;
            // Try and get the IP address from the system property
            String runTimeHostName = System.getProperty(AutomationConstants.IP_ADDRESS);
            try {
                if (runTimeHostName == null) {
                    log.warn("Host name could not be determined from system property.");
                }
                localhostname = (runTimeHostName != null) ? runTimeHostName
                        : InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                log.error("Error parsing out host name", e);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Host name could not be determined: " + e);
                return;
            }

            // build the response
            BmpProxyRegistry.getInstance().addProxy(uuid, proxy);
            proxy.start();
            response.setStatus(HttpServletResponse.SC_CREATED);
            response.setHeader("Location", localhostname + ":" + proxy.getPort());
        }
    } catch (Exception e) {
        log.error("Error starting proxy: " + e, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error starting proxy: " + e);
    }
}

From source file:org.slc.sli.dashboard.security.SLIAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {

    HttpSession session = request.getSession();

    try {/*from w  w w  . ja v  a2 s. co  m*/

        SliApi.setBaseUrl(apiUrl);

        // Setup OAuth service
        OAuthService service = new ServiceBuilder().provider(SliApi.class)
                .apiKey(propDecryptor.getDecryptedClientId())
                .apiSecret(propDecryptor.getDecryptedClientSecret()).callback(callbackUrl).build();

        // Check cookies for token, if found insert into session
        boolean cookieFound = checkCookiesForToken(request, session);

        Object token = session.getAttribute(OAUTH_TOKEN);

        if (token == null && request.getParameter(OAUTH_CODE) == null) {
            // Initiate authentication
            initiatingAuthentication(request, response, session, service);
        } else if (token == null && request.getParameter(OAUTH_CODE) != null) {
            // Verify authentication
            verifyingAuthentication(request, response, session, service);
        } else {
            // Complete authentication
            completeAuthentication(request, response, session, token, cookieFound);
        }
    } catch (OAuthException ex) {
        session.invalidate();
        LOG.error(LOG_MESSAGE_AUTH_EXCEPTION, new Object[] { ex.getMessage() });
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
        return;
    } catch (Exception ex) {
        session.invalidate();
        LOG.error(LOG_MESSAGE_AUTH_EXCEPTION, new Object[] { ex.getMessage() });
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
        return;
    }
}

From source file:gov.nist.appvet.tool.SynchronousService.java

private void sendHttp500(HttpServletResponse response, String message) {
    try {//from  ww w.j a  va  2 s .c  om
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println(message);
        out.flush();
        out.close();
        log.debug("Returned HTTP 500: " + message);
    } catch (IOException e) {
        log.error(e.getMessage());
    }
}