Example usage for java.util Arrays binarySearch

List of usage examples for java.util Arrays binarySearch

Introduction

In this page you can find the example usage for java.util Arrays binarySearch.

Prototype

public static int binarySearch(Object[] a, Object key) 

Source Link

Document

Searches the specified array for the specified object using the binary search algorithm.

Usage

From source file:com.ecyrd.jspwiki.parser.JSPWikiMarkupParser.java

/**
 *  Goes through the current element stack and pops all elements until this
 *  element is found - this essentially "closes" and element.
 *
 *  @param s/*w w w  .  j a  v a2s .  com*/
 *  @return The new current element, or null, if there was no such element in the entire stack.
 */
private Element popElement(String s) {
    int flushedBytes = flushPlainText();

    Element currEl = m_currentElement;

    while (currEl.getParentElement() != null) {
        if (currEl.getName().equals(s) && !currEl.isRootElement()) {
            m_currentElement = currEl.getParentElement();

            //
            //  Check if it's okay for this element to be empty.  Then we will
            //  trick the JDOM generator into not generating an empty element,
            //  by putting an empty string between the tags.  Yes, it's a kludge
            //  but what'cha gonna do about it. :-)
            //

            if (flushedBytes == 0 && Arrays.binarySearch(EMPTY_ELEMENTS, s) < 0) {
                currEl.addContent("");
            }

            return m_currentElement;
        }

        currEl = currEl.getParentElement();
    }

    return null;
}

From source file:fastcall.FastCallSNP.java

private void updateTaxaBamPathMap(File[] bams) {
    String bamDirS = bams[0].getParent();
    String[] existingBam = new String[bams.length];
    for (int i = 0; i < bams.length; i++)
        existingBam[i] = bams[i].getName();
    Arrays.sort(existingBam);//w ww  . j  a  v  a 2s.  c om
    HashSet<String> existingTaxaSet = new HashSet();
    HashMap<String, String[]> updatedTaxaBamMap = new HashMap();
    int cnt = 0;
    ArrayList<String> pathList = new ArrayList();
    for (int i = 0; i < taxaNames.length; i++) {
        String[] bamNames = taxaBamPathMap.get(taxaNames[i]);
        ArrayList<String> bamPathList = new ArrayList();
        for (int j = 0; j < bamNames.length; j++) {
            int index = Arrays.binarySearch(existingBam, bamNames[j]);
            if (index < 0)
                continue;
            String path = new File(bamDirS, bamNames[j]).getAbsolutePath();
            bamPathList.add(path);
            pathList.add(path);
            existingTaxaSet.add(taxaNames[i]);
        }
        if (bamPathList.isEmpty())
            continue;
        bamNames = bamPathList.toArray(new String[bamPathList.size()]);
        Arrays.sort(bamNames);
        updatedTaxaBamMap.put(taxaNames[i], bamNames);
        cnt += bamNames.length;
    }
    String[] updatedTaxaNames = existingTaxaSet.toArray(new String[existingTaxaSet.size()]);
    Arrays.sort(updatedTaxaNames);
    taxaNames = updatedTaxaNames;
    taxaBamPathMap = updatedTaxaBamMap;
    this.bamPaths = pathList.toArray(new String[pathList.size()]);
    Arrays.sort(bamPaths);
    System.out.println("Actual taxa number:\t" + String.valueOf(taxaNames.length));
    System.out.println("Actual bam file number:\t" + String.valueOf(cnt));
    System.out.println();
}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

private @Nonnull List<VirtualMachine> describeInstances(@Nonnull String... instanceIds)
        throws InternalException, CloudException {
    List<VirtualMachine> results = new ArrayList<VirtualMachine>();
    ProviderContext ctx = getProvider().getContext();

    if (ctx == null) {
        throw new CloudException("No context was established for this request");
    }//from w  w w .  j a v  a  2  s  .c  o m

    Future<Iterable<IpAddress>> ipPoolFuture = null;
    Iterable<IpAddress> addresses;
    if (getProvider().hasNetworkServices()) {
        NetworkServices services = getProvider().getNetworkServices();

        if (services != null) {
            if (services.hasIpAddressSupport()) {
                IpAddressSupport support = services.getIpAddressSupport();

                if (support != null) {
                    ipPoolFuture = support.listIpPoolConcurrently(IPVersion.IPV4, false);
                }
            }
        }
    }

    Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(),
            EC2Method.DESCRIBE_INSTANCES);
    EC2Method method;
    NodeList blocks;
    Document doc;

    AWSCloud.addIndexedParameters(parameters, "InstanceId", instanceIds);

    method = new EC2Method(getProvider(), parameters);
    try {
        doc = method.invoke();
    } catch (EC2Exception e) {
        String code = e.getCode();

        if (code != null && code.startsWith("InvalidInstanceID")) {
            return results;
        }
        logger.error(e.getSummary());
        throw new CloudException(e);
    }
    blocks = doc.getElementsByTagName("instancesSet");
    for (int i = 0; i < blocks.getLength(); i++) {
        NodeList instances = blocks.item(i).getChildNodes();

        for (int j = 0; j < instances.getLength(); j++) {
            Node instance = instances.item(j);

            if (instance.getNodeName().equals("item")) {
                try {
                    if (ipPoolFuture != null) {
                        addresses = ipPoolFuture.get(30, TimeUnit.SECONDS);
                    } else {
                        addresses = Collections.emptyList();
                    }
                } catch (InterruptedException e) {
                    logger.error(e.getMessage());
                    addresses = Collections.emptyList();
                } catch (ExecutionException e) {
                    logger.error(e.getMessage());
                    addresses = Collections.emptyList();
                } catch (TimeoutException e) {
                    logger.error(e.getMessage());
                    addresses = Collections.emptyList();
                }
                VirtualMachine server = toVirtualMachine(ctx, instance, addresses);
                if (server != null
                        && Arrays.binarySearch(instanceIds, server.getProviderVirtualMachineId()) >= 0) {
                    results.add(server);
                }
            }
        }
    }
    return results;
}

From source file:com.liferay.document.library.web.internal.portlet.action.EditFileEntryMVCActionCommand.java

protected FileEntry updateFileEntry(PortletConfig portletConfig, ActionRequest actionRequest,
        ActionResponse actionResponse) throws Exception {

    UploadPortletRequest uploadPortletRequest = _portal.getUploadPortletRequest(actionRequest);

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    String cmd = ParamUtil.getString(uploadPortletRequest, Constants.CMD);

    long fileEntryId = ParamUtil.getLong(uploadPortletRequest, "fileEntryId");

    long repositoryId = ParamUtil.getLong(uploadPortletRequest, "repositoryId");
    long folderId = ParamUtil.getLong(uploadPortletRequest, "folderId");
    String sourceFileName = uploadPortletRequest.getFileName("file");
    String title = ParamUtil.getString(uploadPortletRequest, "title");
    String description = ParamUtil.getString(uploadPortletRequest, "description");
    String changeLog = ParamUtil.getString(uploadPortletRequest, "changeLog");
    boolean majorVersion = ParamUtil.getBoolean(uploadPortletRequest, "majorVersion");

    if (folderId > 0) {
        Folder folder = _dlAppService.getFolder(folderId);

        if (folder.getGroupId() != themeDisplay.getScopeGroupId()) {
            throw new NoSuchFolderException("{folderId=" + folderId + "}");
        }//from   www.  j ava2s.c o  m
    }

    InputStream inputStream = null;

    if (cmd.equals(Constants.ADD_DYNAMIC)) {
        title = uploadPortletRequest.getFileName("file");
    }

    try {
        String contentType = uploadPortletRequest.getContentType("file");
        long size = uploadPortletRequest.getSize("file");

        if ((cmd.equals(Constants.ADD) || cmd.equals(Constants.ADD_DYNAMIC)) && (size == 0)) {

            contentType = MimeTypesUtil.getContentType(title);
        }

        if (cmd.equals(Constants.ADD) || cmd.equals(Constants.ADD_DYNAMIC) || (size > 0)) {

            String portletName = portletConfig.getPortletName();

            if (portletName.equals(DLPortletKeys.MEDIA_GALLERY_DISPLAY)) {
                PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

                DLPortletInstanceSettings dlPortletInstanceSettings = DLPortletInstanceSettings
                        .getInstance(themeDisplay.getLayout(), portletDisplay.getId());

                String[] mimeTypes = dlPortletInstanceSettings.getMimeTypes();

                if (Arrays.binarySearch(mimeTypes, contentType) < 0) {
                    throw new FileMimeTypeException(contentType);
                }
            }
        }

        inputStream = uploadPortletRequest.getFileAsStream("file");

        ServiceContext serviceContext = ServiceContextFactory.getInstance(DLFileEntry.class.getName(),
                uploadPortletRequest);

        FileEntry fileEntry = null;

        if (cmd.equals(Constants.ADD) || cmd.equals(Constants.ADD_DYNAMIC)) {

            // Add file entry

            fileEntry = _dlAppService.addFileEntry(repositoryId, folderId, sourceFileName, contentType, title,
                    description, changeLog, inputStream, size, serviceContext);

            if (cmd.equals(Constants.ADD_DYNAMIC)) {
                JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

                jsonObject.put("fileEntryId", fileEntry.getFileEntryId());

                JSONPortletResponseUtil.writeJSON(actionRequest, actionResponse, jsonObject);
            }
        } else if (cmd.equals(Constants.UPDATE_AND_CHECKIN)) {

            // Update file entry and checkin

            fileEntry = _dlAppService.updateFileEntryAndCheckIn(fileEntryId, sourceFileName, contentType, title,
                    description, changeLog, majorVersion, inputStream, size, serviceContext);
        } else {

            // Update file entry

            fileEntry = _dlAppService.updateFileEntry(fileEntryId, sourceFileName, contentType, title,
                    description, changeLog, majorVersion, inputStream, size, serviceContext);
        }

        return fileEntry;
    } finally {
        StreamUtil.cleanUp(inputStream);
    }
}

From source file:fr.landel.utils.commons.StringUtilsTest.java

/**
 * Test method for {@link StringUtils#prepareFormat} .
 *///from   w  w w  . j  av a  2  s .  c o  m
@Test
public void testPrepareFormat() {
    assertEquals("e = %2$+10.4f %3$11d %1$2d",
            StringUtils.prepareFormat("e = %+10.4f %11d %2d*", 1, 2).toString());

    assertEquals("e = %2$+10.4f %3$11d%1$2d %4$d",
            StringUtils.prepareFormat("e = %+10.4f %11d%2d* %$d", 1, 3).toString());

    assertEquals("e = %1$+10.4f   1$s", StringUtils.prepareFormat("e = %+10.4f %s %s* %s1$s", 0, 1).toString());

    assertEquals("e = %2$+10.4f %2$s %1$s %3$s1$s",
            StringUtils.prepareFormat("e = %1$+10.4f %s %s* %s1$s", 1, 2).toString());

    assertEquals("e = %1$+10.4f  ", StringUtils.prepareFormat("e = %+10.4f %11222d %2d*", 0, 1).toString());

    assertEquals("e = %1$+10.4f  ", StringUtils.prepareFormat("e = %+10.4f %2$11d %1$2d*", 0, 1).toString());

    assertEquals("e = %1$+10.4f  %1$* ",
            StringUtils.prepareFormat("e = %+10.4f %2$11d %1$* ", 0, 1).toString());

    assertEquals("Duke's Birthday: %2$tb %2$te, %2$tY",
            StringUtils.prepareFormat("Duke's Birthday: %1$tb %1$te, %1$tY", 1, 3).toString());
    assertEquals("Duke's Birthday: %2$tm %2$<te,%3$<TY",
            StringUtils.prepareFormat("Duke's Birthday: %1$tm %<te,%<TY", 1, 3).toString());

    byte[] authorized = new byte[] { 32, 35 };

    for (int i = AsciiUtils.MIN; i <= AsciiUtils.MAX; i++) {
        String ch = String.valueOf((char) i);
        String format = StringUtils.prepareFormat("%" + ch, 0, 1).toString();
        if (AsciiUtils.IS_ALPHA.test(i) || i == '%') {
            assertEquals("%1$" + ch, format);
        } else if (Arrays.binarySearch(authorized, (byte) i) == -1) {
            assertNotEquals("%1$" + ch, format);
        }
    }
}

From source file:com.facebook.infrastructure.service.StorageService.java

public void relocate(String[] keys) throws IOException {
    if (keys.length > 0) {
        isLoadState_ = true;/*from w w  w. j  a v  a 2s  .  c om*/
        BigInteger token = tokenMetadata_.getToken(StorageService.tcpAddr_);
        Map<BigInteger, EndPoint> tokenToEndPointMap = tokenMetadata_.cloneTokenEndPointMap();
        BigInteger[] tokens = tokenToEndPointMap.keySet().toArray(new BigInteger[0]);
        Arrays.sort(tokens);
        int index = Arrays.binarySearch(tokens, token) * (keys.length / tokens.length);
        BigInteger newToken = hash(keys[index]);
        /* update the token */
        updateToken(newToken);
    }
}

From source file:com.alibaba.citrus.maven.eclipse.base.eclipse.EclipsePlugin.java

private boolean validate() throws MojoExecutionException {
    // validate sanity of the current m2 project
    if (Arrays.binarySearch(WTP_SUPPORTED_VERSIONS, wtpversion) < 0) {
        throw new MojoExecutionException(Messages.getString("EclipsePlugin.unsupportedwtp", new Object[] { //$NON-NLS-1$
                wtpversion, StringUtils.join(WTP_SUPPORTED_VERSIONS, " ") })); //$NON-NLS-1$
    }//from   w w w.ja va  2  s  . c  o m

    assertNotEmpty(executedProject.getGroupId(), POM_ELT_GROUP_ID);
    assertNotEmpty(executedProject.getArtifactId(), POM_ELT_ARTIFACT_ID);

    if (executedProject.getFile() == null || !executedProject.getFile().exists()) {
        throw new MojoExecutionException(Messages.getString("EclipsePlugin.missingpom")); //$NON-NLS-1$
    }

    if ("pom".equals(packaging) && eclipseProjectDir == null) //$NON-NLS-1$
    {
        getLog().info(Messages.getString("EclipsePlugin.pompackaging")); //$NON-NLS-1$
        return false;
    }

    if ("eclipse-plugin".equals(packaging)) {
        pde = true;
    }

    if (eclipseProjectDir == null) {
        eclipseProjectDir = executedProject.getFile().getParentFile();
    }

    if (!eclipseProjectDir.exists() && !eclipseProjectDir.mkdirs()) {
        throw new MojoExecutionException(Messages.getString("EclipsePlugin.cantcreatedir", eclipseProjectDir)); //$NON-NLS-1$
    }

    if (!eclipseProjectDir.equals(executedProject.getFile().getParentFile())) {
        if (!eclipseProjectDir.isDirectory()) {
            throw new MojoExecutionException(Messages.getString("EclipsePlugin.notadir", eclipseProjectDir)); //$NON-NLS-1$
        }
        eclipseProjectDir = new File(eclipseProjectDir, executedProject.getArtifactId());
        if (!eclipseProjectDir.isDirectory() && !eclipseProjectDir.mkdirs()) {
            throw new MojoExecutionException(
                    Messages.getString("EclipsePlugin.cantcreatedir", eclipseProjectDir)); //$NON-NLS-1$
        }
    }

    validateExtras();

    return true;
}

From source file:com.link_intersystems.lang.reflect.Class2.java

/**
 * The string representation of a {@link Class2}.
 *
 * <ul>//  www  .j  a va2s .c om
 * <li>
 * Types are represented by their canonical name. If a type is a
 * &quot;well-known&quot; type (all types in java.lang) the type's simple
 * name is used. E.g. String - java.util.List.</li>
 * <ul>
 * <li>
 * Arrays are represented by their type and appended by []. E.g. int[]
 * String[] java.beans.PropertyDescriptor[].</li>
 *
 * @param wellKnownPackages
 *            packages that are &quot;well known&quot; will not be printed
 *            in the string representation. E.g. if java.lang is defined as
 *            well known the Class2 that represents a String class will be
 *            printed just as &quot;String&quot; and not java.lang.String.
 *
 * @return a string representation of this {@link Class2};
 * @since 1.0.0.0
 */
public String toString(String... wellKnownPackages) {
    Assert.notNull("wellKnownPackages", wellKnownPackages);
    StringBuilder toStringBuilder = new StringBuilder();
    Class<?> clazz = getType();
    boolean isArray = clazz.isArray();
    if (isArray) {
        clazz = clazz.getComponentType();
    }
    Package clazzPackage = clazz.getPackage();
    String packageName = StringUtils.EMPTY;
    if (clazzPackage != null) {
        packageName = clazzPackage.getName();
    }

    boolean isWellKnownPackage = Arrays.binarySearch(wellKnownPackages, packageName) > -1;

    if (isWellKnownPackage) {
        toStringBuilder.append(clazz.getSimpleName());
    } else {
        toStringBuilder.append(clazz.getCanonicalName());
    }

    TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
    String typeParametersToString = typeParametersToString(typeParameters);
    toStringBuilder.append(typeParametersToString);

    if (isArray) {
        toStringBuilder.append("[]");
    }
    return toStringBuilder.toString();
}

From source file:edu.cornell.med.icb.goby.alignments.AlignmentCollectionHandler.java

private void encode(final String label, final IntList list, final OutputBitStream out,
        final IntSet distinctSymbols, final int[] symbolValues) throws IOException {
    if (useArithmeticCoding) {
        final FastArithmeticCoderI coder = getCoder(distinctSymbols.size(), list.size());
        for (final int dp : list) {
            final int symbolCode = Arrays.binarySearch(symbolValues, dp);
            assert symbolCode >= 0 : "symbol code must exist.";
            coder.encode(symbolCode, out);
        }//from   w  ww. j  a v  a  2s  .c  o  m
        coder.flush(out);
    } else if (useHuffmanCoding) {
        final int[] frequencies = frequencies(list, symbolValues);
        final HuffmanCodec codec = new HuffmanCodec(frequencies);
        final CodeWordCoder coder = codec.coder();
        for (final int freq : frequencies) {
            out.writeNibble(freq);
        }
        for (final int dp : list) {
            final int symbolCode = Arrays.binarySearch(symbolValues, dp);
            assert symbolCode >= 0 : "symbol code must exist.";
            coder.encode(symbolCode, out);
        }
        coder.flush(out);
    }
}