Example usage for java.util LinkedList toArray

List of usage examples for java.util LinkedList toArray

Introduction

In this page you can find the example usage for java.util LinkedList toArray.

Prototype

@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) 

Source Link

Document

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

Usage

From source file:jext2.DataStructureAccessProvider.java

private StackTraceElement[] filterStrackTraceForLog(StackTraceElement[] stack) {
    LinkedList<StackTraceElement> interresting = new LinkedList<StackTraceElement>();

    for (StackTraceElement element : stack) {
        if (element.getClassName().contains("jext2"))
            interresting.add(element);// w  w  w  . ja v  a2s . c om
    }

    return interresting.toArray(new StackTraceElement[0]);
}

From source file:com.granita.icloudcalsync.resource.RemoteCollection.java

@SuppressWarnings("unchecked")
public Resource[] multiGet(Resource[] resources)
        throws URISyntaxException, IOException, DavException, HttpException {
    try {//from  w  w w .j  a va 2  s.c  om
        if (resources.length == 1)
            return (T[]) new Resource[] { get(resources[0]) };

        Log.i(TAG, "Multi-getting " + resources.length + " remote resource(s)");

        LinkedList<String> names = new LinkedList<String>();
        for (Resource resource : resources)
            names.add(resource.getName());

        LinkedList<T> foundResources = new LinkedList<T>();
        collection.multiGet(multiGetType(), names.toArray(new String[0]));
        if (collection.getMembers() == null)
            throw new DavNoContentException();

        for (WebDavResource member : collection.getMembers()) {
            T resource = newResourceSkeleton(member.getName(), member.getETag());
            try {
                if (member.getContent() != null) {
                    @Cleanup
                    InputStream is = new ByteArrayInputStream(member.getContent());
                    resource.parseEntity(is, getDownloader());
                    foundResources.add(resource);
                } else
                    Log.e(TAG, "Ignoring entity without content");
            } catch (InvalidResourceException e) {
                Log.e(TAG, "Ignoring unparseable entity in multi-response", e);
            }
        }

        return foundResources.toArray(new Resource[0]);
    } catch (InvalidResourceException e) {
        Log.e(TAG, "Couldn't parse entity from GET", e);
    }

    return new Resource[0];
}

From source file:org.loadosophia.client.LoadosophiaAPIClient.java

protected String[] multipartPost(LinkedList<Part> parts, String URL, int expectedSC) throws IOException {
    log.debug("Request POST: " + URL);
    parts.add(new StringPart("token", token));

    PostMethod postRequest = new PostMethod(URL);
    MultipartRequestEntity multipartRequest = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]),
            postRequest.getParams());//from   w  w  w .ja v a 2 s. com
    postRequest.setRequestEntity(multipartRequest);
    int result = httpClient.executeMethod(postRequest);
    if (result != expectedSC) {
        String fname = File.createTempFile("error_", ".html").getAbsolutePath();
        notifier.notifyAbout("Saving server error response to: " + fname);
        FileOutputStream fos = new FileOutputStream(fname);
        FileChannel resultFile = fos.getChannel();
        resultFile.write(ByteBuffer.wrap(postRequest.getResponseBody()));
        resultFile.close();
        throw new HttpException("Request returned not " + expectedSC + " status code: " + result);
    }
    byte[] bytes = postRequest.getResponseBody();
    if (bytes == null) {
        bytes = new byte[0];
    }
    String response = new String(bytes);
    return response.trim().split(";");
}

From source file:de.quadrillenschule.azocamsyncd.ftpservice.FTPConnection.java

public void remountSD() {
    LinkedList<String> commands = new LinkedList<>();
    commands.add("/usr/bin/refresh_sd");
    telnetCommands(commands.toArray(new String[commands.size()]));

}

From source file:jext2.JextReentrantReadWriteLock.java

private String[] getElementsThatRequestedLock(StackTraceElement[] stack) {
    LinkedList<String> interresting = new LinkedList<String>();

    for (StackTraceElement element : stack) {
        if (element.getClassName().contains("jext2")
                && !element.getClassName().contains("JextReentrantReadWriteLock")) {
            interresting.add(element.getFileName() + ":" + element.getLineNumber());
        }/*from   ww w . jav a  2s. c  o m*/
    }
    return interresting.toArray(new String[0]);
}

From source file:com.norconex.commons.lang.file.FileUtil.java

/**
 * Returns the specified number of lines starting from the end
 * of a text file.//www  . j  av a 2  s .  com
 * @param file the file to read lines from
 * @param encoding the file encoding
 * @param numberOfLinesToRead the number of lines to read
 * @param stripBlankLines whether to return blank lines or not
 * @param filter InputStream filter
 * @return array of file lines
 * @throws IOException i/o problem
 */
public static String[] tail(File file, String encoding, final int numberOfLinesToRead, boolean stripBlankLines,
        IInputStreamFilter filter) throws IOException {
    assertFile(file);
    assertNumOfLinesToRead(numberOfLinesToRead);
    LinkedList<String> lines = new LinkedList<String>();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(new ReverseFileInputStream(file), encoding));
    int remainingLinesToRead = numberOfLinesToRead;

    String line;
    while ((line = reader.readLine()) != null) {
        if (remainingLinesToRead-- <= 0) {
            break;
        }
        String newLine = StringUtils.reverse(line);
        if (!stripBlankLines || StringUtils.isNotBlank(line)) {
            if (filter != null && filter.accept(newLine)) {
                lines.addFirst(newLine);
            } else {
                remainingLinesToRead++;
            }
        } else {
            remainingLinesToRead++;
        }
    }
    reader.close();
    return lines.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}

From source file:eu.planets_project.pp.plato.services.action.crib_integration.TUCRiBActionServiceLocator.java

/**
 * Migrates sample record <code>sampleObject</code>  with the migration action  defined in <code>action</code>.
 *  //from   w  w w. j a v a  2s .  co m
 */
public boolean perform(PreservationActionDefinition action, SampleObject sampleObject)
        throws PlatoServiceException {
    try {
        FileObject sampleFile = new FileObject(sampleObject.getData().getData(), sampleObject.getFullname());
        RepresentationObject representationObject = new RepresentationObject(new FileObject[] { sampleFile });
        LinkedList<String> urls = new LinkedList<String>();
        for (Parameter param : action.getParams()) {
            if (param.getName().startsWith("crib::location")) {
                urls.add(param.getValue());
            }
        }
        String[] urlArr = urls.toArray(new String[] {});
        /*
         * convert source object
         */
        TUMigrationBroker migrationBroker = new TUMigrationBroker();
        eu.planets_project.pp.plato.services.crib_integration.tu_client.MigrationResult migrationResult = migrationBroker
                .convert(representationObject, urlArr);

        /*
         * collect migration results
         */
        MigrationResult result = new MigrationResult();
        lastResult = result;

        /*
         * if the migration was successful is indicated by two flags:
         * "process::availability" and "process::stability"
         * - which are float values (!)
         */
        Criterion[] criteria = migrationResult.getReport().getCriteria();
        double availability = Double.parseDouble(getCriterion(criteria, "process::availability"));
        double stability = Double.parseDouble(getCriterion(criteria, "process::stability"));
        result.setSuccessful((availability > 0.0) && (stability > 0.0));
        if (!result.isSuccessful()) {
            result.setReport(String.format("Service '%s' failed to migrate sample '%s'.", action.getShortname(),
                    sampleObject.getFullname()));//+ getCriterion(criteria, "message::reason"));
            log.debug(String.format("Service '%s' failed to migrate sample '%s': %s", action.getShortname(),
                    sampleObject.getFullname(), getCriterion(criteria, "message::reason")));
            return true;
        } else {
            result.setReport(String.format("Migrated object '%s' to format '%s'. Completed at %s.",
                    sampleObject.getFullname(), action.getTargetFormat(),
                    migrationResult.getReport().getDatetime()));
        }
        result.getMigratedObject().getData()
                .setData(migrationResult.getRepresentation().getFiles()[0].getBitstream().clone());

        /*
         * message::filename contains the name of the source-file, NOT the migrated
         */
        String filename = migrationResult.getRepresentation().getFiles()[0].getFilename();

        /*
         * if filename is missing, use name from the source object (without extension)
         */
        if ((filename == null) || "".equals(filename)) {
            filename = sampleObject.getFullname();
            int bodyEnd = filename.lastIndexOf(".");
            if (bodyEnd >= 0)
                filename = filename.substring(0, bodyEnd);
        }
        result.getMigratedObject().setFullname(filename);
        int bodyEnd;

        /*
         * CRiB does not provide forther information about the format of the migrated object,
         * therfore the file extension of the migrated object is derived from the action's target formats 
         */
        bodyEnd = filename.lastIndexOf(".");
        if ((bodyEnd < 0) && ((result.getTargetFormat().getDefaultExtension() == null)
                || "".equals(result.getTargetFormat().getDefaultExtension()))) {
            FormatInfo targetFormat = new FormatInfo();
            setFormatFromCRiBID(action.getTargetFormat(), targetFormat);
            result.setTargetFormat(targetFormat);
            filename = filename + "." + result.getTargetFormat().getDefaultExtension();
            result.getMigratedObject().setFullname(filename);
            result.getMigratedObject().getFormatInfo().assignValues(targetFormat);
        }
        lastResult = result;
        return true;
    } catch (NumberFormatException e) {
        throw new PlatoServiceException("Migration failed, CRiB returned an invalid result.", e);
    } catch (RemoteException e) {
        throw new PlatoServiceException("Migration failed, could not access CRiB.", e);
    } catch (EJBException e) {
        throw new PlatoServiceException("Migration failed, could not access CRiB.", e);
    }
}

From source file:org.fusesource.meshkeeper.distribution.provisioner.embedded.SpawnedServer.java

public synchronized void start() throws MeshProvisioningException {
    if (isDeployed()) {
        return;// w  w w  .j  av a  2 s  .  c  o  m
    }

    if (!serverDirectory.exists()) {
        try {
            serverDirectory = serverDirectory.getCanonicalFile();
            serverDirectory.mkdirs();
            if (!serverDirectory.exists()) {
                throw new FileNotFoundException(serverDirectory.getPath());
            }
        } catch (Exception e) {
            throw new MeshProvisioningException("Unable to create server directory: " + serverDirectory, e);
        }
    }

    JavaLaunch jl = new JavaLaunch();
    jl.setWorkingDir(file(serverDirectory.getPath()));
    String jvm = System.getProperty("java.home") + "/bin/java";
    if (ProcessSupport.isWindows()) {
        jl.setJvm(file(jvm + ".exe"));
    } else {
        jl.setJvm(file(jvm));
    }

    //Resolve the meshkeeper classpath:
    try {
        PluginResolver resolver = PluginClassLoader.getDefaultPluginLoader().getPluginResolver();
        jl.setClasspath(resolver.resolveClassPath(PluginResolver.PROJECT_GROUP_ID + ":"
                + PluginResolver.PROJECT_ARTIFACT_ID + ":" + PluginClassLoader.getDefaultPluginVersion()));
    } catch (Exception e) {
        throw new MeshProvisioningException("Unable to resolve meshkeeper classpath:" + e.getMessage(), e);
    }

    String log4jConf = System.getProperty("log4j.configuration");
    if (log4jConf == null) {
        URL u = this.getClass().getClassLoader().getResource("meshkeeperlog4j.properties");
        if (u == null) {
            u = this.getClass().getClassLoader().getResource("log4j.properties");
        }
        if (u != null) {
            log4jConf = u.toString();
        }
    }

    if (log4jConf != null) {
        jl.addSystemProperty("log4j.configuration", log4jConf);
        //jl.addSystemProperty("log4j.debug", "true");
    }

    jl.setMainClass(Main.class.getName());
    jl.addArgs(Main.DIRECTORY_SWITCH).addArgs(file(serverDirectory.toString()));
    jl.addArgs(Main.REGISTRY_SWITCH, "zk:tcp://0.0.0.0:" + registryPort);
    if (startLaunchAgent) {
        jl.addArgs(Main.START_EMBEDDED_AGENT);
    }

    LaunchDescription ld = jl.toLaunchDescription();
    //ld.propagateSystemProperties(System.getProperties(), LaunchAgent.PROPAGATED_SYSTEM_PROPERTIES);

    LinkedList<String> cmdList = new LinkedList<String>(ld.evaluate(new Properties()));

    String[] cmdArray = cmdList.toArray(new String[] {});
    String command = "";
    try {
        command = ld.evaluateCommandLine(System.getProperties());

        //If it's windows dump the command to script into a script and execute
        if (createWindow && ProcessSupport.isWindows()) {

            File batFile = new File(serverDirectory, "meshkeeper.bat");
            if (batFile.exists()) {
                batFile.delete();
            }
            batFile.createNewFile();
            BufferedWriter writer = new BufferedWriter(new FileWriter(batFile));
            writer.write("@echo off\r\n");
            writer.write("TITLE MeshKeeper\r\n");
            writer.write(command + "\r\n");
            if (isCreateWindow() && pauseWindow) {
                writer.write("pause\r\n");
            }

            command = "START " + batFile.getCanonicalPath();
            writer.flush();
            writer.close();

            cmdArray = new String[] { "START", batFile.getCanonicalPath() };
            Execute e = new Execute(jl.getWorkingDir().evaluate());
            e.setCommandline(cmdArray);
            e.spawn();

            createWindow = true;
        } else {
            createWindow = false;
            Execute e = new Execute(jl.getWorkingDir().evaluate());
            e.setCommandline(cmdArray);
            e.spawn();
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Launching command: " + command);
        }

        long timeout = System.currentTimeMillis() + provisioningTimeout;
        while (!isDeployed() && System.currentTimeMillis() < timeout) {
            Thread.sleep(100);
        }

        if (!isDeployed()) {
            throw new MeshProvisioningException("Timed out spawning meshkeeper server");
        }

    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        if (isDeployed()) {
            throw new MeshProvisioningException("Interrupted spawning meshkeeper control server");
        }
    } catch (Exception ioe) {
        throw new MeshProvisioningException(
                "Unable to spawn meshkeeper control server with command line of " + command, ioe);
    }
}

From source file:org.cocos2dx.lib.Cocos2dxBitmap.java

private static String[] splitString(String content, int maxHeight, int maxWidth, Paint paint) {
    String[] lines = content.split("\\n");
    String[] ret = null;//from   w  w  w. j  a  va 2 s.c  o  m
    FontMetricsInt fm = paint.getFontMetricsInt();
    int heightPerLine = (int) Math.ceil(fm.bottom - fm.top);
    int maxLines = maxHeight / heightPerLine;

    if (maxWidth != 0) {
        LinkedList<String> strList = new LinkedList<String>();
        for (String line : lines) {
            /*
             * The width of line is exceed maxWidth, should divide it into
             * two or more lines.
             */
            int lineWidth = (int) Math.ceil(paint.measureText(line));
            if (lineWidth > maxWidth) {
                strList.addAll(divideStringWithMaxWidth(paint, line, maxWidth));
            } else {
                strList.add(line);
            }

            /*
             * Should not exceed the max height;
             */
            if (maxLines > 0 && strList.size() >= maxLines) {
                break;
            }
        }

        /*
         * Remove exceeding lines
         */
        if (maxLines > 0 && strList.size() > maxLines) {
            while (strList.size() > maxLines) {
                strList.removeLast();
            }
        }

        ret = new String[strList.size()];
        strList.toArray(ret);
    } else if (maxHeight != 0 && lines.length > maxLines) {
        /*
         * Remove exceeding lines
         */
        LinkedList<String> strList = new LinkedList<String>();
        for (int i = 0; i < maxLines; i++) {
            strList.add(lines[i]);
        }
        ret = new String[strList.size()];
        strList.toArray(ret);
    } else {
        ret = lines;
    }

    return ret;
}