Example usage for java.math BigInteger valueOf

List of usage examples for java.math BigInteger valueOf

Introduction

In this page you can find the example usage for java.math BigInteger valueOf.

Prototype

private static BigInteger valueOf(int val[]) 

Source Link

Document

Returns a BigInteger with the given two's complement representation.

Usage

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Generates and saves info.xml//www . ja va 2  s  .  co  m
 *
 * @param path
 * @param mets
 */
public static void saveInfoFile(String path, MetsContext metsContext, String md5, String fileMd5Name,
        File metsFile) throws MetsExportException {
    File infoFile = new File(path + File.separator + metsContext.getPackageID() + File.separator + "info_"
            + metsContext.getPackageID() + ".xml");
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(new Date());
    XMLGregorianCalendar date2;
    try {
        date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    } catch (DatatypeConfigurationException e1) {
        throw new MetsExportException("Error while generating info.xml file", false, e1);
    }
    Info infoJaxb = new Info();
    infoJaxb.setCreated(date2);
    infoJaxb.setMainmets("./" + metsFile.getName());
    Checksum checkSum = new Checksum();
    checkSum.setChecksum(md5);
    checkSum.setType("MD5");
    addModsIdentifiersRecursive(metsContext.getRootElement(), infoJaxb);
    checkSum.setValue(fileMd5Name);
    infoJaxb.setChecksum(checkSum);
    Validation validation = new Validation();
    validation.setValue("W3C-XML");
    validation.setVersion(Float.valueOf("0.0"));
    infoJaxb.setValidation(validation);
    infoJaxb.setCreator(metsContext.getCreatorOrganization());
    infoJaxb.setPackageid(metsContext.getPackageID());
    if (Const.PERIODICAL_TITLE.equalsIgnoreCase(metsContext.getRootElement().getElementType())) {
        infoJaxb.setMetadataversion((float) 1.5);
    } else {
        infoJaxb.setMetadataversion((float) 1.1);
    }
    Itemlist itemList = new Itemlist();
    infoJaxb.setItemlist(itemList);
    itemList.setItemtotal(BigInteger.valueOf(metsContext.getFileList().size()));
    List<FileMD5Info> fileList = metsContext.getFileList();
    long size = 0;
    for (FileMD5Info fileName : fileList) {
        itemList.getItem()
                .add(fileName.getFileName().replaceAll(Matcher.quoteReplacement(File.separator), "/"));
        size += fileName.getSize();
    }
    int infoTotalSize = (int) (size / 1024);
    infoJaxb.setSize(infoTotalSize);
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Info.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        // SchemaFactory factory =
        // SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        // factory.setResourceResolver(MetsLSResolver.getInstance());
        // Schema schema = factory.newSchema(new
        // StreamSource(Info.class.getResourceAsStream("info.xsd")));
        // marshaller.setSchema(schema);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
        marshaller.marshal(infoJaxb, infoFile);
    } catch (Exception ex) {
        throw new MetsExportException("Error while generating info.xml", false, ex);
    }

    List<String> validationErrors;
    try {
        validationErrors = MetsUtils.validateAgainstXSD(infoFile, Info.class.getResourceAsStream("info.xsd"));
    } catch (Exception e) {
        throw new MetsExportException("Error while validating info.xml", false, e);
    }

    if (validationErrors.size() > 0) {
        MetsExportException metsException = new MetsExportException(
                "Invalid info file:" + infoFile.getAbsolutePath(), false, null);
        metsException.getExceptions().get(0).setValidationErrors(validationErrors);
        for (String error : validationErrors) {
            LOG.fine(error);
        }
        throw metsException;
    }
}

From source file:fr.fastconnect.factory.tibco.bw.maven.packaging.ApplicationManagement.java

/**
 * /application/services/bw/bindings/binding/shutdown/*
 *//*from   ww  w  . j a  va2  s .  c o m*/
private Object addShutdownParameter(Shutdown shutdown, String key, String value) {
    if ("checkpoint".equals(key)) {
        shutdown.setCheckpoint(Boolean.parseBoolean(value));
    } else if ("timeout".equals(key)) {
        shutdown.setTimeout(BigInteger.valueOf(Long.parseLong(value)));
    }

    return shutdown;
}

From source file:fr.fastconnect.factory.tibco.bw.maven.packaging.ApplicationManagement.java

/**
 * /application/services/bw/bwprocesses/bwprocess/*
 *///from   ww  w. ja va 2  s.co m
private void addBWProcessParameter(Bwprocess bwProcess, String key, String value) {
    if ("starter".equals(key)) {
        bwProcess.setStarter(value);
    } else if ("enabled".equals(key)) {
        bwProcess.setEnabled(Boolean.parseBoolean(value));
    } else if ("maxJob".equals(key)) {
        bwProcess.setMaxJob(BigInteger.valueOf(Long.parseLong(value)));
    } else if ("activation".equals(key)) {
        bwProcess.setActivation(Boolean.parseBoolean(value));
    } else if ("flowLimit".equals(key)) {
        bwProcess.setFlowLimit(BigInteger.valueOf(Long.parseLong(value)));
    }
}

From source file:net.pms.util.Rational.java

/**
 * Returns a {@link Rational} whose value is {@code (this / value)}.
 *
 * @param value the value by which this {@link Rational} is to be divided.
 * @return The division result./*  w  ww .  j av a2  s .  c o  m*/
 */
@Nonnull
public Rational divide(long value) {
    if (isNaN()) {
        return NaN;
    }

    if (value == 0) {
        if (signum() == 0) {
            return NaN;
        }
        return signum() > 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY;
    }

    if (signum() == 0 || isInfinite() || 1 == Math.abs(value)) {
        return value < 0 ? negate() : this;
    }

    // Keep the sign in the numerator and the denominator positive
    if (value < 0) {
        return valueOf(reducedNumerator.negate(), reducedDenominator.multiply(BigInteger.valueOf(-value)));
    }
    return valueOf(reducedNumerator, reducedDenominator.multiply(BigInteger.valueOf(value)));
}

From source file:org.osgp.adapter.protocol.dlms.domain.commands.DlmsHelperService.java

private BigInteger byteArrayToBigInteger(final byte[] bitStringValue) {
    if (bitStringValue == null || bitStringValue.length == 0) {
        return null;
    }/* www. j a  va  2s  .  c  o  m*/
    BigInteger value = BigInteger.valueOf(0);
    for (final byte element : bitStringValue) {
        value = value.shiftLeft(8);
        value = value.add(BigInteger.valueOf(element & 0xFF));
    }
    return value;
}

From source file:com.sun.honeycomb.admin.mgmt.server.HCCellAdapterBase.java

/**
 * Update the service tag data associated with a single cell.   This routine
 * must be called on ever cell in order to keep the silo_info.xml
 * up to date./*  ww w .j  av a 2  s.co m*/
 * <P>
 * On the master cell this routine will clear the service tag registry
 * and attempt to repopulate it with the new service tag registry 
 * information.
 * @param evt the callback handle
 * @param tagData the service tag data to update
 * @param updateRegistry boolean to indicate whether the registry
 * file should be rebuilt.  If the callee already knows the 
 * service tag data is invalid they will call this value with a
 * value of 0.  In this case this api is getting used to clear the
 * registry and the instanceURNs
 * @return BigInteger, 0 for SUCCESS, -1 for failure.  
 * Currently always returns 0
 * @throws com.sun.honeycomb.mgmt.common.MgmtException
 */
public BigInteger updateAllServiceTagData(EventSender evt, HCServiceTags tagData, BigInteger updateRegistry)
        throws MgmtException {

    boolean updateRegistryFile = updateRegistry.intValue() == 1;
    MultiCellLib multiCell = MultiCellLib.getInstance();
    boolean isStandAlone = multiCell.isCellStandalone();
    StringBuffer buf = new StringBuffer();
    buf.append(" service tag data for cell");
    if (isStandAlone == false) {
        buf.append(" ").append(getCellId());
    }
    buf.append(".");
    Reassure reassureThread = null;
    try {
        reassureThread = new Reassure(evt);
        reassureThread.start();
        boolean isSupported = ServiceTagsRegistry.isSupported();
        boolean isMaster = multiCell.isCellMaster();
        if (isSupported && isMaster) {
            // If we modify an service tag data the service tag registry
            // is considered out of date.  As such we clear the registry
            // of all ST5800 service tags.
            clearRegistry();
        }

        List<HCServiceTagCellData> list = tagData.getData();
        HCServiceTagCellData[] hCellData = (HCServiceTagCellData[]) list
                .toArray(new HCServiceTagCellData[list.size()]);
        ServiceTagCellData[] cellData = new ServiceTagCellData[hCellData.length];
        for (int i = 0; i < hCellData.length; i++) {
            ServiceTagData data = new ServiceTagData(hCellData[i].getProductNumber(),
                    hCellData[i].getProductSerialNumber(), hCellData[i].getMarketingNumber(),
                    hCellData[i].getInstanceURN());
            ServiceTagCellData cell = new ServiceTagCellData(hCellData[i].getCellId(), data);
            cellData[i] = cell;
        }

        multiCell.updateServiceTagData(cellData);
        buf.insert(0, "Successfully updated");
        logger.log(Level.INFO, buf.toString());
        //evt.sendAsynchronousEvent(buf.toString()); 

        if (updateRegistryFile && isMaster) {
            // Reset the buf to new action in case of exception
            buf = new StringBuffer(" service tag registry.");
            if (isSupported == false) {
                evt.sendAsynchronousEvent(SERVICE_TAG_REGISTRY_IS_NOT_AVAILABLE_MSG);
                return BigInteger.valueOf(CliConstants.FAILURE);
            }
            // The silo_info.xml has been updated.
            // Now update the service tag registry
            ServiceTagsGenerator generator = new ServiceTagsGenerator(cellData);
            if (generator.isValid() == false) {
                // This should technically never happen is everything is
                // done via the cli since the validation check on the cli
                // side should of failed and prevented this call from
                // ever occurring
                buf = new StringBuffer();
                buf.append("Failed to update service tag registry due to a ");
                buf.append("validation error.\nSee logs for further details.");
                // Validation errors found via ServiceTagsGenerator are
                // logged by default
                evt.sendAsynchronousEvent(buf.toString());
                return BigInteger.valueOf(CliConstants.SERVICE_TAG_REGISTRY_VALIDATION_FAILURE);
            } else {
                ServiceTagsRegistry.update(generator.getServiceTags());
                buf.insert(0, "Successfully updated");
                logger.log(Level.INFO, buf.toString());
            }
        }
        return BigInteger.ZERO;
    } catch (MultiCellLibError mcle) {
        buf.insert(0, "Failed to update");
        logger.log(Level.SEVERE, buf.toString(), mcle);
        buf.append(" Reason: ");
        buf.append(mcle.getMessage());
        buf.append(".\n");
        buf.append("Ensure that the servicetag entries are all valid by invoking the command,\n");
        buf.append("'servicetags --refresh'.");

        evt.sendAsynchronousEvent(buf.toString());
        return BigInteger.valueOf(CliConstants.FAILURE);
    } catch (Exception ex) {
        buf.insert(0, "Failed to update");
        logger.log(Level.SEVERE, buf.toString(), ex);
        buf.append(" Reason: ");
        buf.append(ex.getMessage());
        buf.append(".\n");
        buf.append("Ensure that the servicetag entries are all valid by invoking the command,\n");
        buf.append("'servicetags --refresh'");
        evt.sendAsynchronousEvent(buf.toString());
        return BigInteger.valueOf(CliConstants.FAILURE);
    } finally {
        if (reassureThread != null)
            reassureThread.safeStop();
    }
}

From source file:fr.fastconnect.factory.tibco.bw.maven.packaging.ApplicationManagement.java

/**
 * /application/services/bw/faultTolerant/*
 *///w ww .  j  a v a2 s  . co  m
private void addFaultTolerantParameter(FaultTolerant faultTolerant, String key, String value) {
    if ("activationInterval".equals(key)) {
        faultTolerant.setActivationInterval(BigInteger.valueOf(Long.parseLong(value)));
    } else if ("hbInterval".equals(key)) {
        faultTolerant.setHbInterval(BigInteger.valueOf(Long.parseLong(value)));
    } else if ("preparationDelay".equals(key)) {
        faultTolerant.setPreparationDelay(BigInteger.valueOf(Long.parseLong(value)));
    }
}

From source file:com.google.cloud.dns.testing.LocalDnsHelper.java

/**
 * Creates new managed zone and stores it in the collection. Assumes that project exists.
 *///from   ww w .  j  a v a  2 s.  co  m
@VisibleForTesting
Response createZone(String projectId, ManagedZone zone, String... fields) {
    Response errorResponse = checkZone(zone);
    if (errorResponse != null) {
        return errorResponse;
    }
    ManagedZone completeZone = new ManagedZone();
    completeZone.setName(zone.getName());
    completeZone.setDnsName(zone.getDnsName());
    completeZone.setDescription(zone.getDescription());
    completeZone.setNameServerSet(zone.getNameServerSet());
    completeZone.setCreationTime(ISODateTimeFormat.dateTime().withZoneUTC().print(System.currentTimeMillis()));
    completeZone.setId(BigInteger.valueOf(Math.abs(ID_GENERATOR.nextLong() % Long.MAX_VALUE)));
    completeZone.setNameServers(randomNameservers());
    ZoneContainer zoneContainer = new ZoneContainer(completeZone);
    ImmutableSortedMap<String, ResourceRecordSet> defaultsRecords = defaultRecords(completeZone);
    zoneContainer.dnsRecords().set(defaultsRecords);
    Change change = new Change();
    change.setAdditions(ImmutableList.copyOf(defaultsRecords.values()));
    change.setStatus("done");
    change.setId("0");
    change.setStartTime(ISODateTimeFormat.dateTime().withZoneUTC().print(System.currentTimeMillis()));
    zoneContainer.changes().add(change);
    ProjectContainer projectContainer = findProject(projectId);
    ZoneContainer oldValue = projectContainer.zones().putIfAbsent(completeZone.getName(), zoneContainer);
    if (oldValue != null) {
        return Error.ALREADY_EXISTS.response(String
                .format("The resource 'entity.managedZone' named '%s' already exists", completeZone.getName()));
    }
    ManagedZone result = OptionParsers.extractFields(completeZone, fields);
    try {
        return new Response(HTTP_OK, jsonFactory.toString(result));
    } catch (IOException e) {
        return Error.INTERNAL_ERROR
                .response(String.format("Error when serializing managed zone %s.", result.getName()));
    }
}

From source file:de.tudarmstadt.ukp.dkpro.lexsemresource.graph.EntityGraphJGraphT.java

/**
 * Computes the depth of the graph, i.e. the maximum path length starting with the root node (if
 * a single root exists)/*from  ww  w.  j  av  a 2s.com*/
 *
 * @return The depth of the hierarchy.
 * @throws UnsupportedOperationException
 * @throws LexicalSemanticResourceException
 */
private double computeDepth() throws LexicalSemanticResourceException {
    List<Entity> roots = new Stack<Entity>();
    roots.addAll(getRoots());
    if (roots.size() == 0) {
        logger.error("There is no root for this lexical semantic resource.");
        return Double.NaN;
    } else if (roots.size() > 1) {
        logger.warn("There are " + roots.size() + " roots for this lexical semantic resource.");
        logger.info("Trying to get root from underlying lexical semantic resource.");

        Entity root = lexSemRes.getRoot();
        if (root == null) {
            EntityGraph lcc = getLargestConnectedComponent();
            int nrOfLccNodes = lcc.getNumberOfNodes();
            int nrOfGraphNodes = this.getNumberOfNodes();

            double ratio = (double) nrOfLccNodes / (double) nrOfGraphNodes;

            logger.info("Falling back to the depth of the LCC.");

            if (ratio < 0.7) {
                logger.warn("The largest connected component contains only " + ratio * 100
                        + "% of all nodes. Depth might not be meaningful.");
            }

            return lcc.getDepth();
        } else {
            roots.clear(); // we know the real root, so remove the others
            roots.add(root);
        }
    }

    Entity root = roots.get(0);
    BigInteger bigMaxPathLength = BigInteger.valueOf(0);
    BigInteger[] returnValues = computeShortestPathLengths(root, BigInteger.ZERO, bigMaxPathLength,
            new HashSet<Entity>());
    bigMaxPathLength = returnValues[1];
    return bigMaxPathLength.doubleValue();

}

From source file:com.sun.honeycomb.adm.client.AdminClientImpl.java

/**
 * Wipe disk for the specified cell//from ww w . j ava2s  . co  m
 * @param cell the cell to wipe the disks on
 * @return int 0 on success, -1 on failure
 */
public int wipeDisks(HCCell cell) throws MgmtException, ConnectException, PermissionException {

    if (!loggedIn())
        throw new PermissionException();

    Object[] params = { Long.toString(this._sessionId), Byte.toString(cell.getCellId()) };
    this.extLog(ExtLevel.EXT_INFO, AdminResourcesConstants.MSG_KEY_WIPE_CELL_DISKS, params, "wipeDisks");

    BigInteger result = cell.wipe(new StatusCallback(), BigInteger.valueOf(0));
    return result.intValue();
}