Example usage for java.lang Integer decode

List of usage examples for java.lang Integer decode

Introduction

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

Prototype

public static Integer decode(String nm) throws NumberFormatException 

Source Link

Document

Decodes a String into an Integer .

Usage

From source file:org.kchine.r.server.http.RHttpProxy.java

public static RServices getR(final String url, final String sessionId, final boolean handleCallbacks,
        final int maxNbrRactionsOnPop) {
    final HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    if (System.getProperty("proxy_host") != null && !System.getProperty("proxy_host").equals("")) {
        httpClient.getHostConfiguration().setProxy(System.getProperty("proxy_host"),
                Integer.decode(System.getProperty("proxy_port")));
    }/*  w  ww . j  av a2 s .c o m*/
    final Object proxy = Proxy.newProxyInstance(RHttpProxy.class.getClassLoader(), new Class<?>[] {
            RServices.class, ScilabServices.class, OpenOfficeServices.class, HttpMarker.class },
            new InvocationHandler() {

                Vector<RCallBack> rCallbacks = new Vector<RCallBack>();
                Vector<RCollaborationListener> rCollaborationListeners = new Vector<RCollaborationListener>();
                Vector<RConsoleActionListener> rConsoleActionListeners = new Vector<RConsoleActionListener>();

                GenericCallbackDevice genericCallBackDevice = null;
                Thread popThread = null;

                boolean _stopThreads = false;
                {
                    if (handleCallbacks) {

                        try {
                            genericCallBackDevice = newGenericCallbackDevice(url, sessionId);
                            popThread = new Thread(new Runnable() {
                                public void run() {
                                    while (true && !_stopThreads) {
                                        popActions();

                                        try {
                                            Thread.sleep(10);
                                        } catch (Exception e) {
                                        }
                                    }

                                }
                            });
                            popThread.start();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                private synchronized void popActions() {
                    try {

                        Vector<RAction> ractions = genericCallBackDevice.popRActions(maxNbrRactionsOnPop);
                        if (ractions != null) {

                            for (int i = 0; i < ractions.size(); ++i) {
                                final RAction action = ractions.elementAt(i);
                                if (action.getActionName().equals("notify")) {
                                    HashMap<String, String> parameters = (HashMap<String, String>) action
                                            .getAttributes().get("parameters");
                                    for (int j = 0; j < rCallbacks.size(); ++j) {
                                        rCallbacks.elementAt(j).notify(parameters);
                                    }
                                }
                                if (action.getActionName().equals("rConsoleActionPerformed")) {
                                    RConsoleAction consoleAction = (RConsoleAction) action.getAttributes()
                                            .get("consoleAction");
                                    for (int j = 0; j < rConsoleActionListeners.size(); ++j) {
                                        rConsoleActionListeners.elementAt(j)
                                                .rConsoleActionPerformed(consoleAction);
                                    }
                                } else if (action.getActionName().equals("chat")) {
                                    String sourceUID = (String) action.getAttributes().get("sourceUID");
                                    String user = (String) action.getAttributes().get("user");
                                    String message = (String) action.getAttributes().get("message");
                                    for (int j = 0; j < rCollaborationListeners.size(); ++j) {
                                        rCollaborationListeners.elementAt(j).chat(sourceUID, user, message);
                                    }
                                } else if (action.getActionName().equals("consolePrint")) {
                                    String sourceUID = (String) action.getAttributes().get("sourceUID");
                                    String user = (String) action.getAttributes().get("user");
                                    String expression = (String) action.getAttributes().get("expression");
                                    String result = (String) action.getAttributes().get("result");
                                    for (int j = 0; j < rCollaborationListeners.size(); ++j) {
                                        rCollaborationListeners.elementAt(j).consolePrint(sourceUID, user,
                                                expression, result);
                                    }
                                }
                            }

                        }

                    } catch (NotLoggedInException nle) {

                        nle.printStackTrace();
                    } catch (Exception e) {

                        e.printStackTrace();
                    }

                }

                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Object result = null;
                    if (method.getName().equals("newDevice")) {
                        result = newDevice(url, sessionId, (Integer) args[0], (Integer) args[1], false);
                    } else if (method.getName().equals("newBroadcastedDevice")) {
                        result = newDevice(url, sessionId, (Integer) args[0], (Integer) args[1], true);
                    } else if (method.getName().equals("listDevices")) {
                        result = listDevices(url, sessionId);
                    } else if (method.getName().equals("addRCallback")) {
                        rCallbacks.add((RCallBack) args[0]);
                    } else if (method.getName().equals("removeRCallback")) {
                        rCallbacks.remove((RCallBack) args[0]);
                    } else if (method.getName().equals("removeAllRCallbacks")) {
                        rCallbacks.removeAllElements();
                    }

            else if (method.getName().equals("addRCollaborationListener")) {
                        rCollaborationListeners.add((RCollaborationListener) args[0]);
                    } else if (method.getName().equals("removeRCollaborationListener")) {
                        rCollaborationListeners.remove((RCollaborationListener) args[0]);
                    } else if (method.getName().equals("removeAllRCollaborationListeners")) {
                        rCollaborationListeners.removeAllElements();
                    }

            else if (method.getName().equals("addRConsoleActionListener")) {
                        rConsoleActionListeners.add((RConsoleActionListener) args[0]);
                    } else if (method.getName().equals("removeRConsoleActionListener")) {
                        rConsoleActionListeners.remove((RConsoleActionListener) args[0]);
                    } else if (method.getName().equals("removeAllRConsoleActionListeners")) {
                        rConsoleActionListeners.removeAllElements();
                    }

            else if (method.getName().equals("newSpreadsheetTableModelRemote")) {
                        SpreadsheetModelDevice d = newSpreadsheetModelDevice(url, sessionId, "",
                                ((Integer) args[0]).toString(), ((Integer) args[1]).toString());
                        result = new SpreadsheetModelRemoteProxy(d);
                    } else if (method.getName().equals("getSpreadsheetTableModelRemote")) {
                        SpreadsheetModelDevice d = newSpreadsheetModelDevice(url, sessionId, (String) args[0],
                                "", "");
                        result = new SpreadsheetModelRemoteProxy(d);
                    }

            else if (method.getName().equals("stopThreads")) {
                        _stopThreads = true;
                        popThread.join();
                        try {
                            // IMPORTANT !!!!!!!!!!!!!!!!!!!!!!!!!!!!
                            // genericCallBackDevice.dispose();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (method.getName().equals("popActions")) {
                        popActions();
                    }

            else {

                        result = RHttpProxy.invoke(url, sessionId, "R", method.getName(),
                                method.getParameterTypes(), args, httpClient);
                    }

                    if (method.getName().equals("asynchronousConsoleSubmit")) {
                        popActions();
                    }

                    return result;

                }
            });

    return (RServices) proxy;
}

From source file:org.apache.catalina.core.NamingContextListener.java

/**
 * Set the specified environment entries in the naming context.
 *///from   w  ww.j av a2 s . com
public void addEnvironment(ContextEnvironment env) {

    Object value = null;
    // Instantiating a new instance of the correct object type, and
    // initializing it.
    String type = env.getType();
    try {
        if (type.equals("java.lang.String")) {
            value = env.getValue();
        } else if (type.equals("java.lang.Byte")) {
            if (env.getValue() == null) {
                value = new Byte((byte) 0);
            } else {
                value = Byte.decode(env.getValue());
            }
        } else if (type.equals("java.lang.Short")) {
            if (env.getValue() == null) {
                value = new Short((short) 0);
            } else {
                value = Short.decode(env.getValue());
            }
        } else if (type.equals("java.lang.Integer")) {
            if (env.getValue() == null) {
                value = new Integer(0);
            } else {
                value = Integer.decode(env.getValue());
            }
        } else if (type.equals("java.lang.Long")) {
            if (env.getValue() == null) {
                value = new Long(0);
            } else {
                value = Long.decode(env.getValue());
            }
        } else if (type.equals("java.lang.Boolean")) {
            value = Boolean.valueOf(env.getValue());
        } else if (type.equals("java.lang.Double")) {
            if (env.getValue() == null) {
                value = new Double(0);
            } else {
                value = Double.valueOf(env.getValue());
            }
        } else if (type.equals("java.lang.Float")) {
            if (env.getValue() == null) {
                value = new Float(0);
            } else {
                value = Float.valueOf(env.getValue());
            }
        } else if (type.equals("java.lang.Character")) {
            if (env.getValue() == null) {
                value = new Character((char) 0);
            } else {
                if (env.getValue().length() == 1) {
                    value = new Character(env.getValue().charAt(0));
                } else {
                    throw new IllegalArgumentException();
                }
            }
        } else {
            log(sm.getString("naming.invalidEnvEntryType", env.getName()));
        }
    } catch (NumberFormatException e) {
        log(sm.getString("naming.invalidEnvEntryValue", env.getName()));
    } catch (IllegalArgumentException e) {
        log(sm.getString("naming.invalidEnvEntryValue", env.getName()));
    }

    // Binding the object to the appropriate name
    if (value != null) {
        try {
            if (debug >= 2)
                log("  Adding environment entry " + env.getName());
            createSubcontexts(envCtx, env.getName());
            envCtx.bind(env.getName(), value);
        } catch (NamingException e) {
            log(sm.getString("naming.invalidEnvEntryValue", e));
        }
    }

}

From source file:com.taobao.android.tpatch.utils.SmaliUtils.java

/**
 * dex?smali/*from  www  . jav a  2  s. c  o  m*/
 * @param dex
 * @param outputDir
 * @param includeClasses ??
 */
public static boolean disassembleDexFile(File dex, File outputDir, final Set<String> includeClasses)
        throws IOException {
    final baksmaliOptions options = createBaksmaliOptions();
    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }
    DexFile dexFile = DexFileFactory.loadDexFile(dex, DEFAULT_API_LEVEL, true);
    options.outputDirectory = outputDir.getAbsolutePath();
    //1. 
    options.jobs = 3;
    if (options.registerInfo != 0 || options.deodex) {
        try {
            Iterable<String> extraClassPathEntries;
            if (options.extraClassPathEntries != null) {
                extraClassPathEntries = options.extraClassPathEntries;
            } else {
                extraClassPathEntries = ImmutableList.of();
            }

            options.classPath = ClassPath.fromClassPath(options.bootClassPathDirs,
                    Iterables.concat(options.bootClassPathEntries, extraClassPathEntries), dexFile,
                    options.apiLevel, options.checkPackagePrivateAccess, options.experimental);

            if (options.customInlineDefinitions != null) {
                options.inlineResolver = new CustomInlineMethodResolver(options.classPath,
                        options.customInlineDefinitions);
            }
        } catch (Exception ex) {
            System.err.println("\n\nError occurred while loading boot class path files. Aborting.");
            ex.printStackTrace(System.err);
            return false;
        }
    }

    if (options.resourceIdFileEntries != null) {
        class PublicHandler extends DefaultHandler {

            String prefix = null;

            public PublicHandler(String prefix) {
                super();
                this.prefix = prefix;
            }

            public void startElement(String uri, String localName, String qName, Attributes attr)
                    throws SAXException {
                if (qName.equals("public")) {
                    String type = attr.getValue("type");
                    String name = attr.getValue("name").replace('.', '_');
                    Integer public_key = Integer.decode(attr.getValue("id"));
                    String public_val = new StringBuffer().append(prefix).append(".").append(type).append(".")
                            .append(name).toString();
                    options.resourceIds.put(public_key, public_val);
                }
            }
        }
        ;

        for (Map.Entry<String, String> entry : options.resourceIdFileEntries.entrySet()) {
            try {
                SAXParser saxp = SAXParserFactory.newInstance().newSAXParser();
                String prefix = entry.getValue();
                saxp.parse(entry.getKey(), new PublicHandler(prefix));
            } catch (ParserConfigurationException e) {
                continue;
            } catch (SAXException e) {
                continue;
            } catch (IOException e) {
                continue;
            }
        }
    }

    File outputDirectoryFile = new File(options.outputDirectory);
    if (!outputDirectoryFile.exists()) {
        if (!outputDirectoryFile.mkdirs()) {
            System.err.println("Can't create the output directory " + options.outputDirectory);
            return false;
        }
    }

    // sort the classes, so that if we're on a case-insensitive file system and need to handle classes with file
    // name collisions, then we'll use the same name for each class, if the dex file goes through multiple
    // baksmali/smali cycles for some reason. If a class with a colliding name is added or removed, the filenames
    // may still change of course
    List<? extends ClassDef> classDefs = Ordering.natural().sortedCopy(dexFile.getClasses());

    if (!options.noAccessorComments) {
        options.syntheticAccessorResolver = new SyntheticAccessorResolver(classDefs);
    }

    final ClassFileNameHandler fileNameHandler = new ClassFileNameHandler(outputDirectoryFile, ".smali");

    ExecutorService executor = Executors.newFixedThreadPool(options.jobs);
    List<Future<Boolean>> tasks = Lists.newArrayList();

    for (final ClassDef classDef : classDefs) {
        tasks.add(executor.submit(new Callable<Boolean>() {

            @Override
            public Boolean call() throws Exception {
                String className = getDalvikClassName(classDef.getType());
                if (null != includeClasses) {
                    if (includeClasses.contains(className)) {
                        BakSmali.disassembleClass(classDef, fileNameHandler, options);
                    }
                    return true;
                } else {
                    return BakSmali.disassembleClass(classDef, fileNameHandler, options);
                }
            }
        }));
    }

    boolean errorOccurred = false;
    try {
        for (Future<Boolean> task : tasks) {
            while (true) {
                try {
                    if (!task.get()) {
                        errorOccurred = true;
                    }
                } catch (InterruptedException ex) {
                    continue;
                } catch (ExecutionException ex) {
                    throw new RuntimeException(ex);
                }
                break;
            }
        }
    } finally {
        executor.shutdown();
    }
    return !errorOccurred;
}

From source file:org.jahia.configuration.configurators.PropertiesManager.java

private String unescapeNonASCII(String input) {
    if (input == null || input.length() == 0 || input.trim().length() == 0) {
        return input;
    }//from   w  ww.j  a  v a 2  s  . c  o  m
    StringBuilder output = new StringBuilder();
    boolean processingSlash = false;
    boolean processingUnicode = false;
    StringBuilder unicodeCharacters = new StringBuilder(4);
    for (int i = 0; i < input.length(); i++) {
        char ch = input.charAt(i);
        if (processingUnicode) {
            unicodeCharacters.append(ch);
            if (unicodeCharacters.length() == 4) {
                try {
                    int value = Integer.decode("0x" + unicodeCharacters.toString());
                    output.append((char) value);
                    unicodeCharacters = new StringBuilder(4);
                    processingUnicode = false;
                    processingSlash = false;
                } catch (NumberFormatException nfe) {
                    throw new IllegalArgumentException(
                            "Invalid unicode : " + unicodeCharacters + " in string : " + input, nfe);
                }
            }
            continue;
        }

        if (processingSlash) {
            // handle an escaped value
            processingSlash = false;
            switch (ch) {
            case '\\':
                output.append('\\');
                break;
            case '\'':
                output.append('\'');
                break;
            case '\"':
                output.append('"');
                break;
            case 'r':
                output.append('\r');
                break;
            case 'f':
                output.append('\f');
                break;
            case 't':
                output.append('\t');
                break;
            case 'n':
                output.append('\n');
                break;
            case 'b':
                output.append('\b');
                break;
            case 'u':
                processingUnicode = true;
                break;
            default:
                output.append(ch);
                break;
            }
        } else if (ch == '\\') {
            processingSlash = true;
        } else {
            output.append(ch);
        }
    }

    if (processingSlash) {
        // then we're in the weird case of a \ at the end of the
        // string, let's output it anyway.
        output.append('\\');
    }

    return output.toString();
}

From source file:org.kuali.coeus.s2sgen.impl.print.FormPrintServiceImpl.java

protected boolean isPdfType(byte[] data) {
    final int ATTRIBUTE_CHUNK_SIZE = 1200;// increased for ppt
    final String PRE_HEXA = "0x";

    boolean retValue = false;
    String str[] = { "25", "50", "44", "46" };
    byte byteCheckArr[] = new byte[4];
    byte byteDataArr[] = new byte[4];

    for (int byteIndex = 0; byteIndex < byteCheckArr.length; byteIndex++) {
        byteCheckArr[byteIndex] = Integer.decode(PRE_HEXA + str[byteIndex]).byteValue();
    }//  ww  w  .j av a 2  s. co  m

    int startPoint, endPoint;

    startPoint = 0;
    endPoint = (ATTRIBUTE_CHUNK_SIZE > (data.length / 2)) ? data.length / 2 : ATTRIBUTE_CHUNK_SIZE;

    for (int forwardIndex = startPoint; forwardIndex < endPoint - str.length; forwardIndex++) {
        if (forwardIndex == 0) {
            // Fill All Data
            for (int fillIndex = 0; fillIndex < str.length; fillIndex++) {
                byteDataArr[fillIndex] = toUnsignedByte(data[fillIndex]);
            }
        } else {
            // Push Data, Fill last index
            for (int fillIndex = 0; fillIndex < str.length - 1; fillIndex++) {
                byteDataArr[fillIndex] = byteDataArr[fillIndex + 1];
            }
            byteDataArr[str.length - 1] = toUnsignedByte(data[str.length - 1 + forwardIndex]);
        }

        if (new String(byteCheckArr).equals(new String(byteDataArr))) {
            retValue = true;
        }
    }

    return retValue;
}

From source file:org.jbpm.formModeler.components.editor.WysiwygFormEditor.java

protected void groupField(CommandRequest request, final boolean groupIt) throws Exception {
    setLastMovedFieldPosition(Integer.decode(request.getParameter("position")).intValue());
    Form form = getCurrentForm();/* www  .j  av  a  2  s .com*/
    if (form == null) {
        log.error("Cannot modify unexistant form.");
    } else {
        Field fieldToMove = getFieldInPosition(getLastMovedFieldPosition());
        if (fieldToMove != null) {
            fieldToMove.setGroupWithPrevious(Boolean.valueOf(groupIt));
        } else {
            log.error("Cannot modify unexistant field");
        }
    }
}

From source file:tax.MainForm.java

private void afmTextKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_afmTextKeyPressed
    String text = afmText.getText();

    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        if (text.length() == 9) {

            for (Object key : afmToName.keySet()) {
                if (afmToName.get(key).equals(text))
                    nameText.setText(key.toString());
            }//w  w  w  .  ja  v a2  s .  c o  m

            //                Util.fadeInAndOut(afmText, Util.darkGreen);
            addRowBut.doClick();
        } else if (text.length() == 0) {
            Util.fadeInAndOut(afmText, Color.white);
            nameText.setEnabled(true);
            nameText.requestFocus();
        } else
            Util.fadeInAndOut(afmText, Util.darkOrange);
    } else if (!evt.isActionKey() && !evt.isAltDown() && !evt.isControlDown() && !evt.isShiftDown()
            && !evt.isMetaDown() && (evt.getKeyCode() != KeyEvent.VK_BACK_SPACE)
            && (evt.getKeyCode() != KeyEvent.VK_DELETE) && (evt.getKeyCode() != KeyEvent.VK_ESCAPE)) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                String text = afmText.getText();
                int afmLength = text.length();

                while (lastAFMTextLength == afmLength) {
                    try {
                        Thread.sleep(100);
                        System.out.println("text: " + text);
                        System.out.println(lastAFMTextLength + " " + afmLength);
                        return;
                    } catch (InterruptedException ex) {
                        Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    text = afmText.getText();
                    afmLength = text.length();
                }

                try {
                    int num = Integer.decode(text);
                    if (afmLength > 9) {
                        if (text.length() > 0)
                            afmText.setText(text.substring(0, afmLength - 1));
                        else
                            afmText.setText("");
                        return;
                    }
                } catch (Exception e) {
                    if (text.length() > 0)
                        afmText.setText(text.substring(0, afmLength - 1));
                    else
                        afmText.setText("");
                    return;
                }

                lastAFMTextLength = afmLength;
            }
        });
    }
}

From source file:com.bmd.android.collection.SparseArrayTest.java

public void testTranslations() {

    final SparseArray<Integer> array1 = AndroidCollections.iterate(mArray)
            .translateValues(new Translator<String, Integer>() {

                @Override/*from www.  j  a  v a 2  s  .c  o  m*/
                public Integer translate(final String element) {

                    return Integer.decode(element);
                }
            }).toSparseArray();

    assertThat(AndroidCollections.iterate(array1).values()).containsExactly(0, 1, 2, 3, 4);
    assertThat(AndroidCollections.iterate(array1).replaceValues(new Translator<Integer, Integer>() {

        @Override
        public Integer translate(final Integer element) {

            return element + 1;
        }

    }).values()).containsExactly(1, 2, 3, 4, 5);
    assertThat(AndroidCollections.iterate(array1).values()).containsExactly(1, 2, 3, 4, 5);
    assertThat(AndroidCollections.iterate(array1).toImmutableList()).containsExactly(
            SparseEntries.entry(0, Integer.valueOf(1)), SparseEntries.entry(1, Integer.valueOf(2)),
            SparseEntries.entry(2, Integer.valueOf(3)), SparseEntries.entry(3, Integer.valueOf(4)),
            SparseEntries.entry(4, Integer.valueOf(5)));

    final SparseArray<Integer> array2 = AndroidCollections.iterate(mArray).translate(new IntTranslator() {

        @Override
        public int translate(final int value) {

            return value + 1;
        }
    },

            new Translator<String, Integer>() {

                @Override
                public Integer translate(final String element) {

                    return Integer.decode(element);
                }
            }).toSparseArray();
    assertThat(AndroidCollections.iterate(array2).toImmutableList()).containsExactly(
            SparseEntries.entry(1, Integer.valueOf(0)), SparseEntries.entry(2, Integer.valueOf(1)),
            SparseEntries.entry(3, Integer.valueOf(2)), SparseEntries.entry(4, Integer.valueOf(3)),
            SparseEntries.entry(5, Integer.valueOf(4)));
    AndroidCollections.iterate(array1).only().first(3).putInto(array2);
    assertThat(AndroidCollections.iterate(array2).toImmutableList()).containsExactly(
            SparseEntries.entry(0, Integer.valueOf(1)), SparseEntries.entry(1, Integer.valueOf(2)),
            SparseEntries.entry(2, Integer.valueOf(3)), SparseEntries.entry(3, Integer.valueOf(2)),
            SparseEntries.entry(4, Integer.valueOf(3)), SparseEntries.entry(5, Integer.valueOf(4)));
    AndroidCollections.iterate(array1).only().first(3).appendTo(array2);
    assertThat(AndroidCollections.iterate(array2).toImmutableList()).containsExactly(
            SparseEntries.entry(0, Integer.valueOf(1)), SparseEntries.entry(1, Integer.valueOf(2)),
            SparseEntries.entry(2, Integer.valueOf(3)), SparseEntries.entry(3, Integer.valueOf(2)),
            SparseEntries.entry(4, Integer.valueOf(3)), SparseEntries.entry(5, Integer.valueOf(4)));

    AndroidCollections.iterate(array2).only().keys(2, 3).translateValues(new Translator<Integer, String>() {

        @Override
        public String translate(final Integer element) {

            return element.toString();
        }
    }).putInto(mArray);
    assertThat(AndroidCollections.iterate(mArray).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "3"),
            SparseEntries.entry(3, "2"), SparseEntries.entry(4, "4"));
    AndroidCollections.iterate(array2).only().keys(2, 3).translateValues(new Translator<Integer, String>() {

        @Override
        public String translate(final Integer element) {

            return element.toString();
        }
    }).appendTo(mArray);
    assertThat(AndroidCollections.iterate(mArray).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "3"),
            SparseEntries.entry(3, "2"), SparseEntries.entry(4, "4"));
    AndroidCollections.iterate(array2).only().last(1).translate(new IntTranslator() {

        @Override
        public int translate(final int value) {

            return value - 2;
        }

    }, new Translator<Integer, String>() {

        @Override
        public String translate(final Integer element) {

            return element.toString();
        }

    }).putInto(mArray);
    assertThat(AndroidCollections.iterate(mArray).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "3"),
            SparseEntries.entry(3, "4"), SparseEntries.entry(4, "4"));
    AndroidCollections.iterate(array2).only().last(1).translate(new IntTranslator() {

        @Override
        public int translate(final int value) {

            return value - 2;
        }

    }, new Translator<Integer, String>() {

        @Override
        public String translate(final Integer element) {

            return element.toString();
        }

    }).appendTo(mArray);
    assertThat(AndroidCollections.iterate(mArray).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "3"),
            SparseEntries.entry(3, "4"), SparseEntries.entry(4, "4"));

    final SparseArray<String> array3 = AndroidCollections.iterate(mArray).toSparseArray();
    assertThat(AndroidCollections.iterate(array3).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "3"),
            SparseEntries.entry(3, "4"), SparseEntries.entry(4, "4"));

    AndroidCollections.iterate(array3).but().last(1).translateKeys(new IntTranslator() {

        @Override
        public int translate(final int value) {

            return value + 2;
        }

    }).appendTo(mArray);
    assertThat(AndroidCollections.iterate(mArray).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "0"),
            SparseEntries.entry(3, "1"), SparseEntries.entry(4, "3"), SparseEntries.entry(5, "4"));
    AndroidCollections.iterate(array3).but().last(1).translateKeys(new IntTranslator() {

        @Override
        public int translate(final int value) {

            return value + 2;
        }

    }).putInto(mArray);
    assertThat(AndroidCollections.iterate(mArray).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "0"),
            SparseEntries.entry(3, "1"), SparseEntries.entry(4, "3"), SparseEntries.entry(5, "4"));
}

From source file:com.bmd.android.collection.SparseArrayCompatTest.java

public void testTranslations() {

    final SparseArrayCompat<Integer> arrayCompat1 = AndroidCollections.iterate(mArray)
            .translateValues(new Translator<String, Integer>() {

                @Override/*w ww.j  a  v a  2  s  . c o  m*/
                public Integer translate(final String element) {

                    return Integer.decode(element);
                }
            }).toSparseArray();

    assertThat(AndroidCollections.iterate(arrayCompat1).values()).containsExactly(0, 1, 2, 3, 4);
    assertThat(AndroidCollections.iterate(arrayCompat1).replaceValues(new Translator<Integer, Integer>() {

        @Override
        public Integer translate(final Integer element) {

            return element + 1;
        }

    }).values()).containsExactly(1, 2, 3, 4, 5);
    assertThat(AndroidCollections.iterate(arrayCompat1).values()).containsExactly(1, 2, 3, 4, 5);
    assertThat(AndroidCollections.iterate(arrayCompat1).toImmutableList()).containsExactly(
            SparseEntries.entry(0, Integer.valueOf(1)), SparseEntries.entry(1, Integer.valueOf(2)),
            SparseEntries.entry(2, Integer.valueOf(3)), SparseEntries.entry(3, Integer.valueOf(4)),
            SparseEntries.entry(4, Integer.valueOf(5)));

    final SparseArrayCompat<Integer> arrayCompat2 = AndroidCollections.iterate(mArray)
            .translate(new IntTranslator() {

                @Override
                public int translate(final int value) {

                    return value + 1;
                }
            },

                    new Translator<String, Integer>() {

                        @Override
                        public Integer translate(final String element) {

                            return Integer.decode(element);
                        }
                    })
            .toSparseArray();
    assertThat(AndroidCollections.iterate(arrayCompat2).toImmutableList()).containsExactly(
            SparseEntries.entry(1, Integer.valueOf(0)), SparseEntries.entry(2, Integer.valueOf(1)),
            SparseEntries.entry(3, Integer.valueOf(2)), SparseEntries.entry(4, Integer.valueOf(3)),
            SparseEntries.entry(5, Integer.valueOf(4)));
    AndroidCollections.iterate(arrayCompat1).only().first(3).putInto(arrayCompat2);
    assertThat(AndroidCollections.iterate(arrayCompat2).toImmutableList()).containsExactly(
            SparseEntries.entry(0, Integer.valueOf(1)), SparseEntries.entry(1, Integer.valueOf(2)),
            SparseEntries.entry(2, Integer.valueOf(3)), SparseEntries.entry(3, Integer.valueOf(2)),
            SparseEntries.entry(4, Integer.valueOf(3)), SparseEntries.entry(5, Integer.valueOf(4)));
    AndroidCollections.iterate(arrayCompat1).only().first(3).appendTo(arrayCompat2);
    assertThat(AndroidCollections.iterate(arrayCompat2).toImmutableList()).containsExactly(
            SparseEntries.entry(0, Integer.valueOf(1)), SparseEntries.entry(1, Integer.valueOf(2)),
            SparseEntries.entry(2, Integer.valueOf(3)), SparseEntries.entry(3, Integer.valueOf(2)),
            SparseEntries.entry(4, Integer.valueOf(3)), SparseEntries.entry(5, Integer.valueOf(4)));

    AndroidCollections.iterate(arrayCompat2).only().keys(2, 3)
            .translateValues(new Translator<Integer, String>() {

                @Override
                public String translate(final Integer element) {

                    return element.toString();
                }
            }).putInto(mArray);
    assertThat(AndroidCollections.iterate(mArray).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "3"),
            SparseEntries.entry(3, "2"), SparseEntries.entry(4, "4"));
    AndroidCollections.iterate(arrayCompat2).only().keys(2, 3)
            .translateValues(new Translator<Integer, String>() {

                @Override
                public String translate(final Integer element) {

                    return element.toString();
                }
            }).appendTo(mArray);
    assertThat(AndroidCollections.iterate(mArray).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "3"),
            SparseEntries.entry(3, "2"), SparseEntries.entry(4, "4"));
    AndroidCollections.iterate(arrayCompat2).only().last(1).translate(new IntTranslator() {

        @Override
        public int translate(final int value) {

            return value - 2;
        }

    }, new Translator<Integer, String>() {

        @Override
        public String translate(final Integer element) {

            return element.toString();
        }

    }).putInto(mArray);
    assertThat(AndroidCollections.iterate(mArray).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "3"),
            SparseEntries.entry(3, "4"), SparseEntries.entry(4, "4"));
    AndroidCollections.iterate(arrayCompat2).only().last(1).translate(new IntTranslator() {

        @Override
        public int translate(final int value) {

            return value - 2;
        }

    }, new Translator<Integer, String>() {

        @Override
        public String translate(final Integer element) {

            return element.toString();
        }

    }).appendTo(mArray);
    assertThat(AndroidCollections.iterate(mArray).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "3"),
            SparseEntries.entry(3, "4"), SparseEntries.entry(4, "4"));

    final SparseArrayCompat<String> arrayCompat3 = AndroidCollections.iterate(mArray).toSparseArray();
    assertThat(AndroidCollections.iterate(arrayCompat3).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "3"),
            SparseEntries.entry(3, "4"), SparseEntries.entry(4, "4"));

    AndroidCollections.iterate(arrayCompat3).but().last(1).translateKeys(new IntTranslator() {

        @Override
        public int translate(final int value) {

            return value + 2;
        }

    }).appendTo(mArray);
    assertThat(AndroidCollections.iterate(mArray).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "0"),
            SparseEntries.entry(3, "1"), SparseEntries.entry(4, "3"), SparseEntries.entry(5, "4"));
    AndroidCollections.iterate(arrayCompat3).but().last(1).translateKeys(new IntTranslator() {

        @Override
        public int translate(final int value) {

            return value + 2;
        }

    }).putInto(mArray);
    assertThat(AndroidCollections.iterate(mArray).toImmutableList()).containsExactly(
            SparseEntries.entry(0, "0"), SparseEntries.entry(1, "1"), SparseEntries.entry(2, "0"),
            SparseEntries.entry(3, "1"), SparseEntries.entry(4, "3"), SparseEntries.entry(5, "4"));
}

From source file:org.ohmage.query.impl.SurveyUploadQuery.java

/**
 * Copied directly from ImageQueries.//from   ww  w.  j  a  v  a  2 s  .co m
 * 
 * Gets the directory to which a image should be saved. This should be used
 * instead of accessing the class-level variable directly as it handles the
 * creation of new folders and the checking that the current
 * folder is not full.
 * 
 * @return A File object for where an image should be written.
 */
private File getDirectory() throws DataAccessException {
    // Get the maximum number of items in a directory.
    int numFilesPerDirectory;
    try {
        numFilesPerDirectory = Integer.decode(
                PreferenceCache.instance().lookup(PreferenceCache.KEY_MAXIMUM_NUMBER_OF_FILES_PER_DIRECTORY));
    } catch (CacheMissException e) {
        throw new DataAccessException("Preference cache doesn't know about 'known' key: "
                + PreferenceCache.KEY_MAXIMUM_NUMBER_OF_FILES_PER_DIRECTORY, e);
    } catch (NumberFormatException e) {
        throw new DataAccessException("Stored value for key '"
                + PreferenceCache.KEY_MAXIMUM_NUMBER_OF_FILES_PER_DIRECTORY + "' is not decodable as a number.",
                e);
    }

    // If the leaf directory was never initialized, then we should do
    // that. Note that the initialization is dumb in that it will get to
    // the end of the structure and not check to see if the leaf node is
    // full.
    if (imageLeafDirectory == null) {
        init(numFilesPerDirectory);
    }

    File[] documents = imageLeafDirectory.listFiles();
    // If the 'imageLeafDirectory' directory is full, traverse the tree and
    // find a new directory.
    if (documents.length >= numFilesPerDirectory) {
        getNewDirectory(numFilesPerDirectory);
    }

    return imageLeafDirectory;
}