Example usage for java.util HashMap isEmpty

List of usage examples for java.util HashMap isEmpty

Introduction

In this page you can find the example usage for java.util HashMap isEmpty.

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:com.pearson.eidetic.driver.threads.RefreshAwsAccountVolumes.java

@Override
public void run() {

    ConcurrentHashMap<Region, ArrayList<Volume>> localVolumeNoTime;

    localVolumeNoTime = awsAccount_.getVolumeNoTime_Copy();

    ConcurrentHashMap<Region, ArrayList<Volume>> localVolumeTime;

    localVolumeTime = awsAccount_.getVolumeTime_Copy();

    ConcurrentHashMap<Region, ArrayList<Volume>> localCopyVolumeSnapshots;

    localCopyVolumeSnapshots = awsAccount_.getCopyVolumeSnapshots_Copy();

    JSONParser parser = new JSONParser();

    for (Map.Entry<com.amazonaws.regions.Region, ArrayList<Volume>> entry : localVolumeNoTime.entrySet()) {
        com.amazonaws.regions.Region region = entry.getKey();
        AmazonEC2Client ec2Client = connect(region, awsAccount_.getAwsAccessKeyId(),
                awsAccount_.getAwsSecretKey());

        List<Volume> volumes = initialization(ec2Client, localVolumeNoTime, localVolumeTime,
                localCopyVolumeSnapshots, region);

        for (Volume volume : volumes) {

            JSONObject eideticParameters;
            eideticParameters = getEideticParameters(volume, parser);
            if (eideticParameters == null) {
                continue;
            }//w  w  w. j  a  v  a  2s .  co  m

            JSONObject createSnapshot;
            createSnapshot = getCreateSnapshot(volume, eideticParameters);
            if (createSnapshot == null) {
                continue;
            }

            HashMap<Integer, ConcurrentHashMap<Region, ArrayList<Volume>>> resultSet;
            resultSet = refreshCreateSnapshotVolumes(volume, createSnapshot, localVolumeTime, localVolumeNoTime,
                    region);
            if (resultSet == null) {
                continue;
            }
            if (resultSet.isEmpty()) {
                continue;
            }

            try {
                localVolumeTime = resultSet.get(0);
                localVolumeNoTime = resultSet.get(1);
            } catch (Exception e) {
                logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=\"Error\", Error=\"error getting from resultSet\", Volume_id=\""
                        + volume.getVolumeId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
            }

            //Time for CopyVolumeSnapshots
            //If this volume does not have copysnapshot
            localCopyVolumeSnapshots = refreshCopyVolumeSnapshots(volume, eideticParameters,
                    localCopyVolumeSnapshots, region);

        }

        localVolumeTime = processLocalVolumeTime(localVolumeTime, region);

        localVolumeNoTime = processLocalVolumeNoTime(localVolumeNoTime, region);

        localCopyVolumeSnapshots = processLocalCopyVolumeSnapshots(localCopyVolumeSnapshots, region);

        ec2Client.shutdown();

    }

    awsAccount_.replaceVolumeNoTime(localVolumeNoTime);

    awsAccount_.replaceVolumeTime(localVolumeTime);

    awsAccount_.replaceCopyVolumeSnapshots(localCopyVolumeSnapshots);

}

From source file:ext.tmt.utils.EPMUtil.java

/**
 * update a EPMDoc/*w  w  w . j  a  v  a2s.  c o  m*/
 * @param doc
 * @param name
 * @param filename
 * @param category
 * @param iba
 * @param comments
 * @return
 * @throws Exception
 */
public static EPMDocument updateEPM(EPMDocument doc, String name, String filename, String category, HashMap iba,
        String comments) throws Exception {
    Transaction trans = null;
    try {
        trans = new Transaction();
        trans.start();
        if (!doc.getName().equals(name)) {
            rename(doc, name);
        }
        doc = (EPMDocument) VersionControlUtil.checkout(doc);
        if (iba != null && !iba.isEmpty()) {
            LWCUtil.setValue(doc, iba);
        }

        doc = (EPMDocument) VersionControlUtil.checkin(doc, comments);
        doc = (EPMDocument) PersistenceHelper.manager.save(doc);

        ContentHolder contentholder = (ContentHolder) doc;
        contentholder = ContentHelper.service.getContents(contentholder);
        List contentListForTarget = ContentHelper.getContentListAll(contentholder);
        for (int i = 0; i < contentListForTarget.size(); i++) {
            ContentItem contentItem = (ContentItem) contentListForTarget.get(i);
            if (contentItem.getRole().toString().equals("PRIMARY")) {
                ContentServerHelper.service.deleteContent(contentholder, contentItem);
                break;
            }
        }
        ApplicationData appData = ApplicationData.newApplicationData(doc);
        appData.setRole(ContentRoleType.PRIMARY);
        appData.setFileName(doc.getCADName());
        StandardContentService.setFormat(filename, appData);
        if (StringUtils.isEmpty(category)) {
            category = DEFAULT_CATEGORY;
        }
        appData.setCategory(category);
        FileInputStream is = new FileInputStream(filename);
        appData = ContentServerHelper.service.updateContent(doc, appData, is);
        is.close();
        doc = (EPMDocument) ContentServerHelper.service.updateHolderFormat(doc);
        trans.commit();
        return doc;
    } catch (Exception e) {
        if (trans != null)
            trans.rollback();
        e.printStackTrace();
        return doc;
    }
}

From source file:it.crs4.seal.read_sort.MergeAlignments.java

private Map<String, String> parseReadGroupOptions(Map<String, Option> readGroupOptions, CommandLine args)
        throws ParseException {
    HashMap<String, String> fields = new HashMap<String, String>();

    for (Map.Entry<String, Option> pair : readGroupOptions.entrySet()) {
        String fieldName = pair.getKey();
        Option opt = pair.getValue();
        if (args.hasOption(opt.getOpt())) {
            fields.put(fieldName, args.getOptionValue(opt.getOpt()));
        }//from  w  ww  . ja  va2 s  .c om
    }

    if (!fields.isEmpty()) {
        if (!fields.containsKey("ID") || !fields.containsKey("SM"))
            throw new ParseException(
                    "If you specify read group tags (RG) you must specify at least id and sample");
    }
    return fields;
}

From source file:org.kuali.ole.module.purap.document.web.struts.InvoiceAction.java

/**
 * This method runs two checks based on the user input on PRQS initiate screen: Encumber next fiscal year check and Duplicate
 * payment request check. Encumber next fiscal year is checked first and will display a warning message to the user if it's the
 * case. Duplicate payment request check calls <code>InvoiceService</code> to perform the duplicate payment request
 * check. If one is found, a question is setup and control is forwarded to the question action method. Coming back from the
 * question prompt the button that was clicked is checked and if 'no' was selected they are forward back to the page still in
 * init mode./*w w  w .  ja  v  a2  s.c o  m*/
 *
 * @param mapping         An ActionMapping
 * @param form            An ActionForm
 * @param request         The HttpServletRequest
 * @param response        The HttpServletResponse
 * @param invoiceDocument The InvoiceDocument
 * @return An ActionForward
 * @throws Exception
 * @see org.kuali.ole.module.purap.document.service.InvoiceService
 */
protected ActionForward performDuplicateInvoiceAndEncumberFiscalYearCheck(ActionMapping mapping,
        ActionForm form, HttpServletRequest request, HttpServletResponse response,
        InvoiceDocument invoiceDocument) throws Exception {
    ActionForward forward = null;
    Object question = request.getParameter(OLEConstants.QUESTION_INST_ATTRIBUTE_NAME);
    if (question == null) {
        // perform encumber next fiscal year check and prompt warning message if needs
        if (isEncumberNextFiscalYear(invoiceDocument)) {
            String questionText = SpringContext.getBean(ConfigurationService.class)
                    .getPropertyValueAsString(PurapKeyConstants.WARNING_ENCUMBER_NEXT_FY);
            return this.performQuestionWithoutInput(mapping, form, request, response,
                    PRQSDocumentsStrings.ENCUMBER_NEXT_FISCAL_YEAR_QUESTION, questionText,
                    OLEConstants.CONFIRMATION_QUESTION, OLEConstants.ROUTE_METHOD, "");
        } else {
            // perform duplicate payment request check
            HashMap<String, String> duplicateMessages = SpringContext.getBean(InvoiceService.class)
                    .invoiceDuplicateMessages(invoiceDocument);
            if (!duplicateMessages.isEmpty()) {
                return this.performQuestionWithoutInput(mapping, form, request, response,
                        PRQSDocumentsStrings.DUPLICATE_INVOICE_QUESTION,
                        duplicateMessages.get(PRQSDocumentsStrings.DUPLICATE_INVOICE_QUESTION),
                        OLEConstants.CONFIRMATION_QUESTION, OLEConstants.ROUTE_METHOD, "");
            }
        }
    } else {
        Object buttonClicked = request.getParameter(OLEConstants.QUESTION_CLICKED_BUTTON);
        // If the user replies 'Yes' to the encumber-next-year-question, proceed with duplicate payment check
        if (PRQSDocumentsStrings.ENCUMBER_NEXT_FISCAL_YEAR_QUESTION.equals(question)
                && ConfirmationQuestion.YES.equals(buttonClicked)) {
            HashMap<String, String> duplicateMessages = SpringContext.getBean(InvoiceService.class)
                    .invoiceDuplicateMessages(invoiceDocument);
            if (!duplicateMessages.isEmpty()) {
                return this.performQuestionWithoutInput(mapping, form, request, response,
                        PRQSDocumentsStrings.DUPLICATE_INVOICE_QUESTION,
                        duplicateMessages.get(PRQSDocumentsStrings.DUPLICATE_INVOICE_QUESTION),
                        OLEConstants.CONFIRMATION_QUESTION, OLEConstants.ROUTE_METHOD, "");
            }
        }
        // If the user replies 'No' to either of the questions, redirect to the PRQS initiate page.
        else if ((PRQSDocumentsStrings.ENCUMBER_NEXT_FISCAL_YEAR_QUESTION.equals(question)
                || PRQSDocumentsStrings.DUPLICATE_INVOICE_QUESTION.equals(question))
                && ConfirmationQuestion.NO.equals(buttonClicked)) {
            invoiceDocument.updateAndSaveAppDocStatus(InvoiceStatuses.APPDOC_INITIATE);
            forward = mapping.findForward(OLEConstants.MAPPING_BASIC);
        }
    }

    return forward;
}

From source file:org.kuali.ole.module.purap.document.web.struts.PaymentRequestAction.java

/**
 * This method runs two checks based on the user input on PREQ initiate screen: Encumber next fiscal year check and Duplicate
 * payment request check. Encumber next fiscal year is checked first and will display a warning message to the user if it's the
 * case. Duplicate payment request check calls <code>PaymentRequestService</code> to perform the duplicate payment request
 * check. If one is found, a question is setup and control is forwarded to the question action method. Coming back from the
 * question prompt the button that was clicked is checked and if 'no' was selected they are forward back to the page still in
 * init mode.//  w w  w.  j  a  va2s  .  c o m
 *
 * @param mapping                An ActionMapping
 * @param form                   An ActionForm
 * @param request                The HttpServletRequest
 * @param response               The HttpServletResponse
 * @param paymentRequestDocument The PaymentRequestDocument
 * @return An ActionForward
 * @throws Exception
 * @see org.kuali.ole.module.purap.document.service.PaymentRequestService
 */
protected ActionForward performDuplicatePaymentRequestAndEncumberFiscalYearCheck(ActionMapping mapping,
        ActionForm form, HttpServletRequest request, HttpServletResponse response,
        PaymentRequestDocument paymentRequestDocument) throws Exception {
    ActionForward forward = null;
    Object question = request.getParameter(OLEConstants.QUESTION_INST_ATTRIBUTE_NAME);
    if (question == null) {
        // perform encumber next fiscal year check and prompt warning message if needs
        if (isEncumberNextFiscalYear(paymentRequestDocument)) {
            String questionText = SpringContext.getBean(ConfigurationService.class)
                    .getPropertyValueAsString(PurapKeyConstants.WARNING_ENCUMBER_NEXT_FY);
            return this.performQuestionWithoutInput(mapping, form, request, response,
                    PREQDocumentsStrings.ENCUMBER_NEXT_FISCAL_YEAR_QUESTION, questionText,
                    OLEConstants.CONFIRMATION_QUESTION, OLEConstants.ROUTE_METHOD, "");
        } else {
            // perform duplicate payment request check
            HashMap<String, String> duplicateMessages = SpringContext.getBean(PaymentRequestService.class)
                    .paymentRequestDuplicateMessages(paymentRequestDocument);
            if (!duplicateMessages.isEmpty()) {
                return this.performQuestionWithoutInput(mapping, form, request, response,
                        PREQDocumentsStrings.DUPLICATE_INVOICE_QUESTION,
                        duplicateMessages.get(PREQDocumentsStrings.DUPLICATE_INVOICE_QUESTION),
                        OLEConstants.CONFIRMATION_QUESTION, OLEConstants.ROUTE_METHOD, "");
            }
        }
    } else {
        Object buttonClicked = request.getParameter(OLEConstants.QUESTION_CLICKED_BUTTON);
        // If the user replies 'Yes' to the encumber-next-year-question, proceed with duplicate payment check
        if (PurapConstants.PREQDocumentsStrings.ENCUMBER_NEXT_FISCAL_YEAR_QUESTION.equals(question)
                && ConfirmationQuestion.YES.equals(buttonClicked)) {
            HashMap<String, String> duplicateMessages = SpringContext.getBean(PaymentRequestService.class)
                    .paymentRequestDuplicateMessages(paymentRequestDocument);
            if (!duplicateMessages.isEmpty()) {
                return this.performQuestionWithoutInput(mapping, form, request, response,
                        PREQDocumentsStrings.DUPLICATE_INVOICE_QUESTION,
                        duplicateMessages.get(PREQDocumentsStrings.DUPLICATE_INVOICE_QUESTION),
                        OLEConstants.CONFIRMATION_QUESTION, OLEConstants.ROUTE_METHOD, "");
            }
        }
        // If the user replies 'No' to either of the questions, redirect to the PREQ initiate page.
        else if ((PurapConstants.PREQDocumentsStrings.ENCUMBER_NEXT_FISCAL_YEAR_QUESTION.equals(question)
                || PurapConstants.PREQDocumentsStrings.DUPLICATE_INVOICE_QUESTION.equals(question))
                && ConfirmationQuestion.NO.equals(buttonClicked)) {
            paymentRequestDocument
                    .updateAndSaveAppDocStatus(PurapConstants.PaymentRequestStatuses.APPDOC_INITIATE);
            forward = mapping.findForward(OLEConstants.MAPPING_BASIC);
        }
    }

    return forward;
}

From source file:com.wormsim.data.SimulationConditions.java

public static SimulationConditions read(String str) throws IOException {
    RealDistribution food = null;/*from www  .j  a v  a2 s . c  o m*/
    HashMap<Integer, RealDistribution> pheromones = new HashMap<>();
    HashMap<String, IntegerDistribution> groups = new HashMap<>();

    if (Utils.MULTIBRACKET_VALIDITY_PATTERN.matcher(str).matches()) {
        Matcher m = Utils.SAMPLER_PATTERN.matcher(str);
        while (m.find()) {
            String match = m.group();
            String[] keyvalue = match.split("~");
            if (keyvalue[0].matches("\\s*food\\s*")) {
                food = Utils.readRealDistribution(keyvalue[1].trim());
            } else if (keyvalue[0].matches("\\s*pheromone\\[\\d+\\]\\s*")) {
                int leftbracket = keyvalue[0].indexOf('[') + 1;
                int rightbracket = keyvalue[0].indexOf(']');
                int id = 0;
                try {
                    id = Integer.valueOf(keyvalue[0].substring(leftbracket, rightbracket));
                    if (id < 0) {
                        throw new IOException("Invalid pheromone reference " + id + ", must be positive!");
                    }
                } catch (NumberFormatException ex) {
                    throw new IOException(ex);
                }
                if (pheromones.putIfAbsent(id, Utils.readRealDistribution(keyvalue[1].trim())) != null) {
                    throw new IOException("Duplicate pheromone id " + id);
                }
            } else { // Group Distribution
                groups.put(keyvalue[0].trim(), Utils.readIntegerDistribution(keyvalue[1].trim()));
            }
        }
    } else {
        throw new IOException("Brackets are missing on simulation conditions definition.");
    }
    if (food == null || groups.isEmpty()) {
        throw new IOException("Incomplete Data! Missing food or groups.");
    }

    // Convert pheromones into array
    Optional<Integer> max = pheromones.keySet().stream().max(Integer::max);

    RealDistribution[] pheromone_arr = new RealDistribution[max.orElse(0)];
    pheromones.forEach((k, v) -> pheromone_arr[k - 1] = v);
    for (int i = 0; i < pheromone_arr.length; i++) {
        if (pheromone_arr[i] == null) {
            pheromone_arr[i] = Utils.ZERO_REAL_DISTRIBUTION;
        }
    }

    return new SimulationConditions(food, pheromone_arr, groups);
}

From source file:org.apache.axis2.transport.http.HTTPWorker.java

public void service(final AxisHttpRequest request, final AxisHttpResponse response,
        final MessageContext msgContext) throws HttpException, IOException {
    ConfigurationContext configurationContext = msgContext.getConfigurationContext();
    final String servicePath = configurationContext.getServiceContextPath();
    final String contextPath = (servicePath.startsWith("/") ? servicePath : "/" + servicePath) + "/";

    String uri = request.getRequestURI();
    String method = request.getMethod();
    String soapAction = HttpUtils.getSoapAction(request);
    InvocationResponse pi;//from w  ww  .ja v a  2 s  .  c om

    if (method.equals(HTTPConstants.HEADER_GET)) {
        if (uri.equals("/favicon.ico")) {
            response.setStatus(HttpStatus.SC_MOVED_PERMANENTLY);
            response.addHeader(new BasicHeader("Location", "http://ws.apache.org/favicon.ico"));
            return;
        }
        if (!uri.startsWith(contextPath)) {
            response.setStatus(HttpStatus.SC_MOVED_PERMANENTLY);
            response.addHeader(new BasicHeader("Location", contextPath));
            return;
        }
        if (uri.endsWith("axis2/services/")) {
            String s = HTTPTransportReceiver.getServicesHTML(configurationContext);
            response.setStatus(HttpStatus.SC_OK);
            response.setContentType("text/html");
            OutputStream out = response.getOutputStream();
            out.write(EncodingUtils.getBytes(s, HTTP.ISO_8859_1));
            return;
        }
        if (uri.indexOf("?") < 0) {
            if (!uri.endsWith(contextPath)) {
                if (uri.endsWith(".xsd") || uri.endsWith(".wsdl")) {
                    HashMap services = configurationContext.getAxisConfiguration().getServices();
                    String file = uri.substring(uri.lastIndexOf("/") + 1, uri.length());
                    if ((services != null) && !services.isEmpty()) {
                        Iterator i = services.values().iterator();
                        while (i.hasNext()) {
                            AxisService service = (AxisService) i.next();
                            InputStream stream = service.getClassLoader()
                                    .getResourceAsStream("META-INF/" + file);
                            if (stream != null) {
                                OutputStream out = response.getOutputStream();
                                response.setContentType("text/xml");
                                ListingAgent.copy(stream, out);
                                out.flush();
                                out.close();
                                return;
                            }
                        }
                    }
                }
            }
        }
        if (uri.endsWith("?wsdl2")) {
            String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.length() - 6);
            HashMap services = configurationContext.getAxisConfiguration().getServices();
            AxisService service = (AxisService) services.get(serviceName);
            if (service != null) {
                boolean canExposeServiceMetadata = canExposeServiceMetadata(service);
                if (canExposeServiceMetadata) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.setContentType("text/xml");
                    service.printWSDL2(response.getOutputStream(), getHost(request));
                } else {
                    response.setStatus(HttpStatus.SC_FORBIDDEN);
                }
                return;
            }
        }
        if (uri.endsWith("?wsdl")) {
            /**
             * service name can be hierarchical (axis2/services/foo/1.0.0/Version?wsdl) or
             * normal (axis2/services/Version?wsdl).
             */
            String[] temp = uri.split(configurationContext.getServiceContextPath() + "/");
            String serviceName = temp[1].substring(0, temp[1].length() - 5);

            HashMap services = configurationContext.getAxisConfiguration().getServices();
            AxisService service = (AxisService) services.get(serviceName);
            if (service != null) {
                boolean canExposeServiceMetadata = canExposeServiceMetadata(service);
                if (canExposeServiceMetadata) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.setContentType("text/xml");
                    service.printWSDL(response.getOutputStream(), getHost(request));
                } else {
                    response.setStatus(HttpStatus.SC_FORBIDDEN);
                }
                return;
            }
        }
        if (uri.endsWith("?xsd")) {
            String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.length() - 4);
            HashMap services = configurationContext.getAxisConfiguration().getServices();
            AxisService service = (AxisService) services.get(serviceName);
            if (service != null) {
                boolean canExposeServiceMetadata = canExposeServiceMetadata(service);
                if (canExposeServiceMetadata) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.setContentType("text/xml");
                    service.printSchema(response.getOutputStream());
                } else {
                    response.setStatus(HttpStatus.SC_FORBIDDEN);
                }
                return;
            }
        }
        //cater for named xsds - check for the xsd name
        if (uri.indexOf("?xsd=") > 0) {
            // fix for imported schemas
            String[] uriParts = uri.split("[?]xsd=");
            String serviceName = uri.substring(uriParts[0].lastIndexOf("/") + 1, uriParts[0].length());
            String schemaName = uri.substring(uri.lastIndexOf("=") + 1);

            HashMap services = configurationContext.getAxisConfiguration().getServices();
            AxisService service = (AxisService) services.get(serviceName);
            if (service != null) {
                boolean canExposeServiceMetadata = canExposeServiceMetadata(service);
                if (!canExposeServiceMetadata) {
                    response.setStatus(HttpStatus.SC_FORBIDDEN);
                    return;
                }
                //run the population logic just to be sure
                service.populateSchemaMappings();
                //write out the correct schema
                Map schemaTable = service.getSchemaMappingTable();
                XmlSchema schema = (XmlSchema) schemaTable.get(schemaName);
                if (schema == null) {
                    int dotIndex = schemaName.indexOf('.');
                    if (dotIndex > 0) {
                        String schemaKey = schemaName.substring(0, dotIndex);
                        schema = (XmlSchema) schemaTable.get(schemaKey);
                    }
                }
                //schema found - write it to the stream
                if (schema != null) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.setContentType("text/xml");
                    schema.write(response.getOutputStream());
                    return;
                } else {
                    InputStream instream = service.getClassLoader()
                            .getResourceAsStream(DeploymentConstants.META_INF + "/" + schemaName);

                    if (instream != null) {
                        response.setStatus(HttpStatus.SC_OK);
                        response.setContentType("text/xml");
                        OutputStream outstream = response.getOutputStream();
                        boolean checkLength = true;
                        int length = Integer.MAX_VALUE;
                        int nextValue = instream.read();
                        if (checkLength)
                            length--;
                        while (-1 != nextValue && length >= 0) {
                            outstream.write(nextValue);
                            nextValue = instream.read();
                            if (checkLength)
                                length--;
                        }
                        outstream.flush();
                        return;
                    } else {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        int ret = service.printXSD(baos, schemaName);
                        if (ret > 0) {
                            baos.flush();
                            instream = new ByteArrayInputStream(baos.toByteArray());
                            response.setStatus(HttpStatus.SC_OK);
                            response.setContentType("text/xml");
                            OutputStream outstream = response.getOutputStream();
                            boolean checkLength = true;
                            int length = Integer.MAX_VALUE;
                            int nextValue = instream.read();
                            if (checkLength)
                                length--;
                            while (-1 != nextValue && length >= 0) {
                                outstream.write(nextValue);
                                nextValue = instream.read();
                                if (checkLength)
                                    length--;
                            }
                            outstream.flush();
                            return;
                        }
                        // no schema available by that name  - send 404
                        response.sendError(HttpStatus.SC_NOT_FOUND, "Schema Not Found!");
                        return;
                    }
                }
            }
        }
        if (uri.indexOf("?wsdl2=") > 0) {
            String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("?wsdl2="));
            if (processInternalWSDL(uri, configurationContext, serviceName, response, getHost(request)))
                return;
        }
        if (uri.indexOf("?wsdl=") > 0) {
            String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("?wsdl="));
            if (processInternalWSDL(uri, configurationContext, serviceName, response, getHost(request)))
                return;
        }

        String contentType = null;
        Header[] headers = request.getHeaders(HTTPConstants.HEADER_CONTENT_TYPE);
        if (headers != null && headers.length > 0) {
            contentType = headers[0].getValue();
            int index = contentType.indexOf(';');
            if (index > 0) {
                contentType = contentType.substring(0, index);
            }
        }

        // deal with GET request
        pi = RESTUtil.processURLRequest(msgContext, response.getOutputStream(), contentType);

    } else if (method.equals(HTTPConstants.HEADER_POST)) {
        // deal with POST request

        String contentType = request.getContentType();

        if (HTTPTransportUtils.isRESTRequest(contentType)) {
            pi = RESTUtil.processXMLRequest(msgContext, request.getInputStream(), response.getOutputStream(),
                    contentType);
        } else {
            String ip = (String) msgContext.getProperty(MessageContext.TRANSPORT_ADDR);
            if (ip != null) {
                uri = ip + uri;
            }
            pi = HTTPTransportUtils.processHTTPPostRequest(msgContext, request.getInputStream(),
                    response.getOutputStream(), contentType, soapAction, uri);
        }

    } else if (method.equals(HTTPConstants.HEADER_PUT)) {

        String contentType = request.getContentType();
        msgContext.setProperty(Constants.Configuration.CONTENT_TYPE, contentType);

        pi = RESTUtil.processXMLRequest(msgContext, request.getInputStream(), response.getOutputStream(),
                contentType);

    } else if (method.equals(HTTPConstants.HEADER_DELETE)) {

        pi = RESTUtil.processURLRequest(msgContext, response.getOutputStream(), null);

    } else {
        throw new MethodNotSupportedException(method + " method not supported");
    }

    Boolean holdResponse = (Boolean) msgContext.getProperty(RequestResponseTransport.HOLD_RESPONSE);
    if (pi.equals(InvocationResponse.SUSPEND) || (holdResponse != null && Boolean.TRUE.equals(holdResponse))) {
        try {
            ((RequestResponseTransport) msgContext.getProperty(RequestResponseTransport.TRANSPORT_CONTROL))
                    .awaitResponse();
        } catch (InterruptedException e) {
            throw new IOException("We were interrupted, so this may not function correctly:" + e.getMessage());
        }
    }

    // Finalize response
    RequestResponseTransport requestResponseTransportControl = (RequestResponseTransport) msgContext
            .getProperty(RequestResponseTransport.TRANSPORT_CONTROL);

    if (TransportUtils.isResponseWritten(msgContext)
            || ((requestResponseTransportControl != null) && requestResponseTransportControl.getStatus()
                    .equals(RequestResponseTransport.RequestResponseTransportStatus.SIGNALLED))) {
        // The response is written or signalled.  The current status is used (probably SC_OK).
    } else {
        // The response may be ack'd, mark the status as accepted.
        response.setStatus(HttpStatus.SC_ACCEPTED);
    }
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

private OAuthToken oauthAuthorize(String oauthAuthorizeURL) throws IOException, JDOMException {
    // get pag einfo 
    OAuthToken token = null;// www  .  j  a  v a  2 s  .c om
    WebResponse wr = this.getUrl(oauthAuthorizeURL, false);
    if (wr.statusCode == 200) {
        HashMap<String, ContentBody> formfields = BungeniServiceAccess.getInstance()
                .getAuthorizeFormFieldValues(wr.responseBody);
        if (!formfields.isEmpty()) {
            HttpContext context = new BasicHttpContext();
            // we use the form authorize URL here 
            final HttpPost post = new HttpPost(this.oauthAuthFormUrl);
            // we disable the automatic redirect of the URL since we want to grab 
            // the refresh token and anyway the redirect is to a dummy url
            final HttpParams params = new BasicHttpParams();
            params.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
            post.setParams(params);
            post.setEntity(getMultiPartEntity(formfields));
            HttpResponse authResponse = getClient().execute(post, context);
            String redirectLocation = "";
            Header locationHeader = authResponse.getFirstHeader("location");
            //consume response
            //ResponseHandler<String> responseHandler = new BasicResponseHandler();
            //responseHandler.handleResponse(authResponse);

            if (locationHeader != null) {
                redirectLocation = locationHeader.getValue();
                EntityUtils.consumeQuietly(authResponse.getEntity());
                try {
                    token = getAuthToken(redirectLocation);
                    // do someting with the returned codes
                } catch (MalformedURLException ex) {
                    log.error("Error while getting oauthtoken", ex);
                } catch (URISyntaxException ex) {
                    log.error("Error while getting oauthtoken", ex);
                }

            } else {
                EntityUtils.consumeQuietly(authResponse.getEntity());
                throw new IOException(authResponse.getStatusLine().toString());
            }
        } else {
            throw new IOException("Authorization failed !");
        }
    }
    return token;
}

From source file:org.wso2.carbon.ui.TilesJspServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String actionUrl = request.getRequestURI();

    //This is the layout page defined in
    //"/org.wso2.carbon.component/src/main/resources/web/WEB-INF/tiles/main_defs.xml"
    //Need to serve http requests other than to tiles body page,
    //using the normal OSGi way

    //retrieve urls that should be by-passed from tiles servlet
    String resourceURI = actionUrl.replaceFirst(request.getContextPath() + "/", "../");

    HashMap<String, String> urlsToBeByPassed = new HashMap<String, String>();
    if (bundle != null) {
        ServiceReference reference = bundle.getBundleContext()
                .getServiceReference(CarbonUIDefinitions.class.getName());
        CarbonUIDefinitions carbonUIDefinitions = null;
        if (reference != null) {
            carbonUIDefinitions = (CarbonUIDefinitions) bundle.getBundleContext().getService(reference);
            if (carbonUIDefinitions != null) {
                urlsToBeByPassed = carbonUIDefinitions.getSkipTilesUrls();
            }//w w w.  ja v a 2  s.  c o m
        }
    }

    //if the current uri is marked to be by-passed, let it pass through
    if (!urlsToBeByPassed.isEmpty()) {
        if (urlsToBeByPassed.containsKey(resourceURI)) {
            super.service(request, response);
            return;
        }
    }

    if ((actionUrl.lastIndexOf("/admin/layout/template.jsp") > -1)
            || actionUrl.lastIndexOf("ajaxprocessor.jsp") > -1 || actionUrl.indexOf("gadgets/js") > -1) {
        super.service(request, response);
    } else if (actionUrl.startsWith("/carbon/registry/web/resources/foo/bar")) {
        //TODO : consider the renamed ROOT war scenario
        String resourcePath = actionUrl.replaceFirst("/carbon/registry/web/", "");
        String pathToRegistry = "path=" + resourcePath;
        if (log.isTraceEnabled()) {
            log.trace("Forwarding to registry : " + pathToRegistry);
        }
        RequestDispatcher dispatcher = request
                .getRequestDispatcher("../registry/registry-web.jsp?" + pathToRegistry);
        dispatcher.forward(request, response);
    } else {
        try {
            if (log.isDebugEnabled()) {
                log.debug("request.getContextPath() : " + request.getContextPath());
                log.debug("actionUrl : " + actionUrl);
            }
            String newPath = actionUrl.replaceFirst(request.getContextPath(), "");

            //todo: Insert filter work here

            ActionHelper.render(newPath, request, response);
        } catch (Exception e) {
            log.fatal("Fatal error occurred while rendering UI using Tiles.", e);
        }
    }
}

From source file:com.datatorrent.lib.math.MarginMap.java

/**
 * Generates tuples for each key and emits them. Only keys that are in the denominator are iterated on
 * If the key is only in the numerator, it gets ignored (cannot do divide by 0)
 * Clears internal data/*w ww. j  a  v a2 s.c o m*/
 */
@Override
public void endWindow() {
    HashMap<K, V> tuples = new HashMap<K, V>();
    Double val;
    for (Map.Entry<K, MutableDouble> e : denominators.entrySet()) {
        MutableDouble nval = numerators.get(e.getKey());
        if (nval == null) {
            nval = new MutableDouble(0.0);
        } else {
            numerators.remove(e.getKey()); // so that all left over keys can be reported
        }
        if (percent) {
            val = (1 - nval.doubleValue() / e.getValue().doubleValue()) * 100;
        } else {
            val = 1 - nval.doubleValue() / e.getValue().doubleValue();
        }
        tuples.put(e.getKey(), getValue(val.doubleValue()));
    }
    if (!tuples.isEmpty()) {
        margin.emit(tuples);
    }
    numerators.clear();
    denominators.clear();
}