Example usage for java.lang Integer shortValue

List of usage examples for java.lang Integer shortValue

Introduction

In this page you can find the example usage for java.lang Integer shortValue.

Prototype

public short shortValue() 

Source Link

Document

Returns the value of this Integer as a short after a narrowing primitive conversion.

Usage

From source file:com.intuit.tank.api.model.v1.datafile.DataFileDescriptorTest.java

/**
 * Run the Integer getId() method test.//from w  w  w . j  a  v a  2s  . c  o  m
 *
 * @throws Exception
 *
 * @generatedBy CodePro at 12/15/14 3:00 PM
 */
@Test
public void testGetId_1() throws Exception {
    DataFileDescriptor fixture = new DataFileDescriptor();
    fixture.setComments("");
    fixture.setCreator("");
    fixture.setName("");
    fixture.setDataUrl("");
    fixture.setId(new Integer(1));
    fixture.setCreated(new Date());
    fixture.setModified(new Date());

    Integer result = fixture.getId();

    assertNotNull(result);
    assertEquals("1", result.toString());
    assertEquals((byte) 1, result.byteValue());
    assertEquals((short) 1, result.shortValue());
    assertEquals(1, result.intValue());
    assertEquals(1L, result.longValue());
    assertEquals(1.0f, result.floatValue(), 1.0f);
    assertEquals(1.0, result.doubleValue(), 1.0);
}

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.Swing.CFJInt16Editor.java

public Short getInt16Value() {
    final String S_ProcName = "getInt16Value";
    Short retval;//w  w  w  .  j  a  v  a2  s  .  c o  m
    String text = getText();
    if ((text == null) || (text.length() <= 0)) {
        retval = null;
    } else {
        if (!isEditValid()) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "Field is not valid");
        }
        try {
            commitEdit();
        } catch (ParseException e) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Field is not valid - " + e.getMessage(), e);

        }
        Object obj = getValue();
        if (obj == null) {
            retval = null;
        } else if (obj instanceof Short) {
            Short s = (Short) obj;
            short v = s.shortValue();
            if ((v < getMinValue()) || (v > getMaxValue())) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, getMinValue(), getMaxValue());
            }
            retval = (Short) s;
        } else if (obj instanceof Integer) {
            Integer i = (Integer) obj;
            int v = i.intValue();
            if ((v < getMinValue()) || (v > getMaxValue())) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, getMinValue(), getMaxValue());
            }
            retval = new Short(i.shortValue());
        } else if (obj instanceof Long) {
            Long l = (Long) obj;
            long v = l.longValue();
            if ((v < getMinValue()) || (v > getMaxValue())) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, getMinValue(), getMaxValue());
            }
            retval = new Short(l.shortValue());
        } else if (obj instanceof Number) {
            Number n = (Number) obj;
            long v = n.longValue();
            if ((v < getMinValue()) || (v > getMaxValue())) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, getMinValue(), getMaxValue());
            }
            retval = new Short(n.shortValue());
        } else {
            throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException(getClass(), S_ProcName,
                    "EditedValue", obj, "Short, Integer, Long, or Number");
        }
    }
    return (retval);
}

From source file:com.sfs.captor.controller.AlternativeFlowAction.java

/**
 * Add alternative flow step/*  w ww  .j  a v a 2 s  . c  o  m*/
 * 
 * @throws UCMException
 */
public void addFlowStep() throws UCMException {
    try {
        Integer stepNumber = this.alternativeFlow.getFlowSteps().size() + 1;

        this.alternativeFlowStep = new FlowStep(stepNumber.shortValue());

        if (stepNumber.shortValue() % 2 == 0) {
            // test for previous actor
        } else {
            // system is actor for odd numbered steps
            Actor system = this.projectService.findSystemActor(this.project);
            this.alternativeFlowStep.setActor(system);
        }
    } catch (Exception e) {
        throw new UCMException(e);
    }
}

From source file:com.sfs.ucm.controller.UseCaseFlowAction.java

/**
 * Add basic flow step/*from ww w .  j  av a  2 s  .  co m*/
 * 
 * @throws UCMException
 */
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void addFlowStep() throws UCMException {
    try {
        Integer stepNumber = this.useCase.getBasicFlow().getFlowSteps().size() + 1;
        this.basicFlowStep = new FlowStep(stepNumber.shortValue());

        if (stepNumber.intValue() % 2 == 0) {
            // test for previous actor
        } else {
            // system is actor for odd numbered steps
            Actor system = this.projectService.findSystemActor(this.project);
            this.basicFlowStep.setActor(system);
        }
    } catch (Exception e) {
        throw new UCMException(e);
    }
}

From source file:org.mifos.application.servicefacade.PersonnelServiceFacadeWebTier.java

@Override
public SitePreferenceType retrieveSitePreference(Integer userId) {
    PersonnelBO personnelBO = personnelDao.findPersonnelById(userId.shortValue());
    return SitePreferenceType.getSitePreference(personnelBO.getSitePreference());
}

From source file:com.sfs.captor.controller.UseCaseFlowAction.java

/**
 * Add basic flow step/* www.ja  v a 2s  .c  o  m*/
 * 
 * @throws UCMException
 */
public void addFlowStep() throws UCMException {
    try {
        Integer stepNumber = this.useCase.getBasicFlow().getFlowSteps().size() + 1;
        this.basicFlowStep = new FlowStep(stepNumber.shortValue());

        if (stepNumber.intValue() % 2 == 0) {
            // test for previous actor
        } else {
            // system is actor for odd numbered steps
            Actor system = this.projectService.findSystemActor(this.project);
            this.basicFlowStep.setActor(system);
        }
    } catch (Exception e) {
        throw new UCMException(e);
    }
}

From source file:org.mifos.application.importexport.xls.XlsClientsImporter.java

private Short intToShort(final Integer arg) {
    return (arg == null) ? null : arg.shortValue();
}

From source file:org.mifos.application.servicefacade.PersonnelServiceFacadeWebTier.java

@Override
public UserSettingsDto retrieveUserSettings(Integer genderId, Integer maritalStatusId, Integer localeId,
        Short sitePreferenceId) {

    String gender = getNameForBusinessActivityEntity(genderId);
    String martialStatus = getNameForBusinessActivityEntity(maritalStatusId);
    String language = (localeId != null) ? Localization.getInstance().getDisplayName(localeId.shortValue())
            : "";
    String sitePreference = SitePreferenceType.getSitePreference(sitePreferenceId).name();

    int age = 0;// w  w  w. j a  v a 2s.  c om
    List<ValueListElement> empty = new ArrayList<ValueListElement>();
    return new UserSettingsDto(gender, martialStatus, language, age, sitePreference, empty, empty, empty,
            empty);
}

From source file:voldemort.client.rebalance.ZonedRebalanceNonContiguousZonesTest.java

@Test(timeout = 600000)
public void testProxyPutDuringRebalancing() throws Exception {
    logger.info("Starting testProxyPutDuringRebalancing");
    try {//ww w . j ava2  s. c o m

        int zoneIds[] = new int[] { 1, 3 };
        int nodesPerZone[][] = new int[][] { { 3, 4, 5 }, { 9, 10, 11 } };
        int partitionMap[][] = new int[][] { { 0 }, { 1, 6 }, { 2 }, { 3 }, { 4, 7 }, { 5 } };
        Cluster currentCluster = ServerTestUtils.getLocalNonContiguousZonedCluster(zoneIds, nodesPerZone,
                partitionMap, ClusterTestUtils.getClusterPorts());

        Cluster finalCluster = UpdateClusterUtils.createUpdatedCluster(currentCluster, 5,
                Lists.newArrayList(7));
        finalCluster = UpdateClusterUtils.createUpdatedCluster(finalCluster, 11, Lists.newArrayList(6));

        /**
         * Original partition map
         * 
         * [s3 : p0] [s4 : p1, p6] [s5 : p2]
         * 
         * [s9 : p3] [s10 : p4, p7] [s11 : p5]
         * 
         * final server partition ownership
         * 
         * [s3 : p0] [s4 : p1] [s5 : p2, p7]
         * 
         * [s9 : p3] [s10 : p4] [s11 : p5, p6]
         * 
         * Note that rwStoreDefFileWithReplication is a "2/1/1" store def.
         * 
         * Original server n-ary partition ownership
         * 
         * [s3 : p0, p3-7] [s4 : p0-p7] [s5 : p1-2]
         * 
         * [s9 : p0-3, p6-7] [s10 : p0-p7] [s11 : p4-5]
         * 
         * final server n-ary partition ownership
         * 
         * [s3 : p0, p2-7] [s4 : p0-1] [s5 : p1-p7]
         * 
         * [s9 : p0-3, p5-7] [s10 : p0-4, p7] [s11 : p4-6]
         */
        List<Integer> serverList = Arrays.asList(3, 4, 5, 9, 10, 11);
        Map<String, String> configProps = new HashMap<String, String>();
        configProps.put("admin.max.threads", "5");
        final Cluster updatedCurrentCluster = startServers(currentCluster, rwStoreDefFileWithReplication,
                serverList, configProps);
        ExecutorService executors = Executors.newFixedThreadPool(2);
        final AtomicBoolean rebalancingComplete = new AtomicBoolean(false);
        final List<Exception> exceptions = Collections.synchronizedList(new ArrayList<Exception>());

        // Its is imperative that we test in a single shot since multiple batches would mean the proxy bridges
        // being torn down and established multiple times and we cannot test against the source 
        // cluster topology then. getRebalanceKit uses batch size of infinite, so this should be fine.
        String bootstrapUrl = getBootstrapUrl(updatedCurrentCluster, 3);
        int maxParallel = 2;
        final ClusterTestUtils.RebalanceKit rebalanceKit = ClusterTestUtils.getRebalanceKit(bootstrapUrl,
                maxParallel, finalCluster);
        populateData(currentCluster, rwStoreDefWithReplication);
        final AdminClient adminClient = rebalanceKit.controller.getAdminClient();
        // the plan would cause these partitions to move:
        // Partition : Donor -> stealer
        //
        // p2 (Z-SEC) : s4 -> s3
        // p3-6 (Z-PRI) : s4 -> s5
        // p7 (Z-PRI) : s3 -> s5
        //
        // p5 (Z-SEC): s10 -> s9
        // p6 (Z-PRI): s10 -> s11
        //
        // Rebalancing will run on servers 3, 5, 9, & 11
        final List<ByteArray> movingKeysList = sampleKeysFromPartition(adminClient, 4,
                rwStoreDefWithReplication.getName(), Arrays.asList(6), 20);
        assertTrue("Empty list of moving keys...", movingKeysList.size() > 0);
        final AtomicBoolean rebalancingStarted = new AtomicBoolean(false);
        final AtomicBoolean proxyWritesDone = new AtomicBoolean(false);
        final HashMap<String, String> baselineTuples = new HashMap<String, String>(testEntries);
        final HashMap<String, VectorClock> baselineVersions = new HashMap<String, VectorClock>();
        for (String key : baselineTuples.keySet()) {
            baselineVersions.put(key, new VectorClock());
        }
        final CountDownLatch latch = new CountDownLatch(2);
        // start get operation.
        executors.execute(new Runnable() {
            @Override
            public void run() {
                SocketStoreClientFactory factory = null;
                try {
                    // wait for the rebalancing to begin
                    List<VoldemortServer> serverList = Lists.newArrayList(serverMap.get(3), serverMap.get(5),
                            serverMap.get(9), serverMap.get(11));
                    while (!rebalancingComplete.get()) {
                        Iterator<VoldemortServer> serverIterator = serverList.iterator();
                        while (serverIterator.hasNext()) {
                            VoldemortServer server = serverIterator.next();
                            if (ByteUtils
                                    .getString(server.getMetadataStore()
                                            .get(MetadataStore.SERVER_STATE_KEY, null).get(0).getValue(),
                                            "UTF-8")
                                    .compareTo(VoldemortState.REBALANCING_MASTER_SERVER.toString()) == 0) {
                                logger.info("Server " + server.getIdentityNode().getId()
                                        + " transitioned into REBALANCING MODE");
                                serverIterator.remove();
                            }
                        }
                        if (serverList.size() == 0) {
                            rebalancingStarted.set(true);
                            break;
                        }
                    }
                    if (rebalancingStarted.get()) {
                        factory = new SocketStoreClientFactory(
                                new ClientConfig().setBootstrapUrls(getBootstrapUrl(updatedCurrentCluster, 3))
                                        .setEnableLazy(false).setSocketTimeout(120, TimeUnit.SECONDS)
                                        .setClientZoneId(3));

                        final StoreClient<String, String> storeClientRW = new DefaultStoreClient<String, String>(
                                testStoreNameRW, null, factory, 3);
                        // Now perform some writes and determine the end state of the changed keys. 
                        // Initially, all data now with zero vector clock
                        for (ByteArray movingKey : movingKeysList) {
                            try {
                                String keyStr = ByteUtils.getString(movingKey.get(), "UTF-8");
                                String valStr = "proxy_write";
                                storeClientRW.put(keyStr, valStr);
                                baselineTuples.put(keyStr, valStr);
                                baselineVersions.get(keyStr).incrementVersion(11, System.currentTimeMillis());
                                proxyWritesDone.set(true);
                                if (rebalancingComplete.get()) {
                                    break;
                                }
                            } catch (InvalidMetadataException e) {
                                logger.error("Encountered an invalid metadata exception.. ", e);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("Exception in proxy write thread..", e);
                    exceptions.add(e);
                } finally {
                    if (factory != null)
                        factory.close();
                    latch.countDown();
                }
            }
        });

        executors.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    rebalanceKit.rebalance();
                } catch (Exception e) {
                    logger.error("Error in rebalancing... ", e);
                    exceptions.add(e);
                } finally {
                    rebalancingComplete.set(true);
                    latch.countDown();
                }
            }
        });
        latch.await();
        executors.shutdown();
        executors.awaitTermination(300, TimeUnit.SECONDS);

        assertEquals("Client did not see all server transition into rebalancing state",
                rebalancingStarted.get(), true);
        assertEquals("Not enough time to begin proxy writing", proxyWritesDone.get(), true);
        checkEntriesPostRebalance(updatedCurrentCluster, finalCluster,
                Lists.newArrayList(rwStoreDefWithReplication), Arrays.asList(3, 4, 5, 9, 10, 11),
                baselineTuples, baselineVersions);
        checkConsistentMetadata(finalCluster, serverList);
        // check No Exception
        if (exceptions.size() > 0) {
            for (Exception e : exceptions) {
                e.printStackTrace();
            }
            fail("Should not see any exceptions.");
        }
        // check that the proxy writes were made to the original donor, node 4
        List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverList.size());
        for (Integer nodeid : serverList)
            clockEntries.add(new ClockEntry(nodeid.shortValue(), System.currentTimeMillis()));
        VectorClock clusterXmlClock = new VectorClock(clockEntries, System.currentTimeMillis());
        for (Integer nodeid : serverList)
            adminClient.metadataMgmtOps.updateRemoteCluster(nodeid, currentCluster, clusterXmlClock);
        adminClient.setAdminClientCluster(currentCluster);
        checkForTupleEquivalence(adminClient, 4, testStoreNameRW, movingKeysList, baselineTuples,
                baselineVersions);
        // stop servers
        try {
            stopServer(serverList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } catch (AssertionError ae) {
        logger.error("Assertion broken in testProxyPutDuringRebalancing ", ae);
        throw ae;
    }
}

From source file:se.uu.it.cs.recsys.service.resource.CourseResource.java

@GET
@Path("/year/{year}/period/start/{period}")
@Produces(MediaType.APPLICATION_JSON)/*from   w  w w . j av a2  s.c o  m*/
@ApiOperation(value = "Find course according to taught year and start period.", response = Course.class, responseContainer = "Set")
public Response getCourseByScheduleInfo(
        @ApiParam(name = "year", required = true) @PathParam("year") Integer taughtYear,
        @ApiParam(name = "period", allowableValues = "1,2,3,4", required = true) @PathParam("period") Integer startPeriod) {
    LOGGER.info("Get course taught in {}, started in period {}", taughtYear, startPeriod);

    if (taughtYear == null || taughtYear < UU_FOUND_YEAR) {

        LOGGER.error("Input year is {}, UU founded in {} ", taughtYear, UU_FOUND_YEAR);

        final String REASON = "UU founded yet in year " + UU_FOUND_YEAR;

        return Response.status(Response.Status.BAD_REQUEST).header("Reason", REASON).build();
    }

    if (startPeriod == null) {
        final String REASON = "Start period is null";

        LOGGER.error(REASON);

        return Response.status(Response.Status.BAD_REQUEST).header("Reason", REASON).build();
    }

    Set<Course> courses = this.courseRepository
            .findByTaughtYearAndStartPeriod(taughtYear.shortValue(), startPeriod.shortValue()).stream()
            .map(dbEntity -> CourseConverter.convert(dbEntity)).collect(Collectors.toSet());

    return Response.ok(courses, MediaType.APPLICATION_JSON).build();

}