Java Code Examples for java.util.ArrayList

The following are top voted examples for showing how to use java.util.ArrayList. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: nikeplus-fuelband-se-reversed   File: AdvertisementData.java View source code Vote up 26 votes
private static ArrayList<ParcelUuid> parseUuids(byte[] paramArrayOfByte) {
	ByteBuffer localByteBuffer = ByteBuffer.wrap(paramArrayOfByte);
	localByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
	ArrayList localArrayList = new ArrayList();
	while (localByteBuffer.remaining() >= 16) {
		long l = localByteBuffer.getLong();
		localArrayList.add(new ParcelUuid(new UUID(localByteBuffer
				.getLong(), l)));
	}
	return localArrayList;
}
 
Example 2
Project: jentrata-msh   File: Zip.java View source code Vote up 16 votes
/**
 * Extracts a set of files compressed in a zip file to a directory.
 * 
 * @param fromFile the zip file.
 * @param dir the directory to which the files to be extracted. Current user
 *            directory will be chosen if it is null.
 * @throws UtilitiesException if there is any error in the extraction.
 */
public static void extract(File fromFile, File dir)
        throws UtilitiesException {
    try {
        if (dir == null) {
            dir = new File(System.getProperty("user.dir"));
        }
        else if (!dir.exists()) {
            dir.mkdirs();
        }

        if (!dir.isDirectory()) {
            throw new UtilitiesException("Invalid output directory: " + dir);
        }

        ZipFile zipFile = new ZipFile(fromFile);
        ArrayList fileEntries = new ArrayList();

        Enumeration zipEntries = zipFile.entries();
        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();
            if (zipEntry.isDirectory()) {
                new File(dir, zipEntry.getName()).mkdirs();
            }
            else {
                fileEntries.add(zipEntry);
            }
        }

        Iterator allFiles = fileEntries.iterator();
        while (allFiles.hasNext()) {
            ZipEntry fileEntry = (ZipEntry) allFiles.next();
            File destFile = new File(dir, fileEntry.getName());
            destFile.setLastModified(fileEntry.getTime());
            destFile.getParentFile().mkdirs();
            FileOutputStream outs = new FileOutputStream(destFile);
            InputStream ins = zipFile.getInputStream(fileEntry);
            IOHandler.pipe(ins, outs);
            ins.close();
            outs.close();
        }

        zipFile.close();
    }
    catch (Exception e) {
        throw new UtilitiesException("Unable to extract zip file: "
                + fromFile, e);
    }
}
 
Example 3
Project: sslcertx   File: MySQLXAResource.java View source code Vote up 11 votes
public Xid[] recover(int flags) throws XAException {
    // Return all Xid  at once, when STARTRSCAN is specified
    // Return zero-length array otherwise.

    if ( ((flags & TMSTARTRSCAN) == 0) && ((flags & TMENDRSCAN) == 0) && (flags != TMNOFLAGS))
        throw new XAException(XAException.XAER_INVAL);

    if ((flags & TMSTARTRSCAN) == 0)
        return new MySQLXid[0];

    try {
        ResultSet rs = connection.createStatement().executeQuery("XA RECOVER");
        ArrayList<MySQLXid> xidList= new ArrayList<MySQLXid>();

        while(rs.next()) {
            int formatId = rs.getInt(1);
            int len1 = rs.getInt(2);
            int len2 = rs.getInt(3);
            byte[] arr = rs.getBytes(4);

            byte[] globalTransactionId = new byte[len1];
            byte[] branchQualifier = new byte[len2];
            System.arraycopy(arr, 0, globalTransactionId, 0, len1);
            System.arraycopy(arr, len1, branchQualifier, 0, len2);
            xidList.add(new MySQLXid(formatId,globalTransactionId, branchQualifier));
        }
        Xid[] xids = new Xid[xidList.size()];
        xidList.toArray(xids);
        return xids;
    }catch (SQLException sqle) {
       throw mapXAException(sqle);
    }
}
 
Example 4
Project: richfaces   File: SelectManyHelper.java View source code Vote up 10 votes
public static List<ClientSelectItem> getClientSelectItems(FacesContext facesContext, AbstractSelectManyComponent select, Iterator<SelectItem> selectItems) {
    List<ClientSelectItem> clientSelectItems = new ArrayList<ClientSelectItem>();
    Object object = select.getValue();
    List values;
    if (object == null) {
        values = new ArrayList();
    }
    else if (object instanceof List) {
        values = (List) object;
    } else if (object instanceof Object[]) {
        values = Arrays.asList((Object[]) object);
    } else {
        throw new IllegalArgumentException("Value expression must evaluate to either a List or Object[]");
    }
    int count = values.size();
    // TODO: Deal with SelectItemGroups
    while (selectItems.hasNext()) {
        SelectItem selectItem = selectItems.next();
        boolean selected;
        int sortOrder;
        if (values.contains(selectItem.getValue())) { // TODO: this requires value#equals() to be overridden. Redo with comparators?
            selected = true;
            sortOrder = values.indexOf(selectItem.getValue());
        } else {
            selected = false;
            sortOrder = count;
        }
        ClientSelectItem clientSelectItem = SelectHelper.generateClientSelectItem(facesContext, select, selectItem, sortOrder, selected);
        clientSelectItems.add(clientSelectItem);
        if (!selected) {
            count++;
        }
    }
    Collections.sort(clientSelectItems, clientSelectItemComparator);
    return clientSelectItems;
}
 
Example 5
Project: BioWiki   File: SearchByAttributeActivity.java View source code Vote up 8 votes
public void onAttributeDecided(ArrayList<Integer> ids, int logLevel) {
    ToastUtils.showToast(getApplicationContext(), "Switching...\n" + ids);
    List<ArrayList<String>> correspondingPlants = getCorrespondingPlants(ids);
    ArrayList<String> unfilteredPlants = correspondingPlants.get(0);
    ArrayList<String> filteredPlants = new ArrayList<String>();
    for (ArrayList<String> plantList : correspondingPlants) {
        if (logLevel > LOG_LEVEL_LOW)
            Log.d("COMPARISION", "Comparing \n" + plantList + "\nto\n" + unfilteredPlants);
        for (String plant : plantList) {
            if (unfilteredPlants.contains(plant)) {
                if (logLevel > LOG_LEVEL_MEDIUM)
                    Log.d("COMPARISION", plant + " is included within array");
                filteredPlants.add(plant);
            } else {
                if (logLevel > LOG_LEVEL_MEDIUM)
                    Log.d("COMPARISION", plant + " ISN'T included within array");
            }
        }
        unfilteredPlants = new ArrayList<String>(filteredPlants);
        filteredPlants.clear();
        if (logLevel > LOG_LEVEL_NONE)
            Log.d("COMPARISION", "Filtered : \n" + unfilteredPlants);
    }
    if (logLevel > LOG_LEVEL_NONE)
        Log.d("COMPARISION", "----------------------END OF COMPARISION----------------------");

    Intent intent = new Intent(this, SearchResultsViewerActivity.class);
    intent.putExtra("plants", unfilteredPlants);
    startActivity(intent);
}
 
Example 6
Project: breakout   File: MultiplexOutputStream.java View source code Vote up 8 votes
@Override
public void write( int b ) throws IOException
{
	ArrayList<Throwable> downstreamExceptions = null;
	for( OutputStream target : downstreams )
	{
		try
		{
			target.write( b );
		}
		catch( Throwable t )
		{
			if( downstreamExceptions == null )
			{
				downstreamExceptions = new ArrayList<Throwable>( );
			}
			downstreamExceptions.add( t );
		}
	}
	
	if( downstreamExceptions != null )
	{
		downstreamExceptions.trimToSize( );
		throw new DownstreamException( downstreamExceptions );
	}
}
 
Example 7
Project: xapi   File: AttributeInfo.java View source code Vote up 8 votes
public static AttributeInfo lookup(ArrayList<?> list, String name) {
    if (list == null) {
      return null;
    }

    ListIterator<?> iterator = list.listIterator();
    while (iterator.hasNext()) {
        AttributeInfo ai = (AttributeInfo)iterator.next();
        if (ai.getName().equals(name)) {
          return ai;
        }
    }

    return null;            // no such attribute
}
 
Example 8
Project: SimpleAlgebra_V2   File: EinsteinTensorElem.java View source code Vote up 8 votes
@Override
public EinsteinTensorElem<Z, R, S> cloneThread( final BigInteger threadIndex )
{
	final S facs = this.getFac().getFac().cloneThread(threadIndex);
	// The indices in each array list are presumed to be immutable.
	final ArrayList<Z> contravars = (ArrayList<Z>)( contravariantIndices.clone() );
	final ArrayList<Z> covars = (ArrayList<Z>)( covariantIndices.clone() );
	final EinsteinTensorElem<Z, R, S> ret = new EinsteinTensorElem<Z, R, S>( facs , contravars , covars );
	Iterator<ArrayList<BigInteger>> it = map.keySet().iterator();
	while( it.hasNext() )
	{
		final ArrayList<BigInteger> key = it.next();
		final R val = map.get( key );
		final R vals = val.cloneThread(threadIndex);
		final ArrayList<BigInteger> keys = (ArrayList<BigInteger>)( key.clone() );
		ret.setVal(keys, vals);
	}
	return( ret );
}
 
Example 9
Project: jentrata-msh   File: PluginRegistry.java View source code Vote up 7 votes
/**
 * Gets all extensions corresponding to the specified extension point.
 * 
 * @param point the extension point.
 * @return all extensions corresponding to the specified extension point.
 */
public Collection getAllExtensions(String point) {
    ArrayList list = new ArrayList();
    if (point != null) {
        Iterator plugins = getPlugins().iterator();
        while (plugins.hasNext()) {
            Plugin plugin = (Plugin) plugins.next();
            Collection extensions = plugin.getExtensions(point);
            list.addAll(extensions);
        }
    }
    return list;
}
 
Example 10
Project: aws-toolkit-eclipse   File: BasicEnvironmentConfigEditorPart.java View source code Vote up 7 votes
private List<HumanReadableConfigEditorSection> createEditorSections(List<ConfigurationOptionDescription> options) {

        List<HumanReadableConfigEditorSection> editorSections = new ArrayList<HumanReadableConfigEditorSection>();

        for ( Collection<String> namespaces : sectionOrder ) {
            ArrayList<ConfigurationOptionDescription> optionsInEditorSection = new ArrayList<ConfigurationOptionDescription>();
            for ( ConfigurationOptionDescription o : options ) {
                if ( namespaces.contains(o.getNamespace()) && editorSectionsByNamespace.containsKey(namespaces) ) {
                    if ( optionsInEditorSection.isEmpty() ) {
                        HumanReadableConfigEditorSection editor = editorSectionsByNamespace.get(namespaces);
                        editor.setOptions(optionsInEditorSection);
                        editorSections.add(editor);
                        editor.setParentComposite(compositesByNamespace.get(o.getNamespace()));
                    }
                    optionsInEditorSection.add(o);
                }
            }
        }

        return editorSections;
    }
 
Example 11
Project: aws-toolkit-eclipse   File: ListAttributesStatement.java View source code Vote up 7 votes
@Override
ExecutionResult execute(final String queryText, final int startingRow, final int maxRows, final int requestSize,
        final String nextToken) throws SQLException {

    super.execute(queryText, startingRow, maxRows, requestSize, nextToken);

    ArrayList<String> attrs = new ArrayList<String>(this.data.getAttributes());
    int itemNameColumn = -1;
    if (attrs.size() > 0) { // there was something in the domain
        itemNameColumn = this.data.getItemNameColumn(0);
    }

    this.data = new RawData();

    // to avoid attr order change on new value appearance, which breaks open editors' table structure
    String itemName = null;
    if (itemNameColumn >= 0) {
        itemName = attrs.remove(itemNameColumn);
    }
    Collections.sort(attrs);
    if (itemNameColumn >= 0) {
        attrs.add(itemNameColumn, itemName);
    }

    String domainName = getDomainName();
    for (int i = 0; i < attrs.size(); i++) {
        addColumnData(domainName, attrs.get(i), i == itemNameColumn, i);
    }

    // If no attributes were returned, we still want to report itemName()
    // otherwise we'll cause an error when opening the TableData editor.
    if (attrs.size() == 0) {
        addColumnData(domainName, "itemName()", true, 0);
    }

    return new ExecutionResult(null, attrs.size());
}
 
Example 12
Project: jentrata-msh   File: EbxmlMessage.java View source code Vote up 7 votes
/**
 * Checks whether the number of payloads in the SOAP message matches with
 * the Manifest element in the header or not, and return the Content-ID of
 * the inconsistent payload.
 * 
 * @return content-id of the inconsistent payload; null if all payloads are
 *         consistent.
 */
public String getPayloadInError() {
    Manifest manifest = headerContainer.getManifest();
    if (manifest == null) {
        // no manifest exist.. assume ok.
        return null;
    }
    ArrayList contentIDs = new ArrayList();
    Iterator i = getPayloadContainers();
    while (i.hasNext()) {
        PayloadContainer pc = (PayloadContainer) i.next();
        contentIDs.add(pc.getContentId());
    }

    i = manifest.getReferences();
    while (i.hasNext()) {
        Reference r = (Reference) i.next();
        String cid = r.getHref();
        if (cid.startsWith("cid:")) {
            cid = cid.substring(4);
        }
        if (!contentIDs.contains(cid)) {
            return cid;
        }
    }

    return null;
}
 
Example 13
Project: easyfpga-sdk-java   File: IDGenerator.java View source code Vote up 7 votes
@Override
public synchronized String toString() {
    ArrayList<Integer> freeIDs = new ArrayList<Integer>();
    for (int i = 1; i < 255; i++) {
        freeIDs.add(i);
    }
    freeIDs.removeAll(idQueue);

    return "IDs taken:" + freeIDs.toString();
}
 
Example 14
Project: e4rover   File: Players.java View source code Vote up 7 votes
public List<IPlayer> getTopPlayers(int howMany) {
	if (howMany < 0)
		throw new IllegalArgumentException("Asking for " + howMany + " top players is invalid.");
	ArrayList<IPlayer> players = new ArrayList<IPlayer>(playerMap.values());
	Collections.sort(players);
	if (howMany == 0)
		howMany = players.size();
	howMany = Math.min(players.size(), howMany);
	
	return players.subList(0, howMany);
}
 
Example 15
Project: ExcusePro   File: AuthorizationClient.java View source code Vote up 7 votes
void getTokenCompleted(AuthorizationRequest request, Bundle result) {
    getTokenClient = null;

    notifyBackgroundProcessingStop();

    if (result != null) {
        ArrayList<String> currentPermissions = result.getStringArrayList(NativeProtocol.EXTRA_PERMISSIONS);
        List<String> permissions = request.getPermissions();
        if ((currentPermissions != null) &&
                ((permissions == null) || currentPermissions.containsAll(permissions))) {
            // We got all the permissions we needed, so we can complete the auth now.
            AccessToken token = AccessToken
                    .createFromNativeLogin(result, AccessTokenSource.FACEBOOK_APPLICATION_SERVICE);
            Result outcome = Result.createTokenResult(token);
            completeAndValidate(outcome);
            return;
        }

        // We didn't get all the permissions we wanted, so update the request with just the permissions
        // we still need.
        ArrayList<String> newPermissions = new ArrayList<String>();
        for (String permission : permissions) {
            if (!currentPermissions.contains(permission)) {
                newPermissions.add(permission);
            }
        }
        request.setPermissions(newPermissions);
    }

    tryNextHandler();
}
 
Example 16
Project: Desktop   File: FormatTranslation.java View source code Vote up 7 votes
private int process(File[] inputFiles, boolean checkOnly) {
	try {
		int countFormattingRequired = 0;
		for (int i = 0; i < inputFiles.length; i++) {
			File inputFile = inputFiles[i];
			log("processing " + inputFile + "...", Project.MSG_DEBUG);
			final String input = TaskUtils.readFile(inputFile);
			final ArrayList<String> lines = new ArrayList<String>(2048);
			boolean eolStyleMatches = TaskUtils.checkEolStyleAndReadLines(input, lines, lineSeparator);
			final ArrayList<String> sortedLines = processLines(inputFile.getName(), new ArrayList<String>(lines));
			final boolean contentChanged = !lines.equals(sortedLines);
			final boolean formattingRequired = !eolStyleMatches || contentChanged;
			if (formattingRequired) {
				++countFormattingRequired;
				if (checkOnly)
					warn(inputFile + " requires formatting - " + formatCause(contentChanged, eolStyleMatches));
				else
					log(inputFile + "formatted - " + formatCause(contentChanged, eolStyleMatches),
					    Project.MSG_DEBUG);
			}
			if (!checkOnly && (formattingRequired || writeIfUnchanged)) {
				File outputFile;
				if (outputDir != null)
					outputFile = new File(outputDir, inputFile.getName());
				else
					outputFile = inputFile;
				TaskUtils.writeFile(outputFile, sortedLines, lineSeparator);
			}
		}
		return countFormattingRequired;
	}
	catch (IOException e) {
		throw new BuildException(e);
	}
}
 
Example 17
Project: property-db   File: FocusFinder.java View source code Vote up 7 votes
private static View getNextFocusable(View focused, ArrayList<View> focusables, int count) {
    if (focused != null) {
        int position = focusables.lastIndexOf(focused);
        if (position >= 0 && position + 1 < count) {
            return focusables.get(position + 1);
        }
    }
    if (!focusables.isEmpty()) {
        return focusables.get(0);
    }
    return null;
}
 
Example 18
Project: eGov   File: SearchEstimateAction.java View source code Vote up 7 votes
public List<String> getEstimateActions() {
    String actions = "";
    final List<Role> copyEstActionRoles = new ArrayList<Role>();
    boolean allowCopyEst = false;
    List<String> actionList = new ArrayList<String>();
    String copyEstActionName;

    actions = worksService.getWorksConfigValue("ESTIMATES_SEARCH_ACTIONS");
    if (actions != null) {
        actionList = new ArrayList(Arrays.asList(actions.split(",")));
        copyEstActionName = actionList.get(actionList.size() - 1);

        // get the roles for the Copy Estimate action
        final org.egov.infra.admin.master.entity.Action copyEstaction = actionService.getActionByName(copyEstActionName);
        copyEstActionRoles.addAll(copyEstaction.getRoles());

        // check if the userroles contains the copy estimate action roles
        for (final Role copyEstrole : copyEstActionRoles)
            if (roles.contains(copyEstrole)) {
                allowCopyEst = true;
                break;
            }

        // To remove the last element(ie.Copy Estimate) from action list
        if (!allowCopyEst) {
            final List<String> tempActionList = new ArrayList<String>();
            for (final String action : actionList)
                if (!action.equals(copyEstActionName))
                    tempActionList.add(action);
            actionList.retainAll(tempActionList);
        }
    }

    return actionList;
}
 
Example 19
Project: gs-collections   File: ArrayListIterate.java View source code Vote up 7 votes
/**
 * @see Iterate#removeIf(Iterable, Predicate)
 */
public static <T> boolean removeIf(ArrayList<T> list, Predicate<? super T> predicate)
{
    boolean changed;
    if (list.getClass() == ArrayList.class && ArrayListIterate.SIZE_FIELD != null)
    {
        int currentFilledIndex = 0;
        int size = list.size();
        T[] elements = ArrayListIterate.getInternalArray(list);
        for (int i = 0; i < size; i++)
        {
            if (!predicate.accept(elements[i]))
            {
                // keep it
                if (currentFilledIndex != i)
                {
                    elements[currentFilledIndex] = elements[i];
                }
                currentFilledIndex++;
            }
        }
        changed = currentFilledIndex < size;
        ArrayListIterate.wipeAndResetTheEnd(currentFilledIndex, size, elements, list);
    }
    else
    {
        return RandomAccessListIterate.removeIf(list, predicate);
    }
    return changed;
}
 
Example 20
Project: thundernetwork   File: MySQLConnection.java View source code Vote up 7 votes
/**
 * Gets the payments for updating channel ordered.
 *
 * @param conn      the conn
 * @param channelId the channel id
 * @param amount    the amount
 * @return the payments for updating channel ordered
 * @throws SQLException the SQL exception
 */
public static ArrayList<Payment> getPaymentsForUpdatingChannelOrdered (Connection conn, int channelId, int amount) throws SQLException {
    if (amount == 0) {
        return new ArrayList<Payment>();
    }
    ArrayList<Payment> paymentList = MySQLConnection.getPaymentsIncludedInChannelWithNoSecret(conn, channelId);
    if (amount == paymentList.size()) {
        return paymentList;
    }
    System.out.println(amount + " - " + paymentList.size());
    ArrayList<Payment> addPayments = MySQLConnection.getPaymentsIncludedInChannelWithPaymentsNotAddedYet(conn, channelId, (amount - paymentList.size()));
    paymentList.addAll(addPayments);

    paymentList.sort(new Comparator<Payment>() {
        public int compare (Payment arg0, Payment arg1) {
            return arg0.getId() - arg1.getId();
        }
    });
    return paymentList;

}
 
Example 21
Project: heron   File: TripleStoreImplV2.java View source code Vote up 7 votes
/**
 * Fetches all [email protected] Bundle bundles} related to the given search keys (SHA-256 hashes),
 * including bundles having the same [email protected] IdentifierNode} as those containing the keys
 * (typically [email protected] Bundles} containing additional metadata related to PGP signatures)
 *
 * @param searchKeys the SHA-256 hashes of the keys to search for
 * @return the bundles found
 */
@Override
public List<Bundle> findByHash(List<byte[]> searchKeys) {
    Transaction txn = environment.beginTransaction(null, null);
    ArrayList<SecondaryCursor> cursors = new ArrayList<>();
    DatabaseEntry foundData = new DatabaseEntry();
    try {
        // get a cursor for each search key and check if any data is found
        OperationStatus operationStatus = OperationStatus.NOTFOUND;
        for (byte[] searchKey : searchKeys) {
            // open a cursor for each key
            SecondaryCursor ngramIndexCursor = stringObjectNgramIndex.openCursor(txn, null);
            cursors.add(ngramIndexCursor);
            operationStatus = ngramIndexCursor.getSearchKey(new DatabaseEntry(searchKey), foundData, LockMode.DEFAULT);
            logger.debug("Operation status={}", operationStatus);
            if (!OperationStatus.SUCCESS.equals(operationStatus)) {
                break; // forget it, a key was not found. No use going further
            }
        }
        // was anything found?
        if (OperationStatus.SUCCESS.equals(operationStatus)) {
            List<Bundle> foundBundles = new ArrayList<>();
            try (JoinCursor join = bundleStore.join(cursors.toArray(new SecondaryCursor[cursors.size()]), null)) {
                DatabaseEntry key = new DatabaseEntry();
                while (join.getNext(key, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
                    Bundle foundBundle = bundleBinding.entryToObject(foundData);
                    // this is a bundle directly related to the search keys
                    byte[] foundSubjectId = foundBundle.getSubject().getNodeId();
                    // TODO - not very efficient, we're re-fetching everything a second time
                    foundBundles.addAll(getBundlesForSubjectId(txn, foundSubjectId));
                    logger.debug("Added bundle={}", HexUtil.bytesToHex(foundBundle.getSubject().getNodeId()));
                }
            }
            return foundBundles;
        }
    } finally {
        cursors.forEach(Cursor::close);
        txn.commit();
    }
    return Collections.emptyList();
}
 
Example 22
Project: my-ministry-assistant   File: TimeEditorFragment.java View source code Vote up 6 votes
/** Insert values into database */
private boolean saveTime() {
	/** Flag to know if the literature should be inserted or deleted */
	boolean isNew = (timeId == 0) ? true : false;
	
	double totalTime = Helper.getDifference(selectedDateStart, selectedDateEnd);
	
	/** No zero or negative hours allowed */
	if(totalTime < 0) {
		Toast.makeText(getActivity(), getActivity().getApplicationContext().getString(R.string.toast_saved_problem), Toast.LENGTH_SHORT).show();
	}
	else {
		/** Values to save */
		ContentValues values = new ContentValues();
		values.put(Time.PUBLISHER_ID, publisherId);
		values.put(Time.ENTRY_TYPE_ID, entryTypeId);
		values.put(Time.DATE_START, TimeUtils.dbDateFormat.format(selectedDateStart.getTime()));
		values.put(Time.DATE_END, TimeUtils.dbDateFormat.format(selectedDateEnd.getTime()));
		values.put(Time.TIME_START, saveTimeFormat.format(selectedDateStart.getTime()));
		values.put(Time.TIME_END, saveTimeFormat.format(selectedDateEnd.getTime()));
		
		/** Let's save the info to the times table */
		database.openWritable();
		if(timeId > 0) {
			if(database.saveTime(timeId, values) == 0) {
				Toast.makeText(getActivity(), getActivity().getApplicationContext().getString(R.string.toast_saved_problem), Toast.LENGTH_SHORT).show();
				return false;
			}
		}
		else {
			timeId = (int) database.createTime(values);
			if(timeId == -1) {
				Toast.makeText(getActivity(), getActivity().getApplicationContext().getString(R.string.toast_created_problem), Toast.LENGTH_SHORT).show();
				return false;
			}
		}
		
		/** Do we need to check for two publishers for the changing of the guard? :) */
		if(!isNew && publisherId != originalPublisherId) {
			/** Run the rollover checkup on the original publisher. */
			database.processRolloverTime(originalPublisherId, originalSelectedDateStart);
		}
		
		if(originalSelectedDateStart.after(selectedDateStart))
			database.processRolloverTime(publisherId, selectedDateStart);
		else
			database.processRolloverTime(publisherId, originalSelectedDateStart);
		
		database.close();
		
		long[] householderPKIDs = new long[householderList.size()];
		int[] householderIDs = new int[householderList.size()];
		long[] placedIDs;
		
		database.openWritable();
		
		/** Loop over our householder list to save */
		for(int i = 0;i < householderList.size(); i++) {
			householderForTime = householderList.get(i);
			values = new ContentValues();
			values.put(TimeHouseholder.TIME_ID, timeId);
			values.put(TimeHouseholder.HOUSEHOLDER_ID, householderForTime.getID());
			values.put(TimeHouseholder.RETURN_VISIT, householderForTime.isCountedForReturnVisit());
			
			/** Bible Study */
			if(entryTypeId == MinistryDatabase.ID_BIBLE_STUDY)
				values.put(TimeHouseholder.STUDY, 1);
			else
				values.put(TimeHouseholder.STUDY, 0);
			
			/** Check to see if the record exists */
			if(householderForTime.getTimeHouseholderPK() == MinistryDatabase.CREATE_ID) {
				householderForTime.setTimeHouseholderPK(database.createTimeHouseholder(values));
			}
			else {
				database.saveTimeHouseholder(householderForTime.getTimeHouseholderPK(), values);
			}
			
			if(householderForTime.getNotes() != null && householderForTime.getNotes().length() > 0) {
				values = new ContentValues();
				values.put(Notes.TIME_ID, timeId);
				values.put(Notes.HOUSEHOLDER_ID, householderForTime.getID());
				values.put(Notes.NOTES, householderForTime.getNotes());
				if(householderForTime.getNotesID() == 0)
					database.createNotes(values);
				else
					database.saveNotes(householderForTime.getNotesID(), values);
			}
			
			/** We need to delete a note that existed before but has been removed. */
			if(householderForTime.getNotesID() != 0 && (householderForTime.getNotes() == null || (householderForTime.getNotes() != null && householderForTime.getNotes().length() == 0)))
				database.deleteNoteByID(householderForTime.getNotesID());
			
			householderPKIDs[i] = householderForTime.getTimeHouseholderPK();
			householderIDs[i] = householderForTime.getID();
			
			ArrayList<QuickLiterature> litList = householderList.get(i).getLit();
			if(litList == null)
				placedIDs = null;
			else {
				placedIDs = new long[litList.size()];
				for(int j = 0;j < litList.size();j++) {
					quickLit = litList.get(j);
					values = new ContentValues();
					values.put(LiteraturePlaced.TIME_ID, timeId);
					values.put(LiteraturePlaced.HOUSEHOLDER_ID, householderForTime.getID());
					values.put(LiteraturePlaced.LITERATURE_ID, quickLit.getID());
					values.put(LiteraturePlaced.PUBLISHER_ID, publisherId);
					values.put(LiteraturePlaced.DATE, TimeUtils.dbDateFormat.format(selectedDateStart.getTime()));
					values.put(LiteraturePlaced.COUNT, quickLit.getCount());

					/** Check to see if the record exists */
					quickLit.setPlacedID(database.fetchPlacedLitByTimeAndHouseholderAndLitID(timeId, householderForTime.getID(), quickLit.getID()));
					
					if(quickLit.getPlacedID() == 0) {
						quickLit.setPlacedID(database.createPlacedLiterature(values));
					}
					else {
						database.savePlacedLiterature(quickLit.getPlacedID(), values);
					}
					
					placedIDs[j] = quickLit.getPlacedID();
				}
			}
			
			if(!isNew) {
				/** Delete orphaned litPlaced records */
				database.deletePlacedLiteratureOrphans(timeId, householderForTime.getID(), placedIDs);
			} 
		}
		
		if(!isNew) {
			/** Delete orphaned timeHouseholder and records */
			database.deleteTimeHouseholderOrphans(timeId, householderPKIDs);
			/** Delete orphaned litPlaced records that aren't for the householders */
			database.deleteTimeHouseholderLiteraturePlacedOrphans(timeId, householderIDs);
			/** Delete orphaned notes records */
			database.deleteTimeHouseholderNotesOrphans(timeId, householderIDs);
		}
		
		database.close();
		
		if(isNew)
			Toast.makeText(getActivity(), getActivity().getApplicationContext().getString(R.string.toast_created), Toast.LENGTH_SHORT).show();
		else
			Toast.makeText(getActivity(), getActivity().getApplicationContext().getString(R.string.toast_saved), Toast.LENGTH_SHORT).show();
		
		return true;
	}
	
	return false;
}
 
Example 23
Project: ArubaSyslog   File: PPDetector.java View source code Vote up 6 votes
public static ArrayList<APRecord> RemovePP(ArrayList<String> tmp_ap_list,
		ArrayList<Long> tmp_start_times, ArrayList<Long> tmp_durations, ArrayList<Boolean> tmp_flags)
/*
 *  The core algorithm of filtering the Ping-Pong-Effect data points
 */
{
	
	System.out.println("len: " + tmp_ap_list.size());
	
	ArrayList<APRecord> filtered_records = new ArrayList<APRecord>();
	int ap_count = tmp_durations.size();
	if ( ap_count >= 3) {
		// Calculating the Ping-pong-effect measure matrix
		int m = ap_count-2;
		int n = ap_count-2;
		DataPoint[][] ppe_measure_matrix = new DataPoint[m][n];
		for ( int i = 0; i < m; i++)
			for ( int j =0; j < n; j++)
				ppe_measure_matrix[i][j] = calculate_ppe_measure(tmp_ap_list, j, i+3);
		
		if (DebugFlag.debug) {
			// Print out the measure matrix
			System.out.println("\nPPE measure matrix:");
			DecimalFormat format = new DecimalFormat("0.000");
			for ( int i = 0; i < m; i++) {
				for ( int j =0; j < n; j++)
					System.out.print(format.format(ppe_measure_matrix[i][j].measure()) + "\t");
				System.out.println();
			}
		}
		
		// Find the Ping-pong segments
		List<DataPoint> ppps = find_pp_points(ppe_measure_matrix);
		
		if ( DebugFlag.debug)
			System.out.println("\nindex(0,0)\tstart_index(0:)\tmask_length(1:)\tscore");
		
		for ( DataPoint dp : ppps ){
			
			if ( DebugFlag.debug)
				System.out.println("("+dp.i+","+dp.j+")"+"\t"+dp.start_index()+"\t"+dp.mask_length()+"\t"+dp.measure());
			
			String fap_name = "";
			Set<String> fap_name_set = new HashSet<String>();
			long fap_start_time = -1;
			long fap_duration = 0;
			for ( int i=dp.start_index(); i<=dp.stop_index(); i++) {
				// NOTE: we accumulate the durations from start to stop and without the
				// stop, to avoid the repeated addition of the item when two segments
				// have the covered number (==1)
				fap_name_set.add(tmp_ap_list.get(i));
				if ( fap_start_time == -1 && tmp_flags.get(i).booleanValue() == true )
					fap_start_time = tmp_start_times.get(i);
				if ( tmp_flags.get(i).booleanValue() == true){	
					fap_duration += tmp_durations.get(i);
					tmp_flags.set(i, false);
				}
				
			}
			for ( String s : fap_name_set) {
				if ( fap_name.equals(""))
					fap_name += s;
				else
					fap_name += (","+s);
			}
			filtered_records.add(new APRecord(fap_name, fap_start_time, fap_duration));
		}
	}
	// Add the left records which are not contained by the ping-pong segments
	for ( int j=0; j<tmp_flags.size(); j++)
		if ( tmp_flags.get(j) )
			filtered_records.add(new APRecord(tmp_ap_list.get(j), tmp_start_times.get(j), tmp_durations.get(j)));
	// Order the records by start_time
	Collections.sort(filtered_records,new Comparator<APRecord>(){
           public int compare(APRecord arg0, APRecord arg1) {
               return new Long(arg0.start_time).compareTo(new Long(arg1.start_time));   
            }   
        });  
	return filtered_records;
}
 
Example 24
Project: NewsSpeakServer   File: ParserUtils.java View source code Vote up 6 votes
/**
 * Split the input string considering as string separator
 * all the not numerical characters
 * with the only exception of the characters specified in charsDoNotBeRemoved param.
 * <BR>For example if you call splitButDigits(&quot;&lt;DIV&gt;  +12.5, +3.4 &lt;/DIV&gt;&quot;, &quot;+.&quot;),
 * <BR>you obtain an array of strings {&quot;+12.5&quot;, &quot;+3.4&quot;} as output (1,2,3,4 and 5 are digits and +,. are chars that do not be removed).
 * @param input The string in input.
 * @param charsDoNotBeRemoved The chars that do not be removed.
 * @return The array of strings as output.
*/
public static String[] splitButDigits (String input, String charsDoNotBeRemoved)
{
 	
    ArrayList output = new ArrayList();
    int minCapacity = 0;
    StringBuffer str = new StringBuffer();

    boolean charFound = false;
    boolean toBeAdd = false;
    for (int index=0; index<input.length(); index++)
    {    
        charFound=false;
        for (int charsCount=0; charsCount<charsDoNotBeRemoved.length(); charsCount++)
            if (charsDoNotBeRemoved.charAt(charsCount)==input.charAt(index))
                charFound=true;
        if ((Character.isDigit(input.charAt(index))) || (charFound))
        {
            str.append(input.charAt(index));
            toBeAdd=false;
        }
        else
            if (!toBeAdd)
                toBeAdd=true;
        // finished to parse one string
        if (toBeAdd && (str.length()!=0)) {
            minCapacity++;
            output.ensureCapacity(minCapacity);
            if (output.add(str.toString()))
                str = new StringBuffer();
            else
                minCapacity--;
        }
    }
    // add the last string
    if (str.length()!=0) {
        minCapacity++;
        output.ensureCapacity(minCapacity);
        if (output.add(str.toString()))
            str = new StringBuffer();
        else
            minCapacity--;
    }

    output.trimToSize();
    Object[] outputObj = output.toArray();
    String[] outputStr = new String[output.size()];
    for (int i=0; i<output.size(); i++)
        outputStr[i] = new String((String) outputObj[i]);
    return outputStr;
    
}