Example usage for java.lang Integer toBinaryString

List of usage examples for java.lang Integer toBinaryString

Introduction

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

Prototype

public static String toBinaryString(int i) 

Source Link

Document

Returns a string representation of the integer argument as an unsigned integer in base 2.

Usage

From source file:uk.bl.wa.util.Normalisation.java

private static String escapeUTF8(final byte[] utf8, boolean escapeHighOrder, boolean normaliseLowOrder) {
    ByteArrayOutputStream sb = new ByteArrayOutputStream(utf8.length * 2);
    int i = 0;/*from   ww  w.  java 2 s  . c  o m*/
    boolean paramSection = false; // Affects handling of space and plus
    while (i < utf8.length) {
        int c = 0xFF & utf8[i];
        paramSection |= c == '?';
        if (paramSection && c == ' ') { // In parameters, space becomes plus
            sb.write(0xFF & '+');
        } else if (c == '%') {
            int codePoint = Integer.parseInt("" + (char) utf8[i + 1] + (char) utf8[i + 2], 16);
            if (paramSection && codePoint == ' ') { // In parameters, space becomes plus
                sb.write(0xFF & '+');
            } else if (mustEscape(codePoint) || keepEscape(codePoint) || !normaliseLowOrder) { // Pass on unmodified
                hexEscape(codePoint, sb);
            } else { // Normalise to ASCII
                sb.write(0xFF & codePoint);
            }
            i += 2;
        } else if ((0b10000000 & c) == 0) { // ASCII
            if (mustEscape(c)) {
                hexEscape(c, sb);
            } else {
                sb.write(0xFF & c);
            }
        } else if ((0b11000000 & c) == 0b10000000) { // Non-first UTF-8 byte as first byte
            hexEscape(c, sb);
        } else if ((0b11100000 & c) == 0b11000000) { // 2 byte UTF-8
            if (i >= utf8.length - 1 || (0b11000000 & utf8[i + 1]) != 0b10000000) { // No byte or wrong byte follows
                hexEscape(c, sb);
            } else if (escapeHighOrder) {
                hexEscape(0xff & utf8[i++], sb);
                hexEscape(0xff & utf8[i], sb);
            } else {
                sb.write(utf8[i++]);
                sb.write(utf8[i]);
            }
        } else if ((0b11110000 & utf8[i]) == 0b11100000) { // 3 byte UTF-8
            if (i >= utf8.length - 2 || (0b11000000 & utf8[i + 1]) != 0b10000000
                    || (0b11000000 & utf8[i + 2]) != 0b10000000) { // Too few or wrong bytes follows
                hexEscape(c, sb);
            } else {
                hexEscape(0xff & utf8[i++], sb);
                hexEscape(0xff & utf8[i++], sb);
                hexEscape(0xff & utf8[i], sb);
            }
        } else if ((0b11111000 & utf8[i]) == 0b11110000) { // 4 byte UTF-8
            if (i >= utf8.length - 3 || (0b11000000 & utf8[i + 1]) != 0b10000000 || // Too few or wrong bytes follows
                    (0b11000000 & utf8[i + 2]) != 0b10000000 || (0b11000000 & utf8[i + 3]) != 0b10000000) {
                hexEscape(c, sb);
            } else {
                hexEscape(0xff & utf8[i++], sb);
                hexEscape(0xff & utf8[i++], sb);
                hexEscape(0xff & utf8[i++], sb);
                hexEscape(0xff & utf8[i], sb);
            }
        } else { // Illegal first byte for UTF-8
            hexEscape(c, sb);
            log.debug("Sanity check: Unexpected code path encountered.: The input byte-array did not translate"
                    + " to supported UTF-8 with invalid first-byte for UTF-8 codepoint '0b"
                    + Integer.toBinaryString(c) + "'. Writing escape code for byte " + c);
        }
        i++;
    }
    try {
        return sb.toString("utf-8");
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Internal error: UTF-8 must be supported by the JVM", e);
    }
}

From source file:com.dnanexus.DXFileTest.java

@Test
public void testUploadDownloadBinary() throws IOException {
    String uploadData = Integer.toBinaryString(12345678);
    byte[] uploadBytes = uploadData.getBytes();

    DXFile f = DXFile.newFile().setProject(testProject).build();
    f.upload(uploadBytes);/*from w  w w .  ja v  a2s  .c o  m*/
    f.closeAndWait();
    byte[] downloadBytes = f.downloadBytes();

    Assert.assertArrayEquals(uploadBytes, downloadBytes);
}

From source file:org.o3project.optsdn.don.openflow.OpenFlowHandler.java

/**
 * Get binary value of the tsmap in the ODU SIGID.
 * // w  w w . ja v a  2 s . c  o m
 * @param oduSigid ODU SIGID
 * @return Binary Value
 */
private String toTsmapBinary(OduSigid oduSigid) {
    short tsmapNum = oduSigid.getTsmap();
    String binary = Integer.toBinaryString(tsmapNum);
    String spacePadding = String.format("%8s", binary);
    String zeroPadding = spacePadding.replace(" ", "0");
    return zeroPadding;
}

From source file:net.minecraftforge.common.util.EnumHelper.java

@SuppressWarnings({ "unchecked", "serial" })
@Nullable/* w w  w. j a va  2  s  . com*/
private static <T extends Enum<?>> T addEnum(boolean test, final Class<T> enumType, @Nullable String enumName,
        final Class<?>[] paramTypes, @Nullable Object[] paramValues) {
    if (!isSetup) {
        setup();
    }

    Field valuesField = null;
    Field[] fields = enumType.getDeclaredFields();

    for (Field field : fields) {
        String name = field.getName();
        if (name.equals("$VALUES") || name.equals("ENUM$VALUES")) //Added 'ENUM$VALUES' because Eclipse's internal compiler doesn't follow standards
        {
            valuesField = field;
            break;
        }
    }

    int flags = (FMLForgePlugin.RUNTIME_DEOBF ? Modifier.PUBLIC : Modifier.PRIVATE) | Modifier.STATIC
            | Modifier.FINAL | 0x1000 /*SYNTHETIC*/;
    if (valuesField == null) {
        String valueType = String.format("[L%s;", enumType.getName().replace('.', '/'));

        for (Field field : fields) {
            if ((field.getModifiers() & flags) == flags
                    && field.getType().getName().replace('.', '/').equals(valueType)) //Apparently some JVMs return .'s and some don't..
            {
                valuesField = field;
                break;
            }
        }
    }

    if (valuesField == null) {
        final List<String> lines = Lists.newArrayList();
        lines.add(String.format("Could not find $VALUES field for enum: %s", enumType.getName()));
        lines.add(String.format("Runtime Deobf: %s", FMLForgePlugin.RUNTIME_DEOBF));
        lines.add(String.format("Flags: %s",
                String.format("%16s", Integer.toBinaryString(flags)).replace(' ', '0')));
        lines.add("Fields:");
        for (Field field : fields) {
            String mods = String.format("%16s", Integer.toBinaryString(field.getModifiers())).replace(' ', '0');
            lines.add(String.format("       %s %s: %s", mods, field.getName(), field.getType().getName()));
        }

        for (String line : lines)
            FMLLog.log.fatal(line);

        if (test) {
            throw new EnhancedRuntimeException("Could not find $VALUES field for enum: " + enumType.getName()) {
                @Override
                protected void printStackTrace(WrappedPrintStream stream) {
                    for (String line : lines)
                        stream.println(line);
                }
            };
        }
        return null;
    }

    if (test) {
        Object ctr = null;
        Exception ex = null;
        try {
            ctr = getConstructorAccessor(enumType, paramTypes);
        } catch (Exception e) {
            ex = e;
        }
        if (ctr == null || ex != null) {
            throw new EnhancedRuntimeException(
                    String.format("Could not find constructor for Enum %s", enumType.getName()), ex) {
                private String toString(Class<?>[] cls) {
                    StringBuilder b = new StringBuilder();
                    for (int x = 0; x < cls.length; x++) {
                        b.append(cls[x].getName());
                        if (x != cls.length - 1)
                            b.append(", ");
                    }
                    return b.toString();
                }

                @Override
                protected void printStackTrace(WrappedPrintStream stream) {
                    stream.println("Target Arguments:");
                    stream.println("    java.lang.String, int, " + toString(paramTypes));
                    stream.println("Found Constructors:");
                    for (Constructor<?> ctr : enumType.getDeclaredConstructors()) {
                        stream.println("    " + toString(ctr.getParameterTypes()));
                    }
                }
            };
        }
        return null;
    }

    valuesField.setAccessible(true);

    try {
        T[] previousValues = (T[]) valuesField.get(enumType);
        T newValue = makeEnum(enumType, enumName, previousValues.length, paramTypes, paramValues);
        setFailsafeFieldValue(valuesField, null, ArrayUtils.add(previousValues, newValue));
        cleanEnumCache(enumType);

        return newValue;
    } catch (Exception e) {
        FMLLog.log.error("Error adding enum with EnumHelper.", e);
        throw new RuntimeException(e);
    }
}

From source file:pl.dp.bz.poid.fouriertest.FourierProc.java

private Complex[] computeDIFForOneDimension(Complex[] pixelTable) {
    int bits = 9;
    double N = pixelTable.length;

    Complex[] transformedSignal = new Complex[(int) N];

    for (int i = 0; i < transformedSignal.length; i++) {
        transformedSignal[i] = new Complex(0.0, 0.0);
    }/* w w  w .  j  a  v a  2s . c o m*/

    Complex signalTab[] = new Complex[(int) N];
    Complex[] localTR = new Complex[(int) N];
    int index = 0;
    for (int i = 0; i < pixelTable.length; i++) {
        signalTab[index] = new Complex(pixelTable[i].getReal(), pixelTable[i].getImaginary());
        index++;
    }

    index = 0;
    for (Complex cv : signalTab) {
        //            System.out.println("x(" + index + ") = " + cv.getReal() + " IM: i" + cv.getImaginary());
        index++;
    }
    //Zmienna okrelajca na jakiej wielkoci ma operowa na tablicy
    int part = 2;
    //Ptla okrelajca cykl przechodzenia, przez kolejne kolumny 
    for (int iteration = 1; iteration <= bits; iteration++) {
        //            System.out.println("PART "+part);
        //Ile razy ma si wykona
        for (int i = 0; i < part; i += 2) {

            int r = 0;
            for (int actualIndex = (signalTab.length / part) * i, counter = 0; counter < signalTab.length
                    / part; counter++, actualIndex++) {
                int secondIndex = (actualIndex + (signalTab.length / part));
                Complex a = signalTab[actualIndex].add(signalTab[secondIndex]);
                Complex b = signalTab[actualIndex].subtract(signalTab[secondIndex]);
                Complex W = new Complex(Math.cos((2.0 * Math.PI * r) / N), -Math.sin((2.0 * Math.PI * r) / N));
                b = b.multiply(W);
                signalTab[actualIndex] = a;
                signalTab[secondIndex] = b;
                r += part - (part / 2);
            }
        }
        part += part;
    }

    localTR[0] = signalTab[0];
    localTR[localTR.length - 1] = signalTab[signalTab.length - 1];
    for (int i = 1; i < signalTab.length - 1; i++) {
        String bitIndex = Integer.toBinaryString(i);
        if (bitIndex.length() < bits) {
            while (bitIndex.length() < bits) {
                bitIndex = "0" + bitIndex;
            }
        }
        char[] tab = bitIndex.toCharArray();

        for (int j = 0; j < tab.length / 2; j++) {
            char temp = tab[j];
            tab[j] = tab[tab.length - j - 1];
            tab[tab.length - j - 1] = temp;
        }
        bitIndex = new String(tab);
        localTR[Integer.parseInt(bitIndex, 2)] = signalTab[i];
    }
    for (int i = 0; i < localTR.length; i++) {
        transformedSignal[i] = new Complex(localTR[i].getReal(), localTR[i].getImaginary());
    }
    return transformedSignal;
}

From source file:com.xclong.vehiclemonitordemo.service.CommunicationService.java

private void dealWithCMD17() {
    //        value = Integer.valueOf(recStr.substring(14, 18), 2).toString();
    value1 = Integer.toBinaryString(Integer.parseInt(recStr.substring(14, 15), 16));
    value2 = Integer.toBinaryString(Integer.parseInt(recStr.substring(15, 16), 16));
    value3 = Integer.toBinaryString(Integer.parseInt(recStr.substring(16, 17), 16));
    value4 = Integer.toBinaryString(Integer.parseInt(recStr.substring(17, 18), 16));

    switch (value1.length()) {
    case 1:/*  ww w.j  a v a  2  s.  co m*/
        value1 = "000" + value1;
        break;
    case 2:
        value1 = "00" + value1;
        break;
    case 3:
        value1 = "0" + value1;
        break;
    default:
        break;
    }

    switch (value2.length()) {
    case 1:
        value2 = "000" + value2;
        break;
    case 2:
        value2 = "00" + value2;
        break;
    case 3:
        value2 = "0" + value2;
        break;
    default:
        break;
    }

    switch (value3.length()) {
    case 1:
        value3 = "000" + value3;
        break;
    case 2:
        value3 = "00" + value3;
        break;
    case 3:
        value3 = "0" + value3;
        break;
    default:
        break;
    }

    /*switch (value4.length()) {
    case 1:
        value4 = "000" + value4;
        break;
    case 2:
        value4 = "00" + value4;
        break;
    case 3:
        value4 = "0" + value4;
        break;
    default:
        break;
    }*/

    power = (value1.substring(0, 1).equals("0") ? "" : "");
    abnormals[0] = power.equals("") ? 0 : 1;
    twoway_value_failure = (value1.substring(1, 2).equals("0") ? "" : "");
    abnormals[1] = twoway_value_failure.equals("") ? 0 : 1;
    metering_pump_failure = (value1.substring(2, 3).equals("0") ? "" : "");
    abnormals[2] = metering_pump_failure.equals("") ? 0 : 1;
    nozzle_block_failure = (value1.substring(3, 4).equals("0") ? "" : "");
    abnormals[3] = nozzle_block_failure.equals("") ? 0 : 1;

    LQ8486_failure = (value2.substring(0, 1).equals("0") ? "" : "");
    abnormals[4] = LQ8486_failure.equals("") ? 0 : 1;
    NOx_overproof_failure = (value2.substring(1, 2).equals("0") ? "" : "");
    abnormals[5] = NOx_overproof_failure.equals("") ? 0 : 1;
    NOx_sensor_failure = (value2.substring(2, 3).equals("0") ? "" : "");
    abnormals[6] = NOx_sensor_failure.equals("") ? 0 : 1;
    urea_level_failure = (value2.substring(3, 4).equals("0") ? "" : "");
    abnormals[7] = urea_level_failure.equals("") ? 0 : 1;

    urea_quality_failure = (value3.substring(0, 1).equals("0") ? "" : "");
    abnormals[8] = urea_quality_failure.equals("") ? 0 : 1;
    SCR_failure = (value3.substring(1, 2).equals("0") ? "" : "");
    abnormals[9] = SCR_failure.equals("") ? 0 : 1;
    dePM_catalyzer_failure = (value3.substring(2, 3).equals("0") ? "" : "");
    abnormals[10] = dePM_catalyzer_failure.equals("") ? 0 : 1;

    vehicledInfo.setPower(power);
    vehicledInfo.setTwoway_value_failure(twoway_value_failure);
    vehicledInfo.setMetering_pump_failure(metering_pump_failure);
    vehicledInfo.setNozzle_block_failure(nozzle_block_failure);
    vehicledInfo.setLQ8486_failure(LQ8486_failure);
    vehicledInfo.setNOx_overproof_failure(NOx_overproof_failure);
    vehicledInfo.setNOx_sensor_failure(NOx_sensor_failure);
    vehicledInfo.setUrea_level_failure(urea_level_failure);
    vehicledInfo.setUrea_quality_failure(urea_quality_failure);
    vehicledInfo.setSCR_failure(SCR_failure);
    vehicledInfo.setDePM_catalyzer_failure(dePM_catalyzer_failure);

    if (power == "" || twoway_value_failure == "" || metering_pump_failure == ""
            || nozzle_block_failure == "" || LQ8486_failure == ""
            || NOx_overproof_failure == "" || NOx_sensor_failure == ""
            || urea_level_failure == "" || urea_quality_failure == "" || SCR_failure == ""
            || dePM_catalyzer_failure == "") {
        vehicledInfo.setStatus("1");
    } else
        vehicledInfo.setStatus("2");
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfDocumentWriter.java

/**
 * Extracts the Page Layout and page mode settings for this PDF (ViewerPreferences). All preferences are defined as
 * properties which have to be set before the target is opened.
 *
 * @return the ViewerPreferences.//ww w .jav a2  s . c om
 */
private int getViewerPreferences() {
    final String pageLayout = config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.PageLayout");
    final String pageMode = config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.PageMode");
    final String fullScreenMode = config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.FullScreenMode");
    final boolean hideToolBar = "true".equals(config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.HideToolBar"));
    final boolean hideMenuBar = "true".equals(config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.HideMenuBar"));
    final boolean hideWindowUI = "true".equals(config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.HideWindowUI"));
    final boolean fitWindow = "true".equals(config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.FitWindow"));
    final boolean centerWindow = "true".equals(config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.CenterWindow"));
    final boolean displayDocTitle = "true".equals(config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.DisplayDocTitle"));
    final boolean printScalingNone = "true".equals(config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.PrintScalingNone"));
    final String direction = config.getConfigProperty(
            "org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.Direction");

    int viewerPreferences = 0;
    if ("PageLayoutOneColumn".equals(pageLayout)) {
        viewerPreferences = PdfWriter.PageLayoutOneColumn;
    } else if ("PageLayoutSinglePage".equals(pageLayout)) {
        viewerPreferences = PdfWriter.PageLayoutSinglePage;
    } else if ("PageLayoutTwoColumnLeft".equals(pageLayout)) {
        viewerPreferences = PdfWriter.PageLayoutTwoColumnLeft;
    } else if ("PageLayoutTwoColumnRight".equals(pageLayout)) {
        viewerPreferences = PdfWriter.PageLayoutTwoColumnRight;
    } else if ("PageLayoutTwoPageLeft".equals(pageLayout)) {
        viewerPreferences = PdfWriter.PageLayoutTwoPageLeft;
    } else if ("PageLayoutTwoPageRight".equals(pageLayout)) {
        viewerPreferences = PdfWriter.PageLayoutTwoPageRight;
    }

    if ("PageModeUseNone".equals(pageMode)) {
        viewerPreferences |= PdfWriter.PageModeUseNone;
    } else if ("PageModeUseOutlines".equals(pageMode)) {
        viewerPreferences |= PdfWriter.PageModeUseOutlines;
    } else if ("PageModeUseThumbs".equals(pageMode)) {
        viewerPreferences |= PdfWriter.PageModeUseThumbs;
    } else if ("PageModeFullScreen".equals(pageMode)) {
        viewerPreferences |= PdfWriter.PageModeFullScreen;
        if ("NonFullScreenPageModeUseNone".equals(fullScreenMode)) {
            viewerPreferences = PdfWriter.NonFullScreenPageModeUseNone;
        } else if ("NonFullScreenPageModeUseOC".equals(fullScreenMode)) {
            viewerPreferences |= PdfWriter.NonFullScreenPageModeUseOC;
        } else if ("NonFullScreenPageModeUseOutlines".equals(fullScreenMode)) {
            viewerPreferences |= PdfWriter.NonFullScreenPageModeUseOutlines;
        } else if ("NonFullScreenPageModeUseThumbs".equals(fullScreenMode)) {
            viewerPreferences |= PdfWriter.NonFullScreenPageModeUseThumbs;
        }
    } else if ("PageModeUseOC".equals(pageMode)) {
        viewerPreferences |= PdfWriter.PageModeUseOC;
    } else if ("PageModeUseAttachments".equals(pageMode)) {
        viewerPreferences |= PdfWriter.PageModeUseAttachments;
    }

    if (hideToolBar) {
        viewerPreferences |= PdfWriter.HideToolbar;
    }

    if (hideMenuBar) {
        viewerPreferences |= PdfWriter.HideMenubar;
    }

    if (hideWindowUI) {
        viewerPreferences |= PdfWriter.HideWindowUI;
    }

    if (fitWindow) {
        viewerPreferences |= PdfWriter.FitWindow;
    }
    if (centerWindow) {
        viewerPreferences |= PdfWriter.CenterWindow;
    }
    if (displayDocTitle) {
        viewerPreferences |= PdfWriter.DisplayDocTitle;
    }
    if (printScalingNone) {
        viewerPreferences |= PdfWriter.PrintScalingNone;
    }

    if ("DirectionL2R".equals(direction)) {
        viewerPreferences |= PdfWriter.DirectionL2R;
    } else if ("DirectionR2L".equals(direction)) {
        viewerPreferences |= PdfWriter.DirectionR2L;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("viewerPreferences = 0b" + Integer.toBinaryString(viewerPreferences));
    }
    return viewerPreferences;
}

From source file:com.fengduo.bee.commons.util.StringFormatter.java

private static boolean isMatch(char charAt) {
    String binaryString = Integer.toBinaryString(charAt);
    if (binaryString.length() > 8) {
        return false;
    } else {//from  w  w  w .ja  v a2s  .c  o  m
        return !ArrayUtils.contains(array, charAt);
    }
}

From source file:org.kuali.student.r2.common.validator.DefaultValidatorImpl.java

public void validateField(List<ValidationResultInfo> results, FieldDefinition field,
        ObjectStructureHierarchy objStruct, ConstraintDataProvider dataProvider, Stack<String> elementStack,
        Object rootData, ObjectStructureDefinition rootObjectStructure, ContextInfo contextInfo) {

    Object value = dataProvider.getValue(field.getName());

    // Handle null values in field
    if (value == null || "".equals(value.toString().trim())) {
        processConstraint(results, field, objStruct, value, dataProvider, elementStack, rootData,
                rootObjectStructure, contextInfo);
        return; // no need to do further processing
    }//w  ww.ja  va2s  .c o  m

    /*
     * For complex object structures only the following constraints apply 1. TypeStateCase 2. MinOccurs 3. MaxOccurs
     */
    if (DataType.COMPLEX.equals(field.getDataType())) {
        ObjectStructureHierarchy nestedObjStruct = new ObjectStructureHierarchy();
        nestedObjStruct.setParentObjectStructureHierarchy(objStruct);

        if (null != field.getDataObjectStructure()) {
            nestedObjStruct.setObjectStructure(field.getDataObjectStructure());
        }

        elementStack.push(field.getName());
        // beanPathStack.push(field.isDynamic()?"attributes("+field.getName()+")":field.getName());

        if (value instanceof Collection) {

            String xPathForCollection = getElementXpath(elementStack) + "/*";

            int i = 0;
            for (Object o : (Collection<?>) value) {
                elementStack.push(Integer.toString(i));
                // beanPathStack.push(!beanPathStack.isEmpty()?beanPathStack.pop():""+"["+i+"]");
                processNestedObjectStructure(results, o, nestedObjStruct, field, elementStack, rootData,
                        rootObjectStructure, dataProvider, contextInfo);
                // beanPathStack.pop();
                // beanPathStack.push(field.isDynamic()?"attributes("+field.getName()+")":field.getName());
                elementStack.pop();
                i++;
            }
            if (field.getMinOccurs() != null && field.getMinOccurs() > ((Collection<?>) value).size()) {
                ValidationResultInfo valRes = new ValidationResultInfo(xPathForCollection, value);
                valRes.setError(MessageUtils.interpolate(getMessage("validation.minOccurs", contextInfo),
                        toMap(field)));
                results.add(valRes);
            }

            Integer maxOccurs = tryParse(field.getMaxOccurs());
            if (maxOccurs != null && maxOccurs < ((Collection<?>) value).size()) {
                ValidationResultInfo valRes = new ValidationResultInfo(xPathForCollection, value);
                valRes.setError(MessageUtils.interpolate(getMessage("validation.maxOccurs", contextInfo),
                        toMap(field)));
                results.add(valRes);
            }
        } else {
            if (null != value) {
                processNestedObjectStructure(results, value, nestedObjStruct, field, elementStack, rootData,
                        rootObjectStructure, dataProvider, contextInfo);
            } else {
                if (field.getMinOccurs() != null && field.getMinOccurs() > 0) {
                    ValidationResultInfo val = new ValidationResultInfo(getElementXpath(elementStack), value);
                    if (field.getLabelKey() != null) {
                        val.setError(getMessage(field.getLabelKey(), contextInfo));
                    } else {
                        val.setError(getMessage("validation.required", contextInfo));
                    }
                    results.add(val);
                }
            }
        }

        // beanPathStack.pop();
        elementStack.pop();

    } else { // If non complex data type

        if (value instanceof Collection) {

            if (((Collection<?>) value).isEmpty()) {
                processConstraint(results, field, objStruct, "", dataProvider, elementStack, rootData,
                        rootObjectStructure, contextInfo);
            }

            int i = 0;
            for (Object o : (Collection<?>) value) {
                // This is tricky, change the field name to the index in the elementStack(this is for lists of non
                // complex types)
                elementStack.push(field.getName());
                FieldDefinition tempField = new FieldDefinition();
                BeanUtils.copyProperties(field, tempField);
                tempField.setName(Integer.toBinaryString(i));
                processConstraint(results, tempField, objStruct, o, dataProvider, elementStack, rootData,
                        rootObjectStructure, contextInfo);
                elementStack.pop();
                i++;
            }

            String xPath = getElementXpath(elementStack) + "/" + field.getName() + "/*";
            if (field.getMinOccurs() != null && field.getMinOccurs() > ((Collection<?>) value).size()) {
                ValidationResultInfo valRes = new ValidationResultInfo(xPath, value);
                valRes.setError(MessageUtils.interpolate(getMessage("validation.minOccurs", contextInfo),
                        toMap(field)));
                results.add(valRes);
            }

            Integer maxOccurs = tryParse(field.getMaxOccurs());
            if (maxOccurs != null && maxOccurs < ((Collection<?>) value).size()) {
                ValidationResultInfo valRes = new ValidationResultInfo(xPath, value);
                valRes.setError(MessageUtils.interpolate(getMessage("validation.maxOccurs", contextInfo),
                        toMap(field)));
                results.add(valRes);
            }
        } else {
            processConstraint(results, field, objStruct, value, dataProvider, elementStack, rootData,
                    rootObjectStructure, contextInfo);
        }

    }
}

From source file:com.datatorrent.stram.plan.physical.PhysicalPlanTest.java

@Test
public void testDefaultPartitioning() {
    LogicalPlan dag = new LogicalPlan();
    dag.setAttribute(OperatorContext.STORAGE_AGENT, new StramTestSupport.MemoryStorageAgent());

    GenericTestOperator node1 = dag.addOperator("node1", GenericTestOperator.class);
    GenericTestOperator node2 = dag.addOperator("node2", GenericTestOperator.class);
    dag.addStream("node1.outport1", node1.outport1, node2.inport2, node2.inport1);

    int initialPartitionCount = 5;
    OperatorMeta node2Decl = dag.getMeta(node2);
    node2Decl.getAttributes().put(OperatorContext.PARTITIONER,
            new StatelessPartitioner<GenericTestOperator>(initialPartitionCount));

    PhysicalPlan plan = new PhysicalPlan(dag, new TestPlanContext());

    List<PTOperator> n2Instances = plan.getOperators(node2Decl);
    Assert.assertEquals("partition instances " + n2Instances, initialPartitionCount, n2Instances.size());

    List<Integer> assignedPartitionKeys = Lists.newArrayList();

    for (int i = 0; i < n2Instances.size(); i++) {
        PTOperator n2Partition = n2Instances.get(i);
        Assert.assertNotNull("partition keys null: " + n2Partition, n2Partition.getPartitionKeys());
        Map<InputPort<?>, PartitionKeys> pkeys = n2Partition.getPartitionKeys();
        Assert.assertEquals("partition keys size: " + pkeys, 1, pkeys.size()); // one port partitioned
        InputPort<?> expectedPort = node2.inport2;
        Assert.assertEquals("partition port: " + pkeys, expectedPort, pkeys.keySet().iterator().next());

        Assert.assertEquals("partition mask: " + pkeys, "111",
                Integer.toBinaryString(pkeys.get(expectedPort).mask));
        Set<Integer> pks = pkeys.get(expectedPort).partitions;
        Assert.assertTrue("number partition keys: " + pkeys, pks.size() == 1 || pks.size() == 2);
        assignedPartitionKeys.addAll(pks);
    }/*  w w w .jav a 2  s .  co m*/

    int expectedMask = Integer.parseInt("111", 2);
    Assert.assertEquals("assigned partitions ", expectedMask + 1, assignedPartitionKeys.size());
    for (int i = 0; i <= expectedMask; i++) {
        Assert.assertTrue("" + assignedPartitionKeys, assignedPartitionKeys.contains(i));
    }

}