Example usage for java.util ArrayList addAll

List of usage examples for java.util ArrayList addAll

Introduction

In this page you can find the example usage for java.util ArrayList addAll.

Prototype

public boolean addAll(Collection<? extends E> c) 

Source Link

Document

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.

Usage

From source file:br.ufrgs.inf.dsmoura.repository.controller.solr.SolrConversionUtil.java

public static List<Term> fromAssetToTerms(Asset asset) {
    ArrayList<Term> terms = new ArrayList<Term>();
    terms.addAll(extractTerms(SolrField.ID.getName(), asset.getId(), true));
    terms.addAll(extractTerms(SolrField.NAME.getName(), asset.getName(), false));
    terms.addAll(extractTerms(SolrField.VERSION.getName(), asset.getVersion(), false));
    if (asset.getType() != null) {
        terms.addAll(extractTerms(SolrField.TYPE.getName(), asset.getType().getName(), true));
        if (FieldsUtil.isValidType(asset.getType()) && asset.getType().getName().equalsIgnoreCase("Other")) {
            terms.addAll(extractTerms(SolrField.OTHER_TYPE.getName(), asset.getOtherType(), true));
        }/*from w  w  w. ja va 2  s  .co m*/
    }
    if (asset.getState() != null) {
        terms.addAll(extractTerms(SolrField.STATE.getName(), asset.getState().getName(), true));
    }
    if (asset.getSoftwareLicenseDTO() != null) {
        terms.addAll(extractTerms(SolrField.SOFTWARE_LICENSE_ASSET.getName(),
                asset.getSoftwareLicenseDTO().getName(), true));
        if (FieldsUtil.isValidSoftwareLicense(asset.getSoftwareLicenseDTO())
                && asset.getSoftwareLicenseDTO().getName().equalsIgnoreCase("Other")) {
            terms.addAll(extractTerms(SolrField.OTHER_SOFTWARE_LICENSE_ASSET.getName(),
                    asset.getOtherSoftwareLicense(), true));
        }
    }

    /* USAGE */
    if (asset.getUsage().getCreatorUsername() != null) {
        terms.addAll(
                extractTerms(SolrField.CREATOR_NAME.getName(), asset.getUsage().getCreatorUsername(), true));
    }
    if (asset.getUsage().getAuthorUserDTO() != null) {
        terms.addAll(extractTerms(SolrField.AUTHOR_USERNAME.getName(),
                asset.getUsage().getAuthorUserDTO().getUsername(), true));
        terms.addAll(extractTerms(SolrField.AUTHOR_NAME.getName(),
                asset.getUsage().getAuthorUserDTO().getName(), true));
    }
    if (asset.getUsage().getCertifierUserDTO() != null) {
        terms.addAll(extractTerms(SolrField.CERTIFIER_USERNAME.getName(),
                asset.getUsage().getCertifierUserDTO().getUsername(), true));
        terms.addAll(extractTerms(SolrField.CERTIFIER_NAME.getName(),
                asset.getUsage().getCertifierUserDTO().getName(), true));
    }
    for (ConsumptionDTO consumptionDTO : asset.getUsage().getConsumptionDTOs()) {
        terms.addAll(extractTerms(SolrField.CONSUMER_USERNAME.getName(),
                consumptionDTO.getConsumerUserDTO().getUsername(), true));
        terms.addAll(extractTerms(SolrField.CONSUMER_NAME.getName(),
                consumptionDTO.getConsumerUserDTO().getName(), true));
    }
    for (UserCommentDTO userCommentDTO : asset.getUsage().getUserCommentDTOs()) {
        terms.addAll(extractTerms(SolrField.USER_COMMENT_USERNAME.getName(),
                userCommentDTO.getUserDTO().getUsername(), true));
        terms.addAll(extractTerms(SolrField.USER_COMMENT_USER_NAME.getName(),
                userCommentDTO.getUserDTO().getName(), true));
    }

    /* CLASSIFICATION */
    for (ApplicationSubdomain applicationSubdomain : asset.getClassification().getApplicationSubdomains()) {
        if (applicationSubdomain.getName() != null) {
            terms.addAll(extractTerms(SolrField.APPLICATION_SUBDOMAIN.getName(), applicationSubdomain.getName(),
                    true));
        }
        if (applicationSubdomain.getApplicationDomain() != null
                && applicationSubdomain.getApplicationDomain().getName() != null) {
            terms.addAll(extractTerms(SolrField.APPLICATION_DOMAIN.getName(),
                    applicationSubdomain.getApplicationDomain().getName(), true));
        }
        if (FieldsUtil.isValidApplicationSubdomain(applicationSubdomain)
                && applicationSubdomain.getName().equalsIgnoreCase("Other")) {
            terms.addAll(extractTerms(SolrField.OTHER_APPLICATION_DOMAIN.getName(),
                    asset.getClassification().getOtherApplicationDomain(), true));
            terms.addAll(extractTerms(SolrField.OTHER_APPLICATION_SUBDOMAIN.getName(),
                    asset.getClassification().getOtherApplicationSubdomain(), true));
        }
    }
    for (ProjectDTO project : asset.getClassification().getProjectDTOs()) {
        if (project.getName() != null) {
            terms.addAll(extractTerms(SolrField.PROJECT.getName(), project.getName(), true));
        }
        if (project.getOrganizationDTO().getName() != null) {
            terms.addAll(extractTerms(SolrField.ORGANIZATION.getName(), project.getOrganizationDTO().getName(),
                    true));
        }
    }
    for (TagDTO tagDTO : asset.getClassification().getTagDTOs()) {
        if (tagDTO != null) {
            terms.addAll(extractTerms(SolrField.TAG.getName(), tagDTO.getName(), true));
        }
    }

    /* REQUIREMENTS */
    for (InternationalizationTypeDTO internat : asset.getSolution().getRequirements()
            .getInternationalizationTypeDTOs()) {
        if (internat != null) {
            terms.addAll(extractTerms(SolrField.LANGUAGE.getName(), internat.getName(), true));
        }
    }
    for (OperationalSystemTypeDTO operSyst : asset.getSolution().getRequirements()
            .getOperationalSystemTypeDTOs()) {
        if (operSyst != null) {
            terms.addAll(extractTerms(SolrField.OPERATIONAL_SYSTEM.getName(), operSyst.getName(), true));
        }
    }
    for (FunctionalRequirementDTO functional : asset.getSolution().getRequirements()
            .getFunctionalRequirementDTOs()) {
        if (functional != null && functional.getFunctionalRequirementTypeDTO() != null) {
            terms.addAll(extractTerms(SolrField.FUNCTIONAL_REQUIREMENT_TYPE.getName(),
                    functional.getFunctionalRequirementTypeDTO().getName(), true));
        }
    }
    for (NonFunctionalRequirementDTO nonFunctional : asset.getSolution().getRequirements()
            .getNonFunctionalRequirementDTOs()) {
        if (nonFunctional != null && nonFunctional.getNonFunctionalRequirementTypeDTO() != null) {
            terms.addAll(extractTerms(SolrField.NON_FUNCTIONAL_REQUIREMENT_TYPE.getName(),
                    nonFunctional.getNonFunctionalRequirementTypeDTO().getName(), true));
        }
    }

    /* DESIGN */
    for (InterfaceSpecDTO specDTO : asset.getSolution().getDesign().getInterfaceSpecDTOs()) {
        if (specDTO != null) {
            terms.addAll(extractTerms(SolrField.INTERFACE_SPEC.getName(), specDTO.getName(), false));
            if (specDTO.getOperationDTOs().size() > 0) {
                OperationDTO operationDTO = specDTO.getOperationDTOs().get(0);
                if (operationDTO != null) {
                    terms.addAll(
                            extractTerms(SolrField.OPERATION_NAME.getName(), operationDTO.getName(), false));
                }
            }
        }

    }

    /* IMPLEMENTATION */
    for (ProgrammingLanguageDTO progrLang : asset.getSolution().getImplementation()
            .getProgrammingLanguageDTOs()) {
        if (progrLang != null) {
            terms.addAll(extractTerms(SolrField.PROGRAMMING_LANGUAGE.getName(), progrLang.getName(), true));
        }
        if (FieldsUtil.isValidProgrammingLanguage(progrLang) && progrLang.getName().equalsIgnoreCase("Other")) {
            terms.addAll(extractTerms(SolrField.OTHER_PROGRAMMING_LANGUAGE.getName(),
                    asset.getSolution().getImplementation().getOtherProgrammingLanguage(), true));
        }
    }
    for (DesignPatternDTO designPatternDTO : asset.getSolution().getImplementation().getDesignPatternDTOs()) {
        if (designPatternDTO != null) {
            terms.addAll(extractTerms(SolrField.DESIGN_PATTERN.getName(), designPatternDTO.getName(), true));
        }
    }

    for (SourceCodeDTO sourceCodeDTO : asset.getSolution().getImplementation().getSourceCodeDTOs()) {
        if (sourceCodeDTO != null) {
            if (sourceCodeDTO.getSourceCodeTypeDTO() != null) {
                terms.addAll(extractTerms(SolrField.SOURCE_CODE_TYPE.getName(), sourceCodeDTO.getName(), true));
            }
            if (sourceCodeDTO.getSoftwareLicenseDTO() != null) {
                terms.addAll(extractTerms(SolrField.SOFTWARE_LICENSE.getName(), sourceCodeDTO.getName(), true));
            }
        }
    }

    for (UserInterfaceDTO uiDTO : asset.getSolution().getImplementation().getUserInterfaceDTOs()) {
        if (uiDTO != null) {
            if (uiDTO.getUserInterfaceTypeDTO() != null) {
                terms.addAll(extractTerms(SolrField.USER_INTERFACE_TYPE.getName(), uiDTO.getName(), true));
            }
        }
    }

    /* TEST */
    for (TestTypeDTO testTypeDTO : asset.getSolution().getTest().getTestTypeDTOs()) {
        if (testTypeDTO != null) {
            terms.addAll(extractTerms(SolrField.TEST_TYPE.getName(), testTypeDTO.getName(), true));
        }
    }
    for (TestMethodTypeDTO testMethodTypeDTO : asset.getSolution().getTest().getTestMethodTypeDTOs()) {
        if (testMethodTypeDTO != null) {
            terms.addAll(extractTerms(SolrField.TEST_METHOD_TYPE.getName(), testMethodTypeDTO.getName(), true));
        }
    }
    for (ProgrammingLanguageDTO progrLang : asset.getSolution().getTest().getProgrammingLanguageDTOs()) {
        if (progrLang != null) {
            terms.addAll(extractTerms(SolrField.PROGRAMMING_LANGUAGE.getName(), progrLang.getName(), true));
            if (FieldsUtil.isValidProgrammingLanguage(progrLang)
                    && progrLang.getName().equalsIgnoreCase("Other")) {
                terms.addAll(extractTerms(SolrField.OTHER_PROGRAMMING_LANGUAGE.getName(),
                        asset.getSolution().getTest().getOtherProgrammingLanguage(), true));
            }
        }
    }
    for (DesignPatternDTO designPatternDTO : asset.getSolution().getTest().getDesignPatternDTOs()) {
        if (designPatternDTO != null) {
            terms.addAll(extractTerms(SolrField.DESIGN_PATTERN.getName(), designPatternDTO.getName(), true));
        }
    }
    for (RelatedAsset relatedAsset : asset.getRelatedAssets()) {
        if (relatedAsset != null) {
            terms.addAll(extractTerms(SolrField.RELATED_ASSET_ID.getName(), relatedAsset.getId(), true));
            terms.addAll(extractTerms(SolrField.RELATED_ASSET_NAME.getName(), relatedAsset.getName(), false));
            terms.addAll(
                    extractTerms(SolrField.RELATED_ASSET_VERSION.getName(), relatedAsset.getVersion(), false));
            if (relatedAsset.getRelatedAssetTypeDTO() != null) {
                terms.addAll(extractTerms(SolrField.RELATED_ASSET_TYPE.getName(),
                        relatedAsset.getRelatedAssetTypeDTO().getName(), true));
            }
        }
    }

    if (terms.size() == 0) {
        logger.warn("term list is empty!");
    } else {
        logger.info("terms: " + terms);
    }
    return terms;
}

From source file:com.android.quicksearchbox.ShortcutRepositoryTest.java

static <A extends Comparable<A>, B extends Comparable<B>> List<A> sortByValues(Map<A, B> map) {
    Comparator<Map.Entry<A, B>> comp = new Comparator<Map.Entry<A, B>>() {
        public int compare(Entry<A, B> object1, Entry<A, B> object2) {
            int diff = object1.getValue().compareTo(object2.getValue());
            if (diff != 0) {
                return diff;
            } else {
                return object1.getKey().compareTo(object2.getKey());
            }//from w  ww  .j a  v a2s  .c  o m
        }
    };
    ArrayList<Map.Entry<A, B>> sorted = new ArrayList<Map.Entry<A, B>>(map.size());
    sorted.addAll(map.entrySet());
    Collections.sort(sorted, comp);
    ArrayList<A> out = new ArrayList<A>(sorted.size());
    for (Map.Entry<A, B> e : sorted) {
        out.add(e.getKey());
    }
    return out;
}

From source file:org.opendatakit.odktables.relation.DbColumnDefinitions.java

/**
 * This code needs to parallel that of the javascript in ODK Survey and the java
 * code in ODK Tables and the ODK Database layer.
 * //from w  ww.  j av a  2s.  c  o m
 * @param defnList
 */
public static void markUnitOfRetention(List<DbColumnDefinitionsEntity> defnList) {
    // for all arrays, mark all descendants of the array as not-retained
    // because they are all folded up into the json representation of the array
    Map<String, DbColumnDefinitionsEntity> defn = new HashMap<String, DbColumnDefinitionsEntity>();
    for (DbColumnDefinitionsEntity colDefn : defnList) {
        defn.put(colDefn.getElementKey(), colDefn);
    }

    for (DbColumnDefinitionsEntity colDefn : defnList) {
        if (!colDefn.isUnitOfRetention()) {
            // this has already been processed
            continue;
        }
        String elementType = colDefn.getElementType();
        ArrayList<String> childElementKeys = colDefn.getArrayListChildElementKeys();
        ElementType type = ElementType.parseElementType(elementType, !childElementKeys.isEmpty());
        if (type.getDataType() == ElementDataType.array) {
            ArrayList<String> scratchArray = new ArrayList<String>();
            while (!childElementKeys.isEmpty()) {
                for (String childKey : childElementKeys) {
                    DbColumnDefinitionsEntity subDefn = defn.get(childKey);
                    if (!subDefn.isUnitOfRetention()) {
                        // this has already been processed
                        continue;
                    }
                    subDefn.setNotUnitOfRetention();
                    if (subDefn.getListChildElementKeys() != null) {
                        scratchArray.addAll(subDefn.getArrayListChildElementKeys());
                    }
                }
                childElementKeys = scratchArray;
                scratchArray = new ArrayList<String>();
            }
        }
    }
    // and mark any non-arrays with multiple fields as not retained
    for (DbColumnDefinitionsEntity colDefn : defnList) {
        if (!colDefn.isUnitOfRetention()) {
            // this has already been processed
            continue;
        }
        String elementType = colDefn.getElementType();
        ArrayList<String> childElementKeys = colDefn.getArrayListChildElementKeys();
        ElementType type = ElementType.parseElementType(elementType, !childElementKeys.isEmpty());
        if (type.getDataType() != ElementDataType.array) {
            if (!colDefn.getArrayListChildElementKeys().isEmpty()) {
                colDefn.setNotUnitOfRetention();
            }
        }
    }
}

From source file:com.siemens.sw360.importer.ComponentImportUtils.java

public static RequestSummary writeToDatabase(Iterable<ComponentCSVRecord> compCSVRecords,
        ComponentService.Iface componentClient, VendorService.Iface vendorClient,
        AttachmentService.Iface attachmentClient, User user) throws TException {

    Map<String, String> vendorNameToVendorId = getVendorNameToId(compCSVRecords, vendorClient);
    log.debug(format("Read vendors: (%d) %s ", vendorNameToVendorId.size(), vendorNameToVendorId));

    final RequestSummary componentRequestSummary = updateComponents(compCSVRecords, componentClient, user);

    Map<String, String> componentNameToId = new HashMap<>();
    final ArrayList<Release> releases = new ArrayList<>();
    for (Component component : componentClient.getComponentDetailedSummaryForExport()) {
        componentNameToId.put(component.getName(), component.getId());
        final List<Release> componentReleases = component.getReleases();
        if (componentReleases != null && componentReleases.size() > 0)
            releases.addAll(componentReleases);
    }//from   w  w w. jav a2s. com
    Set<String> knownReleaseIdentifiers = Sets.newHashSet(getReleaseIdentifiers(releases));

    List<ComponentCSVRecord> relevantCSVRecords = new ArrayList<>();
    final HashMap<String, List<String>> releaseIdentifierToDownloadURL = new HashMap<>();

    List<AttachmentContent> attachmentContentsToUpdate = new ArrayList<>();

    filterRelevantCSVRecordsAndGetAttachmentContents(compCSVRecords, componentNameToId, knownReleaseIdentifiers,
            relevantCSVRecords, releaseIdentifierToDownloadURL, attachmentContentsToUpdate);

    attachmentContentsToUpdate = attachmentClient.makeAttachmentContents(attachmentContentsToUpdate);
    final ImmutableMap<String, AttachmentContent> URLtoAttachment = Maps.uniqueIndex(attachmentContentsToUpdate,
            new Function<AttachmentContent, String>() {
                @Override
                public String apply(AttachmentContent input) {
                    return input.getRemoteUrl();
                }
            });

    Set<Release> releasesToUpdate = new HashSet<>();

    //I do not need so many checks here because I only iterate over the relevant CSV records
    for (ComponentCSVRecord componentCSVRecord : relevantCSVRecords) {
        String releaseIdentifier = componentCSVRecord.getReleaseIdentifier();
        String vendorName = componentCSVRecord.getVendorName();
        String vendorId = vendorNameToVendorId.get(vendorName);

        String componentId = componentNameToId.get(componentCSVRecord.getComponentName());
        List<AttachmentContent> attachmentContents = getAttachmentContents(releaseIdentifierToDownloadURL,
                URLtoAttachment, releaseIdentifier);

        Release releaseToAdd = componentCSVRecord.getRelease(vendorId, componentId, attachmentContents);
        knownReleaseIdentifiers.add(releaseIdentifier);
        if (releaseToAdd != null) {
            releasesToUpdate.add(releaseToAdd);
        }

    }

    final RequestSummary releaseRequestSummary = componentClient.updateReleases(releasesToUpdate, user);

    return CommonUtils.addRequestSummaries(componentRequestSummary, "component", releaseRequestSummary,
            "release");
}

From source file:com.projity.pm.assignment.HasAssignmentsImpl.java

public static List extractOppositeList(List list, boolean leftObject) {
    Iterator i = list.iterator();
    ArrayList assignments = new ArrayList();
    while (i.hasNext()) { // go thru tasks or resources
        Object object = i.next();
        if (!(object instanceof HasAssignments))
            continue; //TODO currently getting voidNodeImpl's.  This should go away when fixed
        HasAssignments hasAssignments = (HasAssignments) object;
        assignments.addAll(hasAssignments.getAssignments());
    }/*  w w w. jav  a 2s  .c o m*/
    return AssociationList.extractDistinct(assignments, leftObject);
}

From source file:it.tizianofagni.sparkboost.DataUtils.java

public static JavaRDD<LabelDocuments> getLabelDocuments(JavaRDD<MultilabelPoint> documents) {
    return documents.flatMapToPair(doc -> {
        int[] labels = doc.getLabels();
        ArrayList<Integer> docAr = new ArrayList<Integer>();
        docAr.add(doc.getPointID());//from  w  w  w.jav a 2  s  .c om
        ArrayList<Tuple2<Integer, ArrayList<Integer>>> ret = new ArrayList<Tuple2<Integer, ArrayList<Integer>>>();
        for (int i = 0; i < labels.length; i++) {
            ret.add(new Tuple2<>(labels[i], docAr));
        }
        return ret;
    }).reduceByKey((list1, list2) -> {
        ArrayList<Integer> ret = new ArrayList<Integer>();
        ret.addAll(list1);
        ret.addAll(list2);
        Collections.sort(ret);
        return ret;
    }).map(item -> {
        return new LabelDocuments(item._1(), item._2().stream().mapToInt(i -> i).toArray());
    });
}

From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java

static public IDPConfiguration generateIDPConfiguration(IDPConfig idmIdpConfig) {

    Validate.notNull(idmIdpConfig, "IDPConfig for the external IDP is not intialized");

    ArrayList<String> nameIDFormatStrs = null;
    if (idmIdpConfig.getNameIDFormats() != null) {
        nameIDFormatStrs = new ArrayList<String>(idmIdpConfig.getNameIDFormats());
    }/*  www. j  av a  2  s .  co  m*/

    //Creating a com.vmware.identity.websso.client.SingleSignOnService list
    Validate.notNull(idmIdpConfig.getSsoServices(), "IDPConfig SsoServices is not initialized");
    ArrayList<ServiceEndpoint> idm_sso_services = new ArrayList<ServiceEndpoint>(idmIdpConfig.getSsoServices());
    ArrayList<com.vmware.identity.websso.client.SingleSignOnService> ssolib_sso_services = new ArrayList<com.vmware.identity.websso.client.SingleSignOnService>();

    for (ServiceEndpoint s : idm_sso_services) {
        com.vmware.identity.websso.client.SingleSignOnService ssolib_sso_service = new com.vmware.identity.websso.client.SingleSignOnService(
                s.getEndpoint(), s.getBinding());
        ssolib_sso_services.add(ssolib_sso_service);
    }
    Validate.notEmpty(ssolib_sso_services, "Empty client lib SingleSignOnService");

    //Creating a com.vmware.identity.websso.client.SingleLogoutService list
    ArrayList<ServiceEndpoint> idm_slo_services = new ArrayList<ServiceEndpoint>();
    if (idmIdpConfig.getSloServices() != null) {
        idm_slo_services.addAll(idmIdpConfig.getSloServices());
    }
    ArrayList<com.vmware.identity.websso.client.SingleLogoutService> ssolib_slo_services = new ArrayList<com.vmware.identity.websso.client.SingleLogoutService>();

    for (ServiceEndpoint m : idm_slo_services) {
        com.vmware.identity.websso.client.SingleLogoutService ssolib_slo_service = new com.vmware.identity.websso.client.SingleLogoutService(
                m.getEndpoint(), m.getBinding());
        ssolib_slo_services.add(ssolib_slo_service);
    }

    String idpAlias = (idmIdpConfig.getAlias() == null || idmIdpConfig.getAlias().isEmpty())
            ? idmIdpConfig.getEntityID()
            : idmIdpConfig.getAlias();
    IDPConfiguration clientIdpConfig = IDPConfigurationFactory.createIDPConfigurationWithoutSiteAffinity(
            idpAlias, idmIdpConfig.getEntityID(), idmIdpConfig.getSigningCertificateChain().get(0), //TODO should client lib take a chain?
            nameIDFormatStrs, ssolib_sso_services, ssolib_slo_services);
    log.debug("created IDPConfig for external authn : idpAlias=" + idmIdpConfig.getAlias() + "entityID="
            + idmIdpConfig.getEntityID());
    return clientIdpConfig;
}

From source file:com.nubits.nubot.options.OptionsJSON.java

/**
 *
 * @param paths/*from   w  ww . j  av  a 2 s.  c  om*/
 * @return
 */
public static OptionsJSON parseOptions(String[] paths) {
    OptionsJSON options = null;
    ArrayList<String> filePaths = new ArrayList();
    filePaths.addAll(Arrays.asList(paths));

    try {
        JSONObject inputJSON = parseFiles(filePaths);
        JSONObject optionsJSON = (JSONObject) inputJSON.get("options");

        //First try to parse compulsory parameters
        String exchangeName = (String) optionsJSON.get("exchangename");

        String apiKey = "";

        if (!exchangeName.equalsIgnoreCase(Constant.CCEX)) { //for ccex this parameter can be omitted
            if (!optionsJSON.containsKey("apikey")) {
                Utils.exitWithMessage("The apikey parameter is compulsory.");
            } else {
                apiKey = (String) optionsJSON.get("apikey");
            }

        }

        String apiSecret = (String) optionsJSON.get("apisecret");

        String mailRecipient = (String) optionsJSON.get("mail-recipient");

        String pairStr = (String) optionsJSON.get("pair");
        CurrencyPair pair = CurrencyPair.getCurrencyPairFromString(pairStr, "_");

        boolean aggregate = true; //true only for USD
        if (!pair.getPaymentCurrency().getCode().equalsIgnoreCase("USD")) {
            aggregate = false; //default to false
        }

        boolean dualside = (boolean) optionsJSON.get("dualside");

        //Based on the pair, set a parameter do define whether setting SecondaryPegOptionsJSON i necessary or not
        boolean requireCryptoOptions = Utils.requiresSecondaryPegStrategy(pair);
        org.json.JSONObject pegOptionsJSON;
        SecondaryPegOptionsJSON cpo = null;
        if (requireCryptoOptions) {

            if (optionsJSON.containsKey("secondary-peg-options")) {

                Map setMap = new HashMap();

                //convert from simple JSON to org.json.JSONObject
                JSONObject oldObject = (JSONObject) optionsJSON.get("secondary-peg-options");

                Set tempSet = oldObject.entrySet();
                for (Object o : tempSet) {
                    Map.Entry entry = (Map.Entry) o;
                    setMap.put(entry.getKey(), entry.getValue());
                }

                pegOptionsJSON = new org.json.JSONObject(setMap);
                cpo = SecondaryPegOptionsJSON.create(pegOptionsJSON, pair);
            } else {
                LOG.severe("secondary-peg-options are required in the options");
                System.exit(0);
            }

            /*
             org.json.JSONObject jsonString = new org.json.JSONObject(optionsString);
             org.json.JSONObject optionsJSON2 = (org.json.JSONObject) jsonString.get("options");
             pegOptionsJSON = (org.json.JSONObject) optionsJSON2.get("secondary-peg-options");
             cpo = SecondaryPegOptionsJSON.create(pegOptionsJSON, pair);*/
        }

        //Then parse optional settings. If not use the default value declared here

        String nudIp = "127.0.0.1";
        boolean sendMails = true;
        boolean submitLiquidity = true;
        boolean executeOrders = true;
        boolean verbose = false;
        boolean sendHipchat = true;

        boolean multipleCustodians = false;
        int executeStrategyInterval = 41;
        int sendLiquidityInterval = Integer.parseInt(Global.settings.getProperty("submit_liquidity_seconds"));

        double txFee = 0.2;
        double priceIncrement = 0.0003;
        double keepProceeds = 0;

        double maxSellVolume = 0;
        double maxBuyVolume = 0;

        int emergencyTimeout = 60;

        if (optionsJSON.containsKey("nudip")) {
            nudIp = (String) optionsJSON.get("nudip");
        }

        if (optionsJSON.containsKey("priceincrement")) {
            priceIncrement = Utils.getDouble(optionsJSON.get("priceincrement"));
        }

        if (optionsJSON.containsKey("txfee")) {
            txFee = Utils.getDouble(optionsJSON.get("txfee"));
        }

        if (optionsJSON.containsKey("submit-liquidity")) {
            submitLiquidity = (boolean) optionsJSON.get("submit-liquidity");
        }

        if (optionsJSON.containsKey("max-sell-order-volume")) {
            maxSellVolume = Utils.getDouble(optionsJSON.get("max-sell-order-volume"));
        }

        if (optionsJSON.containsKey("max-buy-order-volume")) {
            maxBuyVolume = Utils.getDouble(optionsJSON.get("max-buy-order-volume"));
        }

        //Now require the parameters only if submitLiquidity is true, otherwise can use the default value

        String nubitAddress = "", rpcPass = "", rpcUser = "";
        int nudPort = 9091;

        if (submitLiquidity) {
            if (optionsJSON.containsKey("nubitaddress")) {
                nubitAddress = (String) optionsJSON.get("nubitaddress");
            } else {
                Utils.exitWithMessage("When submit-liquidity is set to true "
                        + "you need to declare a value for \"nubitaddress\" ");
            }

            if (optionsJSON.containsKey("rpcpass")) {
                rpcPass = (String) optionsJSON.get("rpcpass");
            } else {
                Utils.exitWithMessage("When submit-liquidity is set to true "
                        + "you need to declare a value for \"rpcpass\" ");
            }

            if (optionsJSON.containsKey("rpcuser")) {
                rpcUser = (String) optionsJSON.get("rpcuser");
            } else {
                Utils.exitWithMessage("When submit-liquidity is set to true "
                        + "you need to declare a value for \"rpcuser\" ");
            }

            if (optionsJSON.containsKey("nudport")) {
                long nudPortlong = (long) optionsJSON.get("nudport");
                nudPort = (int) nudPortlong;
            } else {
                Utils.exitWithMessage("When submit-liquidity is set to true "
                        + "you need to declare a value for \"nudport\" ");
            }

        }

        if (optionsJSON.containsKey("executeorders")) {
            executeOrders = (boolean) optionsJSON.get("executeorders");
        }

        if (optionsJSON.containsKey("verbose")) {
            verbose = (boolean) optionsJSON.get("verbose");
        }

        if (optionsJSON.containsKey("hipchat")) {
            sendHipchat = (boolean) optionsJSON.get("hipchat");
        }

        if (optionsJSON.containsKey("mail-notifications")) {
            sendMails = (boolean) optionsJSON.get("mail-notifications");
        }

        /*Ignore this parameter to prevent one custodian to execute faster than others (walls collapsing)
         if (optionsJSON.containsKey("check-balance-interval")) {
         long checkBalanceIntervallong = (long) optionsJSON.get("check-balance-interval");
         checkBalanceInterval = (int) checkBalanceIntervallong;
         }
                
         if (optionsJSON.containsKey("check-orders-interval")) {
         long checkOrdersIntevallong = (long) optionsJSON.get("check-orders-interval");
         checkOrdersInteval = (int) checkOrdersIntevallong;
         }
         */

        if (optionsJSON.containsKey("emergency-timeout")) {
            long emergencyTimeoutLong = (long) optionsJSON.get("emergency-timeout");
            emergencyTimeout = (int) emergencyTimeoutLong;
        }

        if (optionsJSON.containsKey("keep-proceeds")) {
            keepProceeds = Utils.getDouble((optionsJSON.get("keep-proceeds")));
        }

        if (optionsJSON.containsKey("multiple-custodians")) {
            multipleCustodians = (boolean) optionsJSON.get("multiple-custodians");
        }
        //Create a new Instance
        options = new OptionsJSON(dualside, apiKey, apiSecret, nubitAddress, rpcUser, rpcPass, nudIp, nudPort,
                priceIncrement, txFee, submitLiquidity, exchangeName, executeOrders, verbose, pair,
                executeStrategyInterval, sendLiquidityInterval, sendHipchat, sendMails, mailRecipient,
                emergencyTimeout, keepProceeds, aggregate, multipleCustodians, maxSellVolume, maxBuyVolume,
                cpo);

    } catch (NumberFormatException e) {
        LOG.severe("Error while parsing the options file : " + e);
    }
    return options;
}

From source file:de.mpg.mpdl.inge.transformation.Util.java

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * //from   w ww  . ja v  a 2s .co  m
 * @param model The type of object (e.g. "persons")
 * @param name The query string.
 * @param ou Specialty for persons
 * @param coneSession A JSESSIONID to not produce a new session with each call.
 * @return A DOM node containing the results.
 */
public static Node queryConeExactWithIdentifier(String model, String identifier, String ou) {
    DocumentBuilder documentBuilder;

    try {
        logger.info("queryConeExactWithIdentifier: " + model + " identifier: " + identifier + " ou: " + ou);

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);

        String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/query?format=jquery&dc:identifier/" + URLEncoder.encode("rdf:value", "UTF-8") + "="
                + URLEncoder.encode("\"" + identifier + "\"", "UTF-8") + "&"
                + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "="
                + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8");
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);
        logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
        if (method.getStatusCode() == 200) {
            ArrayList<String> results = new ArrayList<String>();
            results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n")));
            Set<String> oldIds = new HashSet<String>();
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String id = result.split("\\|")[1];
                    if (!oldIds.contains(id)) {
                        // TODO "&redirect=true" must be reinserted again
                        GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle="
                                + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")));
                        detailMethod.setFollowRedirects(true);

                        ProxyHelper.setProxy(client, detailsUrl.replace("$1", id));
                        client.executeMethod(detailMethod);
                        // TODO "&redirect=true" must be reinserted again
                        logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle="
                                + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))
                                + " returned " + detailMethod.getResponseBodyAsString());
                        if (detailMethod.getStatusCode() == 200) {
                            Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
                            element.appendChild(document.importNode(details.getFirstChild(), true));
                        } else {
                            logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                                    + detailMethod.getResponseBodyAsString());
                        }
                        oldIds.add(id);
                    }
                }
            }
        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }
        return document;
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. "
                + "Otherwise it should be clarified if any measures have to be taken.", e);
        return null;
        // throw new RuntimeException(e);
    }
}

From source file:com.clustercontrol.jobmanagement.util.JobUtil.java

/**
 * ??????/*from  w ww.  j av  a  2s .  c o m*/
 * @param item
 * @param list
 * @return
 */
public static ArrayList<JobInfo> findReferJob(JobTreeItem item) {
    ArrayList<JobInfo> ret = new ArrayList<JobInfo>();
    if (item == null || item.getData() == null) {
        return ret;
    }
    //ID?
    m_log.trace("checkReferJob Id=" + item.getData().getId());
    JobInfo jobInfo = item.getData();
    if (jobInfo.getType() == JobConstant.TYPE_REFERJOB) {
        if (jobInfo.getReferJobUnitId() != null && jobInfo.getReferJobId() != null) {
            ret.add(item.getData());
            m_log.trace("JobId =" + jobInfo.getId() + ", UnitId =" + jobInfo.getReferJobUnitId()
                    + ", referJobId =" + jobInfo.getReferJobId());
        }
    }
    //?JobTreeItem?
    for (JobTreeItem child : item.getChildren()) {
        ret.addAll(findReferJob(child));
    }
    return ret;
}