Example usage for java.util LinkedHashSet add

List of usage examples for java.util LinkedHashSet add

Introduction

In this page you can find the example usage for java.util LinkedHashSet add.

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (optional operation).

Usage

From source file:lv.semti.morphology.webservice.VerbResource.java

private String tagChunk(LinkedList<Word> tokens) {
     LinkedHashSet<String> tags = new LinkedHashSet<String>();
     // da?di minjumi. norm?li bu tikai ar sintakses analzi
     //tags.add(String.valueOf(tokens.size()));
     //tags.add(tokens.get(0).getToken());
     //tags.add(tokens.get(0).getPartOfSpeech());
     if (tokens.size() > 1 && tokens.get(0).isRecognized()
             && tokens.get(0).hasAttribute(AttributeNames.i_PartOfSpeech, AttributeNames.v_Preposition)) {
         // ja fr?ze s?kas ar priev?rdu
         for (Wordform wf : tokens.get(0).wordforms) {
             //tags.add(wf.getDescription());
             if (wf.isMatchingStrong(AttributeNames.i_PartOfSpeech, AttributeNames.v_Preposition)) {
                 String ncase = wf.getValue(AttributeNames.i_Rekcija);
                 if (ncase != null)
                     tags.add(wf.getToken() + caseCode(ncase));
             }//  www  .j a  v  a  2s . c  o m
         }
     }

     //ja s?kas ar saikli, tad vareetu buut paliigteikums
     if (tokens.size() > 1 && tokens.get(0).isRecognized()
             && tokens.get(0).hasAttribute(AttributeNames.i_PartOfSpeech, AttributeNames.v_Conjunction)) {
         tags.add("S");
     }

     if (tags.isEmpty())
         return tagWord(tokens.getLast(), false); // Ja nesaprat?m, dodam pdj? v?rda analzi - Gunta teica, ka esot ticam?k t?

     return formatJSON(tags);
 }

From source file:org.eclipse.skalli.view.internal.filter.ext.GitGerritFilter.java

Set<String> getRepositoryNames(List<Project> projects, Pattern scmPattern) {
    LinkedHashSet<String> repositoryNames = new LinkedHashSet<String>();
    for (Project project : projects) {
        DevInfProjectExt devInf = project.getExtension(DevInfProjectExt.class);
        if (devInf == null || project.isInherited(DevInfProjectExt.class)) {
            continue;
        }//from   w ww  .  j  av  a2 s  .co m
        for (String scmLocation : devInf.getScmLocations()) {
            Matcher matcher = scmPattern.matcher(scmLocation);
            if (matcher.matches() && matcher.groupCount() > 0) {
                repositoryNames.add(matcher.group(1));
            }
        }
    }
    return repositoryNames;
}

From source file:com.unboundid.scim.tools.SCIMQueryRate.java

/**
 * {@inheritDoc}//from ww  w  .j  a v a 2 s  .  c  o  m
 */
@Override()
public void addToolArguments(final ArgumentParser parser) throws ArgumentException {
    host = new StringArgument('h', "hostname", true, 1, INFO_QUERY_TOOL_ARG_PLACEHOLDER_HOSTNAME.get(),
            INFO_QUERY_TOOL_ARG_DESC_HOSTNAME.get(), "localhost");
    parser.addArgument(host);

    port = new IntegerArgument('p', "port", true, 1, INFO_QUERY_TOOL_ARG_PLACEHOLDER_PORT.get(),
            INFO_QUERY_TOOL_ARG_DESC_PORT.get(), 1, 65535, 80);
    parser.addArgument(port);

    contextPath = new StringArgument(null, "contextPath", false, 1,
            INFO_QUERY_TOOL_ARG_PLACEHOLDER_CONTEXT_PATH.get(), INFO_QUERY_TOOL_ARG_DESC_CONTEXT_PATH.get(),
            Arrays.asList("/"));
    parser.addArgument(contextPath);

    authID = new StringArgument(null, "authID", false, 1, INFO_QUERY_TOOL_ARG_PLACEHOLDER_AUTHID.get(),
            INFO_QUERY_TOOL_ARG_DESC_AUTHID.get());
    parser.addArgument(authID);

    authPassword = new StringArgument('w', "authPassword", false, 1,
            INFO_QUERY_TOOL_ARG_PLACEHOLDER_AUTH_PASSWORD.get(), INFO_QUERY_TOOL_ARG_DESC_AUTH_PASSWORD.get());
    parser.addArgument(authPassword);

    bearerToken = new StringArgument(null, "bearerToken", false, 1,
            INFO_QUERY_TOOL_ARG_PLACEHOLDER_BEARER_TOKEN.get(), INFO_QUERY_TOOL_ARG_DESC_BEARER_TOKEN.get());
    parser.addArgument(bearerToken);

    authPasswordFile = new FileArgument('j', "authPasswordFile", false, 1,
            INFO_QUERY_TOOL_ARG_PLACEHOLDER_AUTH_PASSWORD_FILE.get(),
            INFO_QUERY_TOOL_ARG_DESC_AUTH_PASSWORD_FILE.get(), true, true, true, false);
    parser.addArgument(authPasswordFile);

    resourceName = new StringArgument(null, "resourceName", false, 1,
            INFO_QUERY_TOOL_ARG_PLACEHOLDER_RESOURCE_NAME.get(), INFO_QUERY_TOOL_ARG_DESC_RESOURCE_NAME.get(),
            null, Arrays.asList("User"));
    parser.addArgument(resourceName);

    xmlFormat = new BooleanArgument('x', "xml", 1, INFO_QUERY_TOOL_ARG_DESC_XML_FORMAT.get());
    parser.addArgument(xmlFormat);

    filter = new StringArgument('f', "filter", false, 1, INFO_QUERY_TOOL_ARG_PLACEHOLDER_FILTER.get(),
            INFO_QUERY_TOOL_ARG_DESC_FILTER.get());
    parser.addArgument(filter);

    resourceId = new StringArgument('d', "resourceID", false, 1,
            INFO_QUERY_TOOL_ARG_PLACEHOLDER_RESOURCE_ID.get(), INFO_QUERY_TOOL_ARG_DESC_RESOURCE_ID.get());
    parser.addArgument(resourceId);

    attributes = new StringArgument('A', "attribute", false, 0, INFO_QUERY_TOOL_ARG_PLACEHOLDER_ATTRIBUTE.get(),
            INFO_QUERY_TOOL_ARG_DESC_ATTRIBUTE.get());
    parser.addArgument(attributes);

    numThreads = new IntegerArgument('t', "numThreads", true, 1,
            INFO_QUERY_TOOL_ARG_PLACEHOLDER_NUM_THREADS.get(), INFO_QUERY_TOOL_ARG_DESC_NUM_THREADS.get(), 1,
            Integer.MAX_VALUE, 1);
    parser.addArgument(numThreads);

    collectionInterval = new IntegerArgument('i', "intervalDuration", true, 1,
            INFO_QUERY_TOOL_ARG_PLACEHOLDER_INTERVAL_DURATION.get(),
            INFO_QUERY_TOOL_ARG_DESC_INTERVAL_DURATION.get(), 1, Integer.MAX_VALUE, 5);
    parser.addArgument(collectionInterval);

    numIntervals = new IntegerArgument('I', "numIntervals", true, 1,
            INFO_QUERY_TOOL_ARG_PLACEHOLDER_NUM_INTERVALS.get(), INFO_QUERY_TOOL_ARG_DESC_NUM_INTERVALS.get(),
            1, Integer.MAX_VALUE, Integer.MAX_VALUE);
    parser.addArgument(numIntervals);

    ratePerSecond = new IntegerArgument('r', "ratePerSecond", false, 1,
            INFO_QUERY_TOOL_ARG_PLACEHOLDER_RATE_PER_SECOND.get(),
            INFO_QUERY_TOOL_ARG_DESC_RATE_PER_SECOND.get(), 1, Integer.MAX_VALUE);
    parser.addArgument(ratePerSecond);

    warmUpIntervals = new IntegerArgument(null, "warmUpIntervals", true, 1,
            INFO_QUERY_TOOL_ARG_PLACEHOLDER_WARM_UP_INTERVALS.get(),
            INFO_QUERY_TOOL_ARG_DESC_WARM_UP_INTERVALS.get(), 0, Integer.MAX_VALUE, 0);
    parser.addArgument(warmUpIntervals);

    final LinkedHashSet<String> allowedFormats = new LinkedHashSet<String>(3);
    allowedFormats.add("none");
    allowedFormats.add("with-date");
    allowedFormats.add("without-date");
    timestampFormat = new StringArgument(null, "timestampFormat", true, 1,
            INFO_QUERY_TOOL_ARG_PLACEHOLDER_TIMESTAMP_FORMAT.get(),
            INFO_QUERY_TOOL_ARG_DESC_TIMESTAMP_FORMAT.get(), allowedFormats, "none");
    parser.addArgument(timestampFormat);

    csvFormat = new BooleanArgument('c', "csv", 1, INFO_QUERY_TOOL_ARG_DESC_CSV_FORMAT.get());
    parser.addArgument(csvFormat);

    randomSeed = new IntegerArgument('R', "randomSeed", false, 1,
            INFO_QUERY_TOOL_ARG_PLACEHOLDER_RANDOM_SEED.get(), INFO_QUERY_TOOL_ARG_DESC_RANDOM_SEED.get());
    parser.addArgument(randomSeed);

    useSSL = new BooleanArgument('Z', "useSSL", 1, INFO_SCIM_TOOL_DESCRIPTION_USE_SSL.get());
    parser.addArgument(useSSL);

    trustAll = new BooleanArgument('X', "trustAll", 1, INFO_SCIM_TOOL_DESCRIPTION_TRUST_ALL.get());
    parser.addArgument(trustAll);

    keyStorePath = new StringArgument('K', "keyStorePath", false, 1, INFO_SCIM_TOOL_PLACEHOLDER_PATH.get(),
            INFO_SCIM_TOOL_DESCRIPTION_KEY_STORE_PATH.get());
    parser.addArgument(keyStorePath);

    keyStorePassword = new StringArgument('W', "keyStorePassword", false, 1,
            INFO_SCIM_TOOL_PLACEHOLDER_PASSWORD.get(), INFO_SCIM_TOOL_DESCRIPTION_KEY_STORE_PASSWORD.get());
    parser.addArgument(keyStorePassword);

    keyStorePasswordFile = new FileArgument('u', "keyStorePasswordFile", false, 1,
            INFO_SCIM_TOOL_PLACEHOLDER_PATH.get(), INFO_SCIM_TOOL_DESCRIPTION_KEY_STORE_PASSWORD_FILE.get());
    parser.addArgument(keyStorePasswordFile);

    keyStoreFormat = new StringArgument(null, "keyStoreFormat", false, 1,
            INFO_SCIM_TOOL_PLACEHOLDER_FORMAT.get(), INFO_SCIM_TOOL_DESCRIPTION_KEY_STORE_FORMAT.get());
    parser.addArgument(keyStoreFormat);

    trustStorePath = new StringArgument('P', "trustStorePath", false, 1, INFO_SCIM_TOOL_PLACEHOLDER_PATH.get(),
            INFO_SCIM_TOOL_DESCRIPTION_TRUST_STORE_PATH.get());
    parser.addArgument(trustStorePath);

    trustStorePassword = new StringArgument('T', "trustStorePassword", false, 1,
            INFO_SCIM_TOOL_PLACEHOLDER_PASSWORD.get(), INFO_SCIM_TOOL_DESCRIPTION_TRUST_STORE_PASSWORD.get());
    parser.addArgument(trustStorePassword);

    trustStorePasswordFile = new FileArgument('U', "trustStorePasswordFile", false, 1,
            INFO_SCIM_TOOL_PLACEHOLDER_PATH.get(), INFO_SCIM_TOOL_DESCRIPTION_TRUST_STORE_PASSWORD_FILE.get());
    parser.addArgument(trustStorePasswordFile);

    trustStoreFormat = new StringArgument(null, "trustStoreFormat", false, 1,
            INFO_SCIM_TOOL_PLACEHOLDER_FORMAT.get(), INFO_SCIM_TOOL_DESCRIPTION_TRUST_STORE_FORMAT.get());
    parser.addArgument(trustStoreFormat);

    certificateNickname = new StringArgument('N', "certNickname", false, 1,
            INFO_SCIM_TOOL_PLACEHOLDER_CERT_NICKNAME.get(), INFO_SCIM_TOOL_DESCRIPTION_CERT_NICKNAME.get());
    parser.addArgument(certificateNickname);

    parser.addDependentArgumentSet(authID, authPassword, authPasswordFile);
    parser.addExclusiveArgumentSet(authPassword, authPasswordFile, bearerToken);
    parser.addExclusiveArgumentSet(authID, bearerToken);
    parser.addExclusiveArgumentSet(keyStorePassword, keyStorePasswordFile);
    parser.addExclusiveArgumentSet(trustStorePassword, trustStorePasswordFile);
    parser.addExclusiveArgumentSet(trustAll, trustStorePath);
    parser.addExclusiveArgumentSet(filter, resourceId);
}

From source file:org.rhq.modules.plugins.jbossas7.patching.PatchHandlerComponent.java

@Override
public BundlePurgeResult purgeBundle(BundlePurgeRequest request) {
    BundlePurgeResult result = new BundlePurgeResult();

    ServerControl control = ServerControl.onServer(request.getReferencedConfiguration(),
            AS7Mode.valueOf(request.getDestinationTarget().getPath()), context.getSystemInformation());

    Result<Void> check = sanityCheck(control, request.getReferencedConfiguration(),
            request.getBundleManagerProvider(), request.getLiveResourceDeployment(), false);
    if (check.failed()) {
        result.setErrorMessage(check.errorMessage);
        return result;
    }//from ww w . j  a  v  a 2s  .  c o  m

    Result<BundleMetadata> metadata = BundleMetadata.forDeployment(request.getLiveResourceDeployment(),
            request.getReferencedConfiguration());
    if (metadata.failed()) {
        result.setErrorMessage(metadata.errorMessage);
        return result;
    }

    LinkedHashSet<String> pidsToRollback = new LinkedHashSet<String>();
    for (BundleMetadata.DeploymentMetadata dm : metadata.result.deployments) {
        for (PatchDetails pd : dm.applied) {
            pidsToRollback.add(pd.getId());
        }
    }

    ASConnection connection = new ASConnection(
            ASConnectionParams.createFrom(new ServerPluginConfiguration(request.getReferencedConfiguration())));

    String errorMessage = rollbackPatches(control, request.getBundleManagerProvider(),
            request.getLiveResourceDeployment(), connection, "purge", new ArrayList<String>(pidsToRollback));

    if (errorMessage != null) {
        result.setErrorMessage(errorMessage);
        return result;
    }

    forgetState(request.getLiveResourceDeployment(), request.getReferencedConfiguration());

    return result;
}

From source file:at.flack.activity.NewSMSContactActivity.java

public ArrayList<ContactModel> readSMSContacts(Activity activity) {
    LinkedHashSet<ContactModel> smsList = new LinkedHashSet<ContactModel>();
    Cursor phones = activity.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null, null, null, null);/*from w  w  w.  j  a  v  a  2s .c o m*/
    while (phones.moveToNext()) {
        String name = phones
                .getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phoneNumber = phones.getString(phones
                .getColumnIndex(PhoneNumberUtils.formatNumber(ContactsContract.CommonDataKinds.Phone.NUMBER)));
        String photo = phones
                .getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
        String primary = name;
        if (name == null)
            primary = phoneNumber;
        smsList.add(new ContactModel(fetchThumbnail(activity, photo != null ? Uri.parse(photo) : null), primary,
                phoneNumber, "", false));
    }
    phones.close();
    ArrayList<ContactModel> unsorted = new ArrayList<ContactModel>(smsList);
    Collections.sort(unsorted, new Comparator<ContactModel>() {
        @Override
        public int compare(ContactModel lhs, ContactModel rhs) {
            return lhs.getTitle().compareTo(rhs.getTitle());
        }
    });
    return unsorted;
}

From source file:org.opencb.opencga.storage.core.variant.io.VariantVcfDataWriter.java

private void addCohortInfo(LinkedHashSet<VCFHeaderLine> meta) {
    for (String cohortName : studyConfiguration.getCohortIds().keySet()) {
        if (cohortName.equals(StudyEntry.DEFAULT_COHORT)) {
            meta.add(new VCFInfoHeaderLine(VCFConstants.ALLELE_COUNT_KEY, VCFHeaderLineCount.A,
                    VCFHeaderLineType.Integer, "Total number of alternate alleles in called genotypes,"
                            + " for each ALT allele, in the same order as listed"));
            meta.add(new VCFInfoHeaderLine(VCFConstants.ALLELE_FREQUENCY_KEY, VCFHeaderLineCount.A,
                    VCFHeaderLineType.Float,
                    "Allele Frequency, for each ALT allele, calculated from AC and AN, in the range (0,1),"
                            + " in the same order as listed"));
            meta.add(new VCFInfoHeaderLine(VCFConstants.ALLELE_NUMBER_KEY, 1, VCFHeaderLineType.Integer,
                    "Total number of alleles in called genotypes"));
            continue;
        }//from   www .j  a v  a 2s  .  c  o m
        //            header.addMetaDataLine(new VCFInfoHeaderLine(cohortName + VCFConstants.ALLELE_COUNT_KEY, VCFHeaderLineCount.A,
        //                    VCFHeaderLineType.Integer, "Total number of alternate alleles in called genotypes,"
        //                    + " for each ALT allele, in the same order as listed"));
        meta.add(new VCFInfoHeaderLine(cohortName + "_" + VCFConstants.ALLELE_FREQUENCY_KEY,
                VCFHeaderLineCount.A, VCFHeaderLineType.Float,
                "Allele frequency in the " + cohortName
                        + " cohort calculated from AC and AN, in the range (0,1),"
                        + " in the same order as listed"));
        //            header.addMetaDataLine(new VCFInfoHeaderLine(cohortName + VCFConstants.ALLELE_NUMBER_KEY, 1, VCFHeaderLineType.Integer,
        //                    "Total number of alleles in called genotypes"));
    }
}

From source file:org.geotools.coverage.io.netcdf.NetCDFPolyphemusTest.java

@Test
public void geoToolsReader() throws IllegalArgumentException, IOException, NoSuchAuthorityCodeException {
    boolean isInteractiveTest = TestData.isInteractiveTest();

    // create a base driver
    final DefaultFileDriver driver = new NetCDFDriver();
    final File[] files = TestData.file(this, ".").listFiles(new FileFilter() {

        @Override//from ww  w.jav a 2  s. c  om
        public boolean accept(File pathname) {
            return FilenameUtils.getName(pathname.getAbsolutePath()).equalsIgnoreCase("O3-NO2.nc");
        }

    });

    for (File f : files) {

        // move to test directory
        final File file = new File(testDirectory, "O3-NO2.nc");
        FileUtils.copyFile(f, file);

        // get the file
        final URL source = file.toURI().toURL();
        assertTrue(driver.canProcess(DriverCapabilities.CONNECT, source, null));

        LOGGER.info("ACCEPTED: " + source.toString());

        // getting access to the file
        CoverageAccess access = null;

        try {
            access = driver.process(DriverCapabilities.CONNECT, source, null, null, null);
            if (access == null) {
                throw new IOException("Unable to connect");
            }
            // get the names
            final List<Name> names = access.getNames(null);
            for (Name name : names) {
                // get a source
                final CoverageSource gridSource = access.access(name, null, AccessType.READ_ONLY, null, null);
                if (gridSource == null) {
                    throw new IOException("Unable to access");
                }
                LOGGER.info("Connected to coverage: " + name.toString());

                // TEMPORAL DOMAIN
                final TemporalDomain temporalDomain = gridSource.getTemporalDomain();
                if (temporalDomain == null) {
                    LOGGER.info("Temporal domain is null");
                } else {
                    // temporal crs
                    LOGGER.info("TemporalCRS: " + temporalDomain.getCoordinateReferenceSystem());

                    // print the temporal domain elements
                    for (DateRange tg : temporalDomain.getTemporalElements(true, null)) {
                        LOGGER.info("Global Temporal Domain: " + tg.toString());
                    }

                    // print the temporal domain elements with overall = true
                    StringBuilder overallTemporal = new StringBuilder(
                            "Temporal domain element (overall = true):\n");
                    for (DateRange tg : temporalDomain.getTemporalElements(false, null)) {
                        overallTemporal.append(tg.toString()).append("\n");
                    }
                    LOGGER.info(overallTemporal.toString());
                }

                // VERTICAL DOMAIN
                final VerticalDomain verticalDomain = gridSource.getVerticalDomain();
                if (verticalDomain == null) {
                    LOGGER.info("Vertical domain is null");
                } else {
                    // vertical crs
                    LOGGER.info("VerticalCRS: " + verticalDomain.getCoordinateReferenceSystem());

                    // print the Vertical domain elements
                    for (NumberRange<Double> vg : verticalDomain.getVerticalElements(true, null)) {
                        LOGGER.info("Vertical domain element: " + vg.toString());
                    }

                    // print the Vertical domain elements with overall = true
                    StringBuilder overallVertical = new StringBuilder(
                            "Vertical domain element (overall = true):\n");
                    for (NumberRange<Double> vg : verticalDomain.getVerticalElements(false, null)) {
                        overallVertical.append(vg.toString()).append("\n");
                    }
                    LOGGER.info(overallVertical.toString());
                }

                // HORIZONTAL DOMAIN
                final SpatialDomain spatialDomain = gridSource.getSpatialDomain();
                if (spatialDomain == null) {
                    LOGGER.info("Horizontal domain is null");
                } else {
                    // print the horizontal domain elements
                    final CoordinateReferenceSystem crs2D = spatialDomain.getCoordinateReferenceSystem2D();
                    assert crs2D != null;
                    final MathTransform2D g2w = spatialDomain.getGridToWorldTransform(null);
                    assert g2w != null;
                    final Set<? extends BoundingBox> spatialElements = spatialDomain.getSpatialElements(true,
                            null);
                    assert spatialElements != null && !spatialElements.isEmpty();

                    final StringBuilder buf = new StringBuilder();
                    buf.append("Horizontal domain is as follows:\n");
                    buf.append("G2W:").append("\t").append(g2w).append("\n");
                    buf.append("CRS2D:").append("\t").append(crs2D).append("\n");
                    for (BoundingBox bbox : spatialElements) {
                        buf.append("BBOX:").append("\t").append(bbox).append("\n");
                    }
                    LOGGER.info(buf.toString());
                }

                CoverageReadRequest readRequest = new CoverageReadRequest();
                // //
                //
                // Setting up a limited range for the request.
                //
                // //

                LinkedHashSet<NumberRange<Double>> requestedVerticalSubset = new LinkedHashSet<NumberRange<Double>>();
                SortedSet<? extends NumberRange<Double>> verticalElements = verticalDomain
                        .getVerticalElements(false, null);
                final int numLevels = verticalElements.size();
                final Iterator<? extends NumberRange<Double>> iterator = verticalElements.iterator();
                for (int i = 0; i < numLevels; i++) {
                    NumberRange<Double> level = iterator.next();
                    if (i % (numLevels / 5) == 1) {
                        requestedVerticalSubset.add(level);
                    }
                }
                readRequest.setVerticalSubset(requestedVerticalSubset);

                SortedSet<DateRange> requestedTemporalSubset = new DateRangeTreeSet();
                SortedSet<? extends DateRange> temporalElements = temporalDomain.getTemporalElements(false,
                        null);
                final int numTimes = temporalElements.size();
                Iterator<? extends DateRange> iteratorT = temporalElements.iterator();
                for (int i = 0; i < numTimes; i++) {
                    DateRange time = iteratorT.next();
                    if (i % (numTimes / 5) == 1) {
                        requestedTemporalSubset.add(time);
                    }
                }
                readRequest.setTemporalSubset(requestedTemporalSubset);

                CoverageResponse response = gridSource.read(readRequest, null);
                if (response == null || response.getStatus() != Status.SUCCESS
                        || !response.getExceptions().isEmpty()) {
                    throw new IOException("Unable to read");
                }

                final Collection<? extends Coverage> results = response.getResults(null);
                int index = 0;
                for (Coverage c : results) {
                    GridCoverageResponse resp = (GridCoverageResponse) c;
                    GridCoverage2D coverage = resp.getGridCoverage2D();
                    String title = coverage.getSampleDimension(0).getDescription().toString();
                    // Crs and envelope
                    if (isInteractiveTest) {
                        // ImageIOUtilities.visualize(coverage.getRenderedImage(), "tt",true);
                        coverage.show(title + " " + index++);
                    } else {
                        PlanarImage.wrapRenderedImage(coverage.getRenderedImage()).getTiles();
                    }

                    final StringBuilder buffer = new StringBuilder();
                    buffer.append("GridCoverage CRS: ")
                            .append(coverage.getCoordinateReferenceSystem2D().toWKT()).append("\n");
                    buffer.append("GridCoverage GG: ").append(coverage.getGridGeometry().toString())
                            .append("\n");
                    LOGGER.info(buffer.toString());
                }
                gridSource.dispose();
            }
        } catch (Throwable t) {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.log(Level.WARNING, t.getLocalizedMessage(), t);
            }
        } finally {
            if (access != null) {
                try {
                    access.dispose();
                } catch (Throwable t) {
                    // Does nothing
                }
            }
        }
    }
}

From source file:com.ge.predix.acs.service.policy.evaluation.PolicyEvaluationServiceImpl.java

LinkedHashSet<PolicySet> filterPolicySetsByPriority(final String subjectIdentifier, final String uri,
        final List<PolicySet> allPolicySets, final LinkedHashSet<String> policySetsEvaluationOrder)
        throws IllegalArgumentException {

    if (policySetsEvaluationOrder.isEmpty()) {
        if (allPolicySets.size() > 1) {
            LOGGER.error(String.format(
                    "Found more than one policy set during policy evaluation and "
                            + "no evaluation order is provided. subjectIdentifier='%s', resourceURI='%s'",
                    subjectIdentifier, uri));
            throw new IllegalArgumentException("More than one policy set exists for this zone. "
                    + "Please provide an ordered list of policy set names to consider for this evaluation and "
                    + "resubmit the request.");
        } else {//from   ww  w . j  av  a  2 s. c  o m
            return allPolicySets.stream().collect(Collectors.toCollection(LinkedHashSet::new));
        }
    }

    Map<String, PolicySet> allPolicySetsMap = allPolicySets.stream()
            .collect(Collectors.toMap(PolicySet::getName, Function.identity()));
    LinkedHashSet<PolicySet> filteredPolicySets = new LinkedHashSet<PolicySet>();
    for (String policySetId : policySetsEvaluationOrder) {
        PolicySet policySet = allPolicySetsMap.get(policySetId);
        if (policySet == null) {
            LOGGER.error("No existing policy set matches policy set in the evaluation order of the request. "
                    + "Subject: " + subjectIdentifier + ", Resource: " + uri);
            throw new IllegalArgumentException(
                    "No existing policy set matches policy set in the evaluaion order of the request. "
                            + "Please review the policy evauation order and resubmit the request.");
        } else {
            filteredPolicySets.add(policySet);
        }
    }
    return filteredPolicySets;
}

From source file:com.odoko.solrcli.actions.CrawlPostAction.java

/**
 * This method takes as input a list of start URL strings for crawling,
 * adds each one to a backlog and then starts crawling
 * @param args the raw input args from main()
 * @param startIndexInArgs offset for where to start
 * @param out outputStream to write results to
 * @return the number of web pages posted
 *//* www. j a va2  s  . c  o  m*/
public int postWebPages(List<String>args, int startIndexInArgs, OutputStream out) {
  reset();
  LinkedHashSet<URL> s = new LinkedHashSet<URL>();
  for (int j = startIndexInArgs; j < args.length; j++) {
    try {
      URL u = new URL(normalizeUrlEnding(args[j]));
      s.add(u);
    } catch(MalformedURLException e) {
      warn("Skipping malformed input URL: "+args[j]);
    }
  }
  // Add URLs to level 0 of the backlog and start recursive crawling
  backlog.add(s);
  return webCrawl(0, out);
}

From source file:nl.mpcjanssen.simpletask.AddTask.java

@Override
public void onCreate(Bundle savedInstanceState) {
    Log.v(TAG, "onCreate()");

    m_app = (TodoApplication) getApplication();
    m_app.setActionBarStyle(getWindow());
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    super.onCreate(savedInstanceState);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Constants.BROADCAST_UPDATE_UI);
    intentFilter.addAction(Constants.BROADCAST_SYNC_START);
    intentFilter.addAction(Constants.BROADCAST_SYNC_DONE);

    localBroadcastManager = m_app.getLocalBroadCastManager();

    m_broadcastReceiver = new BroadcastReceiver() {
        @Override//from  w w w. j a  va2 s  .  c  o m
        public void onReceive(Context context, @NotNull Intent intent) {
            if (intent.getAction().equals(Constants.BROADCAST_SYNC_START)) {
                setProgressBarIndeterminateVisibility(true);
            } else if (intent.getAction().equals(Constants.BROADCAST_SYNC_DONE)) {
                setProgressBarIndeterminateVisibility(false);
            }
        }
    };
    localBroadcastManager.registerReceiver(m_broadcastReceiver, intentFilter);

    ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
    final Intent intent = getIntent();
    ActiveFilter mFilter = new ActiveFilter();
    mFilter.initFromIntent(intent);
    final String action = intent.getAction();
    // create shortcut and exit
    if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
        Log.d(TAG, "Setting up shortcut icon");
        setupShortcut();
        finish();
        return;
    } else if (Intent.ACTION_SEND.equals(action)) {
        Log.d(TAG, "Share");
        if (intent.hasExtra(Intent.EXTRA_TEXT)) {
            share_text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT).toString();
        } else {
            share_text = "";
        }
        if (!m_app.hasShareTaskShowsEdit()) {
            if (!share_text.equals("")) {
                addBackgroundTask(share_text);
            }
            finish();
            return;
        }
    } else if ("com.google.android.gm.action.AUTO_SEND".equals(action)) {
        // Called as note to self from google search/now
        noteToSelf(intent);
        finish();
        return;
    } else if (Constants.INTENT_BACKGROUND_TASK.equals(action)) {
        Log.v(TAG, "Adding background task");
        if (intent.hasExtra(Constants.EXTRA_BACKGROUND_TASK)) {
            addBackgroundTask(intent.getStringExtra(Constants.EXTRA_BACKGROUND_TASK));
        } else {
            Log.w(TAG, "Task was not in extras");
        }
        finish();
        return;
    }

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);

    setContentView(R.layout.add_task);

    // text
    textInputField = (EditText) findViewById(R.id.taskText);
    m_app.setEditTextHint(textInputField, R.string.tasktexthint);

    if (share_text != null) {
        textInputField.setText(share_text);
    }

    Task iniTask = null;
    setTitle(R.string.addtask);

    m_backup = m_app.getTaskCache(this).getTasksToUpdate();
    if (m_backup != null && m_backup.size() > 0) {
        ArrayList<String> prefill = new ArrayList<String>();
        for (Task t : m_backup) {
            prefill.add(t.inFileFormat());
        }
        String sPrefill = Util.join(prefill, "\n");
        textInputField.setText(sPrefill);
        setTitle(R.string.updatetask);
    } else {
        if (textInputField.getText().length() == 0) {
            iniTask = new Task(1, "");
            iniTask.initWithFilter(mFilter);
        }

        if (iniTask != null && iniTask.getTags().size() == 1) {
            List<String> ps = iniTask.getTags();
            String project = ps.get(0);
            if (!project.equals("-")) {
                textInputField.append(" +" + project);
            }
        }

        if (iniTask != null && iniTask.getLists().size() == 1) {
            List<String> cs = iniTask.getLists();
            String context = cs.get(0);
            if (!context.equals("-")) {
                textInputField.append(" @" + context);
            }
        }
    }
    // Listen to enter events, use IME_ACTION_NEXT for soft keyboards
    // like Swype where ENTER keyCode is not generated.

    int inputFlags = InputType.TYPE_CLASS_TEXT;

    if (m_app.hasCapitalizeTasks()) {
        inputFlags |= InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
    }
    textInputField.setRawInputType(inputFlags);
    textInputField.setImeOptions(EditorInfo.IME_ACTION_NEXT);
    textInputField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, @Nullable KeyEvent keyEvent) {

            boolean hardwareEnterUp = keyEvent != null && keyEvent.getAction() == KeyEvent.ACTION_UP
                    && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER;
            boolean hardwareEnterDown = keyEvent != null && keyEvent.getAction() == KeyEvent.ACTION_DOWN
                    && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER;
            boolean imeActionNext = (actionId == EditorInfo.IME_ACTION_NEXT);

            if (imeActionNext || hardwareEnterUp) {
                // Move cursor to end of line
                int position = textInputField.getSelectionStart();
                String remainingText = textInputField.getText().toString().substring(position);
                int endOfLineDistance = remainingText.indexOf('\n');
                int endOfLine;
                if (endOfLineDistance == -1) {
                    endOfLine = textInputField.length();
                } else {
                    endOfLine = position + endOfLineDistance;
                }
                textInputField.setSelection(endOfLine);
                replaceTextAtSelection("\n", false);

                if (hasCloneTags()) {
                    String precedingText = textInputField.getText().toString().substring(0, endOfLine);
                    int lineStart = precedingText.lastIndexOf('\n');
                    String line;
                    if (lineStart != -1) {
                        line = precedingText.substring(lineStart, endOfLine);
                    } else {
                        line = precedingText;
                    }
                    Task t = new Task(0, line);
                    LinkedHashSet<String> tags = new LinkedHashSet<String>();
                    for (String ctx : t.getLists()) {
                        tags.add("@" + ctx);
                    }
                    for (String prj : t.getTags()) {
                        tags.add("+" + prj);
                    }
                    replaceTextAtSelection(Util.join(tags, " "), true);
                }
                endOfLine++;
                textInputField.setSelection(endOfLine);
            }
            return (imeActionNext || hardwareEnterDown || hardwareEnterUp);
        }
    });

    setCloneTags(m_app.isAddTagsCloneTags());
    setWordWrap(m_app.isWordWrap());

    findViewById(R.id.cb_wrap).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setWordWrap(hasWordWrap());
        }
    });

    int textIndex = 0;
    textInputField.setSelection(textIndex);

    // Set button callbacks
    findViewById(R.id.btnContext).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showContextMenu();
        }
    });
    findViewById(R.id.btnProject).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showTagMenu();
        }
    });
    findViewById(R.id.btnPrio).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showPrioMenu();
        }
    });

    findViewById(R.id.btnDue).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            insertDate(Task.DUE_DATE);
        }
    });
    findViewById(R.id.btnThreshold).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            insertDate(Task.THRESHOLD_DATE);
        }
    });

    if (m_backup != null && m_backup.size() > 0) {
        textInputField.setSelection(textInputField.getText().length());
    }
}