Example usage for java.util TreeSet add

List of usage examples for java.util TreeSet add

Introduction

In this page you can find the example usage for java.util TreeSet add.

Prototype

public boolean add(E e) 

Source Link

Document

Adds the specified element to this set if it is not already present.

Usage

From source file:com.apelon.akcds.loinc.LoincToEConcepts.java

private void processDataLine(String[] fields) throws ParseException, IOException, TerminologyException {
    Integer index = fieldMap_.get("DT_LAST_CH");
    if (index == null) {
        index = fieldMap_.get("DATE_LAST_CHANGED"); // They changed this in 2.38 release
    }//ww w  .j av  a 2  s. c om
    String lastChanged = fields[index];
    long time = (StringUtils.isBlank(lastChanged) ? conceptUtility_.defaultTime_
            : sdf_.parse(lastChanged).getTime());

    UUID statusUUID = mapStatus(fields[fieldMap_.get("STATUS")]);

    String code = fields[fieldMap_.get("LOINC_NUM")];

    EConcept concept = conceptUtility_.createConcept(buildUUID(code), time, statusUUID);
    ArrayList<ValuePropertyPair> descriptions = new ArrayList<>();

    for (int fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) {
        if (fields[fieldIndex] != null && fields[fieldIndex].length() > 0) {
            PropertyType pt = propertyToPropertyType_.get(fieldMapInverse_.get(fieldIndex));
            if (pt == null) {
                ConsoleUtil.printErrorln("ERROR: No property type mapping for the property "
                        + fieldMapInverse_.get(fieldIndex) + ":" + fields[fieldIndex]);
                continue;
            }

            Property p = pt.getProperty(fieldMapInverse_.get(fieldIndex));

            if (pt instanceof PT_Annotations) {
                if ((p.getSourcePropertyNameFSN().equals("COMMON_TEST_RANK")
                        || p.getSourcePropertyNameFSN().equals("COMMON_ORDER_RANK")
                        || p.getSourcePropertyNameFSN().equals("COMMON_SI_TEST_RANK"))
                        && fields[fieldIndex].equals("0")) {
                    continue; //Skip attributes of these types when the value is 0
                } else if (p.getSourcePropertyNameFSN().equals("RELATEDNAMES2")
                        || p.getSourcePropertyNameFSN().equals("RELAT_NMS")) {
                    String[] values = fields[fieldIndex].split(";");
                    TreeSet<String> uniqueValues = new TreeSet<>();
                    for (String s : values) {
                        s = s.trim();
                        if (s.length() > 0) {
                            uniqueValues.add(s);
                        }
                    }
                    for (String s : uniqueValues) {
                        conceptUtility_.addStringAnnotation(concept, s, p.getUUID(), p.isDisabled());
                    }
                } else {
                    conceptUtility_.addStringAnnotation(concept, fields[fieldIndex], p.getUUID(),
                            p.isDisabled());
                }
            } else if (pt instanceof PT_Descriptions) {
                //Gather for later
                descriptions.add(new ValuePropertyPair(fields[fieldIndex], p));
            } else if (pt instanceof PT_IDs) {
                conceptUtility_.addAdditionalIds(concept, fields[fieldIndex], p.getUUID(), p.isDisabled());
            } else if (pt instanceof PT_SkipAxis) {
                // See if this class object exists yet.
                UUID potential = ConverterUUID
                        .createNamespaceUUIDFromString(pt_SkipAxis_.getPropertyTypeDescription() + ":"
                                + fieldMapInverse_.get(fieldIndex) + ":" + fields[fieldIndex], true);

                EConcept axisConcept = concepts_.get(potential);
                if (axisConcept == null) {
                    axisConcept = conceptUtility_.createConcept(potential, fields[fieldIndex]);
                    conceptUtility_.addRelationship(axisConcept,
                            pt_SkipAxis_.getProperty(fieldMapInverse_.get(fieldIndex)).getUUID());
                    concepts_.put(axisConcept.primordialUuid, axisConcept);
                }
                // We changed these from attributes to relations
                // conceptUtility_.addAnnotation(concept, axisConcept, pt_SkipAxis_.getPropertyUUID(fieldMapInverse_.get(fieldIndex)));
                String relTypeName = "Has_" + fieldMapInverse_.get(fieldIndex);
                PropertyType relType = propertyToPropertyType_.get(relTypeName);
                conceptUtility_.addRelationship(concept, axisConcept.getPrimordialUuid(),
                        relType.getProperty(relTypeName).getUUID(), null);
            } else if (pt instanceof PT_SkipClass) {
                // See if this class object exists yet.
                UUID potential = ConverterUUID
                        .createNamespaceUUIDFromString(pt_SkipClass_.getPropertyTypeDescription() + ":"
                                + fieldMapInverse_.get(fieldIndex) + ":" + fields[fieldIndex], true);

                EConcept classConcept = concepts_.get(potential);
                if (classConcept == null) {
                    classConcept = conceptUtility_.createConcept(potential,
                            classMapping_.getMatchValue(fields[fieldIndex]));
                    if (classMapping_.hasMatch(fields[fieldIndex])) {
                        conceptUtility_
                                .addAdditionalIds(
                                        classConcept, fields[fieldIndex], propertyToPropertyType_
                                                .get("ABBREVIATION").getProperty("ABBREVIATION").getUUID(),
                                        false);
                    }
                    conceptUtility_.addRelationship(classConcept,
                            pt_SkipClass_.getProperty(fieldMapInverse_.get(fieldIndex)).getUUID());
                    concepts_.put(classConcept.primordialUuid, classConcept);
                }
                // We changed these from attributes to relations
                // conceptUtility_.addAnnotation(concept, classConcept, pt_SkipClass_.getPropertyUUID(fieldMapInverse_.get(fieldIndex)));
                String relTypeName = "Has_" + fieldMapInverse_.get(fieldIndex);
                PropertyType relType = propertyToPropertyType_.get(relTypeName);
                conceptUtility_.addRelationship(concept, classConcept.getPrimordialUuid(),
                        relType.getProperty(relTypeName).getUUID(), null);
            } else if (pt instanceof PT_Relations) {
                conceptUtility_.addRelationship(concept, buildUUID(fields[fieldIndex]),
                        pt.getProperty(fieldMapInverse_.get(fieldIndex)), null);
            } else if (pt instanceof PT_SkipOther) {
                conceptUtility_.getLoadStats().addSkippedProperty();
            } else {
                ConsoleUtil.printErrorln("oops - unexpected property type: " + pt);
            }
        }
    }

    //MAP_TO moved to a different file in 2.42.
    HashMap<String, String> mappings = mapToData.get(code);
    if (mappings != null) {
        for (Entry<String, String> mapping : mappings.entrySet()) {
            String target = mapping.getKey();
            String comment = mapping.getValue();
            TkRelationship r = conceptUtility_.addRelationship(concept, buildUUID(target),
                    propertyToPropertyType_.get("MAP_TO").getProperty("MAP_TO"), null);
            if (comment != null && comment.length() > 0) {
                conceptUtility_.addStringAnnotation(r, comment,
                        propertyToPropertyType_.get("COMMENT").getProperty("COMMENT").getUUID(), false);
            }
        }
    }

    //Now add all the descriptions
    if (descriptions.size() == 0) {
        if ("DEL".equals(fields[fieldMap_.get("CHNG_TYPE")])) {
            //They put a bunch of these in 2.44... leaving out most of the important info... just makes a mess.  Don't load them.
            skippedDeletedItems++;
            return;
        } else {
            ConsoleUtil.printErrorln("ERROR: no name for " + code);
            conceptUtility_.addFullySpecifiedName(concept, code);
        }
    } else {
        conceptUtility_.addDescriptions(concept, descriptions);
    }

    EConcept current = concepts_.put(concept.primordialUuid, concept);
    if (current != null) {
        ConsoleUtil.printErrorln("Duplicate LOINC code (LOINC_NUM):" + code);
    }
}

From source file:net.spfbl.core.Reverse.java

public static TreeSet<String> getPointerSet(String host) throws NamingException {
    if (host == null) {
        return null;
    } else {/*from   w w  w.  ja v  a2  s. c  o  m*/
        TreeSet<String> reverseSet = new TreeSet<String>();
        if (Subnet.isValidIP(host)) {
            if (SubnetIPv4.isValidIPv4(host)) {
                host = getHostReverse(host, "in-addr.arpa");
            } else if (SubnetIPv6.isValidIPv6(host)) {
                host = getHostReverse(host, "ip6.arpa");
            }
        }
        Attributes atributes = Server.getAttributesDNS(host, new String[] { "PTR" });
        if (atributes != null) {
            Attribute attribute = atributes.get("PTR");
            if (attribute != null) {
                for (int index = 0; index < attribute.size(); index++) {
                    host = (String) attribute.get(index);
                    if (host != null) {
                        host = host.trim();
                        if (host.endsWith(".")) {
                            int endIndex = host.length() - 1;
                            host = host.substring(0, endIndex);
                        }
                        if (Domain.isHostname(host)) {
                            host = Domain.normalizeHostname(host, true);
                            reverseSet.add(host);
                        }
                    }
                }
            }
        }
        return reverseSet;
    }
}

From source file:ca.uhn.fhir.jpa.dao.dstu3.SearchParamExtractorDstu3.java

@Override
public Set<ResourceIndexedSearchParamDate> extractSearchParamDates(ResourceTable theEntity,
        IBaseResource theResource) {/*from w  w  w  .  j a  v  a2 s. c om*/
    HashSet<ResourceIndexedSearchParamDate> retVal = new HashSet<ResourceIndexedSearchParamDate>();

    RuntimeResourceDefinition def = getContext().getResourceDefinition(theResource);
    for (RuntimeSearchParam nextSpDef : def.getSearchParams()) {
        if (nextSpDef.getParamType() != RestSearchParameterTypeEnum.DATE) {
            continue;
        }

        String nextPath = nextSpDef.getPath();
        if (isBlank(nextPath)) {
            continue;
        }

        boolean multiType = false;
        if (nextPath.endsWith("[x]")) {
            multiType = true;
        }

        for (Object nextObject : extractValues(nextPath, theResource)) {
            if (nextObject == null) {
                continue;
            }

            ResourceIndexedSearchParamDate nextEntity;
            if (nextObject instanceof BaseDateTimeType) {
                BaseDateTimeType nextValue = (BaseDateTimeType) nextObject;
                if (nextValue.isEmpty()) {
                    continue;
                }
                nextEntity = new ResourceIndexedSearchParamDate(nextSpDef.getName(), nextValue.getValue(),
                        nextValue.getValue());
            } else if (nextObject instanceof Period) {
                Period nextValue = (Period) nextObject;
                if (nextValue.isEmpty()) {
                    continue;
                }
                nextEntity = new ResourceIndexedSearchParamDate(nextSpDef.getName(), nextValue.getStart(),
                        nextValue.getEnd());
            } else if (nextObject instanceof Timing) {
                Timing nextValue = (Timing) nextObject;
                if (nextValue.isEmpty()) {
                    continue;
                }
                TreeSet<Date> dates = new TreeSet<Date>();
                for (DateTimeType nextEvent : nextValue.getEvent()) {
                    if (nextEvent.getValue() != null) {
                        dates.add(nextEvent.getValue());
                    }
                }
                if (dates.isEmpty()) {
                    continue;
                }

                nextEntity = new ResourceIndexedSearchParamDate(nextSpDef.getName(), dates.first(),
                        dates.last());
            } else if (nextObject instanceof StringType) {
                // CarePlan.activitydate can be a string
                continue;
            } else {
                if (!multiType) {
                    throw new ConfigurationException("Search param " + nextSpDef.getName()
                            + " is of unexpected datatype: " + nextObject.getClass());
                } else {
                    continue;
                }
            }
            if (nextEntity != null) {
                nextEntity.setResource(theEntity);
                retVal.add(nextEntity);
            }
        }
    }

    return retVal;
}

From source file:fr.inria.oak.paxquery.common.xml.navigation.NavigationTreePattern.java

/**
 * Gets the normal form of a tree pattern.
 * @return the normal tree pattern//  w ww  .ja va  2s  . c  o  m
 */
public NavigationTreePattern getNormalizedTreePattern() {
    NavigationTreePattern normalizedTreePattern = deepCopy();

    int counter = 1;
    TreeSet<NavigationTreePatternNode> sortedSetChildrenNodes = new TreeSet<NavigationTreePatternNode>();
    int newCounter = counter + normalizedTreePattern.root.getEdges().size();
    for (NavigationTreePatternEdge edge : normalizedTreePattern.root.getEdges()) {
        newCounter = recGetNormalizedTreePattern(edge.n2, newCounter);
        sortedSetChildrenNodes.add(edge.n2);
    }

    normalizedTreePattern.root.cleanEdges();
    for (NavigationTreePatternNode node : sortedSetChildrenNodes.descendingSet()) {
        node.setNodeCode(counter);
        counter++;
        node.getParentEdge().n1.addEdge(node.getParentEdge());
    }

    return normalizedTreePattern;
}

From source file:net.dv8tion.jda.core.entities.impl.ReceivedMessage.java

@Override
public String getContentStripped() {
    if (strippedContent != null)
        return strippedContent;
    synchronized (mutex) {
        if (strippedContent != null)
            return strippedContent;
        String tmp = getContentDisplay();
        //all the formatting keys to keep track of
        String[] keys = new String[] { "*", "_", "`", "~~" };

        //find all tokens (formatting strings described above)
        TreeSet<FormatToken> tokens = new TreeSet<>(Comparator.comparingInt(t -> t.start));
        for (String key : keys) {
            Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(tmp);
            while (matcher.find())
                tokens.add(new FormatToken(key, matcher.start()));
        }//from w w  w.j av  a  2s .co m

        //iterate over all tokens, find all matching pairs, and add them to the list toRemove
        Deque<FormatToken> stack = new ArrayDeque<>();
        List<FormatToken> toRemove = new ArrayList<>();
        boolean inBlock = false;
        for (FormatToken token : tokens) {
            if (stack.isEmpty() || !stack.peek().format.equals(token.format)
                    || stack.peek().start + token.format.length() == token.start)

            {
                //we are at opening tag
                if (!inBlock) {
                    //we are outside of block -> handle normally
                    if (token.format.equals("`")) {
                        //block start... invalidate all previous tags
                        stack.clear();
                        inBlock = true;
                    }
                    stack.push(token);
                } else if (token.format.equals("`")) {
                    //we are inside of a block -> handle only block tag
                    stack.push(token);
                }
            } else if (!stack.isEmpty()) {
                //we found a matching close-tag
                toRemove.add(stack.pop());
                toRemove.add(token);
                if (token.format.equals("`") && stack.isEmpty())
                    //close tag closed the block
                    inBlock = false;
            }
        }

        //sort tags to remove by their start-index and iteratively build the remaining string
        toRemove.sort(Comparator.comparingInt(t -> t.start));
        StringBuilder out = new StringBuilder();
        int currIndex = 0;
        for (FormatToken formatToken : toRemove) {
            if (currIndex < formatToken.start)
                out.append(tmp.substring(currIndex, formatToken.start));
            currIndex = formatToken.start + formatToken.format.length();
        }
        if (currIndex < tmp.length())
            out.append(tmp.substring(currIndex));
        //return the stripped text, escape all remaining formatting characters (did not have matching
        // open/close before or were left/right of block
        return strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~");
    }
}

From source file:com.limewoodmedia.nsdroid.activities.Nation.java

private void doGovernmentSetup() {
    governmentTitle.setText(getString(R.string.nation_government_title, Utils.capitalize(data.demonym)));
    // Government size and percent
    double gov = 0;
    if (data.sectors.containsKey(IndustrySector.GOVERNMENT)) {
        gov = data.sectors.get(IndustrySector.GOVERNMENT);
    }/*  w w w .  jav a 2s.  com*/
    governmentSize.setText(getString(R.string.nation_government_size,
            Utils.formatCurrencyAmount(this, Math.round(data.gdp * (gov / 100d))), data.currency));
    governmentPercent.setText(getString(R.string.nation_government_percent, String.format("%.1f", gov)));
    governmentSeries.clear();
    governmentRenderer.removeAllRenderers();
    Set<Map.Entry<Department, Float>> depts = data.governmentBudget.entrySet();
    TreeSet<Map.Entry<IDescriptable, Float>> departments = new TreeSet<>();
    for (Map.Entry<Department, Float> d : depts) {
        departments.add(new DescriptionMapEntry(d));
    }
    NumberFormat format = NumberFormat.getPercentInstance();
    format.setMaximumFractionDigits(1);
    Map<IDescriptable, String> legends = new HashMap<>();
    StringBuilder legend;
    String desc;
    int colour;
    for (Map.Entry<IDescriptable, Float> d : departments) {
        if (d.getValue() == 0)
            continue;
        desc = d.getKey().getDescription();
        governmentSeries.add(desc, d.getValue() / 100f);
        SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
        colour = CHART_COLOURS[(governmentSeries.getItemCount() - 1) % CHART_COLOURS.length];
        renderer.setColor(colour);
        renderer.setChartValuesFormat(format);
        governmentRenderer.addSeriesRenderer(renderer);
        legend = new StringBuilder();
        legend.append("<b><font color='").append(Integer.toString(colour)).append("'>").append(desc);
        legends.put(d.getKey(), legend.toString());
    }
    governmentChart.repaint();

    // Legend
    legend = new StringBuilder();
    for (Department dep : Department.values()) {
        if (legend.length() > 0) {
            legend.append("<br/>");
        }
        if (legends.containsKey(dep)) {
            legend.append(legends.get(dep)).append(": ").append(Float.toString(data.governmentBudget.get(dep)))
                    .append("%</font></b>");
        } else {
            legend.append("<font color='grey'>").append(dep.getDescription()).append(": ").append("0%</font>");
        }
    }
    governmentLegend.setText(Html.fromHtml(legend.toString()), TextView.BufferType.SPANNABLE);
}

From source file:com.limewoodmedia.nsdroid.activities.Nation.java

private void doEconomySetup() {
    economyTitle.setText(getString(R.string.nation_economy_title, Utils.capitalize(data.demonym)));
    // GDP, GDPPC, Poorest and Richest
    economyGDP.setText(//  w  w w  .  j a  v  a  2s .c  om
            getString(R.string.nation_economy_gdp, Utils.formatCurrencyAmount(this, data.gdp), data.currency));
    economyGDPPC.setText(getString(R.string.nation_economy_gdppc,
            Utils.formatCurrencyAmount(this, Math.round(data.gdp / (data.population * 1000000f))),
            data.currency));
    economyPoorest.setText(getString(R.string.nation_economy_poorest,
            Utils.formatCurrencyAmount(this, data.poorest), data.currency));
    economyRichest.setText(getString(R.string.nation_economy_richest,
            Utils.formatCurrencyAmount(this, data.richest), data.currency));

    economySeries.clear();
    economyRenderer.removeAllRenderers();
    Set<Map.Entry<IndustrySector, Float>> secs = data.sectors.entrySet();
    TreeSet<Map.Entry<IDescriptable, Float>> sectors = new TreeSet<>();
    for (Map.Entry<IndustrySector, Float> d : secs) {
        sectors.add(new DescriptionMapEntry(d, false));
    }
    NumberFormat format = NumberFormat.getPercentInstance();
    format.setMaximumFractionDigits(1);

    Map<IDescriptable, String> legends = new HashMap<>();
    StringBuilder legend;
    String desc;
    int colour;
    for (Map.Entry<IDescriptable, Float> s : sectors) {
        if (s.getValue() == 0)
            continue;
        desc = s.getKey().getDescription();
        economySeries.add(desc, s.getValue() / 100f);
        SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
        colour = CHART_COLOURS[(economySeries.getItemCount() - 1) % CHART_COLOURS.length];
        renderer.setColor(colour);
        renderer.setChartValuesFormat(format);
        economyRenderer.addSeriesRenderer(renderer);
        legend = new StringBuilder();
        legend.append("<b><font color='").append(Integer.toString(colour)).append("'>").append(desc);
        legends.put(s.getKey(), legend.toString());
    }
    economyChart.repaint();

    // Legend
    legend = new StringBuilder();
    for (IndustrySector sector : IndustrySector.values()) {
        if (legend.length() > 0) {
            legend.append("<br/>");
        }
        if (legends.containsKey(sector)) {
            legend.append(legends.get(sector)).append(": ").append(Float.toString(data.sectors.get(sector)))
                    .append("%</font></b>");
        } else {
            legend.append("<font color='grey'>").append(sector.getDescription()).append(": ")
                    .append("0%</font>");
        }
    }
    economyLegend.setText(Html.fromHtml(legend.toString()), TextView.BufferType.SPANNABLE);
}

From source file:es.uma.lcc.tasks.EncryptionUploaderTask.java

@Override
public String doInBackground(Void... voids) {

    String dst = null;/*from w  w  w  . ja  v  a2 s  . c  om*/
    String filename = mSrc.substring(mSrc.lastIndexOf("/") + 1, mSrc.lastIndexOf("."));

    ArrayList<Rectangle> rects = new ArrayList<Rectangle>();
    for (String s : mRectangles)
        rects.add(new Rectangle(s));

    mSquareNum = rects.size();
    mHorizStarts = new int[mSquareNum];
    mHorizEnds = new int[mSquareNum];
    mVertStarts = new int[mSquareNum];
    mVertEnds = new int[mSquareNum];
    mKeys = new String[mSquareNum];
    for (int i = 0; i < mSquareNum; i++) {
        mHorizStarts[i] = rects.get(i).x0 / 16;
        mHorizEnds[i] = rects.get(i).xEnd / 16;
        mVertStarts[i] = rects.get(i).y0 / 16;
        mVertEnds[i] = rects.get(i).yEnd / 16;
    }

    mNewId = null;
    boolean permissionToSelf = false;
    JSONArray permissions = new JSONArray();
    try {
        JSONObject obj = new JSONObject();
        JSONArray usernames;
        obj.put(JSON_PROTOCOLVERSION, CURRENT_VERSION);
        obj.put(JSON_FILENAME, filename);
        obj.put(JSON_IMGHEIGHT, mHeight);
        obj.put(JSON_IMGWIDTH, mWidth);
        permissions.put(obj);

        for (int i = 0; i < mSquareNum; i++) {
            TreeSet<String> auxSet = new TreeSet<String>();
            // helps in checking a permission is not granted twice
            obj = new JSONObject();
            obj.put(JSON_HSTART, mHorizStarts[i]);
            obj.put(JSON_HEND, mHorizEnds[i]);
            obj.put(JSON_VSTART, mVertStarts[i]);
            obj.put(JSON_VEND, mVertEnds[i]);
            usernames = new JSONArray();
            usernames.put(mMainActivity.getUserEmail().toLowerCase(Locale.ENGLISH));
            auxSet.add(mMainActivity.getUserEmail().toLowerCase(Locale.ENGLISH));
            for (String str : rects.get(i).getPermissionsArrayList()) {
                if (!auxSet.contains(str.toLowerCase(Locale.ENGLISH))) {
                    usernames.put(str.toLowerCase(Locale.ENGLISH));
                    auxSet.add(str.toLowerCase(Locale.ENGLISH));
                } else if (str.equalsIgnoreCase(mMainActivity.getUserEmail()))
                    permissionToSelf = true;
            }
            obj.put(JSON_USERNAME, usernames);
            permissions.put(obj);
        }
    } catch (JSONException jsonex) {
        // Will never happen: every value is either a number, or a correctly formatted email
    }
    if (permissionToSelf) {
        publishProgress(5);
    }
    DefaultHttpClient httpclient = new DefaultHttpClient();
    final HttpParams params = new BasicHttpParams();
    HttpClientParams.setRedirecting(params, false);
    httpclient.setParams(params);
    String target = SERVERURL + "?" + QUERYSTRING_ACTION + "=" + ACTION_ONESTEPUPLOAD;
    HttpPost httppost = new HttpPost(target);

    while (mCookie == null) { // loop until authentication finishes, if necessary
        mCookie = mMainActivity.getCurrentCookie();
    }

    try {
        StringEntity permissionsEntity = new StringEntity(permissions.toString());
        permissionsEntity.setContentType(new BasicHeader("Content-Type", "application/json"));
        httppost.setEntity(permissionsEntity);

        httppost.setHeader("Cookie", mCookie.getName() + "=" + mMainActivity.getCurrentCookie().getValue());
        System.out.println("Cookie in header: " + mMainActivity.getCurrentCookie().getValue());

        HttpResponse response = httpclient.execute(httppost);

        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) {
            mConnectionSucceeded = false;
            throw new IOException("Invalid response from server: " + status.toString());
        }

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = entity.getContent();
            ByteArrayOutputStream content = new ByteArrayOutputStream();

            // Read response into a buffered stream
            int readBytes = 0;
            byte[] sBuffer = new byte[256];
            while ((readBytes = inputStream.read(sBuffer)) != -1) {
                content.write(sBuffer, 0, readBytes);
            }
            String result = new String(content.toByteArray());

            try {
                JSONArray jsonArray = new JSONArray(result);
                if (jsonArray.length() == 0) {
                    // should never happen
                    Log.e(APP_TAG, LOG_ERROR + ": Malformed response from server");
                    mConnectionSucceeded = false;
                } else {
                    // Elements in a JSONArray keep their order
                    JSONObject successState = jsonArray.getJSONObject(0);
                    if (successState.get(JSON_RESULT).equals(JSON_RESULT_ERROR)) {
                        if (successState.getBoolean(JSON_ISAUTHERROR) && mIsFirstRun) {
                            mIsAuthError = true;
                            Log.e(APP_TAG, LOG_ERROR + ": Server found an auth error: "
                                    + successState.get(JSON_REASON));
                        } else {
                            mConnectionSucceeded = false;
                            Log.e(APP_TAG,
                                    LOG_ERROR + ": Server found an error: " + successState.get("reason"));
                        }
                    } else { // everything went OK
                        mNewId = jsonArray.getJSONObject(1).getString(JSON_PICTUREID);
                        for (int i = 0; i < mSquareNum; i++) {
                            mKeys[i] = jsonArray.getJSONObject(i + 2).getString(JSON_KEY);
                        }
                        if (mNewId == null) {
                            mConnectionSucceeded = false;
                            Log.e(APP_TAG, "Encryption: Error connecting to server");
                        } else {
                            publishProgress(10);
                            String date = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(new Date());

                            File directory = new File(
                                    Environment.getExternalStorageDirectory() + "/" + APP_TAG);
                            if (!directory.exists()) {
                                directory.mkdir();
                            }

                            dst = Environment.getExternalStorageDirectory() + "/" + APP_TAG + "/"
                                    + ENCRYPTED_FILE_PREFIX + filename + "_" + date + ".jpg";

                            mSuccess = MainActivity.encodeWrapperRegions(mSrc, dst, mSquareNum, mHorizStarts,
                                    mHorizEnds, mVertStarts, mVertEnds, mKeys, mNewId);

                            addToGallery(dst);
                        }
                    }
                }
            } catch (JSONException jsonEx) {
                mConnectionSucceeded = false;
                Log.e(APP_TAG, LOG_ERROR + ": Malformed JSON response from server");
            }
        }
    } catch (ClientProtocolException e) {
        mConnectionSucceeded = false;
    } catch (IOException e) {
        mConnectionSucceeded = false;
    }
    return dst;
}

From source file:info.magnolia.cms.core.NodeTest.java

@Test
public void testNameFilteringWorksForBothBinaryAndNonBinaryProperties() throws Exception {
    String contentProperties = StringUtils.join(Arrays.asList("/somepage/mypage.@type=mgnl:content",
            "/somepage/mypage/paragraphs.@type=mgnl:contentNode",
            "/somepage/mypage/paragraphs/0.@type=mgnl:contentNode",
            "/somepage/mypage/paragraphs/0.@type=mgnl:contentNode",

            // 2 regular props
            "/somepage/mypage/paragraphs/0.attention=booyah",
            "/somepage/mypage/paragraphs/0.imaginary=date:2009-10-14T08:59:01.227-04:00",

            // 3 binaries
            "/somepage/mypage/paragraphs/0/attachment1.@type=mgnl:resource",
            "/somepage/mypage/paragraphs/0/attachment1.fileName=hello",
            "/somepage/mypage/paragraphs/0/attachment1.extension=gif",
            // being a binary node, magnolia knows to store data as jcr:data w/o need to be explicitly told so
            "/somepage/mypage/paragraphs/0/attachment1.jcr\\:data=binary:X",
            "/somepage/mypage/paragraphs/0/attachment1.jcr\\:mimeType=image/gif",
            "/somepage/mypage/paragraphs/0/attachment1.jcr\\:lastModified=date:2009-10-14T08:59:01.227-04:00",

            "/somepage/mypage/paragraphs/0/attachment2.@type=mgnl:resource",
            "/somepage/mypage/paragraphs/0/attachment2.fileName=test",
            "/somepage/mypage/paragraphs/0/attachment2.extension=jpeg",
            "/somepage/mypage/paragraphs/0/attachment2.jcr\\:data=binary:X",
            "/somepage/mypage/paragraphs/0/attachment2.jcr\\:mimeType=image/jpeg",
            "/somepage/mypage/paragraphs/0/attachment2.jcr\\:lastModified=date:2009-10-14T08:59:01.227-04:00",

            "/somepage/mypage/paragraphs/0/image3.@type=mgnl:resource",
            "/somepage/mypage/paragraphs/0/image3.fileName=third",
            "/somepage/mypage/paragraphs/0/image3.extension=png",
            "/somepage/mypage/paragraphs/0/image3.jcr\\:data=binary:X",
            "/somepage/mypage/paragraphs/0/image3.jcr\\:mimeType=image/png",
            "/somepage/mypage/paragraphs/0/image3.jcr\\:lastModified=date:2009-10-14T08:59:01.227-04:00",

            // and more which should not match
            "/somepage/mypage/paragraphs/0.foo=bar", "/somepage/mypage/paragraphs/0.mybool=boolean:true",
            "/somepage/mypage/paragraphs/0/rand.@type=mgnl:resource",
            "/somepage/mypage/paragraphs/0/rand.fileName=randdddd",
            "/somepage/mypage/paragraphs/0/rand.extension=png",
            "/somepage/mypage/paragraphs/0/rand.jcr\\:data=binary:X",
            "/somepage/mypage/paragraphs/0/rand.jcr\\:mimeType=image/png",
            "/somepage/mypage/paragraphs/0/rand.jcr\\:lastModified=date:2009-10-14T08:59:01.227-04:00"), "\n");
    final Session hm = MgnlContext.getJCRSession(RepositoryConstants.WEBSITE);
    new PropertiesImportExport().createNodes(hm.getRootNode(), IOUtils.toInputStream(contentProperties));
    hm.save();/*from  w  w w .j a  v a  2  s  . c  o  m*/

    final Node content = hm.getNode("/somepage/mypage/paragraphs/0");
    final PropertyIterator props = content.getProperties("att*|ima*");

    // sort by name
    final TreeSet<Property> sorted = new TreeSet<Property>(new Comparator<Property>() {
        @Override
        public int compare(Property o1, Property o2) {
            try {
                return o1.getName().compareTo(o2.getName());
            } catch (RepositoryException e) {
                throw new RuntimeException(e);
            }
        }
    });

    while (props.hasNext()) {
        sorted.add(props.nextProperty());
    }

    // TODO: SCRUM-306 (3 binary props are now nodes not props)
    // assertEquals(5, sorted.size());
    //
    // final Iterator<Property> it = sorted.iterator();
    // final Property a = it.next();
    // final Property b = it.next();
    // final Property c = it.next();
    // final Property d = it.next();
    // final Property e = it.next();
    // assertEquals("attachment1", a.getName());
    // assertEquals(PropertyType.BINARY, a.getType());
    // assertEquals("attachment2", b.getName());
    // assertEquals(PropertyType.BINARY, b.getType());
    // assertEquals("image3", d.getName());
    // assertEquals(PropertyType.BINARY, d.getType());
    // assertEquals("image3", d.getName());
    // assertEquals(PropertyType.BINARY, d.getType());
    //
    // assertEquals("attention", c.getName());
    // assertEquals(PropertyType.STRING, c.getType());
    // assertEquals("booyah", c.getString());
    // assertEquals("imaginary", e.getName());
    // assertEquals(PropertyType.DATE, e.getType());
    // assertEquals(true, e.getDate().before(Calendar.getInstance()));
}

From source file:com.feedhenry.sync.activities.ListOfItemsActivity.java

private void fireSync() {

    this.syncClient = FHSyncClient.getInstance();

    //create a new instance of sync config
    FHSyncConfig config = new FHSyncConfig();
    config.setNotifySyncStarted(true);//from ww  w  .j a  v  a 2  s  . com
    config.setNotifyLocalUpdateApplied(true);
    config.setAutoSyncLocalUpdates(true);
    config.setNotifyDeltaReceived(true);
    config.setNotifySyncComplete(true);
    config.setUseCustomSync(false);
    config.setSyncFrequency(10);

    //initialize the sync client
    syncClient.init(getApplicationContext(), config, new FHSyncListener() {

        @Override
        //On sync complete, list all the data and update the adapter
        public void onSyncCompleted(NotificationMessage pMessage) {
            Log.d(TAG, "syncClient - onSyncCompleted");
            Log.d(TAG, "Sync message: " + pMessage.getMessage());

            JSONObject allData = syncClient.list(DATA_ID);
            Iterator<String> it = allData.keys();
            TreeSet<ShoppingItem> itemsToSync = new TreeSet<ShoppingItem>();

            while (it.hasNext()) {
                String key = it.next();
                JSONObject data = allData.getJSONObject(key);
                JSONObject dataObj = data.getJSONObject("data");
                String name = dataObj.optString("name", "NO name");
                if (name.startsWith("N")) {
                    Log.d(TAG, "Sync Complete Name : " + name);
                }
                String created = dataObj.optString("created", "no date");
                ShoppingItem item = new ShoppingItem(key, name, created);
                itemsToSync.add(item);
            }

            adapter.removeMissingItemsFrom(itemsToSync);
            adapter.addNewItemsFrom(itemsToSync);

            adapter.notifyDataSetChanged();
        }

        @Override
        public void onLocalUpdateApplied(NotificationMessage pMessage) {
            Log.d(TAG, "syncClient - onLocalUpdateApplied");

            JSONObject allData = syncClient.list(DATA_ID);

            Iterator<String> it = allData.keys();
            TreeSet<ShoppingItem> itemsToSync = new TreeSet<ShoppingItem>();

            while (it.hasNext()) {
                String key = it.next();
                JSONObject data = allData.getJSONObject(key);
                JSONObject dataObj = data.getJSONObject("data");
                String name = dataObj.optString("name", "NO name");
                if (name.startsWith("N")) {
                    Log.d(TAG, "Local Name : " + name);
                }
                String created = dataObj.optString("created", "no date");
                ShoppingItem item = new ShoppingItem(key, name, created);
                itemsToSync.add(item);
            }

            adapter.removeMissingItemsFrom(itemsToSync);
            adapter.addNewItemsFrom(itemsToSync);

            adapter.notifyDataSetChanged();
        }

        @Override
        public void onDeltaReceived(NotificationMessage pMessage) {
            Log.d(TAG, "syncClient - onDeltaReceived");
            Log.d(TAG, "syncClient : " + pMessage.toString());
        }

        @Override
        public void onUpdateOffline(NotificationMessage pMessage) {
            Log.d(TAG, "syncClient - onUpdateOffline");
        }

        @Override
        public void onSyncStarted(NotificationMessage pMessage) {
            Log.d(TAG, "syncClient - onSyncStarted");
        }

        @Override
        public void onSyncFailed(NotificationMessage pMessage) {
            Log.d(TAG, "syncClient - onSyncFailed");
        }

        @Override
        public void onRemoteUpdateFailed(NotificationMessage pMessage) {
            Log.d(TAG, "syncClient - onRemoteUpdateFailed");

        }

        @Override
        public void onRemoteUpdateApplied(NotificationMessage pMessage) {
            Log.d(TAG, "syncClient - onRemoteUpdateApplied");

        }

        @Override
        public void onCollisionDetected(NotificationMessage pMessage) {
            Log.d(TAG, "syncClient - onCollisionDetected");
        }

        @Override
        public void onClientStorageFailed(NotificationMessage pMessage) {
            Log.d(TAG, "syncClient - onSyncFailed");
        }

    });

    // Start the sync process
    try {
        syncClient.manage(DATA_ID, null, new JSONObject());
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
    }

}