Example usage for java.util ArrayList toString

List of usage examples for java.util ArrayList toString

Introduction

In this page you can find the example usage for java.util ArrayList toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:net.i2cat.csade.life2.backoffice.bl.StatisticsManager.java

/**
 * Returns the necessary data to build a pie with the tipe of connections
 * @return//from w  ww.j  av a2s  .c  o m
 */
public String getDatosDispositivos() {

    int iPads = 0, androids = 0, others = 0;

    try {
        androids = sd.countStats(" Event=" + StatsDAO.LOGIN_EVENT + " and Device like '%ndroid%' "); //
        iPads = sd.countStats("Event=" + StatsDAO.LOGIN_EVENT + " and Device like '%iPad%'");
        others = sd.countStats(" Event=" + StatsDAO.LOGIN_EVENT) + (-androids) + (-iPads);
    } catch (RemoteException e) {
        iPads = 0;
        androids = 0;
        others = 0;
        e.printStackTrace();
    } catch (ServiceException e) {
        iPads = 0;
        androids = 0;
        others = 0;
        e.printStackTrace();
    }
    Pair p1 = new Pair("Ipad connections", iPads);
    Pair p2 = new Pair("Android connections", androids);
    Pair p3 = new Pair("PCs and others", others);

    ArrayList<Pair> datos = new ArrayList<Pair>();
    datos.add(p1);
    datos.add(p2);
    datos.add(p3);
    return datos.toString();
}

From source file:com.nubits.nubot.trading.wrappers.CcedkWrapper.java

@Override
public ApiResponse clearOrders(CurrencyPair pair) {
    //Since there is no API entry point for that, this call will iterate over active
    ApiResponse apiResponse = new ApiResponse();
    ArrayList<String> errorIds = new ArrayList<>();

    ApiResponse activeOrdersResponse = getActiveOrders();
    if (activeOrdersResponse.isPositive()) {
        apiResponse.setResponseObject(true);
        ArrayList<Order> orderList = (ArrayList) activeOrdersResponse.getResponseObject();
        String errorString = "";
        boolean ok = true;
        for (Iterator<Order> order = orderList.iterator(); order.hasNext();) {
            Order thisOrder = order.next();
            if (!pair.equals(thisOrder.getPair())) {
                continue;
            }// w  ww .  j av a  2  s  .c o  m
            ApiResponse deleteOrderResponse = cancelOrder(thisOrder.getId(), null);

            if (deleteOrderResponse.isPositive()) {
                continue;
            } else {
                errorIds.add(thisOrder.getId());
            }
        }
        if (!errorIds.isEmpty()) {
            ApiError error = errors.genericError;
            error.setDescription(errorIds.toString());
            apiResponse.setError(error);
            apiResponse.setResponseObject(false);
        }
    } else {
        apiResponse = activeOrdersResponse;
    }

    return apiResponse;
}

From source file:org.orbeon.oxf.processor.JavaProcessor.java

private Processor getProcessor(PipelineContext context) {
    try {/*from  ww w. java2  s  .c o  m*/
        // Read config input into a String, cache if possible
        ProcessorInput input = getInputByName(INPUT_CONFIG);
        final Config config = readCacheInputAsObject(context, input, new CacheableInputReader<Config>() {
            public Config read(PipelineContext context, ProcessorInput input) {
                Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
                Element configElement = configDocument.getRootElement();
                Config config = new Config();
                config.clazz = configElement.attributeValue("class");

                // Get source path
                String sourcePathAttributeValue = configElement.attributeValue("sourcepath");
                if (sourcePathAttributeValue == null)
                    sourcePathAttributeValue = ".";
                File sourcePath = getFileFromURL(sourcePathAttributeValue,
                        JavaProcessor.this.getLocationData());
                if (!sourcePath.isDirectory())
                    throw new ValidationException(
                            "Invalid sourcepath attribute: cannot find directory for URL: "
                                    + sourcePathAttributeValue,
                            (LocationData) configElement.getData());
                try {
                    config.sourcepath = sourcePath.getCanonicalPath();
                } catch (IOException e) {
                    throw new ValidationException(
                            "Invalid sourcepath attribute: cannot find directory for URL: "
                                    + sourcePathAttributeValue,
                            (LocationData) configElement.getData());
                }

                return config;
            }
        });

        // Check if need to compile
        String sourceFile = config.sourcepath + "/" + config.clazz.replace('.', '/') + ".java";
        String destinationDirectory = SystemUtils.getTemporaryDirectory().getAbsolutePath();
        String destinationFile = destinationDirectory + "/" + config.clazz.replace('.', '/') + ".class";

        // Check if file is up-to-date
        long currentTimeMillis = System.currentTimeMillis();
        Long sourceLastModified;
        Long destinationLastModified;
        synchronized (lastModifiedMap) {
            sourceLastModified = (Long) lastModifiedMap.get(currentTimeMillis, sourceFile);
            if (sourceLastModified == null) {
                sourceLastModified = new Long(new File(sourceFile).lastModified());
                lastModifiedMap.put(currentTimeMillis, sourceFile, sourceLastModified);
            }
            destinationLastModified = (Long) lastModifiedMap.get(currentTimeMillis, destinationFile);
            if (destinationLastModified == null) {
                destinationLastModified = new Long(new File(destinationFile).lastModified());
                lastModifiedMap.put(currentTimeMillis, destinationFile, destinationLastModified);
            }
        }
        boolean fileUpToDate = sourceLastModified.longValue() < destinationLastModified.longValue();

        // Compile
        if (!fileUpToDate) {
            StringBuilderWriter javacOutput = new StringBuilderWriter();

            final ArrayList<String> argLst = new ArrayList<String>();
            final String[] cmdLine;
            {
                argLst.add("-g");
                final String cp = buildClassPath(context);
                if (cp != null) {
                    argLst.add("-classpath");
                    argLst.add(cp);
                }

                if (config.sourcepath != null && config.sourcepath.length() > 0) {
                    argLst.add("-sourcepath");
                    argLst.add(config.sourcepath);
                }
                argLst.add("-d");
                final File tmp = SystemUtils.getTemporaryDirectory();
                final String tmpPth = tmp.getAbsolutePath();
                argLst.add(tmpPth);
                final String fnam = config.sourcepath + "/" + config.clazz.replace('.', '/') + ".java";
                argLst.add(fnam);

                cmdLine = new String[argLst.size()];
                argLst.toArray(cmdLine);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Compiling class '" + config.clazz + "'");
                logger.debug("javac " + argLst.toString());
            }
            Throwable thrown = null;
            int exitCode = 1;
            try {
                // Get compiler class, either user-specified or default to Sun compiler
                String compilerMain = getPropertySet().getString(COMPILER_CLASS_PROPERTY,
                        DEFAULT_COMPILER_MAIN);

                ClassLoader classLoader;
                {
                    URI compilerJarURI = getPropertySet().getURI(COMPILER_JAR_PROPERTY);
                    if (compilerJarURI != null) {
                        // 1: Always honor user-specified compiler JAR if present
                        // Use special class loader pointing to this URL
                        classLoader = new URLClassLoader(new URL[] { compilerJarURI.toURL() },
                                JavaProcessor.class.getClassLoader());
                        if (logger.isDebugEnabled())
                            logger.debug("Java processor using user-specified compiler JAR: "
                                    + compilerJarURI.toString());
                    } else {
                        // 2: Try to use the class loader that loaded this class
                        classLoader = JavaProcessor.class.getClassLoader();
                        try {
                            Class.forName(compilerMain, true, classLoader);
                            logger.debug("Java processor using current class loader");
                        } catch (ClassNotFoundException e) {
                            // Class not found
                            // 3: Try to get to Sun tools.jar
                            String javaHome = System.getProperty("java.home");
                            if (javaHome != null) {
                                File javaHomeFile = new File(javaHome);
                                if (javaHomeFile.getName().equals("jre")) {
                                    File toolsFile = new File(javaHomeFile.getParentFile(),
                                            "lib" + File.separator + "tools.jar");
                                    if (toolsFile.exists()) {
                                        // JAR file exists, will use it to load compiler class
                                        classLoader = new URLClassLoader(
                                                new URL[] { toolsFile.toURI().toURL() },
                                                JavaProcessor.class.getClassLoader());
                                        if (logger.isDebugEnabled())
                                            logger.debug("Java processor using default tools.jar under "
                                                    + toolsFile.toString());
                                    }
                                }
                            }
                        }
                    }
                }

                // Load compiler class using class loader defined above
                Class compilerClass = Class.forName(compilerMain, true, classLoader);

                // Get method and run compiler
                Method compileMethod = compilerClass.getMethod("compile",
                        new Class[] { String[].class, PrintWriter.class });
                Object result = compileMethod.invoke(null, cmdLine, new PrintWriter(javacOutput));
                exitCode = ((Integer) result).intValue();

            } catch (final Throwable t) {
                thrown = t;
            }
            if (exitCode != 0) {
                String javacOutputString = "\n" + javacOutput.toString();
                javacOutputString = StringUtils.replace(javacOutputString, "\n", "\n    ");
                throw new OXFException("Error compiling '" + argLst.toString() + "'" + javacOutputString,
                        thrown);
            }
        }

        // Try to get sourcepath info
        InternalCacheKey sourcepathKey = new InternalCacheKey(JavaProcessor.this, "javaFile",
                config.sourcepath);
        Object sourcepathValidity = new Long(0);
        Sourcepath sourcepath = (Sourcepath) ObjectCache.instance().findValid(sourcepathKey,
                sourcepathValidity);

        // Create classloader
        if (sourcepath == null
                || (sourcepath.callNameToProcessorClass.containsKey(config.clazz) && !fileUpToDate)) {
            if (logger.isDebugEnabled())
                logger.debug("Creating classloader for sourcepath '" + config.sourcepath + "'");
            sourcepath = new Sourcepath();
            sourcepath.classLoader = new URLClassLoader(
                    new URL[] { SystemUtils.getTemporaryDirectory().toURI().toURL(),
                            new File(config.sourcepath).toURI().toURL() },
                    this.getClass().getClassLoader());
            ObjectCache.instance().add(sourcepathKey, sourcepathValidity, sourcepath);
        }

        // Get processor class
        Class<Processor> processorClass = sourcepath.callNameToProcessorClass.get(config.clazz);
        if (processorClass == null) {
            processorClass = (Class<Processor>) sourcepath.classLoader.loadClass(config.clazz);
            sourcepath.callNameToProcessorClass.put(config.clazz, processorClass);
        }

        // Create processor from class
        Thread.currentThread().setContextClassLoader(processorClass.getClassLoader());
        return processorClass.newInstance();

    } catch (final IOException e) {
        throw new OXFException(e);
    } catch (final IllegalAccessException e) {
        throw new OXFException(e);
    } catch (final InstantiationException e) {
        throw new OXFException(e);
    } catch (final ClassNotFoundException e) {
        throw new OXFException(e);
    }
}

From source file:com.kyleszombathy.sms_scheduler.MessageAlarmReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    this.context = context;
    boolean sendSuccessFlag = true;

    // Get wakelock
    Intent service = new Intent(context, MessageAlarmReceiver.class);

    // Start the service, keeping the device awake while it is launching.
    Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
    startWakefulService(context, service);

    // Get data from intent
    ArrayList<String> phoneList = intent.getStringArrayListExtra("pNum");
    String messageContent = intent.getStringExtra("message");
    int alarmNumber = intent.getIntExtra("alarmNumber", -1);
    ArrayList<String> nameList = intent.getStringArrayListExtra("nameList");

    // Split message, regardless if needed - just in case I have the message length number wrong
    final ArrayList<String> messageArrayList = smsManager.divideMessage(messageContent);

    // Sends to multiple recipients
    for (int i = 0; i < phoneList.size(); i++) {
        // Send message and retrieve
        boolean result = sendSMSMessage(phoneList.get(i), messageArrayList);
        if (!result) {
            sendSuccessFlag = false;//from   ww  w.  j av a  2s.  c o m
        }
    }

    /* Register for SMS send action */
    context.getApplicationContext().registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String result = "";
            final String[] TRANSMISSION_TYPE = { "Transmission successful", "Transmission failed", "Radio off",
                    "No PDU defined", "No service" };

            switch (getResultCode()) {
            case Activity.RESULT_OK:
                result = TRANSMISSION_TYPE[0];
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                result = TRANSMISSION_TYPE[1];
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                result = TRANSMISSION_TYPE[2];
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                result = TRANSMISSION_TYPE[3];
                break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                result = TRANSMISSION_TYPE[4];
                break;
            }
            Log.i(TAG, result + " for message " + messageArrayList.toString());
            // Handle error
            if (!Objects.equals(result, TRANSMISSION_TYPE[0])) {
                //messageSendSuccess[0] = false;
            }
        }
    }, new IntentFilter(SENT));

    // Create notification message
    String notificationMessage = Tools.createSentString(context, nameList, 1, sendSuccessFlag);

    // Send notification if message send successfull
    if (sendSuccessFlag) {
        sendNotification(context, notificationMessage, messageContent, true, nameList);
    } else {
        sendNotification(context, notificationMessage, messageContent, false, nameList);
    }
    // Archive, regardless of send success or not
    markAsSent(context, notificationMessage, alarmNumber);
    // Release wakelock
    completeWakefulIntent(service);
}

From source file:org.dcm4chex.archive.hsm.VerifyTar.java

public static Map<String, byte[]> verify(InputStream in, String tarname, byte[] buf,
        ArrayList<String> objectNames) throws IOException, VerifyTarException {
    TarInputStream tar = new TarInputStream(in);
    try {/*from ww  w . j  ava  2 s . c  o  m*/
        log.debug("Verify tar file: {}", tarname);
        TarEntry entry = tar.getNextEntry();
        if (entry == null)
            throw new VerifyTarException("No entries in " + tarname);
        String entryName = entry.getName();
        if (!"MD5SUM".equals(entryName))
            throw new VerifyTarException("Missing MD5SUM entry in " + tarname);
        BufferedReader dis = new BufferedReader(new InputStreamReader(tar));

        HashMap<String, byte[]> md5sums = new HashMap<String, byte[]>();
        String line;
        while ((line = dis.readLine()) != null) {
            char[] c = line.toCharArray();
            byte[] md5sum = new byte[16];
            for (int i = 0, j = 0; i < md5sum.length; i++, j++, j++) {
                md5sum[i] = (byte) ((fromHexDigit(c[j]) << 4) | fromHexDigit(c[j + 1]));
            }
            md5sums.put(line.substring(34), md5sum);
        }
        Map<String, byte[]> entries = new HashMap<String, byte[]>(md5sums.size());
        entries.putAll(md5sums);
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        while ((entry = tar.getNextEntry()) != null) {
            entryName = entry.getName();
            log.debug("START: Check MD5 of entry: {}", entryName);
            if (objectNames != null && !objectNames.remove(entryName))
                throw new VerifyTarException(
                        "TAR " + tarname + " contains entry: " + entryName + " not in file list");
            byte[] md5sum = (byte[]) md5sums.remove(entryName);
            if (md5sum == null)
                throw new VerifyTarException("Unexpected TAR entry: " + entryName + " in " + tarname);
            digest.reset();
            in = new DigestInputStream(tar, digest);
            while (in.read(buf) > 0)
                ;
            if (!Arrays.equals(digest.digest(), md5sum)) {
                throw new VerifyTarException("Failed MD5 check of TAR entry: " + entryName + " in " + tarname);
            }
            log.debug("DONE: Check MD5 of entry: {}", entryName);
        }
        if (!md5sums.isEmpty())
            throw new VerifyTarException("Missing TAR entries: " + md5sums.keySet() + " in " + tarname);
        if (objectNames != null && !objectNames.isEmpty())
            throw new VerifyTarException(
                    "Missing TAR entries from object list: " + objectNames.toString() + " in " + tarname);
        return entries;
    } finally {
        tar.close();
    }
}

From source file:org.apache.jsp.communities_jsp.java

private boolean validateFormFields() {
      boolean isValid = true;
      ArrayList<String> al = new ArrayList<String>();
      if (name.length() < 1)
          al.add("Name");
      if (description.length() < 1)
          al.add("Description");
      if (tags.length() < 1)
          al.add("Tags");
      if (al.size() > 0) {
          isValid = false;//from ww w .  j  a v a  2  s .co  m
          messageToDisplay = "Error, the following required fields are missing: " + al.toString();
      }
      return isValid;
  }

From source file:org.akvo.caddisfly.ui.activity.MainActivity.java

public void onSaveCalibration() {
    final Context context = this;
    final MainApp mainApp = (MainApp) this.getApplicationContext();

    final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
    final EditText input = new EditText(context);
    input.setInputType(InputType.TYPE_CLASS_TEXT);
    input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(22) });

    alertDialogBuilder.setView(input);//from w ww  .  j a  v a2 s.c  o m
    alertDialogBuilder.setCancelable(false);

    alertDialogBuilder.setTitle(R.string.saveCalibration);
    alertDialogBuilder.setMessage(R.string.giveNameForCalibration);

    alertDialogBuilder.setPositiveButton(R.string.ok, null);
    alertDialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int i) {
            closeKeyboard(input);
            dialog.cancel();
        }
    });
    final AlertDialog alertDialog = alertDialogBuilder.create(); //create the box

    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {

        @Override
        public void onShow(DialogInterface dialog) {

            Button b = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {

                    if (!input.getText().toString().trim().isEmpty()) {
                        final ArrayList<String> exportList = new ArrayList<String>();

                        for (ColorInfo aColorList : mainApp.colorList) {
                            exportList.add(ColorUtils.getColorRgbString(aColorList.getColor()));
                        }

                        File external = Environment.getExternalStorageDirectory();
                        final String path = external.getPath() + Config.CALIBRATE_FOLDER_NAME;

                        File file = new File(path + input.getText());
                        if (file.exists()) {
                            AlertUtils.askQuestion(context, R.string.overwriteFile, R.string.nameAlreadyExists,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            FileUtils.saveToFile(path, input.getText().toString(),
                                                    exportList.toString());
                                        }
                                    });
                        } else {
                            FileUtils.saveToFile(path, input.getText().toString(), exportList.toString());
                        }

                        closeKeyboard(input);
                        alertDialog.dismiss();
                    } else {
                        input.setError(getString(R.string.invalidName));
                    }
                }
            });
        }
    });

    input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                    || (actionId == EditorInfo.IME_ACTION_DONE)) {

            }
            return false;
        }
    });

    alertDialog.show();
    input.requestFocus();
    InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

}

From source file:de.zib.scalaris.TransactionSingleOpTest.java

/**
 * Test method for {@link TransactionSingleOp#write(String, List)},
 * {@link TransactionSingleOp#read(String)} and {@link ReadRandomFromListOp}
 * . Writes lists and uses a distinct key for each value. Tries to read the
 * data afterwards.//from   ww  w  . j a  va2s. c om
 *
 * @throws UnknownException
 * @throws ConnectionException
 * @throws NotFoundException
 * @throws AbortException
 * @throws NotAListException
 * @throws EmptyListException
 *
 * @since 3.2
 */
@Test
public void testWriteList1() throws ConnectionException, UnknownException, NotFoundException, AbortException,
        EmptyListException, NotAListException {
    final String key = "_WriteList1_";
    final TransactionSingleOp conn = new TransactionSingleOp();

    try {
        for (int i = 0; i < (testData.length - 1); ++i) {
            final ArrayList<String> list = new ArrayList<String>();
            if ((i % 2) == 0) {
                list.add(testData[i]);
                list.add(testData[i + 1]);
            }
            conn.write(testTime + key + i, list);
        }

        // now try to read the data:

        for (int i = 0; i < (testData.length - 1); ++i) {
            final ArrayList<String> expected = new ArrayList<String>();
            if ((i % 2) == 0) {
                expected.add(testData[i]);
                expected.add(testData[i + 1]);
            }
            final List<String> actual = conn.read(testTime + key + i).stringListValue();
            assertEquals(expected, actual);

            final ReadRandomFromListOp op = new ReadRandomFromListOp(testTime + key + i);
            final ResultList resultList = conn.req_list(op);
            assertEquals(op, resultList.get(0));
            try {
                final ReadRandomFromListOp.Result randResult = op.processResultSingle();
                if ((i % 2) == 0) {
                    assertEquals(expected.size(), randResult.listLength);
                    assertTrue(expected.toString() + ".contains(" + randResult.randomElement + ")",
                            expected.contains(randResult.randomElement.stringValue()));
                } else {
                    assertTrue("Trying to read random list entry from an empty list should fail: " + randResult,
                            false);
                }
            } catch (final EmptyListException e) {
                if ((i % 2) == 0) {
                    assertTrue("Got EmptyListException on non-empty list: " + e, false);
                }
            }
        }
    } finally {
        conn.closeConnection();
    }
}

From source file:org.apache.jsp.people_jsp.java

private boolean validatePassword() {
      boolean isValid = true;
      ArrayList<String> al = new ArrayList<String>();
      if (password.length() < 6)
          al.add("Password must be greater than 5 characters in length");
      if (!password.equals(passwordConfirmation))
          al.add("The Password and Password Confirmation fields must match");
      if (al.size() > 0) {
          isValid = false;//from  w w  w  .j a  va  2 s.  co  m
          messageToDisplay = "Error: " + al.toString();
          //System.out.print(messageToDisplay);
      }
      return isValid;
  }