Example usage for java.lang NumberFormatException printStackTrace

List of usage examples for java.lang NumberFormatException printStackTrace

Introduction

In this page you can find the example usage for java.lang NumberFormatException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:info.alni.comete.android.Comete.java

public void reconnect(View view) {
    try {/*from   w w w .  jav a2 s . c o  m*/
        mConnectingDialog = ProgressDialog.show(Comete.this, "", "Connecting. Please wait...", true);

        Thread t = new Thread(new ConnectTask(getConnectionPrefs().getString("ipAddress", ""),
                Integer.parseInt(getConnectionPrefs().getString("port", "")),
                getConnectionPrefs().getInt("simType", 0)));
        t.start();
    } catch (NumberFormatException e) {
        showMsg(Comete.this, e.toString());
        e.printStackTrace();
    }
}

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

public static Map<String, Object> uspsDeliveryConfirmation(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentId = (String) context.get("shipmentId");
    String shipmentRouteSegmentId = (String) context.get("shipmentRouteSegmentId");
    Locale locale = (Locale) context.get("locale");

    Map<String, Object> shipmentGatewayConfig = ShipmentServices.getShipmentGatewayConfigFromShipment(delegator,
            shipmentId, locale);/*from   w w  w  .j  a v a2 s.  com*/
    String shipmentGatewayConfigId = (String) shipmentGatewayConfig.get("shipmentGatewayConfigId");
    String resource = (String) shipmentGatewayConfig.get("configProps");
    if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsGatewayNotAvailable", locale));
    }

    try {
        GenericValue shipment = EntityQuery.use(delegator).from("Shipment").where("shipmentId", shipmentId)
                .queryOne();
        if (shipment == null) {
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resourceError, "ProductShipmentNotFoundId", locale) + shipmentId);
        }

        GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment")
                .where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne();
        if (shipmentRouteSegment == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "ProductShipmentRouteSegmentNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        // ensure the carrier is USPS
        if (!"USPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNotRouteSegmentCarrier",
                    UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId),
                    locale));
        }

        // get the origin address
        GenericValue originAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false);
        if (originAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentOriginPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(originAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        // get the destination address
        GenericValue destinationAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false);
        if (destinationAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentDestPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(destinationAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        // get the service type from the CarrierShipmentMethod
        String shipmentMethodTypeId = shipmentRouteSegment.getString("shipmentMethodTypeId");
        String partyId = shipmentRouteSegment.getString("carrierPartyId");

        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod")
                .where("partyId", partyId, "roleTypeId", "CARRIER", "shipmentMethodTypeId",
                        shipmentMethodTypeId)
                .queryOne();
        if (carrierShipmentMethod == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNoCarrierShipmentMethod",
                    UtilMisc.toMap("carrierPartyId", partyId, "shipmentMethodTypeId", shipmentMethodTypeId),
                    locale));
        }
        String serviceType = carrierShipmentMethod.getString("carrierServiceCode");
        if (UtilValidate.isEmpty(serviceType)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsUnableDetermineServiceCode", locale));
        }

        // get the packages for this shipment route segment
        List<GenericValue> shipmentPackageRouteSegList = shipmentRouteSegment
                .getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false);
        if (UtilValidate.isEmpty(shipmentPackageRouteSegList)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentPackageRouteSegsNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        for (GenericValue shipmentPackageRouteSeg : shipmentPackageRouteSegList) {
            Document requestDocument = createUspsRequestDocument("DeliveryConfirmationV2.0Request", true,
                    delegator, shipmentGatewayConfigId, resource);
            Element requestElement = requestDocument.getDocumentElement();

            UtilXml.addChildElementValue(requestElement, "Option", "3", requestDocument);
            UtilXml.addChildElement(requestElement, "ImageParameters", requestDocument);

            // From address
            if (UtilValidate.isNotEmpty(originAddress.getString("attnName"))) {
                UtilXml.addChildElementValue(requestElement, "FromName", originAddress.getString("attnName"),
                        requestDocument);
                UtilXml.addChildElementValue(requestElement, "FromFirm", originAddress.getString("toName"),
                        requestDocument);
            } else {
                UtilXml.addChildElementValue(requestElement, "FromName", originAddress.getString("toName"),
                        requestDocument);
            }
            // The following 2 assignments are not typos - USPS address1 = OFBiz address2, USPS address2 = OFBiz address1
            UtilXml.addChildElementValue(requestElement, "FromAddress1", originAddress.getString("address2"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "FromAddress2", originAddress.getString("address1"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "FromCity", originAddress.getString("city"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "FromState",
                    originAddress.getString("stateProvinceGeoId"), requestDocument);
            UtilXml.addChildElementValue(requestElement, "FromZip5", originAddress.getString("postalCode"),
                    requestDocument);
            UtilXml.addChildElement(requestElement, "FromZip4", requestDocument);

            // To address
            if (UtilValidate.isNotEmpty(destinationAddress.getString("attnName"))) {
                UtilXml.addChildElementValue(requestElement, "ToName", destinationAddress.getString("attnName"),
                        requestDocument);
                UtilXml.addChildElementValue(requestElement, "ToFirm", destinationAddress.getString("toName"),
                        requestDocument);
            } else {
                UtilXml.addChildElementValue(requestElement, "ToName", destinationAddress.getString("toName"),
                        requestDocument);
            }
            // The following 2 assignments are not typos - USPS address1 = OFBiz address2, USPS address2 = OFBiz address1
            UtilXml.addChildElementValue(requestElement, "ToAddress1", destinationAddress.getString("address2"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "ToAddress2", destinationAddress.getString("address1"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "ToCity", destinationAddress.getString("city"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "ToState",
                    destinationAddress.getString("stateProvinceGeoId"), requestDocument);
            UtilXml.addChildElementValue(requestElement, "ToZip5", destinationAddress.getString("postalCode"),
                    requestDocument);
            UtilXml.addChildElement(requestElement, "ToZip4", requestDocument);

            GenericValue shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false);

            // WeightInOunces
            String weightStr = shipmentPackage.getString("weight");
            if (UtilValidate.isEmpty(weightStr)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsWeightNotFound",
                        UtilMisc.toMap("shipmentId", shipmentPackage.getString("shipmentId"),
                                "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId")),
                        locale));
            }

            BigDecimal weight = BigDecimal.ZERO;
            try {
                weight = new BigDecimal(weightStr);
            } catch (NumberFormatException nfe) {
                nfe.printStackTrace(); // TODO: handle exception
            }

            String weightUomId = shipmentPackage.getString("weightUomId");
            if (UtilValidate.isEmpty(weightUomId)) {
                // assume weight is in pounds for consistency (this assumption is made in uspsDomesticRate also)
                weightUomId = "WT_lb";
            }
            if (!"WT_oz".equals(weightUomId)) {
                // attempt a conversion to pounds
                GenericValue uomConversion = EntityQuery.use(delegator).from("UomConversion")
                        .where("uomId", weightUomId, "uomIdTo", "WT_oz").queryOne();
                if (uomConversion == null
                        || UtilValidate.isEmpty(uomConversion.getString("conversionFactor"))) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsWeightUnsupported",
                            UtilMisc.toMap("weightUomId", weightUomId, "shipmentId",
                                    shipmentPackage.getString("shipmentId"), "shipmentPackageSeqId",
                                    shipmentPackage.getString("shipmentPackageSeqId"), "weightUom", "WT_oz"),
                            locale));
                }
                weight = weight.multiply(uomConversion.getBigDecimal("conversionFactor"));
            }

            DecimalFormat df = new DecimalFormat("#");
            UtilXml.addChildElementValue(requestElement, "WeightInOunces",
                    df.format(weight.setScale(0, BigDecimal.ROUND_CEILING)), requestDocument);

            UtilXml.addChildElementValue(requestElement, "ServiceType", serviceType, requestDocument);
            UtilXml.addChildElementValue(requestElement, "ImageType", "TIF", requestDocument);
            UtilXml.addChildElementValue(requestElement, "AddressServiceRequested", "True", requestDocument);

            Document responseDocument = null;
            try {
                responseDocument = sendUspsRequest("DeliveryConfirmationV2", requestDocument, delegator,
                        shipmentGatewayConfigId, resource, locale);
            } catch (UspsRequestException e) {
                Debug.logInfo(e, module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsDeliveryConfirmationSendingError",
                        UtilMisc.toMap("errorString", e.getMessage()), locale));
            }
            Element responseElement = responseDocument.getDocumentElement();

            Element respErrorElement = UtilXml.firstChildElement(responseElement, "Error");
            if (respErrorElement != null) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsDeliveryConfirmationResponseError",
                        UtilMisc.toMap("shipmentId", shipmentPackage.getString("shipmentId"),
                                "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId"),
                                "errorString", UtilXml.childElementValue(respErrorElement, "Description")),
                        locale));
            }

            String labelImageString = UtilXml.childElementValue(responseElement, "DeliveryConfirmationLabel");
            if (UtilValidate.isEmpty(labelImageString)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsDeliveryConfirmationResponseIncompleteElementDeliveryConfirmationLabel",
                        locale));
            }
            shipmentPackageRouteSeg.setBytes("labelImage", Base64.base64Decode(labelImageString.getBytes()));
            String trackingCode = UtilXml.childElementValue(responseElement, "DeliveryConfirmationNumber");
            if (UtilValidate.isEmpty(trackingCode)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsDeliveryConfirmationResponsenIncompleteElementDeliveryConfirmationNumber",
                        locale));
            }
            shipmentPackageRouteSeg.set("trackingCode", trackingCode);
            shipmentPackageRouteSeg.store();
        }

    } catch (GenericEntityException gee) {
        Debug.logInfo(gee, module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsDeliveryConfirmationReadingError",
                        UtilMisc.toMap("errorString", gee.getMessage()), locale));
    }

    return ServiceUtil.returnSuccess();
}

From source file:com.ichi2.anki.provider.CardContentProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    Timber.d("CardContentProvider.query");
    Collection col = CollectionHelper.getInstance().getCol(getContext());
    if (col == null) {
        return null;
    }/* w ww . j a va2 s  . co  m*/

    // Find out what data the user is requesting
    int match = sUriMatcher.match(uri);

    switch (match) {
    case NOTES: {
        /* Search for notes
         */
        // TODO: Allow sort order, then also update description in FlashCardContract
        String columnsStr = proj2str(projection);
        String query = (selection != null) ? selection : "";
        List<Long> noteIds = col.findNotes(query);
        if ((noteIds != null) && (!noteIds.isEmpty())) {
            String selectedIds = "id in " + Utils.ids2str(noteIds);
            Cursor cur;
            try {
                cur = col.getDb().getDatabase()
                        .rawQuery("select " + columnsStr + " from notes where " + selectedIds, null);
            } catch (SQLException e) {
                throw new IllegalArgumentException("Not possible to query for data for IDs " + selectedIds, e);
            }
            return cur;
        } else {
            return null;
        }
    }
    case NOTES_ID: {
        /* Direct access note
         */
        long noteId;
        noteId = Long.parseLong(uri.getPathSegments().get(1));
        String columnsStr = proj2str(projection);
        String selectedIds = "id = " + noteId;
        Cursor cur;
        try {
            cur = col.getDb().getDatabase()
                    .rawQuery("select " + columnsStr + " from notes where " + selectedIds, null);
        } catch (SQLException e) {
            throw new IllegalArgumentException("Not possible to query for data for ID \"" + noteId + "\"", e);
        }
        return cur;
    }

    case NOTES_ID_CARDS: {
        Note currentNote = getNoteFromUri(uri, col);
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Card.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        for (Card currentCard : currentNote.cards()) {
            addCardToCursor(currentCard, rv, col, columns);
        }
        return rv;
    }
    case NOTES_ID_CARDS_ORD: {
        Card currentCard = getCardFromUri(uri, col);
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Card.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        addCardToCursor(currentCard, rv, col, columns);
        return rv;
    }
    case MODELS: {
        HashMap<Long, JSONObject> models = col.getModels().getModels();
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Model.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        for (Long modelId : models.keySet()) {
            addModelToCursor(modelId, models, rv, columns);
        }
        return rv;
    }
    case MODELS_ID: {
        long modelId = getModelIdFromUri(uri, col);
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Model.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        HashMap<Long, JSONObject> models = col.getModels().getModels();
        addModelToCursor(modelId, models, rv, columns);
        return rv;
    }
    case MODELS_ID_TEMPLATES: {
        /* Direct access model templates
         */
        JSONObject currentModel = col.getModels().get(getModelIdFromUri(uri, col));
        String[] columns = ((projection != null) ? projection : CardTemplate.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        try {
            JSONArray templates = currentModel.getJSONArray("tmpls");
            for (int idx = 0; idx < templates.length(); idx++) {
                JSONObject template = templates.getJSONObject(idx);
                addTemplateToCursor(template, currentModel, idx + 1, rv, columns);
            }
        } catch (JSONException e) {
            throw new IllegalArgumentException("Model is malformed", e);
        }
        return rv;
    }
    case MODELS_ID_TEMPLATES_ID: {
        /* Direct access model template with specific ID
         */
        int ord = Integer.parseInt(uri.getLastPathSegment());
        JSONObject currentModel = col.getModels().get(getModelIdFromUri(uri, col));
        String[] columns = ((projection != null) ? projection : CardTemplate.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        try {
            JSONObject template = getTemplateFromUri(uri, col);
            addTemplateToCursor(template, currentModel, ord + 1, rv, columns);
        } catch (JSONException e) {
            throw new IllegalArgumentException("Model is malformed", e);
        }
        return rv;
    }

    case SCHEDULE: {
        String[] columns = ((projection != null) ? projection
                : FlashCardsContract.ReviewInfo.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        long selectedDeckBeforeQuery = col.getDecks().selected();
        long deckIdOfTemporarilySelectedDeck = -1;
        int limit = 1; //the number of scheduled cards to return
        int selectionArgIndex = 0;

        //parsing the selection arguments
        if (selection != null) {
            String[] args = selection.split(","); //split selection to get arguments like "limit=?"
            for (String arg : args) {
                String[] keyAndValue = arg.split("="); //split arguments into key ("limit") and value ("?")
                try {
                    //check if value is a placeholder ("?"), if so replace with the next value of selectionArgs
                    String value = keyAndValue[1].trim().equals("?") ? selectionArgs[selectionArgIndex++]
                            : keyAndValue[1];
                    if (keyAndValue[0].trim().equals("limit")) {
                        limit = Integer.valueOf(value);
                    } else if (keyAndValue[0].trim().equals("deckID")) {
                        deckIdOfTemporarilySelectedDeck = Long.valueOf(value);
                        if (!selectDeckWithCheck(col, deckIdOfTemporarilySelectedDeck)) {
                            return rv; //if the provided deckID is wrong, return empty cursor.
                        }
                    }
                } catch (NumberFormatException nfe) {
                    nfe.printStackTrace();
                }
            }
        }

        //retrieve the number of cards provided by the selection parameter "limit"
        col.getSched().reset();
        for (int k = 0; k < limit; k++) {
            Card currentCard = col.getSched().getCard();

            if (currentCard != null) {
                int buttonCount = col.getSched().answerButtons(currentCard);
                JSONArray buttonTexts = new JSONArray();
                for (int i = 0; i < buttonCount; i++) {
                    buttonTexts.put(col.getSched().nextIvlStr(getContext(), currentCard, i + 1));
                }
                addReviewInfoToCursor(currentCard, buttonTexts, buttonCount, rv, col, columns);
            } else {
                break;
            }
        }

        if (deckIdOfTemporarilySelectedDeck != -1) {//if the selected deck was changed
            //change the selected deck back to the one it was before the query
            col.getDecks().select(selectedDeckBeforeQuery);
        }
        return rv;
    }
    case DECKS: {
        List<Sched.DeckDueTreeNode> allDecks = col.getSched().deckDueList();
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Deck.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, allDecks.size());
        for (Sched.DeckDueTreeNode deck : allDecks) {
            long id = deck.did;
            String name = deck.names[0];

            addDeckToCursor(id, name, getDeckCountsFromDueTreeNode(deck), rv, col, columns);
        }
        return rv;
    }
    case DECKS_ID: {
        /* Direct access deck
         */
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Deck.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        List<Sched.DeckDueTreeNode> allDecks = col.getSched().deckDueList();
        long deckId;
        deckId = Long.parseLong(uri.getPathSegments().get(1));
        for (Sched.DeckDueTreeNode deck : allDecks) {
            if (deck.did == deckId) {
                addDeckToCursor(deckId, deck.names[0], getDeckCountsFromDueTreeNode(deck), rv, col, columns);
                return rv;
            }
        }

        return rv;
    }
    case DECK_SELECTED: {

        long id = col.getDecks().selected();
        String name = col.getDecks().name(id);
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Deck.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        JSONArray counts = new JSONArray(Arrays.asList(col.getSched().counts()));
        addDeckToCursor(id, name, counts, rv, col, columns);
        return rv;
    }
    default:
        // Unknown URI type
        throw new IllegalArgumentException("uri " + uri + " is not supported");
    }
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.ddi.DDIFileReader.java

private void calculateDatasetStats(DataTable csvData) {
    String fileUNFvalue = null;//  w w w .ja  v  a 2 s  . c om

    String[] unfValues = new String[getVarQnty()];

    // TODO:
    // Catch and differentiate between different exception
    // that the UNF methods throw.

    for (int j = 0; j < getVarQnty(); j++) {
        int variableTypeNumer = unfVariableTypes.get(variableNameList.get(j));
        String varFormat = smd.getVariableFormatName().get(smd.getVariableName()[j]);

        try {
            dbgLog.finer("j = " + j);

            // Before we pass the variable vector to the UNF calculator,
            // we need to check if is of any supported date/time type.
            // If so, we'll also need to create and pass a list of
            // date formats, so that the UNFs could be properly calculated.
            // (otherwise the date/time values will be treated simply as
            // strings!)

            if (varFormat != null && (varFormat.equals("WKDAY") || varFormat.equals("MONTH")
                    || "date".equals(SPSSConstants.FORMAT_CATEGORY_TABLE.get(varFormat))
                    || "time".equals(SPSSConstants.FORMAT_CATEGORY_TABLE.get(varFormat)))) {

                // TODO:
                // All these date, time, weekday, etc. values need to be validated!

                String[] dateFormats = new String[getCaseQnty()];

                for (int k = 0; k < getCaseQnty(); k++) {
                    if (SPSSConstants.FORMAT_CATEGORY_TABLE.get(varFormat).equals("date")) {
                        dbgLog.finer("date case");
                        dateFormats[k] = sdf_ymd.toPattern();
                    } else if (SPSSConstants.FORMAT_CATEGORY_TABLE.get(varFormat).equals("time")) {
                        dbgLog.finer("time case: DTIME or DATETIME or TIME");

                        if (varFormat.equals("DTIME")) {
                            dateFormats[k] = sdf_dhms.toPattern();
                        } else if (varFormat.equals("DATETIME")) {
                            dateFormats[k] = sdf_ymdhms.toPattern();
                        } else if (varFormat.equals("TIME")) {
                            dateFormats[k] = sdf_hms.toPattern();
                        }
                    } else if (varFormat.equals("WKDAY")) {
                        // TODO: these need to be validated only.
                        dateFormats = null;

                    } else if (varFormat.equals("MONTH")) {
                        // TODO: these need to be validated only.
                        dateFormats = null;
                    }
                }

                unfValues[j] = getUNF(csvData.getData()[j], dateFormats, variableTypeNumer, unfVersionNumber,
                        j);
            } else {
                unfValues[j] = getUNF(csvData.getData()[j], null, variableTypeNumer, unfVersionNumber, j);
            }
            dbgLog.fine(j + "th unf value" + unfValues[j]);

        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        } catch (UnfException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
            //throw ex;
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
    }

    dbgLog.fine("unf set:\n" + Arrays.deepToString(unfValues));

    try {
        fileUNFvalue = UNF5Util.calculateUNF(unfValues);

    } catch (NumberFormatException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
        //throw ex;
    }

    // Set the UNFs we have calculated, the ones for the individual
    // variables and the file-level UNF:

    csvData.setUnf(unfValues);
    csvData.setFileUnf(fileUNFvalue);

    smd.setVariableUNF(unfValues);
    smd.getFileInformation().put("fileUNF", fileUNFvalue);

    dbgLog.fine("file-level unf value:\n" + fileUNFvalue);

}

From source file:neembuu.release1.externalImpl.linkhandler.OtherYoutubeLinkHandlerProvider.java

private BasicLinkHandler.Builder otherExtraction(TrialLinkHandler tlh) throws Exception {
    String url = tlh.getReferenceLinkString();
    BasicLinkHandler.Builder linkHandlerBuilder = BasicLinkHandler.Builder.create();

    try {/*  w  ww .j  ava  2  s .  c o m*/
        DefaultHttpClient httpClient = NHttpClient.getNewInstance();
        HttpPost httpPost = new HttpPost("http://www.clipconverter.cc/check.php");

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("mediaurl", url));

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httpPost.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpPost);

        final String responseString = EntityUtils.toString(httpResponse.getEntity());

        JSONObject jSonObject = new JSONObject(responseString);
        //LOGGER.log(Level.INFO,jSonObject);

        JSONArray jSonArray = jSonObject.getJSONArray("url");

        LOGGER.log(Level.INFO, "urls: " + jSonArray);

        //Set the group name as the name of the video
        String nameOfVideo = jSonObject.getString("filename");
        //normalize name of video

        //nameOfVideo = jpfm.util.UniversallyValidFileName.makeUniversallyValidFileName(nameOfVideo);
        linkHandlerBuilder.setGroupName(nameOfVideo);

        // Davide you cannot create a this.fileName field
        // this.filename = jSonObject.getString("filename") + ".mp4";
        // The same YoutubeLinkHandler object will be used for hanlding
        // all Youtube links. We "do" it in different threads in 
        // neembuu.release1.ui.actions.LinkActionsImpl line 128
        // void reAddAction(boolean anotherThread) 
        long c_duration = -1;

        for (int i = 0; i < jSonArray.length(); i++) {
            jSonObject = (JSONObject) jSonArray.get(i);
            String fileName = jSonObject.getString("text");
            LOGGER.log(Level.INFO, "Filename: {0}", fileName);

            final String extension = jSonObject.getString("filetype").toLowerCase();
            fileName = StringUtils.stringBetweenTwoStrings(fileName, ">", "<");
            fileName = fileName + "." + extension;

            String singleUrl = jSonObject.getString("url");
            //singleUrl = singleUrl.substring(0, singleUrl.indexOf("#"));
            //did some changes, but this doesn't help :(
            LOGGER.log(Level.INFO, "Before normalization URL: {0}", singleUrl);
            long length = tryFindingSize(singleUrl);
            singleUrl = Utils.normalize(singleUrl);
            LOGGER.log(Level.INFO, "Normalized URL: {0}", singleUrl);

            if (length == 0) {
                length = NHttpClientUtils.calculateLength(singleUrl, httpClient);
            }
            //LOGGER.log(Level.INFO,"Length: " + length);

            if (length <= 0) {
                continue;
                /*skip this url*/ }

            BasicOnlineFile.Builder fileBuilder = linkHandlerBuilder.createFile();

            try { // finding video/audio length
                String dur = StringUtils.stringBetweenTwoStrings(singleUrl, "dur=", "&");
                long duration = (int) (Double.parseDouble(dur) * 1000);
                if (c_duration < 0) {
                    c_duration = duration;
                }
                fileBuilder.putLongPropertyValue(PropertyProvider.LongProperty.MEDIA_DURATION_IN_MILLISECONDS,
                        duration);
                LOGGER.log(Level.INFO, "dur={0}", dur);
            } catch (NumberFormatException a) {
                // ignore
            }

            try { // finding the quality short name
                String type = fileName.substring(fileName.indexOf("(") + 1);
                type = type.substring(0, type.indexOf(")"));
                fileBuilder.putStringPropertyValue(PropertyProvider.StringProperty.VARIANT_DESCRIPTION, type);
                if (type.contains("480") || type.contains("1080")) {
                    fileBuilder.putBooleanPropertyValue(PropertyProvider.BooleanProperty.UNSTABLE_VARIANT,
                            true);
                }
                LOGGER.log(Level.INFO, "type={0}", type);
            } catch (Exception a) {
                a.printStackTrace();
            }

            fileName = nameOfVideo + " " + fileName;

            fileBuilder.setName(fileName).setUrl(singleUrl).setSize(length).next();
        }

        for (OnlineFile of : linkHandlerBuilder.getFiles()) {
            long dur = of.getPropertyProvider()
                    .getLongPropertyValue(PropertyProvider.LongProperty.MEDIA_DURATION_IN_MILLISECONDS);
            if (dur < 0 && c_duration > 0 && of.getPropertyProvider() instanceof BasicPropertyProvider) {
                ((BasicPropertyProvider) of.getPropertyProvider()).putLongPropertyValue(
                        PropertyProvider.LongProperty.MEDIA_DURATION_IN_MILLISECONDS, c_duration);
            }
        }
    } catch (Exception ex) {
        //            int retryLimit = ((YoutubeLinkHandlerProvider.YT_TLH) tlh).retryLimit;
        ex.printStackTrace();
        //            LOGGER.log(Level.INFO, "retry no. = " + retryCount);
        //            if (retryCount > retryLimit) {
        //                throw ex;
        //            }
        //            return clipConverterExtraction(tlh, retryCount + 1);
    }

    return linkHandlerBuilder;
}

From source file:gate.util.reporting.DocTimeReporter.java

/**
 * Parses the report command lime arguments.
 *
 * @param args array containing the command line arguments.
 *///from  w  ww  .j  a v  a  2 s  . c o m
@Override
public void parseArguments(String[] args) {
    Getopt g = new Getopt("gate.util.reporting.DocTimeReporter", args, "i:m:d:p:o:l:h");
    int c;
    String argNoOfDocs = null;
    while ((c = g.getopt()) != -1) {
        switch (c) {
        // -i inputFile
        case 'i':
            String argInPath = g.getOptarg();
            if (argInPath != null) {
                setBenchmarkFile(new File(argInPath));
            }
            break;
        // -m printMedia
        case 'm':
            String argPrintMedia = g.getOptarg();
            if (argPrintMedia != null) {
                setPrintMedia(argPrintMedia);
            }
            break;
        // -d noOfDocs
        case 'd':
            argNoOfDocs = g.getOptarg();
            if (argNoOfDocs == null) {
                setMaxDocumentInReport(maxDocumentInReport);
            }
            break;
        // -p prName
        case 'p':
            String argPrName = g.getOptarg();
            if (argPrName != null) {
                setPRMatchingRegex(argPrName);
            } else {
                setPRMatchingRegex(PRMatchingRegex);
            }
            break;
        // -o Report File
        case 'o':
            String argOutPath = g.getOptarg();
            if (argOutPath != null) {
                setReportFile(new File(argOutPath));
            }
            break;
        // -l logical start
        case 'l':
            String argLogicalStart = g.getOptarg();
            if (argLogicalStart != null) {
                setLogicalStart(argLogicalStart);
            }
            break;
        // -h usage information
        case 'h':
        case '?':
            usage();
            System.exit(STATUS_NORMAL);
            break;

        default:
            usage();
            System.exit(STATUS_ERROR);
            break;

        } // getopt switch
    }
    if (argNoOfDocs != null) {
        try {
            setMaxDocumentInReport(Integer.parseInt(argNoOfDocs));
        } catch (NumberFormatException e) {
            e.printStackTrace();
            usage();
            System.exit(STATUS_ERROR);
        }
    }
}

From source file:com.kiandastream.musicplayer.MusicService.java

void processResumeRequest() {
    if (mState == State.Starting) {
        if (song_playlist != null && song_playlist.size() > 0) {
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try {
                //String songurl="http://api.kiandastream.globusapps.com/static/songs/"+song_playlist.get(0).getSong_id()+".mp3";
                System.out.println("url of song playing is " + song_playlist.get(0).getSongurl());
                mPlayer.setDataSource(song_playlist.get(0).getSongurl());
                setNotification("Loading");
                mState = State.Preparing;
                //Setting title in notification bar

                mPlayer.prepareAsync();/*from  w ww  .j av a 2s  . co  m*/
                if (!mWifiLock.isHeld())
                    mWifiLock.acquire();
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    } else if (mState == State.Paused) {
        if (mPlayer != null) {
            mPlayer.start();

            if (listener != null)
                listener.startUpdating(mPlayer);
            mState = State.Playing;
            setNotification(song_playlist.get(Integer.parseInt(positionofsong)).getSong_name());
        }

    }
}

From source file:nz.ac.otago.psyanlab.common.designer.program.stage.EditPropPropertiesFragment.java

/**
 * Get the prop with properties set from the user entered values.
 * /*from ww  w.j ava  2s .  c om*/
 * @return Prop with user values.
 */
public Prop getConfiguredProp() {
    for (String name : mViewMap.keySet()) {
        Field field = mFieldMap.get(name);
        View view = mViewMap.get(name);

        Object value;

        if (view instanceof EditText) {
            String in = ((EditText) view).getText().toString();
            if (in == null) {
                continue;
            }

            if (field.getType().isAssignableFrom(Integer.TYPE)) {
                try {
                    value = Integer.valueOf(((EditText) view).getText().toString());
                } catch (NumberFormatException e) {
                    // Bad input here can be ignored. Continue to next item.
                    continue;
                }
            } else if (field.getType().isAssignableFrom(Float.TYPE)) {
                try {
                    value = Float.valueOf(((EditText) view).getText().toString());
                } catch (NumberFormatException e) {
                    // Bad input here can be ignored. Continue to next item.
                    continue;
                }
            } else if (field.getType().isAssignableFrom(String.class)) {
                value = ((EditText) view).getText().toString();
            } else {
                continue;
            }
        } else {
            continue;
        }

        try {
            field.set(mProp, value);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    return mProp;
}

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

public static Map<String, Object> uspsUpdateShipmentRateInfo(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String shipmentId = (String) context.get("shipmentId");
    String shipmentRouteSegmentId = (String) context.get("shipmentRouteSegmentId");
    Locale locale = (Locale) context.get("locale");

    Map<String, Object> shipmentGatewayConfig = ShipmentServices.getShipmentGatewayConfigFromShipment(delegator,
            shipmentId, locale);/*from   w  w  w  .  ja va 2s  . c  om*/
    String shipmentGatewayConfigId = (String) shipmentGatewayConfig.get("shipmentGatewayConfigId");
    String resource = (String) shipmentGatewayConfig.get("configProps");
    if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsGatewayNotAvailable", locale));
    }

    try {
        GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment")
                .where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne();
        if (shipmentRouteSegment == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "ProductShipmentRouteSegmentNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        // ensure the carrier is USPS
        if (!"USPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNotRouteSegmentCarrier",
                    UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId),
                    locale));
        }

        // get the origin address
        GenericValue originAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false);
        if (originAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentOriginPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(originAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        String originZip = originAddress.getString("postalCode");
        if (UtilValidate.isEmpty(originZip)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginZipCodeMissing",
                    UtilMisc.toMap("contactMechId", originAddress.getString("contactMechId")), locale));
        }

        // get the destination address
        GenericValue destinationAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false);
        if (destinationAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentDestPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(destinationAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        String destinationZip = destinationAddress.getString("postalCode");
        if (UtilValidate.isEmpty(destinationZip)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentDestinationZipCodeMissing",
                    UtilMisc.toMap("contactMechId", destinationAddress.getString("contactMechId")), locale));
        }

        // get the service type from the CarrierShipmentMethod
        String shipmentMethodTypeId = shipmentRouteSegment.getString("shipmentMethodTypeId");
        String partyId = shipmentRouteSegment.getString("carrierPartyId");

        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod")
                .where("partyId", partyId, "roleTypeId", "CARRIER", "shipmentMethodTypeId",
                        shipmentMethodTypeId)
                .queryOne();
        if (carrierShipmentMethod == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNoCarrierShipmentMethod",
                    UtilMisc.toMap("carrierPartyId", partyId, "shipmentMethodTypeId", shipmentMethodTypeId),
                    locale));
        }
        String serviceType = carrierShipmentMethod.getString("carrierServiceCode");
        if (UtilValidate.isEmpty(serviceType)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNoCarrierServiceCodeFound",
                    UtilMisc.toMap("carrierPartyId", partyId, "shipmentMethodTypeId", shipmentMethodTypeId),
                    locale));
        }

        // get the packages for this shipment route segment
        List<GenericValue> shipmentPackageRouteSegList = shipmentRouteSegment
                .getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false);
        if (UtilValidate.isEmpty(shipmentPackageRouteSegList)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentPackageRouteSegsNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        BigDecimal actualTransportCost = BigDecimal.ZERO;

        String carrierDeliveryZone = null;
        String carrierRestrictionCodes = null;
        String carrierRestrictionDesc = null;

        // send a new request for each package
        for (Iterator<GenericValue> i = shipmentPackageRouteSegList.iterator(); i.hasNext();) {

            GenericValue shipmentPackageRouteSeg = i.next();
            Document requestDocument = createUspsRequestDocument("RateRequest", true, delegator,
                    shipmentGatewayConfigId, resource);

            Element packageElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "Package",
                    requestDocument);
            packageElement.setAttribute("ID", "0");

            UtilXml.addChildElementValue(packageElement, "Service", serviceType, requestDocument);
            UtilXml.addChildElementValue(packageElement, "ZipOrigination", originZip, requestDocument);
            UtilXml.addChildElementValue(packageElement, "ZipDestination", destinationZip, requestDocument);

            GenericValue shipmentPackage = null;
            shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false);

            // weight elements - Pounds, Ounces
            String weightStr = shipmentPackage.getString("weight");
            if (UtilValidate.isEmpty(weightStr)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsWeightNotFound",
                        UtilMisc.toMap("shipmentId", shipmentPackage.getString("shipmentId"),
                                "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId")),
                        locale));
            }

            BigDecimal weight = BigDecimal.ZERO;
            try {
                weight = new BigDecimal(weightStr);
            } catch (NumberFormatException nfe) {
                nfe.printStackTrace(); // TODO: handle exception
            }

            String weightUomId = shipmentPackage.getString("weightUomId");
            if (UtilValidate.isEmpty(weightUomId)) {
                weightUomId = "WT_lb"; // assume weight is in pounds
            }
            if (!"WT_lb".equals(weightUomId)) {
                // attempt a conversion to pounds
                Map<String, Object> result = new HashMap<String, Object>();
                try {
                    result = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId",
                            weightUomId, "uomIdTo", "WT_lb", "originalValue", weight));
                } catch (GenericServiceException ex) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsWeightConversionError",
                            UtilMisc.toMap("errorString", ex.getMessage()), locale));
                }

                if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_SUCCESS)
                        && result.get("convertedValue") != null) {
                    weight = weight.multiply((BigDecimal) result.get("convertedValue"));
                } else {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsWeightUnsupported",
                            UtilMisc.toMap("weightUomId", weightUomId, "shipmentId",
                                    shipmentPackage.getString("shipmentId"), "shipmentPackageSeqId",
                                    shipmentPackage.getString("shipmentPackageSeqId"), "weightUom", "WT_lb"),
                            locale));
                }

            }

            BigDecimal weightPounds = weight.setScale(0, BigDecimal.ROUND_FLOOR);
            BigDecimal weightOunces = weight.multiply(new BigDecimal("16")).remainder(new BigDecimal("16"))
                    .setScale(0, BigDecimal.ROUND_CEILING);

            DecimalFormat df = new DecimalFormat("#");
            UtilXml.addChildElementValue(packageElement, "Pounds", df.format(weightPounds), requestDocument);
            UtilXml.addChildElementValue(packageElement, "Ounces", df.format(weightOunces), requestDocument);

            // Container element
            GenericValue carrierShipmentBoxType = null;
            List<GenericValue> carrierShipmentBoxTypes = null;
            carrierShipmentBoxTypes = shipmentPackage.getRelated("CarrierShipmentBoxType",
                    UtilMisc.toMap("partyId", "USPS"), null, false);

            if (carrierShipmentBoxTypes.size() > 0) {
                carrierShipmentBoxType = carrierShipmentBoxTypes.get(0);
            }

            if (carrierShipmentBoxType != null
                    && UtilValidate.isNotEmpty(carrierShipmentBoxType.getString("packagingTypeCode"))) {
                UtilXml.addChildElementValue(packageElement, "Container",
                        carrierShipmentBoxType.getString("packagingTypeCode"), requestDocument);
            } else {
                // default to "None", for customers using their own package
                UtilXml.addChildElementValue(packageElement, "Container", "None", requestDocument);
            }

            // Size element
            if (carrierShipmentBoxType != null && UtilValidate.isNotEmpty("oversizeCode")) {
                UtilXml.addChildElementValue(packageElement, "Size",
                        carrierShipmentBoxType.getString("oversizeCode"), requestDocument);
            } else {
                // default to "Regular", length + girth measurement <= 84 inches
                UtilXml.addChildElementValue(packageElement, "Size", "Regular", requestDocument);
            }

            // Although only applicable for Parcel Post, this tag is required for all requests
            UtilXml.addChildElementValue(packageElement, "Machinable", "False", requestDocument);

            Document responseDocument = null;
            try {
                responseDocument = sendUspsRequest("Rate", requestDocument, delegator, shipmentGatewayConfigId,
                        resource, locale);
            } catch (UspsRequestException e) {
                Debug.logInfo(e, module);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticSendingError",
                                UtilMisc.toMap("errorString", e.getMessage()), locale));
            }

            Element respPackageElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(),
                    "Package");
            if (respPackageElement == null) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsRateDomesticResponseIncompleteElementPackage", locale));
            }

            Element respErrorElement = UtilXml.firstChildElement(respPackageElement, "Error");
            if (respErrorElement != null) {
                return ServiceUtil
                        .returnError(UtilProperties
                                .getMessage(resourceError, "FacilityShipmentUspsRateDomesticResponseError",
                                        UtilMisc.toMap("errorString",
                                                UtilXml.childElementValue(respErrorElement, "Description")),
                                        locale));
            }

            // update the ShipmentPackageRouteSeg
            String postageString = UtilXml.childElementValue(respPackageElement, "Postage");
            if (UtilValidate.isEmpty(postageString)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsRateDomesticResponseIncompleteElementPostage", locale));
            }

            BigDecimal postage = BigDecimal.ZERO;
            try {
                postage = new BigDecimal(postageString);
            } catch (NumberFormatException nfe) {
                nfe.printStackTrace(); // TODO: handle exception
            }
            actualTransportCost = actualTransportCost.add(postage);

            shipmentPackageRouteSeg.setString("packageTransportCost", postageString);
            shipmentPackageRouteSeg.store();

            // if this is the last package, get the zone and APO/FPO restrictions for the ShipmentRouteSegment
            if (!i.hasNext()) {
                carrierDeliveryZone = UtilXml.childElementValue(respPackageElement, "Zone");
                carrierRestrictionCodes = UtilXml.childElementValue(respPackageElement, "RestrictionCodes");
                carrierRestrictionDesc = UtilXml.childElementValue(respPackageElement,
                        "RestrictionDescription");
            }
        }

        // update the ShipmentRouteSegment
        shipmentRouteSegment.set("carrierDeliveryZone", carrierDeliveryZone);
        shipmentRouteSegment.set("carrierRestrictionCodes", carrierRestrictionCodes);
        shipmentRouteSegment.set("carrierRestrictionDesc", carrierRestrictionDesc);
        shipmentRouteSegment.setString("actualTransportCost", String.valueOf(actualTransportCost));
        shipmentRouteSegment.store();

    } catch (GenericEntityException gee) {
        Debug.logInfo(gee, module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticReadingError",
                        UtilMisc.toMap("errorString", gee.getMessage()), locale));
    }

    return ServiceUtil.returnSuccess();
}

From source file:org.fao.geonet.OgpAppHandler.java

/**
 * Inits the engine, loading all needed data.
 */// w w  w  .  j a v  a 2s.  c o  m
public Object start(Element config, ServiceContext context) throws Exception {
    context.setAsThreadLocal();
    this._applicationContext = context.getApplicationContext();
    ApplicationContextHolder.set(this._applicationContext);

    logger = context.getLogger();
    // If an error occur during logger configuration
    // Continue starting the application with
    // a logger initialized with the default log4j.xml.
    try {
        LogUtils.refreshLogConfiguration();
    } catch (OperationAbortedEx e) {
        logger.error("Error while setting log configuration. "
                + "Check the setting in the database for logger configuration file.");
        logger.error(e.getMessage());
    }
    ConfigurableListableBeanFactory beanFactory = context.getApplicationContext().getBeanFactory();

    ServletPathFinder finder = new ServletPathFinder(this._applicationContext.getBean(ServletContext.class));
    appPath = finder.getAppPath();
    String baseURL = context.getBaseUrl();
    String webappName = baseURL.substring(1);
    // TODO : if webappName is "". ie no context

    final SystemInfo systemInfo = _applicationContext.getBean(SystemInfo.class);
    String version = systemInfo.getVersion();
    String subVersion = systemInfo.getSubVersion();

    logger.info("Initializing GeoNetwork " + version + "." + subVersion + " ...");

    // Get main service config handler
    @SuppressWarnings("unchecked")
    List<Element> serviceConfigElems = config.getChildren();
    ServiceConfig handlerConfig = new ServiceConfig(serviceConfigElems);

    // Init configuration directory
    final GeonetworkDataDirectory dataDirectory = _applicationContext.getBean(GeonetworkDataDirectory.class);
    dataDirectory.init(webappName, appPath, handlerConfig, context.getServlet());

    // Get config handler properties
    String systemDataDir = handlerConfig.getMandatoryValue(Geonet.Config.SYSTEM_DATA_DIR);
    String thesauriDir = handlerConfig.getMandatoryValue(Geonet.Config.CODELIST_DIR);
    String luceneDir = handlerConfig.getMandatoryValue(Geonet.Config.LUCENE_DIR);
    String luceneConfigXmlFile = handlerConfig.getMandatoryValue(Geonet.Config.LUCENE_CONFIG);

    logger.info("Data directory: " + systemDataDir);

    setProps(appPath, handlerConfig);

    importDatabaseData(context);

    // Status actions class - load it
    String statusActionsClassName = handlerConfig.getMandatoryValue(Geonet.Config.STATUS_ACTIONS_CLASS);
    @SuppressWarnings("unchecked")
    Class<StatusActions> statusActionsClass = (Class<StatusActions>) Class.forName(statusActionsClassName);

    JeevesJCS.setConfigFilename(appPath.resolve("WEB-INF/classes/cache.ccf"));

    // force caches to be config'd so shutdown hook works correctly
    JeevesJCS.getInstance(Processor.XLINK_JCS);
    JeevesJCS.getInstance(XmlResolver.XMLRESOLVER_JCS);

    //------------------------------------------------------------------------
    //--- initialize settings subsystem

    logger.info("  - Setting manager...");

    SettingManager settingMan = this._applicationContext.getBean(SettingManager.class);

    //--- initialize ThreadUtils with setting manager and rm props
    final DataSource dataSource = context.getBean(DataSource.class);
    Connection conn = null;
    try {
        conn = dataSource.getConnection();
        ThreadUtils.init(conn.getMetaData().getURL(), settingMan);
    } finally {
        if (conn != null) {
            conn.close();
        }
    }

    //------------------------------------------------------------------------
    //--- initialize Z39.50

    logger.info("  - Z39.50...");

    boolean z3950Enable = settingMan.getValueAsBool("system/z3950/enable", false);
    String z3950port = settingMan.getValue("system/z3950/port");

    logger.info("     - Z39.50 is enabled: " + z3950Enable);
    if (z3950Enable) {
        // build Z3950 repositories file first from template
        URL url = getClass().getClassLoader().getResource(Geonet.File.JZKITCONFIG_TEMPLATE);

        if (Repositories.build(url, context)) {
            logger.info("     Repositories file built from template.");

            try {
                ConfigurableApplicationContext appContext = context.getApplicationContext();

                // to have access to the GN context in spring-managed objects
                ContextContainer cc = (ContextContainer) appContext.getBean("ContextGateway");
                cc.setSrvctx(context);

                if (!z3950Enable) {
                    logger.info("     Server is Disabled.");
                } else {
                    logger.info("     Server is Enabled.");

                    Server.init(z3950port, appContext);
                }
            } catch (Exception e) {
                logger.error(
                        "     Repositories file init FAILED - Z3950 server disabled and Z3950 client services (remote search, "
                                + "harvesting) may not work. Error is:" + e.getMessage());
                e.printStackTrace();
            }

        } else {
            logger.error(
                    "     Repositories file builder FAILED - Z3950 server disabled and Z3950 client services (remote search, "
                            + "harvesting) may not work.");
        }
    }
    //------------------------------------------------------------------------
    //--- initialize SchemaManager

    logger.info("  - Schema manager...");

    Path schemaPluginsDir = dataDirectory.getSchemaPluginsDir();
    Path schemaCatalogueFile = dataDirectory.getConfigDir().resolve(Geonet.File.SCHEMA_PLUGINS_CATALOG);
    boolean createOrUpdateSchemaCatalog = handlerConfig
            .getMandatoryValue(Geonet.Config.SCHEMA_PLUGINS_CATALOG_UPDATE).equals("true");
    logger.info("         - Schema plugins directory: " + schemaPluginsDir);
    logger.info("         - Schema Catalog File     : " + schemaCatalogueFile);
    SchemaManager schemaMan = _applicationContext.getBean(SchemaManager.class);
    schemaMan.configure(_applicationContext, appPath, dataDirectory.getResourcesDir(), schemaCatalogueFile,
            schemaPluginsDir, context.getLanguage(),
            handlerConfig.getMandatoryValue(Geonet.Config.PREFERRED_SCHEMA), createOrUpdateSchemaCatalog);

    //------------------------------------------------------------------------
    //--- initialize search and editing

    logger.info("  - Search...");

    boolean logSpatialObject = "true"
            .equalsIgnoreCase(handlerConfig.getMandatoryValue(Geonet.Config.STAT_LOG_SPATIAL_OBJECTS));
    boolean logAsynch = "true".equalsIgnoreCase(handlerConfig.getMandatoryValue(Geonet.Config.STAT_LOG_ASYNCH));
    logger.info("  - Log spatial object: " + logSpatialObject);
    logger.info("  - Log in asynch mode: " + logAsynch);

    String luceneTermsToExclude = "";
    luceneTermsToExclude = handlerConfig.getMandatoryValue(Geonet.Config.STAT_LUCENE_TERMS_EXCLUDE);

    LuceneConfig lc = _applicationContext.getBean(LuceneConfig.class);
    lc.configure(luceneConfigXmlFile);
    logger.info("  - Lucene configuration is:");
    logger.info(lc.toString());

    try {
        _applicationContext.getBean(DataStore.class);
    } catch (NoSuchBeanDefinitionException e) {
        DataStore dataStore = createShapefileDatastore(luceneDir);
        _applicationContext.getBeanFactory().registerSingleton("dataStore", dataStore);
        //--- no datastore for spatial indexing means that we can't continue
        if (dataStore == null) {
            throw new IllegalArgumentException(
                    "GeoTools datastore creation failed - check logs for more info/exceptions");
        }
    }

    String maxWritesInTransactionStr = handlerConfig.getMandatoryValue(Geonet.Config.MAX_WRITES_IN_TRANSACTION);
    int maxWritesInTransaction = SpatialIndexWriter.MAX_WRITES_IN_TRANSACTION;
    try {
        maxWritesInTransaction = Integer.parseInt(maxWritesInTransactionStr);
    } catch (NumberFormatException nfe) {
        logger.error(
                "Invalid config parameter: maximum number of writes to spatial index in a transaction (maxWritesInTransaction)"
                        + ", Using " + maxWritesInTransaction + " instead.");
        nfe.printStackTrace();
    }

    SettingInfo settingInfo = context.getBean(SettingInfo.class);
    searchMan = _applicationContext.getBean(SearchManager.class);
    searchMan.init(logAsynch, logSpatialObject, luceneTermsToExclude, maxWritesInTransaction);

    // if the validator exists the proxyCallbackURL needs to have the external host and
    // servlet name added so that the cas knows where to send the validation notice
    ServerBeanPropertyUpdater.updateURL(settingInfo.getSiteUrl(true) + baseURL, _applicationContext);

    //------------------------------------------------------------------------
    //--- extract intranet ip/mask and initialize AccessManager

    logger.info("  - Access manager...");

    //------------------------------------------------------------------------
    //--- get edit params and initialize DataManager

    logger.info("  - Xml serializer and Data manager...");

    SvnManager svnManager = _applicationContext.getBean(SvnManager.class);
    XmlSerializer xmlSerializer = _applicationContext.getBean(XmlSerializer.class);

    if (xmlSerializer instanceof XmlSerializerSvn && svnManager != null) {
        svnManager.setContext(context);
        Path subversionPath = dataDirectory.getMetadataRevisionDir().toAbsolutePath().normalize();
        svnManager.setSubversionPath(subversionPath.toString());
        svnManager.init();
    }

    /**
     * Initialize language detector
     */
    LanguageDetector.init(
            appPath.resolve(_applicationContext.getBean(Geonet.Config.LANGUAGE_PROFILES_DIR, String.class)));

    //------------------------------------------------------------------------
    //--- Initialize thesaurus

    logger.info("  - Thesaurus...");

    _applicationContext.getBean(ThesaurusManager.class).init(false, context, thesauriDir);

    //------------------------------------------------------------------------
    //--- initialize catalogue services for the web

    logger.info("  - Open Archive Initiative (OAI-PMH) server...");

    OaiPmhDispatcher oaipmhDis = new OaiPmhDispatcher(settingMan, schemaMan);

    GeonetContext gnContext = new GeonetContext(_applicationContext, false, statusActionsClass);

    //------------------------------------------------------------------------
    //--- return application context

    beanFactory.registerSingleton("serviceHandlerConfig", handlerConfig);
    beanFactory.registerSingleton("oaipmhDisatcher", oaipmhDis);

    _applicationContext.getBean(DataManager.class).init(context, false);
    _applicationContext.getBean(HarvestManager.class).init(context, gnContext.isReadOnly());

    _applicationContext.getBean(ThumbnailMaker.class).init(context);

    logger.info("Site ID is : " + settingMan.getSiteId());

    // Creates a default site logo, only if the logo image doesn't exists
    // This can happen if the application has been updated with a new version preserving the database and
    // images/logos folder is not copied from old application
    createSiteLogo(settingMan.getSiteId(), context, context.getAppPath());

    // Notify unregistered metadata at startup. Needed, for example, when the user enables the notifier config
    // to notify the existing metadata in database
    // TODO: Fix DataManager.getUnregisteredMetadata and uncomment next lines
    metadataNotifierControl = new MetadataNotifierControl(context);
    metadataNotifierControl.runOnce();

    // Reindex Blank template metadata
    DataManager dm = _applicationContext.getBean(DataManager.class);
    Set<Integer> metadataToReindex = new HashSet<>();
    metadataToReindex.add(new Integer(1));
    context.info("Re-indexing metadata");
    BatchOpsMetadataReindexer r = new BatchOpsMetadataReindexer(dm, metadataToReindex);
    r.process();

    //--- load proxy information from settings into Jeeves for observers such
    //--- as jeeves.utils.XmlResolver to use
    ProxyInfo pi = JeevesProxyInfo.getInstance();
    boolean useProxy = settingMan.getValueAsBool("system/proxy/use", false);
    if (useProxy) {
        String proxyHost = settingMan.getValue("system/proxy/host");
        String proxyPort = settingMan.getValue("system/proxy/port");
        String username = settingMan.getValue("system/proxy/username");
        String password = settingMan.getValue("system/proxy/password");
        pi.setProxyInfo(proxyHost, Integer.valueOf(proxyPort), username, password);
    }

    boolean inspireEnable = settingMan.getValueAsBool("system/inspire/enable", false);

    if (inspireEnable) {

        String atomType = settingMan.getValue("system/inspire/atom");
        String atomSchedule = settingMan.getValue("system/inspire/atomSchedule");

        if (StringUtils.isNotEmpty(atomType) && StringUtils.isNotEmpty(atomSchedule)
                && atomType.equalsIgnoreCase(InspireAtomType.ATOM_REMOTE)) {
            logger.info("  - INSPIRE ATOM feed harvester ...");

            InspireAtomHarvesterScheduler.schedule(atomSchedule, context, gnContext);
        }
    }

    //
    // db heartbeat configuration -- for failover to readonly database
    //
    boolean dbHeartBeatEnabled = Boolean
            .parseBoolean(handlerConfig.getValue(Geonet.Config.DB_HEARTBEAT_ENABLED, "false"));
    if (dbHeartBeatEnabled) {
        Integer dbHeartBeatInitialDelay = Integer
                .parseInt(handlerConfig.getValue(Geonet.Config.DB_HEARTBEAT_INITIALDELAYSECONDS, "5"));
        Integer dbHeartBeatFixedDelay = Integer
                .parseInt(handlerConfig.getValue(Geonet.Config.DB_HEARTBEAT_FIXEDDELAYSECONDS, "60"));
        createDBHeartBeat(gnContext, dbHeartBeatInitialDelay, dbHeartBeatFixedDelay);
    }

    fillCaches(context);

    AbstractEntityListenerManager.setSystemRunning(true);
    return gnContext;
}