List of usage examples for java.util LinkedList toArray
@SuppressWarnings("unchecked") public <T> T[] toArray(T[] a)
From source file:com.norconex.commons.lang.file.FileUtil.java
/** * Returns the specified number of lines starting from the beginning * of a text file, using the given encoding. * @param file the file to read lines from * @param encoding the file encoding//from w w w .j a v a 2s. com * @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[] head(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 FileInputStream(file), encoding)); int remainingLinesToRead = numberOfLinesToRead; String line = StringUtils.EMPTY; while (line != null && remainingLinesToRead-- > 0) { line = reader.readLine(); if (!stripBlankLines || StringUtils.isNotBlank(line)) { if (filter != null && filter.accept(line)) { lines.addFirst(line); } else { remainingLinesToRead++; } } else { remainingLinesToRead++; } } reader.close(); return lines.toArray(ArrayUtils.EMPTY_STRING_ARRAY); }
From source file:com.spmadden.jnfsn.NFSNDns.java
public DNSResourceRecord[] getResourceRecords(final String name, final String type, final String data) throws APIException { try {/* ww w. ja v a 2 s. c o m*/ final String url = getURL("listRRs"); final HTTPConnection conn = new HTTPConnection(url, RequestMethod.POST, generator); if (name != null) { conn.addFormField("name", name); } if (type != null && !"".equals(type)) { conn.addFormField("type", type); } if (data != null && !"".equals(data)) { conn.addFormField("data", data); } final String value = NetUtils.consumeAll(conn.getDataStream()); LOG.debug("JSON: " + value); final JSONArray arr = new JSONArray(value); final LinkedList<DNSResourceRecord> rrs = new LinkedList<>(); for (int i = 0; i < arr.length(); ++i) { rrs.add(DNSResourceRecord.fromJSONObject(arr.getJSONObject(i))); } return rrs.toArray(new DNSResourceRecord[rrs.size()]); } catch (IOException e) { LOG.error(e); } catch (JSONException e) { LOG.error(e); } return null; }
From source file:com.pavikumbhar.javaheart.util.PasswordGenerator.java
private String generatePassword(int length) { int count = c.length; LinkedList<Character> s = new LinkedList<Character>(); LinkedList<Character> s1 = new LinkedList<Character>(); Collections.addAll(s, c);/*from w w w. j a v a 2 s .c om*/ while (count > 0) { long n = generateRandomNumber(); int position = (int) (n % count); s1.add(s.remove(position)); count--; } String pwd = null; //System.out.println(">>"+s1.toString()); Character[] c1 = new Character[s1.size()]; c1 = s1.toArray(c1); String s2 = new String(f1(c1)); //System.out.println(">>"+s2); return RandomStringUtils.random(length, s2); }
From source file:org.gcaldaemon.core.file.CalendarReloader.java
/** * Splitting a string into a command-array. * /* w w w . j av a 2 s .c o m*/ * <BR> * <BR> * word1 word2 word3 -> "word1", "word2", "word3" <BR> * word1 word2="word3 'abc' def" -> "word1", "word2", "word3 'abc' def" <BR> * 'wo"rd1'="word2" word3 -> "wo\"rd1", "word2", "word3" <BR> * etc. * * @param cmdLine * @return String[] */ private static final String[] parseLine(String cmdLine) { char delimiter = ' '; boolean inToken = false; QuickWriter writer = new QuickWriter(100); LinkedList tokens = new LinkedList(); for (int i = 0; i < cmdLine.length(); i++) { char c = cmdLine.charAt(i); if (inToken) { if (c == delimiter || (delimiter == ' ' && c == '=')) { tokens.add(writer.toString()); writer.flush(); if (c == '-') { writer.write(c); } inToken = false; continue; } writer.write(c); } else { if (c == '\'') { delimiter = '\''; inToken = true; } else { if (c == '"') { delimiter = '"'; inToken = true; } else if (c == ' ') { // Skip } else { delimiter = ' '; writer.write(c); inToken = true; } } } if (i == cmdLine.length() - 1 && writer.length() != 0) { tokens.add(writer.toString()); } } String[] array = new String[tokens.size()]; tokens.toArray(array); return array; }
From source file:eu.planets_project.pp.plato.services.action.crib_integration.CRiBActionServiceLocator.java
/** * Migrates sample record <code>sampleObject</code> with the migration action defined in <code>action</code>. * // w w w . j a v a 2s .c o m */ public boolean perform(PreservationActionDefinition action, SampleObject sampleObject) throws PlatoServiceException { try { // all migration actions are done via the metaconverter metaconverterService = metaconverterServiceLocator.getMetaconverter(); // prepare the data of the sample record for migration FileObject sampleFile = new FileObject(sampleObject.getData().getData(), sampleObject.getFullname()); RepresentationObject representationObject = new RepresentationObject(new FileObject[] { sampleFile }); // the action parameters specify which migration service is called MigrationPath migrationPath = new MigrationPath(); LinkedList<String> urls = new LinkedList<String>(); for (Parameter param : action.getParams()) { urls.add(param.getValue()); } String[] urlArr = urls.toArray(new String[] {}); migrationPath.setAccessPoints(urlArr); /* * convert source object */ eu.planets_project.pp.plato.services.crib_integration.remoteclient.MigrationResult migrationResult = metaconverterService .convert(representationObject, migrationPath); /* * 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); } 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 (ServiceException 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:net.datapipe.CloudStack.CloudStackAPI.java
protected HttpMethod makeHttpGet(LinkedList<NameValuePair> queryValues) throws Exception { String query_signature = sign_request(queryValues); queryValues.add(new NameValuePair("signature", query_signature)); HttpMethod method = new GetMethod(apiURL); method.setFollowRedirects(true);//from w ww.ja va 2s .c o m method.setQueryString(queryValues.toArray(new NameValuePair[0])); return method; }
From source file:com.asakusafw.runtime.stage.launcher.LauncherOptionsParser.java
private GenericOptionsParser processGenericOptions(LinkedList<String> rest) throws IOException { String[] args = rest.toArray(new String[rest.size()]); return new GenericOptionsParser(configuration, args); }
From source file:com.project.eden.EdenMain.java
@Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainContext = this; setProgressBarIndeterminateVisibility(true); // start Facebook Login Session.openActiveSession(this, true, new Session.StatusCallback() { // callback when session changes state @Override/*from w w w . j a v a2s.com*/ public void call(Session session, SessionState state, Exception exception) { if (session.isOpened()) { // make request to the /me API Request.executeMyFriendsRequestAsync(session, new Request.GraphUserListCallback() { // callback after Graph API response with user object public void onCompleted(List<GraphUser> users, Response response) { if (users != null && !users.isEmpty()) { LinkedList<String> friendlist = new LinkedList<String>(); for (GraphUser user : users) { String u = "https://graph.facebook.com/" + user.getId() + "/picture?type=large"; friendlist.add(u); } String[] listofurls = friendlist.toArray(new String[friendlist.size()]); // friendlist now is a string list of all of your friend's profile pic url GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new ImageAdapter(mainContext, listofurls)); } } }); } } }); }
From source file:org.jboss.jbossts.fileio.xalib.txdirs.dir.XADir.java
/** * This method lists all the files under the transactional directory. * It lists only files and not <code>File</code>s as in Java this may * also mean directories.//from w w w .j a v a 2s . co m * @return a list of <code>XADirFile</code> objects which represent * the files within the directory */ public synchronized XADirFile[] listTXFiles() { File dir = new File(freMngr.getStoreDir()); File[] files = dir.listFiles(); LinkedList<XADirFile> xaDirFileList = new LinkedList<XADirFile>(); for (File f : files) { if (!f.isDirectory()) { xaDirFileList.add(new XADirFile(f, this)); } } XADirFile[] xaDirFiles = new XADirFile[xaDirFileList.size()]; xaDirFileList.toArray(xaDirFiles); return xaDirFiles; }
From source file:at.bitfire.davdroid.resource.WebDavCollection.java
@SuppressWarnings("unchecked") public Resource[] multiGet(Resource[] resources) throws URISyntaxException, IOException, DavException, HttpException { try {//from w w w. j a va2s . c o m if (resources.length == 1) return new Resource[] { get(resources[0]) }; Log.i(TAG, "Multi-getting " + resources.length + " remote resource(s)"); LinkedList<String> names = new LinkedList<>(); for (Resource resource : resources) names.add(resource.getName()); LinkedList<T> foundResources = new LinkedList<>(); collection.multiGet(multiGetType(), names.toArray(new String[names.size()])); if (collection.getMembers() == null) throw new DavNoContentException(); for (WebDavResource member : collection.getMembers()) { T resource = newResourceSkeleton(member.getName(), member.getProperties().getETag()); try { if (member.getContent() != null) { @Cleanup InputStream is = new ByteArrayInputStream(member.getContent()); resource.parseEntity(is, null, 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[foundResources.size()]); } catch (InvalidResourceException e) { Log.e(TAG, "Couldn't parse entity from GET", e); } return new Resource[0]; }