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:com.lizardtech.expresszip.vaadin.ExportOptionsViewComponent.java

private void configureGridding() {
    GriddingOptions griddingOptions = new GriddingOptions();

    ExportProps props = getExportProps();
    griddingOptions.setExportWidth(props.getWidth());
    griddingOptions.setExportHeight(props.getHeight());

    griddingOptions.setGridding(gridCheckbox.booleanValue() && griddingDrawEnabled);

    if (griddingOptions.isGridding()) {

        if ((String) optGridOpt.getValue() == GRID_NUM_TILES) {
            griddingOptions.setGridMode(GriddingOptions.GridMode.DIVISION);

            int divX = Integer.parseInt(xTilesTextBox.getValue().toString());
            int divY = Integer.parseInt(yTilesTextBox.getValue().toString());
            griddingOptions.setDivX(divX > 0 ? divX : griddingOptions.getDivX());
            griddingOptions.setDivY(divY > 0 ? divY : griddingOptions.getDivY());

        } else { // GRID_TILE_DIMENSIONS or GRID_GROUND_DISTANCE

            griddingOptions.setGridMode(GriddingOptions.GridMode.METERS);
            if ((String) optGridOpt.getValue() == GRID_GROUND_DISTANCE) {
                Double groundResolution = getGroundResolution();
                griddingOptions.setTileSizeX((int) (Double.parseDouble(getDistance_X()) / groundResolution));
                griddingOptions.setTileSizeY((int) (Double.parseDouble(getDistance_Y()) / groundResolution));
            } else {
                griddingOptions.setTileSizeX(Integer.parseInt(getTile_X()));
                griddingOptions.setTileSizeY(Integer.parseInt(getTile_Y()));
            }//from   w  ww.j av  a 2 s  .  c o  m
        }
    }
    getExportProps().setGriddingOptions(griddingOptions);

    // update job summary text
    numTilesLabel.setValue(NUMBER_OF_TILES + griddingOptions.getNumTiles());

    BigInteger size = griddingOptions.getExportSize();
    String format = getImageFormat();
    if (format.equals(PNG))
        size = size.multiply(BigInteger.valueOf(85)).divide(BigInteger.valueOf(100));
    else if (format.equals(JPEG))
        size = size.divide(BigInteger.valueOf(15));
    else if (format.equals(GIF))
        size = size.multiply(BigInteger.valueOf(15)).divide(BigInteger.valueOf(100));
    else if (format.equals(BMP))
        size = size.multiply(BigInteger.valueOf(85)).divide(BigInteger.valueOf(100));
    exportSizeEstimate.setValue(DISK_ESTIMATE + FileUtils.byteCountToDisplaySize(size));
    for (ExportOptionsViewListener listener : listeners)
        listener.updateGridding(getExportProps());
}

From source file:edu.kit.dama.mdm.content.oaipmh.impl.SimpleOAIPMHRepository.java

/**
 * Get all digital objects according to the arguments set at the provided
 * OAIPMHBuilder./*from  w  w  w  .  j a  va 2  s  .c  o  m*/
 *
 * Depending of the values ot 'from', 'until' and 'metadataPrefix' set at
 * the OAIPMHBuilder the result list may contain all or a reduced list of
 * objects. The list might also be empty. In that case a proper OAI-PMH
 * error must be created by the caller.
 *
 * @param builder The OAIPMHBuilder.
 *
 * @return A list of entities which might be empty.
 */
private List<DigitalObject> getEntities(OAIPMHBuilder builder) {
    List<DigitalObject> results = new ArrayList<>();

    String prefix = builder.getMetadataPrefix();
    LOGGER.debug("Getting entities for metadata prefix {} from repository.", prefix);
    IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
    mdm.setAuthorizationContext(getAuthorizationContext());
    try {
        LOGGER.debug("Checking request for resumption token");
        String resumptionToken = builder.getResumptionToken();
        int currentCursor = 0;
        int overallCount = 0;
        //check resumption token
        if (resumptionToken != null) {
            String tokenValue = new String(
                    Base64.getDecoder().decode(URLDecoder.decode(resumptionToken, "UTF-8")));
            LOGGER.debug("Found token with value {}", tokenValue);
            String[] elements = tokenValue.split("/");
            if (elements.length != 2) {
                LOGGER.error("Invalid resumption token. Returning OAI-PMH error BAD_RESUMPTION_TOKEN.");
                builder.addError(OAIPMHerrorcodeType.BAD_RESUMPTION_TOKEN, null);
                return new ArrayList<>();
            }
            try {
                LOGGER.debug("Parsing token values.");
                currentCursor = Integer.parseInt(elements[0]);
                overallCount = Integer.parseInt(elements[1]);
                LOGGER.debug("Obtained {} as current cursor from token.", currentCursor);
            } catch (NumberFormatException ex) {
                //log error
                builder.addError(OAIPMHerrorcodeType.BAD_RESUMPTION_TOKEN, null);
                return new ArrayList<>();
            }
        } else {
            LOGGER.debug("No resumption token found.");
        }

        if (DC_SCHEMA.getSchemaIdentifier().equals(prefix)) {
            LOGGER.debug("Using Dublin Core schema handling.");
            //handle default schema which is supported by ALL objects, so no complex query is needed.
            Date from = builder.getFromDate();
            Date until = builder.getUntilDate();
            if (from != null && until != null) {
                LOGGER.debug("Getting all digital objects from {} until {}.", from, until);
                results = mdm.findResultList(
                        "SELECT o FROM DigitalObject o WHERE o.uploadDate>=?1 AND o.uploadDate <= ?2",
                        new Object[] { from, until }, DigitalObject.class, currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0) ? mdm.findSingleResult(
                        "SELECT COUNT(o) FROM DigitalObject o WHERE o.uploadDate>=?1 AND o.uploadDate <= ?2",
                        new Object[] { from, until }, Number.class).intValue() : overallCount;
            } else if (from != null && until == null) {
                LOGGER.debug("Getting all digital objects from {}.", from);
                results = mdm.findResultList("SELECT o FROM DigitalObject o WHERE o.uploadDate >= ?1",
                        new Object[] { from }, DigitalObject.class, currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0)
                        ? mdm.findSingleResult("SELECT COUNT(o) FROM DigitalObject o WHERE o.uploadDate >= ?1",
                                new Object[] { from }, Number.class).intValue()
                        : overallCount;
            } else if (from == null && until != null) {
                LOGGER.debug("Getting all digital objects until {}.", until);
                results = mdm.findResultList("SELECT o FROM DigitalObject o WHERE o.uploadDate <= ?1",
                        new Object[] { until }, DigitalObject.class, currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0)
                        ? mdm.findSingleResult("SELECT COUNT(o) FROM DigitalObject o WHERE o.uploadDate <= ?1",
                                new Object[] { until }, Number.class).intValue()
                        : overallCount;
            } else {
                LOGGER.debug("Getting all digital object.");
                results = mdm.findResultList("SELECT o FROM DigitalObject o", DigitalObject.class,
                        currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0)
                        ? mdm.findSingleResult("SELECT COUNT(o) FROM DigitalObject o", Number.class).intValue()
                        : overallCount;
            }
        } else {

            //@TODO Check where to obtain the metadata document if no MetadataIndexingTask entry is available, e.g. via DataOrganization?
            LOGGER.debug("Using custom schema handling for prefix {}.", prefix);
            //filter by special schema which might not be supported by all objects
            Date from = builder.getFromDate();
            Date until = builder.getUntilDate();
            if (from != null && until != null) {
                LOGGER.debug("Getting all digital objects from {} until {}.", from, until);
                results = mdm.findResultList(
                        "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate>=?1 AND o.uploadDate <= ?2 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?3",
                        new Object[] { from, until, prefix }, DigitalObject.class, currentCursor,
                        maxElementsPerList);
                overallCount = (overallCount == 0) ? mdm.findSingleResult(
                        "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate>=?1 AND o.uploadDate <= ?2 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?3",
                        new Object[] { from, until, prefix }, Number.class).intValue() : overallCount;
            } else if (from != null && until == null) {
                LOGGER.debug("Getting all digital objects from {}.", from);
                results = mdm.findResultList(
                        "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate>=?1 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?2",
                        new Object[] { from, prefix }, DigitalObject.class, currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0) ? mdm.findSingleResult(
                        "SELECT COUNT(o) FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate>=?1 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?2",
                        new Object[] { from, prefix }, Number.class).intValue() : overallCount;
            } else if (from == null && until != null) {
                LOGGER.debug("Getting all digital objects until {}.", until);
                results = mdm.findResultList(
                        "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate <= ?1 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?2",
                        new Object[] { until, prefix }, DigitalObject.class, currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0) ? mdm.findSingleResult(
                        "SELECT COUNT(o) FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate <= ?1 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?2",
                        new Object[] { until, prefix }, Number.class).intValue() : overallCount;
            } else {
                LOGGER.debug("Getting all digital object.");
                results = mdm.findResultList(
                        "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?1",
                        new Object[] { prefix }, DigitalObject.class, currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0) ? mdm.findSingleResult(
                        "SELECT COUNT(o) FROM DigitalObject o,MetadataIndexingTask t WHERE t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?1",
                        new Object[] { prefix }, Number.class).intValue() : overallCount;
            }
        }

        LOGGER.debug("Setting next resumption token.");
        if (currentCursor + maxElementsPerList > overallCount) {
            LOGGER.debug(
                    "Cursor exceeds element count, no more elements available. Setting resumption token to 'null'.");
            //lsit complete, add no resumptiontoken
            builder.setResumptionToken(null);
        } else {
            ResumptionTokenType token = new ResumptionTokenType();
            //set list size
            token.setCompleteListSize(BigInteger.valueOf(overallCount));
            //set current cursor
            token.setCursor(BigInteger.valueOf(currentCursor + results.size()));
            LOGGER.debug("Setting new resumption token with cursor at position " + token.getCursor());
            //we set no expiration as the token never expires
            String value = token.getCursor().intValue() + "/" + token.getCompleteListSize().intValue();
            LOGGER.debug("Setting resumption token value to {}.", value);
            token.setValue(URLEncoder.encode(Base64.getEncoder().encodeToString(value.getBytes()), "UTF-8"));
            builder.setResumptionToken(token);
        }
    } catch (UnauthorizedAccessAttemptException | UnsupportedEncodingException ex) {
        //error
        LOGGER.error("Failed to get results from repository. Returning empty list.", ex);
    } finally {
        mdm.close();
    }
    return results;
}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * Converts a String to the class that is passed in.
 * @param dataStr the data string to be converted
 * @param cls the class that the string is to be converted t
 * @return the data object/* w w  w  . jav  a 2s.  co  m*/
 */
public static <T> Object convertDataFromString(final String dataStr, final Class<T> cls) {
    try {
        //log.debug("Trying to convertDataFromString dataStr [" + dataStr + "] of class[" + cls + "]");
        if (cls == Integer.class) {
            return StringUtils.isNotEmpty(dataStr) ? Integer.parseInt(dataStr) : null;

        } else if (cls == BigInteger.class) {
            return StringUtils.isNotEmpty(dataStr) ? BigInteger.valueOf(Long.parseLong(dataStr)) : null;

        } else if (cls == Float.class) {
            return StringUtils.isNotEmpty(dataStr) ? Float.parseFloat(dataStr) : null;

        } else if (cls == Double.class) {
            return StringUtils.isNotEmpty(dataStr) ? Double.parseDouble(dataStr) : null;

        } else if (cls == BigDecimal.class) {
            //System.out.println(BigDecimal.valueOf(Double.parseDouble(dataStr)));
            return StringUtils.isNotEmpty(dataStr) ? BigDecimal.valueOf(Double.parseDouble(dataStr)) : null;

        } else if (cls == Long.class) {
            return StringUtils.isNotEmpty(dataStr) ? Long.parseLong(dataStr) : null;

        } else if (cls == Short.class) {
            return StringUtils.isNotEmpty(dataStr) ? Short.parseShort(dataStr) : null;

        } else if (cls == Byte.class) {
            return StringUtils.isNotEmpty(dataStr) ? Byte.parseByte(dataStr) : null;

        } else if (cls == Calendar.class) {
            return StringUtils.isNotEmpty(dataStr) ? getCalendar(dataStr, scrDateFormat) : null;

        } else if (cls == Date.class) {
            return StringUtils.isNotEmpty(dataStr) ? getDate(dataStr, scrDateFormat) : null;

        } else if (cls == Timestamp.class) {
            return StringUtils.isNotEmpty(dataStr) ? getDate(dataStr, scrDateFormat) : null;

        } else if (cls == String.class) {
            return dataStr;

        } else {
            log.error("Unsupported type for conversion[" + cls.getSimpleName() + "]");
        }
    } catch (Exception ex) {

    }
    return null;
}

From source file:com.cloud.network.NetworkModelImpl.java

@Override
public boolean isIP6AddressAvailableInVlan(long vlanId) {
    VlanVO vlan = _vlanDao.findById(vlanId);
    if (vlan.getIp6Range() == null) {
        return false;
    }//  ww w .  jav  a2 s.  c o  m
    long existedCount = _ipv6Dao.countExistedIpsInVlan(vlanId);
    BigInteger existedInt = BigInteger.valueOf(existedCount);
    BigInteger rangeInt = NetUtils.countIp6InRange(vlan.getIp6Range());
    return (existedInt.compareTo(rangeInt) < 0);
}

From source file:co.rsk.peg.BridgeSerializationUtilsTest.java

@Test
public void serializeAndDeserializeFederationWithRealRLP() {
    NetworkParameters networkParms = NetworkParameters.fromID(NetworkParameters.ID_REGTEST);
    byte[][] publicKeyBytes = new byte[][] { BtcECKey.fromPrivate(BigInteger.valueOf(100)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(200)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(300)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(400)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(500)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(600)).getPubKey(), };

    Federation federation = new Federation(
            Arrays.asList(BtcECKey.fromPublicOnly(publicKeyBytes[0]),
                    BtcECKey.fromPublicOnly(publicKeyBytes[1]), BtcECKey.fromPublicOnly(publicKeyBytes[2]),
                    BtcECKey.fromPublicOnly(publicKeyBytes[3]), BtcECKey.fromPublicOnly(publicKeyBytes[4]),
                    BtcECKey.fromPublicOnly(publicKeyBytes[5])),
            Instant.ofEpochMilli(0xabcdef), 42L, networkParms);

    byte[] result = BridgeSerializationUtils.serializeFederation(federation);
    Federation deserializedFederation = BridgeSerializationUtils.deserializeFederation(result, networkParms);
    Assert.assertThat(federation, is(deserializedFederation));
}

From source file:com.ephesoft.gxt.rv.server.ReviewValidateServiceImpl.java

@Override
public List<Span> getHOCRContent(final PointCoordinate pointCoordinate1, final PointCoordinate pointCoordinate2,
        final String batchInstanceIdentifier, final String hocrFileName,
        final boolean rectangularCoordinateSet) {
    List<Span> spanSelectedList = null;
    boolean valid = true;
    if (batchInstanceIdentifier == null) {
        valid = false;//from  ww w  . ja  va 2s  . c o  m
    }
    if (hocrFileName == null) {
        valid = false;
    }
    if (valid) {
        final BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
        final HocrPages hocrPages = batchSchemaService.getHocrPages(batchInstanceIdentifier, hocrFileName);
        if (hocrPages != null && hocrPages.getHocrPage() != null) {
            final List<HocrPage> hocrPageList = hocrPages.getHocrPage();
            if (!hocrPageList.isEmpty()) {
                final HocrPage hocrPage = hocrPageList.get(0);
                List<Span> spanList = new ArrayList<Span>();
                if (hocrPage.getSpans() != null) {
                    spanList = hocrPage.getSpans().getSpan();
                }
                Integer firstSpanIndex = null;
                Integer lastSpanIndex = null;

                final Integer x0Coordinate = pointCoordinate1.getxCoordinate();
                final Integer y0Coordinate = pointCoordinate1.getyCoordinate();
                final Integer x1Coordinate = pointCoordinate2.getxCoordinate();
                final Integer y1Coordinate = pointCoordinate2.getyCoordinate();
                final List<Span> spanSortedList = getSortedList(spanList);
                if (!rectangularCoordinateSet) {

                    int counter = 0;

                    for (final Span span : spanSortedList) {
                        final long spanX0 = span.getCoordinates().getX0().longValue();
                        final long spanY0 = span.getCoordinates().getY0().longValue();
                        final long spanX1 = span.getCoordinates().getX1().longValue();
                        final long spanY1 = span.getCoordinates().getY1().longValue();
                        if (spanX0 < x0Coordinate && spanX1 > x0Coordinate && spanY0 < y0Coordinate
                                && spanY1 > y0Coordinate) {
                            firstSpanIndex = counter;
                        }
                        if (spanX0 < x1Coordinate && spanX1 > x1Coordinate && spanY0 < y1Coordinate
                                && spanY1 > y1Coordinate) {
                            lastSpanIndex = counter;
                        }
                        if (firstSpanIndex != null && lastSpanIndex != null) {
                            break;
                        }
                        counter++;
                    }
                    if (firstSpanIndex != null && lastSpanIndex != null) {
                        counter = 0;
                        for (final Span span : spanSortedList) {
                            if ((counter >= firstSpanIndex && counter <= lastSpanIndex)
                                    || (counter <= firstSpanIndex && counter >= lastSpanIndex)) {
                                if (spanSelectedList == null) {
                                    spanSelectedList = new ArrayList<Span>();
                                }
                                spanSelectedList.add(span);
                            }
                            counter++;
                        }
                    }
                } else {
                    boolean isValidSpan = false;
                    final int defaultvalue = 20;
                    int counter = 0;
                    final StringBuffer valueStringBuffer = new StringBuffer();
                    long currentYCoor = spanSortedList.get(0).getCoordinates().getY1().longValue();
                    for (final Span span : spanSortedList) {
                        isValidSpan = false;
                        final long spanX0 = span.getCoordinates().getX0().longValue();
                        final long spanY0 = span.getCoordinates().getY0().longValue();
                        final long spanX1 = span.getCoordinates().getX1().longValue();
                        final long spanY1 = span.getCoordinates().getY1().longValue();
                        if ((spanY1 - currentYCoor) > defaultvalue) {
                            currentYCoor = spanY1;
                            if (spanSelectedList != null && spanSelectedList.size() > 0) {
                                break;
                            }
                        }
                        if (((spanX1 >= x0Coordinate && spanX1 <= x1Coordinate)
                                || (spanX0 >= x0Coordinate && spanX0 <= x1Coordinate))
                                && ((spanY1 <= y1Coordinate && spanY1 >= y0Coordinate)
                                        || (spanY0 <= y1Coordinate && spanY0 >= y0Coordinate))) {
                            isValidSpan = true;
                        } else if (((x0Coordinate <= spanX0 && x1Coordinate >= spanX0)
                                || (x0Coordinate >= spanX1 && x1Coordinate <= spanX1))
                                && ((y0Coordinate >= spanY0 && y0Coordinate <= spanY1)
                                        || (y1Coordinate >= spanY0 && y1Coordinate <= spanY1))
                                || ((y0Coordinate <= spanY0 && y1Coordinate >= spanY0)
                                        || (y0Coordinate >= spanY1 && y1Coordinate <= spanY1))
                                        && ((x0Coordinate >= spanX0 && x0Coordinate <= spanX1)
                                                || (x1Coordinate >= spanX0 && x1Coordinate <= spanX1))) {
                            isValidSpan = true;
                        } else {
                            if (((x0Coordinate > spanX0 && x0Coordinate < spanX1)
                                    || (x1Coordinate > spanX0 && x1Coordinate < spanX1))
                                    && ((y0Coordinate > spanY0 && y0Coordinate < spanY1)
                                            || (y1Coordinate > spanY0 && y1Coordinate < spanY1))) {
                                isValidSpan = true;
                            }
                        }
                        if (isValidSpan) {
                            if (counter != 0) {
                                valueStringBuffer.append(' ');
                            }
                            valueStringBuffer.append(span.getValue());
                            counter++;
                        }

                    }
                    if (spanSelectedList == null) {
                        spanSelectedList = new ArrayList<Span>();
                    }
                    final Span span = new Span();
                    final Coordinates coordinates = new Coordinates();
                    coordinates.setX0(BigInteger.valueOf(x0Coordinate));
                    coordinates.setX1(BigInteger.valueOf(x1Coordinate));
                    coordinates.setY0(BigInteger.valueOf(y0Coordinate));
                    coordinates.setY1(BigInteger.valueOf(y1Coordinate));
                    span.setCoordinates(coordinates);
                    span.setValue(valueStringBuffer.toString());
                    spanSelectedList.add(span);

                }
            }
        }
    }

    return spanSelectedList;
}

From source file:CentralLimitTheorem.CLT.java

static BigInteger factorial(int n) {
    BigInteger res = BigInteger.ONE;

    for (int i = n; i > 1; i--) {
        res = res.multiply(BigInteger.valueOf(i));
    }/*from  w  w w  .  j  a va  2s .c  om*/
    return (res);
}

From source file:com.gettec.fsnip.fsn.service.market.impl.ResourceServiceImpl.java

/**
 * ???/*from   w  ww.j  a  va  2  s .  c  o  m*/
 * 
 * @param orgAttachments
 * @param businessUnit
 * @return void
 * @throws ServiceException
 * @author ZhangHui
 */
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void saveOrgnizationResource(Set<Resource> orgAttachments, BusinessUnit busUnit)
        throws ServiceException {
    try {
        if (orgAttachments == null || orgAttachments.size() < 1) {
            return;
        }
        EnterpriseRegiste orig_enterprise = enterpriseService.findbyEnterpriteName(busUnit.getName());
        /* ??? */
        LiutongFieldValue ltOrgan_orig = liutongFieldValueService.findByProducerIdAndValueAndDisplay(
                busUnit.getId(), orig_enterprise.getOrganizationNo(), "?");
        List<Long> liutongOrgResId = null;
        if (ltOrgan_orig != null) {
            /* ??-????id */
            liutongOrgResId = liutongFieldValueService.getResourceIds(busUnit.getId(),
                    orig_enterprise.getOrganizationNo(), "?");
        }
        /* 1.?[??]? */
        Set<Resource> removes = getListOfRemoves(
                orig_enterprise == null ? null : orig_enterprise.getOrgAttachments(), orgAttachments);
        /* 2.? */
        Set<Resource> adds = operationResources(orgAttachments, "org", null);
        /* 3.?? */
        if (!CollectionUtils.isEmpty(removes)) {
            orig_enterprise.removeOrgResources(removes);
            for (Resource resource : removes) {
                BigInteger resId = BigInteger.valueOf(resource.getId());
                /* ???-????  */
                if (liutongOrgResId != null && liutongOrgResId.contains(resId)) {
                    ltOrgan_orig.removeResources(resource);
                }
                delete(resource);
            }
        }
        if (!CollectionUtils.isEmpty(adds)) {
            orig_enterprise.addOrgResources(adds);
            if (ltOrgan_orig != null) {
                ltOrgan_orig.addResources(adds);
            }
        }
        enterpriseService.update(orig_enterprise);
        if (ltOrgan_orig != null) {
            liutongFieldValueService.update(ltOrgan_orig);
        }
    } catch (ServiceException e) {
        throw e;
    } catch (Exception e) {
        throw new ServiceException("?", e);
    }
}

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.  On
 * the master node this will clear the registry file.  If the cell is
 * a single cell system the registry file will be updated.  An update
 * does not happen on multi-cell since we can't update all the instanceIDs
 * on all cells.  Therefore we required the operator to do a 
 * "servicetags --refresh"//from  w ww.ja v a  2s  . c  o  m
 * @param evt the callback handle
 * @param cellData the service tag data to update
 * @return BigInteger, 0 for SUCCESS, -1 for failure, -2 for failed
 * to update registry file on a single cell system.   
 * Currently always returns 0
 * @throws com.sun.honeycomb.mgmt.common.MgmtException
 */
public BigInteger updateServiceTagData(EventSender evt, HCServiceTagCellData cellData) throws MgmtException {

    MultiCellLib multiCell = MultiCellLib.getInstance();
    boolean isStandAlone = multiCell.isCellStandalone();
    StringBuffer buf = new StringBuffer();
    buf.append(" service tag data on cell");
    if (isStandAlone == false) {
        buf.append(" ").append(cellData.getCellId()).append(" on cell ");
        buf.append(getCellId());
    }
    buf.append(".");
    Reassure reassureThread = new Reassure(evt);
    try {
        reassureThread.start();
        boolean isSupported = ServiceTagsRegistry.isSupported();
        boolean isMaster = multiCell.isCellMaster();
        if (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.
            if (isSupported)
                clearRegistry();
        }
        String instanceURN = null;
        if (isStandAlone) {
            // When we have a single cell system we can automatically
            // update the service tag registry.  On a multi-cell hive
            // this isn't possible since we can't update all the 
            // instance information on all the cells.  The operator
            // in that scenario must follow up with a "servicetag --refresh"
            // command.
            instanceURN = ServiceTag.generateInstanceURN();
        }
        ServiceTagData data = new ServiceTagData(cellData.getProductNumber(), cellData.getProductSerialNumber(),
                cellData.getMarketingNumber(), instanceURN);

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

        if (isStandAlone) {
            // Reset the buf to new action in case of exception
            buf = new StringBuffer(" service tag registry.");

            ClusterProperties props = ClusterProperties.getInstance();
            boolean disabled = props
                    .getPropertyAsBoolean(ConfigPropertyNames.PROP_SERVICE_TAG_SERVICE_DISABLED);
            if (disabled) {
                evt.sendAsynchronousEvent(
                        "Service Tag service is disabled service tag " + "registry file will not be updated.");
                return BigInteger.valueOf(CliConstants.SERVICE_TAG_REGISTRY_UPDATE_FAILURE);

            }

            // This is a single cell system.
            // We can automatically update the service tag registry
            if (isSupported == false) {
                evt.sendAsynchronousEvent(SERVICE_TAG_REGISTRY_IS_NOT_AVAILABLE_MSG);
                return BigInteger.valueOf(CliConstants.SERVICE_TAG_REGISTRY_UPDATE_FAILURE);
            }
            ServiceTagCellData[] cells = new ServiceTagCellData[] { new ServiceTagCellData(getCellId(), data) };
            ServiceTagsGenerator generator = new ServiceTagsGenerator(cells);
            if (generator.isValid() == false) {
                // This should never happen on a single cell system
                buf = new StringBuffer().append("Failed to update service tag registry due to a ")
                        .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");
                evt.sendAsynchronousEvent(buf.toString());
                logger.log(Level.INFO, buf.toString());
            }
        }
        return BigInteger.ZERO;
    } catch (MgmtException me) {
        buf.insert(0, "Failed to update");
        logger.log(Level.SEVERE, buf.toString(), me);
        buf.append(" Reason: ");
        buf.append(me.getMessage());
        buf.append(".\n");
        buf.append("Ensure that the servicetag entries are all valid by invoking the command,");
        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,");
        buf.append("'servicetags --refresh'");

        evt.sendAsynchronousEvent(buf.toString());
        return BigInteger.valueOf(CliConstants.FAILURE);
    } finally {
        if (reassureThread != null)
            reassureThread.safeStop();
    }
}

From source file:org.alienlabs.hatchetharry.view.page.HomePage.java

private void generateRevealHandLink(final String id) {
    this.add(new AjaxLink<Void>(id) {
        private static final long serialVersionUID = 1L;

        @Override//from   w  w  w  .  j  av  a2 s.  c om
        public void onClick(final AjaxRequestTarget target) {
            final Long _gameId = HomePage.this.session.getGameId();
            final List<BigInteger> allPlayersInGameExceptMe = HomePage.this.persistenceService
                    .giveAllPlayersFromGameExceptMe(_gameId, HomePage.this.session.getPlayer().getId());

            final NotifierCometChannel ncc = new NotifierCometChannel(NotifierAction.REVEAL_HAND, null, null,
                    HomePage.this.session.getPlayer().getName(), "", "", null, "");
            final ConsoleLogStrategy logger = AbstractConsoleLogStrategy.chooseStrategy(
                    ConsoleLogType.REVEAL_HAND, null, null, null, null,
                    HomePage.this.session.getPlayer().getName(), null, null, null, Boolean.FALSE, _gameId);
            final RevealHandCometChannel rhcc = new RevealHandCometChannel(_gameId,
                    HomePage.this.session.getPlayer().getId(),
                    HomePage.this.session.getPlayer().getDeck().getDeckId());
            EventBusPostService.post(allPlayersInGameExceptMe, ncc, new ConsoleLogCometChannel(logger), rhcc);

            final List<BigInteger> playerToWhomToSend = new ArrayList<>();
            playerToWhomToSend.add(BigInteger.valueOf(HomePage.this.session.getPlayer().getId().longValue()));
            EventBusPostService.post(playerToWhomToSend, ncc, new ConsoleLogCometChannel(logger));
        }

    });
}