Example usage for java.lang CharSequence toString

List of usage examples for java.lang CharSequence toString

Introduction

In this page you can find the example usage for java.lang CharSequence toString.

Prototype

public String toString();

Source Link

Document

Returns a string containing the characters in this sequence in the same order as this sequence.

Usage

From source file:de.schildbach.pte.NegentweeProvider.java

private QueryTripsResult queryTrips(HttpUrl url, Location from, @Nullable Location via, Location to)
        throws IOException {
    final CharSequence page;
    try {//w ww  . j a  va2s .  c  o m
        page = httpClient.get(url);
    } catch (InternalErrorException e) {
        return new QueryTripsResult(this.resultHeader, QueryTripsResult.Status.SERVICE_DOWN);
    }

    List<Trip> foundTrips = new ArrayList<>();
    String tripsEarlier, tripsLater;
    try {
        final JSONObject head = new JSONObject(page.toString());

        if (head.has("error")) {
            switch (head.getString("error")) {
            case "WithinWalkingDistance":
                return new QueryTripsResult(this.resultHeader, QueryTripsResult.Status.TOO_CLOSE);
            case "DateOutOfRange":
                return new QueryTripsResult(this.resultHeader, QueryTripsResult.Status.INVALID_DATE);
            case "UnknownLocations":
                String errorDetails = head.getString("details");
                if (errorDetails.startsWith("From:")) {
                    return new QueryTripsResult(this.resultHeader, QueryTripsResult.Status.UNKNOWN_FROM);
                } else if (errorDetails.startsWith("Via:")) {
                    return new QueryTripsResult(this.resultHeader, QueryTripsResult.Status.UNKNOWN_VIA);
                } else if (errorDetails.startsWith("To:")) {
                    return new QueryTripsResult(this.resultHeader, QueryTripsResult.Status.UNKNOWN_TO);
                } else {
                    return new QueryTripsResult(this.resultHeader,
                            QueryTripsResult.Status.UNRESOLVABLE_ADDRESS);
                }
            default:
                return new QueryTripsResult(this.resultHeader, QueryTripsResult.Status.NO_TRIPS);
            }
        }

        if (head.has("exception")) {
            return new QueryTripsResult(this.resultHeader, QueryTripsResult.Status.NO_TRIPS);
        }

        final JSONArray trips = head.optJSONArray("journeys");

        final JSONArray disturbances = head.optJSONArray("disturbances");

        // Prepare disturbances mapping for leg messages
        Map<String, JSONObject> disturbancesMap;
        if (disturbances != null && disturbances.length() > 0) {
            disturbancesMap = new HashMap<>();
            for (int i = 0; i < disturbances.length(); i++) {
                JSONObject disturbance = disturbances.getJSONObject(i);
                disturbancesMap.put(disturbance.getString("plannerDisturbanceId"), disturbance);
            }
        } else {
            disturbancesMap = null;
        }

        tripsEarlier = head.optString("earlier");
        tripsLater = head.optString("later");

        for (int i = 0; i < trips.length(); i++) {
            JSONObject trip = trips.getJSONObject(i);

            // Skip impossible or cancelled trips
            JSONObject realtimeInfo = trip.optJSONObject("realtimeInfo");
            if (realtimeInfo != null && ("fatal".equals(realtimeInfo.optString("delays"))
                    || "cancellations".equals(realtimeInfo.optString("cancellations"))))
                continue;

            foundTrips.add(tripFromJSONObject(trip, from, to, disturbancesMap));
        }
    } catch (final JSONException x) {
        throw new RuntimeException("cannot parse: '" + page + "' on " + url, x);
    }

    return new QueryTripsResult(null, url.toString(), from, via, to,
            new TripsContext(url, tripsEarlier, tripsLater, from, via, to), foundTrips);
}

From source file:de.schildbach.pte.NegentweeProvider.java

@Override
public NearbyLocationsResult queryNearbyLocations(EnumSet<LocationType> types, Location location,
        int maxDistance, int maxLocations) throws IOException {
    // Coordinates are required
    if (!location.hasLocation()) {
        try {//  ww  w  .j ava  2 s . c om
            if (location.hasId()) {
                location = queryLocationById(location.id);
            } else if (location.hasName()) {
                location = queryLocationByName(location.name, EnumSet.of(location.type));
            }
        } catch (InternalErrorException | NotFoundException | RuntimeException e) {
            return new NearbyLocationsResult(this.resultHeader, NearbyLocationsResult.Status.INVALID_ID);
        } catch (IOException e) {
            return new NearbyLocationsResult(this.resultHeader, NearbyLocationsResult.Status.SERVICE_DOWN);
        }

        if (location == null || !location.hasLocation()) {
            return new NearbyLocationsResult(this.resultHeader, NearbyLocationsResult.Status.INVALID_ID);
        }
    }

    // Default query options
    List<QueryParameter> queryParameters = new ArrayList<>();
    queryParameters
            .add(new QueryParameter("latlong", location.getLatAsDouble() + "," + location.getLonAsDouble()));
    queryParameters.add(new QueryParameter("rows",
            String.valueOf(Math.min((maxLocations <= 0) ? DEFAULT_MAX_LOCATIONS : maxLocations, 100))));

    // Add type if specified
    if (!types.contains(LocationType.ANY) && types.size() > 0) {
        StringBuilder typeValue = new StringBuilder();
        for (LocationType type : types) {
            for (String addition : locationStringsFromLocationType(type)) {
                if (typeValue.length() > 0)
                    typeValue.append(",");
                typeValue.append(addition);
            }
        }
        queryParameters.add(new QueryParameter("type", typeValue.toString()));
    }
    HttpUrl url = buildApiUrl("locations", queryParameters);

    CharSequence page;
    try {
        page = httpClient.get(url);
    } catch (InternalErrorException e) {
        return new NearbyLocationsResult(this.resultHeader, NearbyLocationsResult.Status.SERVICE_DOWN);
    }

    // Parse result into location list
    final List<Location> foundLocations = new ArrayList<>();
    try {
        final JSONObject head = new JSONObject(page.toString());
        final JSONArray locations = head.optJSONArray("locations");

        for (int i = 0; i < locations.length(); i++) {
            foundLocations.add(locationFromJSONObject(locations.getJSONObject(i)));
        }
    } catch (final JSONException x) {
        throw new RuntimeException("cannot parse: '" + page + "' on " + url, x);
    }

    return new NearbyLocationsResult(new ResultHeader(network, SERVER_PRODUCT), foundLocations);
}

From source file:gr.abiss.calipso.wicket.ItemView.java

private void addComponents(ItemRenderingTemplate tmpl, final Item item) {
    //Edit item is only possible for "global" administrator and current space administrator
    User currentUser = getPrincipal();//from w ww .  ja va 2  s .c o m
    Space currentSpace = getCurrentSpace();
    if (tmpl != null && tmpl.getShowSpaceName()) {
        add(new Label("title", this.localize(currentSpace)));
    } else {
        add(new Label("title", "").setVisible(false));
    }

    WebMarkupContainer editContainer = new WebMarkupContainer("editContainer");
    add(editContainer.setRenderBodyOnly(true));
    editContainer.add(new Link("edit") {
        @Override
        public void onClick() {
            //breadcrum must be activated in the active panel, that is ItemViewPanel
            ((BreadCrumbPanel) getBreadCrumbModel().getActive()).activate(new IBreadCrumbPanelFactory() {
                @Override
                public BreadCrumbPanel create(String componentId, IBreadCrumbModel breadCrumbModel) {
                    return new ItemFormPanel(componentId, breadCrumbModel, item.getId());
                }
            });
        }
    });
    editContainer.setVisible(currentUser.isGlobalAdmin() || currentUser.isSpaceAdmin(currentSpace));
    if (hideLinks) {
        editContainer.setVisible(false);
    }

    add(new Link("printToPdf") {
        @Override
        public void onClick() {
            // TODO: pickup print template from DB if appropriate
            // TODO: is this needed?
            //panels that change with navigation
            //ItemViewPage itemViewPage = new ItemViewPage(refId, null);
            String markup = "error generating report";
            CharSequence resultCharSequence = renderPageHtmlInNewRequestCycle(ItemTemplateViewPage.class,
                    new PageParameters("0=" + item.getUniqueRefId()));

            markup = resultCharSequence.toString();
            if (StringUtils.isNotBlank(markup)) {
                markup = markup.replaceFirst("../../logo.png", "logo.png").replaceFirst("../logo.png",
                        "logo.png");
            }

            // logger.info("printToPdf: " + markup);
            getRequestCycle().scheduleRequestHandlerAfterCurrent(

                    new PdfRequestTarget(PdfUtils.getPdf(getCalipso(), item, markup, ItemView.this),
                            item.getRefId()));
        }
    });

    String refId = item.getUniqueRefId();

    Link refIdLink = new BookmarkablePageLink("uniqueRefId", ItemViewPage.class,
            new PageParameters("0=" + refId));
    add(refIdLink.add(new Label("uniqueRefId", refId)));

    //Relate Link ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    WebMarkupContainer relatedContainer = new WebMarkupContainer("relatedContainer");
    add(relatedContainer);
    RelateLink relateLink1 = new RelateLink("relate1", item, getBreadCrumbModel(), currentUser, ItemView.this);
    //relateLink1.setVisible(!hideLinks);
    relatedContainer.add(relateLink1);

    if (currentUser.hasRegularRoleForSpace(item.getSpace())) {
        relatedContainer.setVisible(true);
    } else {
        relatedContainer.setVisible(false);
    }
    if (item.getRelatedItems() != null) {
        add(new ListView("relatedItems", new ArrayList(item.getRelatedItems())) {
            @Override
            protected void populateItem(ListItem listItem) {
                final ItemItem itemItem = (ItemItem) listItem.getModelObject();
                String message = null;
                if (itemItem.getType() == DUPLICATE_OF) {
                    message = localize("item_view.duplicateOf");
                } else if (itemItem.getType() == DEPENDS_ON) {
                    message = localize("item_view.dependsOn");
                } else if (itemItem.getType() == RELATED) {
                    message = localize("item_view.relatedTo");
                }
                final String refId = itemItem.getRelatedItem().getUniqueRefId();
                if (hideLinks) {
                    message = message + " " + refId;
                }
                listItem.add(new Label("message", message));
                Link link = new Link("link") {
                    @Override
                    public void onClick() {
                        setResponsePage(ItemViewPage.class, new PageParameters("0=" + refId));
                    }
                };
                link.add(new Label("refId", refId));
                link.setVisible(!hideLinks);
                listItem.add(link);
                listItem.add(new Link("remove") {
                    @Override
                    public void onClick() {
                        setResponsePage(new ItemRelateRemovePage(item.getId(), itemItem));
                    }
                }.setVisible(!hideLinks));
            }
        });
    } else {
        add(new WebMarkupContainer("relatedItems").setVisible(false));
    }

    if (item.getRelatingItems() != null) {
        add(new ListView("relatingItems", new ArrayList(item.getRelatingItems())) {
            @Override
            protected void populateItem(ListItem listItem) {
                final ItemItem itemItem = (ItemItem) listItem.getModelObject();
                // this looks very similar to related items block above
                // but the display strings could be different and in future handling of the 
                // inverse of the bidirectional link could be different as well                    
                String message = null;
                if (itemItem.getType() == DUPLICATE_OF) {
                    message = localize("item_view.duplicateOfThis");
                } else if (itemItem.getType() == DEPENDS_ON) {
                    message = localize("item_view.dependsOnThis");
                } else if (itemItem.getType() == RELATED) {
                    message = localize("item_view.relatedToThis");
                }
                //                    final String refId = itemItem.getItem().getRefId();
                final String refId = itemItem.getItem().getUniqueRefId();
                if (hideLinks) {
                    message = refId + " " + message;
                }
                listItem.add(new Label("message", message));
                Link link = new Link("link") {
                    @Override
                    public void onClick() {
                        setResponsePage(ItemViewPage.class, new PageParameters("0=" + refId));
                    }
                };
                link.add(new Label("refId", refId));
                link.setVisible(!hideLinks);
                listItem.add(link);
                listItem.add(new Link("remove") {
                    @Override
                    public void onClick() {
                        setResponsePage(new ItemRelateRemovePage(item.getId(), itemItem));
                    }
                }.setVisible(!hideLinks));
            }
        });
    } else {
        add(new WebMarkupContainer("relatingItems").setVisible(false));
    }

    add(new Label("status", new PropertyModel(item, "statusValue")));

    //user profile view link
    add(new UserViewLink("loggedBy", getBreadCrumbModel(), item.getLoggedBy())
            .setVisible(!getPrincipal().isAnonymous()));

    if (item.getAssignedTo() != null) {
        add(new UserViewLink("assignedTo", getBreadCrumbModel(), item.getAssignedTo())
                .setVisible(!getPrincipal().isAnonymous()));
    } else {
        Label assignedToLabel = new Label("assignedTo", localize("item.unassigned"));
        if (item.getStatus() != State.CLOSED) {
            assignedToLabel.add(new SimpleAttributeModifier("class", "unassigned"));
        }
        add(assignedToLabel);
    }

    add(new UserViewLink("reportedBy", getBreadCrumbModel(), item.getReportedBy()));

    WebMarkupContainer summaryContainer = new WebMarkupContainer("summaryContainer");
    summaryContainer.add(new Label("summary", new PropertyModel(item, "summary")));
    add(summaryContainer.setVisible(item.getSpace().isItemSummaryEnabled()));

    //detail commented out
    //add(new Label("detail", new PropertyModel(item, "detail")).setEscapeModelStrings(false));

    final SimpleAttributeModifier sam = new SimpleAttributeModifier("class", "alt");
    // All custom fields of the fields that belong to the item and are viewable for 
    // the session user
    final Map<Field.Name, Field> viewableFieldsMap = item.getViewableFieldMap(currentUser);

    // pick up the non-file fields from the list above and put them here for a list view
    final List<Field> noFileViewableFieldNamesList = new ArrayList<Field>();
    // Separate list view for files
    List<Field> fileViewableFieldNamesList = new ArrayList<Field>();
    List<Field> simpleAtachmentViewableFieldNamesList = new ArrayList<Field>();
    for (Field field : viewableFieldsMap.values()) {
        if (!field.getName().isFile()) { // is not file and not hidden (since we got it from getViewbleFieldList)
            noFileViewableFieldNamesList.add(field);
        } else { // if file and not simple attachment, keep for later simpleAtachmentViewableFieldNamesList
            if (field.getName().getText().equals(Field.FIELD_TYPE_SIMPLE_ATTACHEMENT)) {
                simpleAtachmentViewableFieldNamesList.add(field);
            } else {
                fileViewableFieldNamesList.add(field);
            }
        }
    }
    Metadata metadata = getCalipso().getCachedMetadataForSpace(item.getSpace());
    final SimpleDateFormat dateFormat = metadata.getDateFormat(Metadata.DATE_FORMAT_LONG);
    List<FieldGroup> fieldGroupsList = metadata.getFieldGroups();
    @SuppressWarnings("unchecked")
    ListView fieldGroups = new ListView("fieldGroups", fieldGroupsList) {

        @Override
        protected void populateItem(ListItem listItem) {
            // get group
            FieldGroup fieldGroup = (FieldGroup) listItem.getModelObject();
            listItem.add(new Label("fieldGroupLabel", fieldGroup.getName()));
            List<Field> groupFields = fieldGroup.getFields();
            List<Field> viewbleFieldGroups = new LinkedList<Field>();
            // get group fields
            if (CollectionUtils.isNotEmpty(groupFields)) {
                for (Field field : groupFields) {
                    // is viewalble?
                    if (noFileViewableFieldNamesList.contains(field)) {
                        viewbleFieldGroups.add(field);
                    }
                }
            }
            ListView listView = new ListView("fields", viewbleFieldGroups) {
                @Override
                @SuppressWarnings("deprecation")
                protected void populateItem(ListItem listItem) {
                    addFieldValueDisplay(item, sam, dateFormat, listItem);
                }
            };
            if (viewbleFieldGroups.isEmpty()) {
                listItem.setVisible(false);
            }
            listView.setReuseItems(true);
            listItem.add(listView.setRenderBodyOnly(true));

        }

    };
    add(fieldGroups);

    // Iterates custom fields than are not type file
    //        add(new ListView("CustomFieldsListView", noFileViewableFieldNamesList) {
    //            protected void populateItem(ListItem listItem) {
    //                addFieldValueDisplay(item, sam, dateFormat, listItem);
    //            }
    //
    //         
    //        });

    if (fileViewableFieldNamesList.size() > 0) {
        // add custom field type file label
        add(new Label("fileFieldLabel", localize("files")));
        //add values for custom fields type file
        // check for if doesn't exist custom field type file
        // TODO: user should upload a file for every customField type file
        // get Attachments
        ArrayList<Attachment> itemAttachments = item.getAttachments() != null
                ? new ArrayList<Attachment>(item.getAttachments())
                : new ArrayList();
        //logger.info("Files to render: "+itemAttachments.size());
        ListView fileCustomFieldsListView = new ListView("fileCustomFieldsListView", itemAttachments) {
            @Override
            protected void populateItem(ListItem listItem) {
                Attachment tmpAttachment = (Attachment) listItem.getModelObject();
                listItem.add(new AttachmentDownLoadableLinkPanel("fileLink", tmpAttachment));
            }
        };
        add(fileCustomFieldsListView);
    } else {
        // add empty label
        add(new EmptyPanel("fileCustomFieldsListView").setVisible(false));
        // add custom field type file label
        add(new Label("fileFieldLabel", localize("files")));
    }

    // TODO: Dont think this actually checks for user roles rights within the State scope, 
    // plus the *readable* fields are needed instead to feed the historyEntry ("history" ListView) bellow
    //final List<Field> editable = item.getSpace().getMetadata().getEditableFields();
    final List<Field> readable = item.getSpace().getMetadata()
            .getReadableFields(currentUser.getSpaceRoles(item.getSpace()), item.getStatus());
    add(new ListView("labels", readable) {
        @Override
        protected void populateItem(ListItem listItem) {
            Field field = (Field) listItem.getModelObject();
            listItem.add(new Label("label", field.getLabel()));
        }
    });

    currentUser.setRoleSpaceStdFieldList(getCalipso().findSpaceFieldsForUser(currentUser));
    Map<StdField.Field, StdFieldMask> fieldMaskMap = currentUser.getStdFieldsForSpace(currentSpace);

    //Get user fields
    List<RoleSpaceStdField> stdFields = currentUser.getStdFields();

    //Standard fields ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //List of standard Fields
    List<RoleSpaceStdField> standardFields = StdFieldsUtils.filterFieldsBySpace(stdFields, fieldMaskMap,
            currentSpace);

    //Render Standard field
    add(new ListView("stdFields", standardFields) {
        @Override
        protected void populateItem(ListItem listItem) {
            RoleSpaceStdField stdField = (RoleSpaceStdField) listItem.getModelObject();
            boolean invisible = stdField.getStdField().getField().getFieldType().getType()
                    .equals(StdFieldType.Type.ASSET)
                    || stdField.getStdField().getField().getFieldType().getType()
                            .equals(StdFieldType.Type.ASSETTYPE)
                    || stdField.getStdField().getField().equals(StdField.Field.ACTUAL_EFFORT);

            listItem.add(new Label("label", localize("field." + stdField.getStdField().getField().getName()))
                    .setVisible(!invisible));
            IModel value = new Model("");

            if (stdField.getStdField().getField().getFieldType().getType()
                    .equals(StdFieldType.Type.STATISTIC)) {
                Method method = null;
                ReflectionUtils.buildFromProperty("get", stdField.getStdField().getField().getName());

                try {
                    method = item.getClass().getMethod(ReflectionUtils.buildFromProperty("get",
                            stdField.getStdField().getField().getName()));
                    value = new Model(ItemUtils.formatEffort(method.invoke(item), localize("item_list.days"),
                            localize("item_list.hours"), localize("item_list.minutes")));
                } catch (NoSuchMethodException noSuchMethodException) {
                    logger.error(noSuchMethodException);
                } catch (InvocationTargetException invocationTargetException) {
                    logger.error(invocationTargetException);
                } catch (IllegalAccessException illegalAccessException) {
                    logger.error(illegalAccessException);
                }
            } else if (stdField.getStdField().getField().getFieldType().getType()
                    .equals(StdFieldType.Type.INFO)) {
                if (stdField.getStdField().getField().equals(StdField.Field.DUE_TO)) {
                    value = new Model(new StringBuffer().append(DateUtils.format(item.getStateDueTo()))
                            .append(" / ").append(DateUtils.format(item.getDueTo())).toString());
                    if (item.getStatus() != State.CLOSED) {
                        if (item.getDueTo() != null
                                && item.getDueTo().before(Calendar.getInstance().getTime())) {
                            listItem.add(new SimpleAttributeModifier("class", "dueToDate-alarm"));
                        } //if
                        else if (item.getDueTo() != null && item.getPlannedEffort() != null
                                && item.getDueTo().after(Calendar.getInstance().getTime())) {
                            DateTime dueToDateTime = new DateTime(item.getDueTo());
                            DateTime nowDateTime = new DateTime(Calendar.getInstance().getTime());
                            long restTimeToDueTo = DateTime.diff(nowDateTime, dueToDateTime).inSeconds() / 60;
                            if (restTimeToDueTo < item.getPlannedEffort().longValue()) {
                                listItem.add(new SimpleAttributeModifier("class", "dueToDate-warning"));
                            } //if
                        }
                    }
                } //if
                else if (stdField.getStdField().getField().equals(StdField.Field.PLANNED_EFFORT)) {
                    if (item.getPlannedEffort() != null) {
                        value = new Model(
                                new Effort(item.getPlannedEffort()).formatEffort(localize("item_list.days"),
                                        localize("item_list.hours"), localize("item_list.minutes")));
                    }
                }
            }

            listItem.add(new Label("value", value).setVisible(!invisible));
        }
    });

    //Assets ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //Space is integrated with asset or space is not but was perhaps in the past integrated and at least one asset was bind with this item
    boolean userCanViewAssets = fieldMaskMap.get(StdField.Field.ASSET) != null
            && !fieldMaskMap.get(StdField.Field.ASSET).getMask().equals(StdFieldMask.Mask.HIDDEN);
    boolean spaceIsUIntegratedWithAsset = item.getSpace().isAssetEnabled();
    boolean userCanUpdateAssets = fieldMaskMap.get(StdField.Field.ASSET) != null
            && fieldMaskMap.get(StdField.Field.ASSET).getMask().equals(StdFieldMask.Mask.UPDATE);
    boolean userCanAdministrateAssetsForSpace = currentUser != null && currentUser.getId() != 0
            && (currentUser.isGlobalAdmin() || currentUser.isSpaceAdmin(currentSpace));
    boolean userCanSeeComments = currentUser.hasRegularRoleForSpace(currentSpace)
            || (currentSpace.getItemVisibility().equals(Space.ITEMS_VISIBLE_TO_LOGGEDIN_REPORTERS)
                    && currentUser.isGuestForSpace(currentSpace));
    if (userCanSeeComments) {
        // show history?
        userCanSeeComments = !(tmpl != null && tmpl.getHideHistory().booleanValue());
    }
    WebMarkupContainer assetsContainer = new WebMarkupContainer("assetsContainer");
    add(assetsContainer.setRenderBodyOnly(true));
    ItemAssetsPanel itemAssetsPanel = new ItemAssetsPanel("itemAssetsViewPanel", item);

    WebMarkupContainer editAssetContainer = new WebMarkupContainer("editAssetContainer");
    add(editContainer.setRenderBodyOnly(true));

    editAssetContainer.add(new Link("editAsset") {
        @Override
        public void onClick() {
            //breadCrumb must be activated in the active panel, that is ItemViewPanel
            ((BreadCrumbPanel) getBreadCrumbModel().getActive()).activate(new IBreadCrumbPanelFactory() {
                @Override
                public BreadCrumbPanel create(String componentId, IBreadCrumbModel breadCrumbModel) {
                    return new ItemAssetFormPanel(componentId, breadCrumbModel, item.getId());
                }
            });
        }
    });
    editAssetContainer.setVisible(userCanUpdateAssets);
    assetsContainer.add(editAssetContainer);

    if (hideLinks) {
        editAssetContainer.setVisible(false);
    }
    // --- Link to Asset administration for assets 
    SpaceAssetAdminLink spaceAssetAdminLink = new SpaceAssetAdminLink("asset", getBreadCrumbModel()) {
        @Override
        public void onLinkActivate() {
            //do nothing
        }
    };
    assetsContainer.add(spaceAssetAdminLink);
    spaceAssetAdminLink.setVisible(userCanAdministrateAssetsForSpace);
    if (hideLinks) {
        spaceAssetAdminLink.setVisible(false);
    }
    //Case 1:
    //Current space is integrated with assets and user can view these assets
    //Case 2:
    //Current space is NOT integrated with assets BUT was integrated with assets in the past and user can view these assets
    //============
    //Pseudo code:
    //============
    // if (Case 1 OR Case 2) then 
    //   showAssets();
    // fi
    // else
    //   doNotShowAssets();
    // esle

    boolean itemInvolvesAssets = itemAssetsPanel.getItemAssets() != null
            && itemAssetsPanel.getItemAssets().size() > 0;
    if ((spaceIsUIntegratedWithAsset && userCanViewAssets)
            || (!spaceIsUIntegratedWithAsset && itemInvolvesAssets && userCanViewAssets)) {
        itemAssetsPanel.renderItemAssets();
        assetsContainer.add(itemAssetsPanel);
    } //if
    else {
        assetsContainer.setVisible(false);
    } //else

    WebMarkupContainer historyContainer = new WebMarkupContainer("historyContainer");

    historyContainer.add(new WebMarkupContainer("historyComment").setVisible(userCanSeeComments));
    if (item.getHistory() != null && userCanSeeComments) {
        List<History> history = new ArrayList(item.getHistory());
        historyContainer.add(new ListView("history", history) {
            @Override
            protected void populateItem(ListItem listItem) {
                final History h = (History) listItem.getModelObject();

                //First history entry is empty => Add item detail to first history item for view harmonization.  
                if (listItem.getIndex() == 0) {
                    h.setComment(item.getDetail());
                    h.setHtmlComment(item.getHtmlDetail());
                }
                HistoryEntry historyEntry = new HistoryEntry("historyEntry", getBreadCrumbModel(), h, readable);
                if (listItem.getIndex() % 2 == 0) {
                    historyEntry.add(sam);
                }
                listItem.add(historyEntry);
            }
        }.setRenderBodyOnly(true));
    } else {
        historyContainer.add(new WebMarkupContainer("history").add(new WebMarkupContainer("historyEntry")));
        historyContainer.setVisible(false);
    }
    add(historyContainer);

}

From source file:com.pidoco.juri.JURI.java

/**
 * Provides encoded URI - recreates the URI, should not be used if more changes will be applied to the wrapper.
 *//*www .j  a  v  a2s  .co m*/
@Override
public String toString() {
    if (changeUnderway) {
        CharSequence detail;
        try {
            detail = buildNoSideEffects();
        } catch (URISyntaxException e) {
            detail = e.getMessage();
        }
        LOG.warn("Called toString while change is underway - this must only happen during debugging!");
        return detail.toString();
    }
    return getCurrentUri().toASCIIString();
}

From source file:br.msf.commons.text.EnhancedStringBuilder.java

public EnhancedStringBuilder deletePattern(final CharSequence regex) {
    return (CharSequenceUtils.isEmptyOrNull(regex) || this.isEmpty()) ? this
            : deletePattern(Pattern.compile(regex.toString()));
}

From source file:de.schildbach.pte.VrsProvider.java

@Override
public QueryDeparturesResult queryDepartures(final String stationId, @Nullable Date time, int maxDepartures,
        boolean equivs) throws IOException {
    checkNotNull(Strings.emptyToNull(stationId));

    // g=p means group by product; not used here
    // d=minutes overwrites c=count and returns departures for the next d minutes
    final HttpUrl.Builder url = API_BASE.newBuilder();
    url.addQueryParameter("eID", "tx_vrsinfo_ass2_timetable");
    url.addQueryParameter("i", stationId);
    url.addQueryParameter("c", Integer.toString(maxDepartures));
    if (time != null) {
        url.addQueryParameter("t", formatDate(time));
    }//from ww w  .  j  a  v  a 2 s .  c o m
    final CharSequence page = httpClient.get(url.build());

    try {
        final JSONObject head = new JSONObject(page.toString());
        final String error = Strings.emptyToNull(head.optString("error", "").trim());
        if (error != null) {
            if (error.equals("ASS2-Server lieferte leere Antwort."))
                return new QueryDeparturesResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryDeparturesResult.Status.SERVICE_DOWN);
            else if (error.equals("Leere ASS-ID und leere Koordinate"))
                return new QueryDeparturesResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryDeparturesResult.Status.INVALID_STATION);
            else if (error.equals("Keine Abfahrten gefunden."))
                return new QueryDeparturesResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryDeparturesResult.Status.INVALID_STATION);
            else
                throw new IllegalStateException("unknown error: " + error);
        }
        final JSONArray timetable = head.getJSONArray("timetable");
        final ResultHeader header = new ResultHeader(NetworkId.VRS, SERVER_PRODUCT);
        final QueryDeparturesResult result = new QueryDeparturesResult(header);
        // for all stations
        if (timetable.length() == 0) {
            return new QueryDeparturesResult(header, QueryDeparturesResult.Status.INVALID_STATION);
        }
        for (int iStation = 0; iStation < timetable.length(); iStation++) {
            final List<Departure> departures = new ArrayList<Departure>();
            final JSONObject station = timetable.getJSONObject(iStation);
            final Location location = parseLocationAndPosition(station.getJSONObject("stop")).location;
            final JSONArray events = station.getJSONArray("events");
            final List<LineDestination> lines = new ArrayList<LineDestination>();
            // for all departures
            for (int iEvent = 0; iEvent < events.length(); iEvent++) {
                final JSONObject event = events.getJSONObject(iEvent);
                Date plannedTime = null;
                Date predictedTime = null;
                if (event.has("departureScheduled")) {
                    plannedTime = parseDateTime(event.getString("departureScheduled"));
                    predictedTime = parseDateTime(event.getString("departure"));
                } else {
                    plannedTime = parseDateTime(event.getString("departure"));
                }
                final JSONObject lineObj = event.getJSONObject("line");
                final Line line = parseLine(lineObj);
                Position position = null;
                final JSONObject post = event.optJSONObject("post");
                if (post != null) {
                    final String postName = post.getString("name");
                    for (Pattern pattern : NAME_WITH_POSITION_PATTERNS) {
                        Matcher matcher = pattern.matcher(postName);
                        if (matcher.matches()) {
                            position = new Position(matcher.group(2));
                            break;
                        }
                    }
                    if (position == null)
                        log.info("Could not extract position from '{}'", postName);
                }
                final Location destination = new Location(LocationType.STATION, null /* id */, null /* place */,
                        lineObj.getString("direction"));

                final LineDestination lineDestination = new LineDestination(line, destination);
                if (!lines.contains(lineDestination)) {
                    lines.add(lineDestination);
                }
                final Departure d = new Departure(plannedTime, predictedTime, line, position, destination, null,
                        null);
                departures.add(d);
            }

            queryLinesForStation(location.id, lines);

            result.stationDepartures.add(new StationDepartures(location, departures, lines));
        }

        return result;
    } catch (final JSONException x) {
        throw new RuntimeException("cannot parse: '" + page + "' on " + url, x);
    } catch (final ParseException e) {
        throw new RuntimeException("cannot parse: '" + page + "' on " + url, e);
    }
}

From source file:com.clover.android.sdk.examples.InventoryTestActivity.java

private void displayItem(Item item) {
    if (item != null) {
        String textViewContents = "";
        CharSequence text = resultText.getText();
        if (text != null) {
            textViewContents = text.toString();
        }//  www . j  a  va  2 s .c o m
        resultText.setText(textViewContents + "\nitem = " + dumpItem(item));
    }
}

From source file:com.insthub.O2OMobile.Activity.D1_OrderActivity.java

private void showOrderPriceDialog() {
    LayoutInflater inflater = LayoutInflater.from(D1_OrderActivity.this);
    View view = inflater.inflate(R.layout.d1_order_price_dialog, null);
    mPriceDialog = new Dialog(D1_OrderActivity.this, R.style.dialog);
    mPriceDialog.setContentView(view);//from  w w  w  . ja  v a2 s  .  co m
    mPriceDialog.setCanceledOnTouchOutside(false);
    mPriceDialog.show();

    mOrderPriceDialogPrice = (TextView) view.findViewById(R.id.order_price_dialog_price);
    mOrderPriceDialogChangePrice = (EditText) view.findViewById(R.id.order_price_dialog_change_price);
    mOrderPriceDialogOk = (Button) view.findViewById(R.id.order_price_dialog_ok);
    mOrderPriceDialogCancel = (Button) view.findViewById(R.id.order_price_dialog_cancel);

    if (mOrderInfoModel.publicOrder.offer_price != null) {
        mOrderPriceDialogPrice.setText(Utils.formatBalance(mOrderInfoModel.publicOrder.offer_price) + "");
    }

    mOrderPriceDialogChangePrice.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            if (s.toString().length() > 0) {
                if (s.toString().substring(0, 1).equals(".")) {
                    s = s.toString().substring(1, s.length());
                    mOrderPriceDialogChangePrice.setText(s);
                }
            }
            if (s.toString().length() > 1) {
                if (s.toString().substring(0, 1).equals("0")) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        s = s.toString().substring(1, s.length());
                        mOrderPriceDialogChangePrice.setText(s);
                        CharSequence charSequencePirce = mOrderPriceDialogChangePrice.getText();
                        if (charSequencePirce instanceof Spannable) {
                            Spannable spanText = (Spannable) charSequencePirce;
                            Selection.setSelection(spanText, charSequencePirce.length());
                        }
                    }
                }
            }
            boolean flag = false;
            for (int i = 0; i < s.toString().length() - 1; i++) {
                String getstr = s.toString().substring(i, i + 1);
                if (getstr.equals(".")) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                int i = s.toString().indexOf(".");
                if (s.toString().length() - 3 > i) {
                    String getstr = s.toString().substring(0, i + 3);
                    mOrderPriceDialogChangePrice.setText(getstr);
                    CharSequence charSequencePirce = mOrderPriceDialogChangePrice.getText();
                    if (charSequencePirce instanceof Spannable) {
                        Spannable spanText = (Spannable) charSequencePirce;
                        Selection.setSelection(spanText, charSequencePirce.length());
                    }
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }
    });

    mOrderPriceDialogCancel.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mPriceDialog.dismiss();
        }
    });

    mOrderPriceDialogOk.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mOrderInfoModel.done(mOrderId, mOrderPriceDialogChangePrice.getText().toString());
            mPriceDialog.dismiss();
        }
    });

}

From source file:br.msf.commons.text.EnhancedStringBuilder.java

public EnhancedStringBuilder replacePattern(final CharSequence regex, final Object replacement) {
    return (CharSequenceUtils.isEmptyOrNull(regex) || this.isEmpty()) ? this
            : replacePattern(Pattern.compile(regex.toString()), format(replacement));
}

From source file:de.schildbach.pte.VrsProvider.java

@Override
public NearbyLocationsResult queryNearbyLocations(EnumSet<LocationType> types /* only STATION supported */,
        Location location, int maxDistance, int maxLocations) throws IOException {
    // g=p means group by product; not used here
    final HttpUrl.Builder url = API_BASE.newBuilder();
    url.addQueryParameter("eID", "tx_vrsinfo_ass2_timetable");
    if (location.hasLocation()) {
        url.addQueryParameter("r",
                String.format(Locale.ENGLISH, "%.6f,%.6f", location.lat / 1E6, location.lon / 1E6));
    } else if (location.type == LocationType.STATION && location.hasId()) {
        url.addQueryParameter("i", location.id);
    } else {//from w  w w  .  ja v  a2 s .com
        throw new IllegalArgumentException("at least one of stationId or lat/lon must be given");
    }
    // c=1 limits the departures at each stop to 1 - actually we don't need any at this point
    url.addQueryParameter("c", "1");
    if (maxLocations > 0) {
        // s=number of stops, artificially limited by server
        url.addQueryParameter("s", Integer.toString(Math.min(16, maxLocations)));
    }

    final CharSequence page = httpClient.get(url.build());

    try {
        final List<Location> locations = new ArrayList<>();
        final JSONObject head = new JSONObject(page.toString());
        final String error = Strings.emptyToNull(head.optString("error", "").trim());
        if (error != null) {
            if (error.equals("Leere Koordinate.") || error.equals("Leere ASS-ID und leere Koordinate"))
                return new NearbyLocationsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT), locations);
            else if (error.equals("ASS2-Server lieferte leere Antwort."))
                return new NearbyLocationsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        NearbyLocationsResult.Status.SERVICE_DOWN);
            else
                throw new IllegalStateException("unknown error: " + error);
        }
        final JSONArray timetable = head.getJSONArray("timetable");
        long serverTime = 0;
        for (int i = 0; i < timetable.length(); i++) {
            final JSONObject entry = timetable.getJSONObject(i);
            final JSONObject stop = entry.getJSONObject("stop");
            final Location loc = parseLocationAndPosition(stop).location;
            int distance = stop.getInt("distance");
            if (maxDistance > 0 && distance > maxDistance) {
                break; // we rely on the server side sorting by distance
            }
            if (types.contains(loc.type) || types.contains(LocationType.ANY)) {
                locations.add(loc);
            }
            serverTime = parseDateTime(timetable.getJSONObject(i).getString("generated")).getTime();
        }
        final ResultHeader header = new ResultHeader(NetworkId.VRS, SERVER_PRODUCT, null, null, serverTime,
                null);
        return new NearbyLocationsResult(header, locations);
    } catch (final JSONException x) {
        throw new RuntimeException("cannot parse: '" + page + "' on " + url, x);
    } catch (final ParseException e) {
        throw new RuntimeException("cannot parse: '" + page + "' on " + url, e);
    }
}