code
stringlengths
3
1.18M
language
stringclasses
1 value
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.discovery; import java.io.IOException; import java.sql.SQLException; import org.apache.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.common.SolrDocument; import org.dspace.app.xmlui.utils.HandleUtil; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.ReferenceSet; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Community; import org.dspace.content.DSpaceObject; import org.dspace.core.Constants; import org.dspace.discovery.SearchUtils; import org.xml.sax.SAXException; /** * Renders a list of recently submitted items for the community by using discovery * * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public class CommunityRecentSubmissions extends AbstractFiltersTransformer { private static final Logger log = Logger.getLogger(CommunityRecentSubmissions.class); private static final Message T_head_recent_submissions = message("xmlui.ArtifactBrowser.CollectionViewer.head_recent_submissions"); /** * Display a single community (and refrence any sub communites or * collections) */ public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (!(dso instanceof Community)) { return; } // Build the community viewer division. Division home = body.addDivision("community-home", "primary repository community"); performSearch(dso); Division lastSubmittedDiv = home .addDivision("community-recent-submission", "secondary recent-submission"); lastSubmittedDiv.setHead(T_head_recent_submissions); ReferenceSet lastSubmitted = lastSubmittedDiv.addReferenceSet( "community-last-submitted", ReferenceSet.TYPE_SUMMARY_LIST, null, "recent-submissions"); for (SolrDocument doc : queryResults.getResults()) { lastSubmitted.addReference(SearchUtils.findDSpaceObject(context, doc)); } } /** * Get the recently submitted items for the given community or collection. * * @param scope The comm/collection. * @return the response of the query */ public void performSearch(DSpaceObject scope) { if(queryResults != null) { return; }// queryResults; queryArgs = prepareDefaultFilters(getView()); queryArgs.setQuery("search.resourcetype:" + Constants.ITEM); queryArgs.setRows(SearchUtils.getConfig().getInt("solr.recent-submissions.size", 5)); String sortField = SearchUtils.getConfig().getString("recent.submissions.sort-option"); if(sortField != null){ queryArgs.setSortField( sortField, SolrQuery.ORDER.desc ); } /* Set the communities facet filters */ queryArgs.setFilterQueries("location:m" + scope.getID()); try { queryResults = getSearchService().search(queryArgs); } catch (RuntimeException e) { log.error(e.getMessage(),e); } catch (Exception e) { log.error(e.getMessage(),e); } } public String getView() { return "community"; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.discovery; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.apache.cocoon.util.HashUtil; import org.apache.excalibur.source.SourceValidity; import org.apache.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.DSpaceValidity; import org.dspace.app.xmlui.utils.HandleUtil; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.Options; import org.dspace.authorize.AuthorizeException; import org.dspace.content.DSpaceObject; import org.dspace.core.LogManager; import org.dspace.discovery.SearchService; import org.dspace.discovery.SearchServiceException; import org.dspace.discovery.SearchUtils; import org.dspace.discovery.SolrServiceImpl; import org.dspace.handle.HandleManager; import org.dspace.utils.DSpace; import org.xml.sax.SAXException; import java.io.IOException; import java.io.Serializable; import java.sql.SQLException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Renders the side bar filters in discovery * * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public abstract class AbstractFiltersTransformer extends AbstractDSpaceTransformer { private static final Logger log = Logger.getLogger(AbstractFiltersTransformer.class); public abstract String getView(); /** * Cached query results */ protected QueryResponse queryResults; /** * Cached query arguments */ protected SolrQuery queryArgs; /** * Cached validity object */ protected SourceValidity validity; private static final Message T_FILTER_HEAD = message("xmlui.discovery.AbstractFiltersTransformer.filters.head"); private static final Message T_VIEW_MORE = message("xmlui.discovery.AbstractFiltersTransformer.filters.view-more"); protected SearchService getSearchService() { DSpace dspace = new DSpace(); org.dspace.kernel.ServiceManager manager = dspace.getServiceManager() ; return manager.getServiceByName(SearchService.class.getName(),SearchService.class); } /** * Generate the unique caching key. * This key must be unique inside the space of this component. */ public Serializable getKey() { try { DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (dso == null) { return "0"; } return HashUtil.hash(dso.getHandle()); } catch (SQLException sqle) { // Ignore all errors and just return that the component is not // cachable. return "0"; } } /** * Generate the cache validity object. * <p/> * The validity object will include the collection being viewed and * all recently submitted items. This does not include the community / collection * hierarch, when this changes they will not be reflected in the cache. */ public SourceValidity getValidity() { if (this.validity == null) { try { DSpaceObject dso = HandleUtil.obtainHandle(objectModel); DSpaceValidity val = new DSpaceValidity(); // add reciently submitted items, serialize solr query contents. performSearch(dso); // Add the actual collection; if (dso != null) { val.add(dso); } val.add("numFound:" + queryResults.getResults().getNumFound()); for (SolrDocument doc : queryResults.getResults()) { val.add(doc.toString()); } for (SolrDocument doc : queryResults.getResults()) { val.add(doc.toString()); } for (FacetField field : queryResults.getFacetFields()) { val.add(field.getName()); for (FacetField.Count count : field.getValues()) { val.add(count.getName() + count.getCount()); } } this.validity = val.complete(); } catch (Exception e) { log.error(e.getMessage(),e); } //TODO: dependent on tags as well :) } return this.validity; } public abstract void performSearch(DSpaceObject object) throws SearchServiceException, UIException; /** * Determine the current scope. This may be derived from the current url * handle if present or the scope parameter is given. If no scope is * specified then null is returned. * * @return The current scope. */ protected DSpaceObject getScope() throws SQLException { Request request = ObjectModelHelper.getRequest(objectModel); String scopeString = request.getParameter("scope"); // Are we in a community or collection? DSpaceObject dso; if (scopeString == null || "".equals(scopeString)) { // get the search scope from the url handle dso = HandleUtil.obtainHandle(objectModel); } else { // Get the search scope from the location parameter dso = HandleManager.resolveToObject(context, scopeString); } return dso; } protected SolrQuery prepareDefaultFilters(String scope, String ...filterQueries) { queryArgs = new SolrQuery(); SearchUtils.SolrFacetConfig[] facets = SearchUtils.getFacetsForType(scope); log.info("facets for scope, " + scope + ": " + (facets != null ? facets.length : null)); //Set the default limit to 10 int max = 10; try{ max = SearchUtils.getConfig().getInteger("search.facet.max"); }catch (Exception e){ //Ignore, only occurs if property isn't set in the config, default will be used then } //Add one to our facet limit to make sure that if we have more then the shown facets that we show our show more url max++; if (facets != null){ queryArgs.setFacetLimit(max); queryArgs.setFacetMinCount(1); queryArgs.setFacet(true); } /** enable faceting of search results */ if (facets != null){ for (SearchUtils.SolrFacetConfig facet : facets) { if(facet.isDate()){ String dateFacet = facet.getFacetField(); try{ //Get a range query so we can create facet queries ranging from out first to our last date //Attempt to determine our oldest & newest year by checking for previously selected filters int oldestYear = -1; int newestYear = -1; for (String filterQuery : filterQueries) { if(filterQuery.startsWith(facet.getFacetField() + ":")){ //Check for a range Pattern pattern = Pattern.compile("\\[(.*? TO .*?)\\]"); Matcher matcher = pattern.matcher(filterQuery); boolean hasPattern = matcher.find(); if(hasPattern){ filterQuery = matcher.group(0); //We have a range //Resolve our range to a first & endyear int tempOldYear = Integer.parseInt(filterQuery.split(" TO ")[0].replace("[", "").trim()); int tempNewYear = Integer.parseInt(filterQuery.split(" TO ")[1].replace("]", "").trim()); //Check if we have a further filter (or a first one found) if(tempNewYear < newestYear || oldestYear < tempOldYear || newestYear == -1){ oldestYear = tempOldYear; newestYear = tempNewYear; } }else{ if(filterQuery.indexOf(" OR ") != -1){ //Should always be the case filterQuery = filterQuery.split(" OR ")[0]; } //We should have a single date oldestYear = Integer.parseInt(filterQuery.split(":")[1].trim()); newestYear = oldestYear; //No need to look further break; } } } //Check if we have found a range, if not then retrieve our first & last year by using solr if(oldestYear == -1 && newestYear == -1){ SolrQuery yearRangeQuery = new SolrQuery(); yearRangeQuery.setRows(1); //Set our query to anything that has this value yearRangeQuery.setQuery(facet.getFacetField() + ":[* TO *]"); //Set sorting so our last value will appear on top yearRangeQuery.setSortField(dateFacet, SolrQuery.ORDER.asc); yearRangeQuery.addFilterQuery(filterQueries); QueryResponse lastYearResult = getSearchService().search(yearRangeQuery); if(lastYearResult.getResults() != null && 0 < lastYearResult.getResults().size() && lastYearResult.getResults().get(0).getFieldValue(dateFacet) != null){ oldestYear = (Integer) lastYearResult.getResults().get(0).get(dateFacet); } //Now get the first year yearRangeQuery.setSortField(dateFacet, SolrQuery.ORDER.desc); QueryResponse firstYearResult = getSearchService().search(yearRangeQuery); if(firstYearResult.getResults() != null && 0 < firstYearResult.getResults().size() && firstYearResult.getResults().get(0).getFieldValue(dateFacet) != null){ newestYear = (Integer) firstYearResult.getResults().get(0).get(dateFacet); } //No values found! if(newestYear == -1 || oldestYear == -1) { continue; } } int gap = 1; //Attempt to retrieve our gap by the algorithm below int yearDifference = newestYear - oldestYear; if(yearDifference != 0){ while (10 < ((double)yearDifference / gap)){ gap *= 10; } } // We need to determine our top year so we can start our count from a clean year // Example: 2001 and a gap from 10 we need the following result: 2010 - 2000 ; 2000 - 1990 hence the top year int topYear = (int) (Math.ceil((float) (newestYear)/gap)*gap); if(gap == 1){ //We need a list of our years //We have a date range add faceting for our field //The faceting will automatically be limited to the 10 years in our span due to our filterquery queryArgs.addFacetField(facet.getFacetField()); }else{ java.util.List<String> facetQueries = new ArrayList<String>(); //Create facet queries but limit then to 11 (11 == when we need to show a show more url) for(int year = topYear; year > oldestYear && (facetQueries.size() < max); year-=gap){ //Add a filter to remove the last year only if we aren't the last year int bottomYear = year - gap; //Make sure we don't go below our last year found if(bottomYear < oldestYear) { bottomYear = oldestYear; } //Also make sure we don't go above our newest year int currentTop = year; if((year == topYear)) { currentTop = newestYear; } else { //We need to do -1 on this one to get a better result currentTop--; } facetQueries.add(dateFacet + ":[" + bottomYear + " TO " + currentTop + "]"); } for (String facetQuery : facetQueries) { queryArgs.addFacetQuery(facetQuery); } } }catch (Exception e){ log.error(LogManager.getHeader(context, "Error in discovery while setting up date facet range", "date facet: " + dateFacet), e); } }else{ queryArgs.addFacetField(facet.getFacetField()); } } } //Add the default filters queryArgs.addFilterQuery(SearchUtils.getDefaultFilters(scope)); return queryArgs; } @Override public void addOptions(Options options) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { Request request = ObjectModelHelper.getRequest(objectModel); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); java.util.List<String> fqs = Arrays.asList(request.getParameterValues("fq") != null ? request.getParameterValues("fq") : new String[0]); if (this.queryResults != null) { SearchUtils.SolrFacetConfig[] facets = SearchUtils.getFacetsForType(getView()); if (facets != null && 0 < facets.length) { List browse = options.addList("discovery"); browse.setHead(T_FILTER_HEAD); for (SearchUtils.SolrFacetConfig field : facets) { //Retrieve our values java.util.List<FilterDisplayValue> values = new ArrayList<FilterDisplayValue>(); int shownFacets = this.queryArgs.getFacetLimit(); FacetField facet = queryResults.getFacetField(field.getFacetField()); if(facet != null){ java.util.List<FacetField.Count> facetVals = facet.getValues(); if(facetVals == null) { continue; } for (FacetField.Count count : facetVals) { values.add(new FilterDisplayValue(SearchUtils.getFilterQueryDisplay(count.getName()), count.getCount(), count.getAsFilterQuery())); } } if(field.isDate()){ if(0 < values.size()){ //Check for values comming from a facet field. //If we have values we need to sort these & get the newest ones on top //There is no other way for this since solr doesn't support facet sorting TreeMap<String, FilterDisplayValue> sortedVals = new TreeMap<String, FilterDisplayValue>(Collections.reverseOrder()); for (FilterDisplayValue filterDisplayValue : values) { //No need to show empty years if(0 < filterDisplayValue.getCount()) { sortedVals.put(filterDisplayValue.getDisplayedVal(), filterDisplayValue); } } //Make sure we retrieve our sorted values values = Arrays.asList(sortedVals.values().toArray(new FilterDisplayValue[sortedVals.size()])); }else{ //Attempt to retrieve it as a facet query //Since our facet query result is returned as a hashmap we need to sort it by using a treemap TreeMap<String, Integer> sortedFacetQueries = new TreeMap<String, Integer>(queryResults.getFacetQuery()); for(String facetQuery : sortedFacetQueries.descendingKeySet()){ if(facetQuery != null && facetQuery.startsWith(field.getFacetField())){ //We have a facet query, the values looks something like: dateissued.year:[1990 TO 2000] AND -2000 //Prepare the string from {facet.field.name}:[startyear TO endyear] to startyear - endyear String name = facetQuery.substring(facetQuery.indexOf('[') + 1); name = name.substring(0, name.lastIndexOf(']')).replaceAll("TO", "-"); Integer count = sortedFacetQueries.get(facetQuery); //No need to show empty years if(0 < count) { values.add(new FilterDisplayValue(name, count, facetQuery)); } } } } } //This is needed to make sure that the date filters do not remain empty if (0 < values.size()) { Iterator<FilterDisplayValue> iter = values.iterator(); List filterValsList = browse.addList(field.getFacetField()); filterValsList.setHead(message("xmlui.ArtifactBrowser.AdvancedSearch.type_" + field.getFacetField().replace("_lc", ""))); for (int i = 0; i < shownFacets; i++) { if (!iter.hasNext()) { break; } FilterDisplayValue value = iter.next(); if (i < shownFacets - 1) { String displayedValue = value.getDisplayedVal(); String filterQuery = value.getAsFilterQuery(); if (field.getFacetField().equals("location.comm") || field.getFacetField().equals("location.coll")) { //We have a community/collection, resolve it to a dspaceObject displayedValue = SolrServiceImpl.locationToName(context, field.getFacetField(), displayedValue); } if (fqs.contains(filterQuery)) { filterValsList.addItem(Math.random() + "", "selected").addContent(displayedValue + " (" + value.getCount() + ")"); } else { String paramsQuery = ""; Enumeration keys = request.getParameterNames(); if(keys != null){ while (keys.hasMoreElements()){ String key = (String) keys.nextElement(); if(key != null && !"page".equals(key)){ String[] vals = request.getParameterValues(key); for(String paramValue : vals){ paramsQuery += key + "=" + paramValue; paramsQuery += "&"; } } } } filterValsList.addItem().addXref( contextPath + (dso == null ? "" : "/handle/" + dso.getHandle()) + "/discover?" + paramsQuery + "fq=" + filterQuery, displayedValue + " (" + value.getCount() + ")" ); } } //Show a view more url should there be more values, unless we have a date if (i == shownFacets - 1 && !field.isDate()/*&& facetField.getGap() == null*/) { addViewMoreUrl(filterValsList, dso, request, field.getFacetField()); } } } } } } } private void addViewMoreUrl(List facet, DSpaceObject dso, Request request, String fieldName) throws WingException { facet.addItem().addXref( contextPath + (dso == null ? "" : "/handle/" + dso.getHandle()) + "/search-filter?" + BrowseFacet.FACET_FIELD + "=" + fieldName + (request.getQueryString() != null ? "&" + request.getQueryString() : ""), T_VIEW_MORE ); } @Override public void recycle() { queryResults = null; queryArgs = null; } private static final class FilterDisplayValue { private String asFilterQuery; private String displayedVal; private long count; private FilterDisplayValue(String displayedVal, long count, String asFilterQuery) { this.asFilterQuery = asFilterQuery; this.displayedVal = displayedVal; this.count = count; } public String getDisplayedVal() { return displayedVal; } public long getCount() { return count; } public String getAsFilterQuery(){ return asFilterQuery; } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.discovery; import java.io.IOException; import java.sql.SQLException; import java.util.*; import java.util.Collection; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.cocoon.caching.CacheableProcessingComponent; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.dspace.app.xmlui.utils.HandleUtil; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.*; import org.dspace.app.xmlui.wing.element.Item; import org.dspace.app.xmlui.wing.element.List; import org.dspace.authorize.AuthorizeException; import org.dspace.content.*; import org.dspace.core.ConfigurationManager; import org.dspace.discovery.SearchUtils; import org.xml.sax.SAXException; import org.dspace.discovery.SearchServiceException; import org.dspace.discovery.SolrServiceImpl; /** * Preform a simple search of the repository. The user provides a simple one * field query (the url parameter is named query) and the results are processed. * * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public class SimpleSearch extends AbstractSearch implements CacheableProcessingComponent { /** * Language Strings */ private static final Message T_title = message("xmlui.ArtifactBrowser.SimpleSearch.title"); private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_trail = message("xmlui.ArtifactBrowser.SimpleSearch.trail"); private static final Message T_head = message("xmlui.ArtifactBrowser.SimpleSearch.head"); private static final Message T_full_text_search = message("xmlui.ArtifactBrowser.SimpleSearch.full_text_search"); private static final Message T_go = message("xmlui.general.go"); private static final Message T_FILTER_HELP = message("xmlui.Discovery.SimpleSearch.filter_help"); private static final Message T_FILTER_HEAD = message("xmlui.Discovery.SimpleSearch.filter_head"); private static final Message T_FILTERS_SELECTED = message("xmlui.ArtifactBrowser.SimpleSearch.filter.selected"); /** * Add Page metadata. */ public void addPageMeta(PageMeta pageMeta) throws WingException, SQLException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if ((dso instanceof Collection) || (dso instanceof Community)) { HandleUtil.buildHandleTrail(dso, pageMeta, contextPath); } pageMeta.addTrail().addContent(T_trail); } /** * build the DRI page representing the body of the search query. This * provides a widget to generate a new query and list of search results if * present. */ public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { String queryString = getQuery(); // Build the DRI Body Division search = body.addDivision("search", "primary"); search.setHead(T_head); //The search url must end with a / // String searchUrl = SearchUtils.getConfig().getString("solr.search.server"); // if(searchUrl != null && !searchUrl.endsWith("/")) // searchUrl += "/"; String searchUrl = contextPath + "/JSON/discovery/searchSolr"; search.addHidden("solr-search-url").setValue(searchUrl); search.addHidden("contextpath").setValue(contextPath); String[] fqs = getParameterFilterQueries(); Division query = search.addInteractiveDivision("general-query", "discover", Division.METHOD_GET, "secondary search"); List queryList = query.addList("search-query", List.TYPE_FORM); /* if (variableScope()) { Select scope = queryList.addItem().addSelect("scope"); scope.setLabel(T_search_scope); buildScopeList(scope); } */ Text text = queryList.addItem().addText("query"); text.setLabel(T_full_text_search); text.setValue(queryString); // queryList.addItem().addContent("Filters"); //If we have any filters, show them if(fqs.length > 0){ //if(filters != null && filters.size() > 0){ Composite composite = queryList.addItem().addComposite("facet-controls"); composite.setLabel(T_FILTERS_SELECTED); CheckBox box = composite.addCheckBox("fq"); for(String name : fqs){ //for(Map.Entry<String, Integer> filter : filters.entrySet()){ //String name = filter.getKey(); //long count = filter.getValue(); String field = name; String value = name; if(name.contains(":")) { field = name.split(":")[0]; value = name.split(":")[1]; }else{ //We have got no field, so we are using everything field = "*"; } value = value.replace("\\", ""); if("*".equals(field)) { field = "all"; } if(name.startsWith("*:")) { name = name.substring(name.indexOf(":") + 1, name.length()); } Option option = box.addOption(true,name); option.addContent(message("xmlui.ArtifactBrowser.SimpleSearch.filter." + field)); if(field.equals("location.comm") || field.equals("location.coll")){ //We have a community/collection, resolve it to a dspaceObject value = SolrServiceImpl.locationToName(context, field, value); } else if(field.endsWith("_filter")){ value = SearchUtils.getFilterQueryDisplay(value); } //Check for a range query Pattern pattern = Pattern.compile("\\[(.*? TO .*?)\\]"); Matcher matcher = pattern.matcher(value); boolean hasPattern = matcher.find(); if(hasPattern){ String[] years = matcher.group(0).replace("[", "").replace("]", "").split(" TO "); option.addContent(": " + years[0] + " - " + years[1]); continue; } option.addContent(": " + value); } } java.util.List<String> filterFields = SearchUtils.getSearchFilters(); if(0 < filterFields.size()){ //We have at least one filter so add our filter box Item item = queryList.addItem("search-filter-list", "search-filter-list"); Composite filterComp = item.addComposite("search-filter-controls"); filterComp.setLabel(T_FILTER_HEAD); filterComp.setHelp(T_FILTER_HELP); // filterComp.setLabel(""); Select select = filterComp.addSelect("filtertype"); //First of all add a default filter select.addOption("*", message("xmlui.ArtifactBrowser.SimpleSearch.filter.all")); //For each field found (at least one) add options for (String field : filterFields) { select.addOption(field, message("xmlui.ArtifactBrowser.SimpleSearch.filter." + field)); } //Add a box so we can search for our value filterComp.addText("filter"); //And last add an add button filterComp.enableAddOperation(); } buildSearchControls(query); query.addPara(null, "button-list").addButton("submit").setValue(T_go); // Build the DRI Body //Division results = body.addDivision("results", "primary"); //results.setHead(T_head); // Add the result division try { buildSearchResultsDivision(search); } catch (SearchServiceException e) { throw new UIException(e.getMessage(), e); } } /** * Returns a list of the filter queries for use in rendering pages, creating page more urls, .... * @return an array containing the filter queries */ protected String[] getParameterFilterQueries() { Request request = ObjectModelHelper.getRequest(objectModel); java.util.List<String> fqs = new ArrayList<String>(); if(request.getParameterValues("fq") != null) { fqs.addAll(Arrays.asList(request.getParameterValues("fq"))); } //Have we added a filter using the UI if(request.getParameter("filter") != null && !"".equals(request.getParameter("filter")) && request.getParameter("submit_search-filter-controls_add") != null) { fqs.add((request.getParameter("filtertype").equals("*") ? "" : request.getParameter("filtertype") + ":") + request.getParameter("filter")); } return fqs.toArray(new String[fqs.size()]); } /** * Returns all the filter queries for use by solr * This method returns more expanded filter queries then the getParameterFilterQueries * @return an array containing the filter queries */ protected String[] getSolrFilterQueries() { try { java.util.List<String> allFilterQueries = new ArrayList<String>(); Request request = ObjectModelHelper.getRequest(objectModel); java.util.List<String> fqs = new ArrayList<String>(); if(request.getParameterValues("fq") != null) { fqs.addAll(Arrays.asList(request.getParameterValues("fq"))); } String type = request.getParameter("filtertype"); String value = request.getParameter("filter"); if(value != null && !value.equals("") && request.getParameter("submit_search-filter-controls_add") != null){ String exactFq = (type.equals("*") ? "" : type + ":") + value; fqs.add(exactFq + " OR " + exactFq + "*"); } for (String fq : fqs) { //Do not put a wildcard after a range query if (fq.matches(".*\\:\\[.* TO .*\\](?![a-z 0-9]).*")) { allFilterQueries.add(fq); } else { allFilterQueries.add(fq.endsWith("*") ? fq : fq + " OR " + fq + "*"); } } return allFilterQueries.toArray(new String[allFilterQueries.size()]); } catch (RuntimeException re) { throw re; } catch (Exception e) { return null; } } /** * Get the search query from the URL parameter, if none is found the empty * string is returned. */ protected String getQuery() throws UIException { Request request = ObjectModelHelper.getRequest(objectModel); String query = decodeFromURL(request.getParameter("query")); if (query == null) { return ""; } return query.trim(); } /** * Generate a url to the simple search url. */ protected String generateURL(Map<String, String> parameters) throws UIException { String query = getQuery(); if (!"".equals(query)) { parameters.put("query", encodeForURL(query)); } if (parameters.get("page") == null) { parameters.put("page", String.valueOf(getParameterPage())); } if (parameters.get("rpp") == null) { parameters.put("rpp", String.valueOf(getParameterRpp())); } if (parameters.get("group_by") == null) { parameters.put("group_by", String.valueOf(this.getParameterGroup())); } if (parameters.get("sort_by") == null) { parameters.put("sort_by", String.valueOf(getParameterSortBy())); } if (parameters.get("order") == null) { parameters.put("order", getParameterOrder()); } if (parameters.get("etal") == null) { parameters.put("etal", String.valueOf(getParameterEtAl())); } return super.generateURL("discover", parameters); } public String getView() { return "search"; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.discovery.json; import org.apache.avalon.excalibur.pool.Recyclable; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.ProcessingException; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.apache.cocoon.environment.Response; import org.apache.cocoon.environment.SourceResolver; import org.apache.cocoon.reading.AbstractReader; import org.apache.commons.collections.ExtendedProperties; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.log4j.Logger; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.FacetParams; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.constants.Constants; import org.dspace.core.ConfigurationManager; import org.dspace.discovery.SolrServiceImpl; import org.xml.sax.SAXException; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; /** * Class used to search in solr and return a json formatted string * * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public class JSONSolrSearcher extends AbstractReader implements Recyclable { private static Logger log = Logger.getLogger(JSONSolrSearcher.class); /** These are all our parameters which can be used by this generator **/ private String query; private String[] filterQueries; private String[] facetFields; private int facetLimit; private String facetSort; private int facetMinCount; private String solrServerUrl; private String jsonWrf; /** The Cocoon response */ protected Response response; @Override public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par) throws ProcessingException, SAXException, IOException { //Retrieve all the given parameters Request request = ObjectModelHelper.getRequest(objectModel); this.response = ObjectModelHelper.getResponse(objectModel); query = request.getParameter(CommonParams.Q); if(query == null) { query = "*:*"; } //Retrieve all our filter queries filterQueries = request.getParameterValues(CommonParams.FQ); //Retrieve our facet fields facetFields = request.getParameterValues(FacetParams.FACET_FIELD); //Retrieve our facet limit (if any) if(request.getParameter(FacetParams.FACET_LIMIT) != null){ try{ facetLimit = Integer.parseInt(request.getParameter(FacetParams.FACET_LIMIT)); }catch (Exception e){ //Should an invalid value be supplied use -1 facetLimit = -1; } } else { facetLimit = -1; } //Retrieve our sorting value facetSort = request.getParameter(FacetParams.FACET_SORT); //Make sure we have a valid sorting value if(!FacetParams.FACET_SORT_INDEX.equals(facetSort) && !FacetParams.FACET_SORT_COUNT.equals(facetSort)) { facetSort = null; } //Retrieve our facet min count facetMinCount = 1; try{ facetMinCount = Integer.parseInt(request.getParameter(FacetParams.FACET_MINCOUNT)); }catch (Exception e){ facetMinCount = 1; } jsonWrf = request.getParameter("json.wrf"); //Retrieve our discovery solr path ExtendedProperties props = null; //Method that will retrieve all the possible configs we have props = ExtendedProperties.convertProperties(ConfigurationManager.getProperties()); InputStream is = null; try { File config = new File(props.getProperty("dspace.dir") + "/config/dspace-solr-search.cfg"); if (config.exists()) { props.combine(new ExtendedProperties(config.getAbsolutePath())); } else { is = SolrServiceImpl.class.getResourceAsStream("dspace-solr-search.cfg"); ExtendedProperties defaults = new ExtendedProperties(); defaults.load(is); props.combine(defaults); } } catch (Exception e) { log.error("Error while retrieving solr url", e); e.printStackTrace(); } finally { if (is != null) { is.close(); } } if(props.getProperty("solr.search.server") != null) { this.solrServerUrl = props.getProperty("solr.search.server").toString(); } } public void generate() throws IOException, SAXException, ProcessingException { if(solrServerUrl == null) { return; } Map<String, String> params = new HashMap<String, String>(); String solrRequestUrl = solrServerUrl + "/select"; //Add our default parameters params.put(CommonParams.ROWS, "0"); params.put(CommonParams.WT, "json"); //We uwe json as out output type params.put("json.nl", "map"); params.put("json.wrf", jsonWrf); params.put(FacetParams.FACET, Boolean.TRUE.toString()); //Generate our json out of the given params try { params.put(CommonParams.Q, URLEncoder.encode(query, Constants.DEFAULT_ENCODING)); } catch (UnsupportedEncodingException uee) { //Should never occur return; } params.put(FacetParams.FACET_LIMIT, String.valueOf(facetLimit)); if(facetSort != null) { params.put(FacetParams.FACET_SORT, facetSort); } params.put(FacetParams.FACET_MINCOUNT, String.valueOf(facetMinCount)); solrRequestUrl = AbstractDSpaceTransformer.generateURL(solrRequestUrl, params); if (facetFields != null || filterQueries != null) { StringBuilder urlBuilder = new StringBuilder(solrRequestUrl); if(facetFields != null){ //Add our facet fields for (String facetField : facetFields) { urlBuilder.append("&").append(FacetParams.FACET_FIELD).append("="); //This class can only be used for autocomplete facet fields if(!facetField.endsWith(".year") && !facetField.endsWith("_ac")) { urlBuilder.append(URLEncoder.encode(facetField + "_ac", Constants.DEFAULT_ENCODING)); } else { urlBuilder.append(URLEncoder.encode(facetField, Constants.DEFAULT_ENCODING)); } } } if(filterQueries != null){ for (String filterQuery : filterQueries) { urlBuilder.append("&").append(CommonParams.FQ).append("=").append(URLEncoder.encode(filterQuery, Constants.DEFAULT_ENCODING)); } } solrRequestUrl = urlBuilder.toString(); } try { GetMethod get = new GetMethod(solrRequestUrl); new HttpClient().executeMethod(get); String result = get.getResponseBodyAsString(); if(result != null){ ByteArrayInputStream inputStream = new ByteArrayInputStream(result.getBytes("UTF-8")); byte[] buffer = new byte[8192]; response.setHeader("Content-Length", String.valueOf(result.length())); int length; while ((length = inputStream.read(buffer)) > -1) { out.write(buffer, 0, length); } out.flush(); } } catch (Exception e) { log.error("Error while getting json solr result for discovery search recommendation", e); e.printStackTrace(); } } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.discovery; /** * Class used to display facets for an item * * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public class ItemFacets extends org.dspace.app.xmlui.aspect.discovery.AbstractFiltersTransformer { private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(org.dspace.app.xmlui.aspect.discovery.ItemFacets.class); /** * Display a single item */ public void addBody(org.dspace.app.xmlui.wing.element.Body body) throws org.xml.sax.SAXException, org.dspace.app.xmlui.wing.WingException, org.dspace.app.xmlui.utils.UIException, java.sql.SQLException, java.io.IOException, org.dspace.authorize.AuthorizeException { org.dspace.content.DSpaceObject dso = org.dspace.app.xmlui.utils.HandleUtil.obtainHandle(objectModel); if (!(dso instanceof org.dspace.content.Item)) { return; } org.dspace.content.Item item = (org.dspace.content.Item) dso; try { performSearch(item); } catch (org.dspace.discovery.SearchServiceException e) { log.error(e.getMessage(),e); } } @Override public void performSearch(org.dspace.content.DSpaceObject dso) throws org.dspace.discovery.SearchServiceException { if(queryResults != null) { return; } this.queryArgs = prepareDefaultFilters(getView()); this.queryArgs.setRows(1); this.queryArgs.setQuery("handle:" + dso.getHandle()); queryResults = getSearchService().search(queryArgs); } public String getView() { return "item"; } /** * Recycle */ public void recycle() { this.queryArgs = null; this.queryResults = null; super.recycle(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.discovery; import java.io.IOException; import java.io.Serializable; import java.sql.SQLException; import org.apache.cocoon.caching.CacheableProcessingComponent; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.apache.cocoon.util.HashUtil; import org.apache.excalibur.source.SourceValidity; import org.apache.excalibur.source.impl.validity.NOPValidity; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.HandleUtil; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Options; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.authorize.AuthorizeException; import org.dspace.content.DSpaceObject; import org.xml.sax.SAXException; /** * Navigation that adds code needed for discovery search * * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public class Navigation extends AbstractDSpaceTransformer implements CacheableProcessingComponent { /** * Generate the unique caching key. * This key must be unique inside the space of this component. */ public Serializable getKey() { try { Request request = ObjectModelHelper.getRequest(objectModel); String key = request.getScheme() + request.getServerName() + request.getServerPort() + request.getSitemapURI() + request.getQueryString(); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (dso != null) { key += "-" + dso.getHandle(); } return HashUtil.hash(key); } catch (SQLException sqle) { // Ignore all errors and just return that the component is not cachable. return "0"; } } /** * Generate the cache validity object. * * The cache is always valid. */ public SourceValidity getValidity() { return NOPValidity.SHARED_INSTANCE; } /** * Add the basic navigational options: * * Search - advanced search * * browse - browse by Titles - browse by Authors - browse by Dates * * language FIXME: add languages * * context no context options are added. * * action no action options are added. */ public void addOptions(Options options) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { // DSpaceObject dso = HandleUtil.obtainHandle(objectModel); // List test = options.addList("browse"); // List discovery = options.addList("discovery-search"); // discovery.setHead("Discovery"); // // discovery.addItem().addXref(contextPath + "/discover" , "Discover"); /* List browse = options.addList("browse"); browse.setHead(T_head_browse); List browseGlobal = browse.addList("global"); List browseContext = browse.addList("context"); browseGlobal.setHead(T_head_all_of_dspace); if (dso != null) { if (dso instanceof Collection) { browseContext.addItem().addXref(contextPath + "/discovery/?q=search.resourcetype%3A2+AND+location%3Al" + dso.getID(), T_head_this_collection ); } if (dso instanceof Community) { browseContext.addItem().addXref(contextPath + "/discovery/?q=search.resourcetype%3A2+AND+location%3Am" + dso.getID(), T_head_this_community ); } } browseGlobal.addItem().addXref(contextPath + "/community-list", T_head_all_of_dspace ); */ /* regulate the ordering */ options.addList("discovery"); options.addList("browse"); options.addList("account"); options.addList("context"); options.addList("administrative"); } /** * Insure that the context path is added to the page meta. */ public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { // Add metadata for quick searches: pageMeta.addMetadata("search", "simpleURL").addContent( contextPath + "/discover"); pageMeta.addMetadata("search", "advancedURL").addContent( contextPath + "/discover"); pageMeta.addMetadata("search", "queryField").addContent("query"); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.discovery; import org.apache.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.dspace.core.Constants; import org.dspace.discovery.SearchUtils; import org.apache.solr.common.SolrDocument; import org.dspace.app.xmlui.utils.HandleUtil; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.ReferenceSet; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.content.DSpaceObject; import org.xml.sax.SAXException; import java.io.IOException; import java.sql.SQLException; /** * Renders a list of recently submitted items for the collection by using discovery * * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public class CollectionRecentSubmissions extends AbstractFiltersTransformer { private static final Logger log = Logger.getLogger(CollectionRecentSubmissions.class); private static final Message T_head_recent_submissions = message("xmlui.ArtifactBrowser.CollectionViewer.head_recent_submissions"); /** * Display a single collection */ public void addBody(Body body) throws SAXException, WingException, SQLException, IOException, AuthorizeException { DSpaceObject dso = HandleUtil.obtainHandle(objectModel); // Set up the major variables Collection collection = (Collection) dso; performSearch(collection); if(queryResults == null) { return; }// queryResults; // Build the collection viewer division. Division home = body.addDivision("collection-home", "primary repository collection"); Division lastSubmittedDiv = home .addDivision("collection-recent-submission", "secondary recent-submission"); lastSubmittedDiv.setHead(T_head_recent_submissions); ReferenceSet lastSubmitted = lastSubmittedDiv.addReferenceSet( "collection-last-submitted", ReferenceSet.TYPE_SUMMARY_LIST, null, "recent-submissions"); for (SolrDocument doc : queryResults.getResults()) { lastSubmitted.addReference( SearchUtils.findDSpaceObject(context, doc)); } } /** * Get the recently submitted items for the given community or collection. * * @param scope The comm/collection. * @return the response of the query */ public void performSearch(DSpaceObject scope) { if(queryResults != null) { return; }// queryResults; queryArgs = prepareDefaultFilters(getView()); queryArgs.setQuery("search.resourcetype:" + Constants.ITEM); queryArgs.setRows(SearchUtils.getConfig().getInt("solr.recent-submissions.size", 5)); String sortField = SearchUtils.getConfig().getString("recent.submissions.sort-option"); if(sortField != null){ queryArgs.setSortField( sortField, SolrQuery.ORDER.desc ); } queryArgs.setFilterQueries("location:l" + scope.getID()); try { queryResults = getSearchService().search(queryArgs); } catch (RuntimeException e) { log.error(e.getMessage(),e); } catch (Exception e) { log.error(e.getMessage(),e); } } public String getView() { return "collection"; } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.discovery; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.util.HashUtil; import org.apache.excalibur.source.SourceValidity; import org.apache.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.dspace.app.xmlui.utils.DSpaceValidity; import org.dspace.app.xmlui.utils.HandleUtil; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.*; import org.dspace.authorize.AuthorizeException; import org.dspace.content.*; import org.dspace.content.Collection; import org.dspace.content.Item; import org.dspace.core.LogManager; import org.dspace.discovery.*; import org.dspace.sort.SortOption; import org.xml.sax.SAXException; import java.io.IOException; import java.io.Serializable; import java.sql.SQLException; import java.util.*; import java.util.List; /** * This is an abstract search page. It is a collection of search methods that * are common between diffrent search implementation. An implementer must * implement at least three methods: addBody(), getQuery(), and generateURL(). * <p/> * See the implementors SimpleSearch. * * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public abstract class AbstractSearch extends AbstractFiltersTransformer { private static final Logger log = Logger.getLogger(AbstractSearch.class); /** * Language strings */ private static final Message T_result_query = message("xmlui.ArtifactBrowser.AbstractSearch.result_query"); private static final Message T_head1_community = message("xmlui.ArtifactBrowser.AbstractSearch.head1_community"); private static final Message T_head1_collection = message("xmlui.ArtifactBrowser.AbstractSearch.head1_collection"); private static final Message T_head1_none = message("xmlui.ArtifactBrowser.AbstractSearch.head1_none"); private static final Message T_head2 = message("xmlui.ArtifactBrowser.AbstractSearch.head2"); private static final Message T_no_results = message("xmlui.ArtifactBrowser.AbstractSearch.no_results"); private static final Message T_all_of_dspace = message("xmlui.ArtifactBrowser.AbstractSearch.all_of_dspace"); private static final Message T_sort_by_relevance = message("xmlui.ArtifactBrowser.AbstractSearch.sort_by.relevance"); private static final Message T_sort_by = message("xmlui.ArtifactBrowser.AbstractSearch.sort_by"); private static final Message T_order = message("xmlui.ArtifactBrowser.AbstractSearch.order"); private static final Message T_order_asc = message("xmlui.ArtifactBrowser.AbstractSearch.order.asc"); private static final Message T_order_desc = message("xmlui.ArtifactBrowser.AbstractSearch.order.desc"); private static final Message T_rpp = message("xmlui.ArtifactBrowser.AbstractSearch.rpp"); /** * The options for results per page */ private static final int[] RESULTS_PER_PAGE_PROGRESSION = {5, 10, 20, 40, 60, 80, 100}; /** * Cached validity object */ private SourceValidity validity; /** * Generate the unique caching key. * This key must be unique inside the space of this component. */ public Serializable getKey() { try { String key = ""; // Page Parameter key += "-" + getParameterPage(); key += "-" + getParameterRpp(); key += "-" + getParameterSortBy(); key += "-" + getParameterOrder(); key += "-" + getParameterEtAl(); // What scope the search is at DSpaceObject scope = getScope(); if (scope != null) { key += "-" + scope.getHandle(); } // The actual search query. key += "-" + getQuery(); return HashUtil.hash(key); } catch (RuntimeException re) { throw re; } catch (Exception e) { // Ignore all errors and just don't cache. return "0"; } } /** * Generate the cache validity object. * <p/> * This validity object should never "over cache" because it will * perform the search, and serialize the results using the * DSpaceValidity object. */ public SourceValidity getValidity() { if (this.validity == null) { try { DSpaceValidity validity = new DSpaceValidity(); DSpaceObject scope = getScope(); validity.add(scope); performSearch(scope); SolrDocumentList results = this.queryResults.getResults(); if (results != null) { validity.add("size:" + results.size()); for (SolrDocument result : results) { validity.add(result.toString()); } } this.validity = validity.complete(); } catch (RuntimeException re) { throw re; } catch (Exception e) { this.validity = null; } // add log message that we are viewing the item // done here, as the serialization may not occur if the cache is valid logSearch(); } return this.validity; } /** * Build the resulting search DRI document. */ public abstract void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException; /** * Attach a division to the given search division named "search-results" * which contains results for this search query. * * @param search The search division to contain the search-results division. */ protected void buildSearchResultsDivision(Division search) throws IOException, SQLException, WingException, SearchServiceException { try { if (queryResults == null || queryResults.getResults() == null) { DSpaceObject scope = getScope(); this.performSearch(scope); } } catch (RuntimeException e) { log.error(e.getMessage(), e); queryResults = null; } catch (Exception e) { log.error(e.getMessage(), e); queryResults = null; } if (queryResults != null) { search.addPara("result-query", "result-query") .addContent(T_result_query.parameterize(getQuery(), queryResults.getResults().getNumFound())); } Division results = search.addDivision("search-results", "primary"); DSpaceObject searchScope = getScope(); if (searchScope instanceof Community) { Community community = (Community) searchScope; String communityName = community.getMetadata("name"); results.setHead(T_head1_community.parameterize(communityName)); } else if (searchScope instanceof Collection) { Collection collection = (Collection) searchScope; String collectionName = collection.getMetadata("name"); results.setHead(T_head1_collection.parameterize(collectionName)); } else { results.setHead(T_head1_none); } if (queryResults != null && queryResults.getResults().getNumFound() > 0) { SolrDocumentList solrResults = queryResults.getResults(); // Pagination variables. int itemsTotal = (int) solrResults.getNumFound(); int firstItemIndex = (int) solrResults.getStart() + 1; int lastItemIndex = (int) solrResults.getStart() + solrResults.size(); //if (itemsTotal < lastItemIndex) // lastItemIndex = itemsTotal; int currentPage = (int) (solrResults.getStart() / this.queryArgs.getRows()) + 1; int pagesTotal = (int) ((solrResults.getNumFound() - 1) / this.queryArgs.getRows()) + 1; Map<String, String> parameters = new HashMap<String, String>(); parameters.put("page", "{pageNum}"); String pageURLMask = generateURL(parameters); //Check for facet queries ? If we have any add them String[] fqs = getParameterFilterQueries(); if(fqs != null) { StringBuilder maskBuilder = new StringBuilder(pageURLMask); for (String fq : fqs) { maskBuilder.append("&fq=").append(fq); } pageURLMask = maskBuilder.toString(); } results.setMaskedPagination(itemsTotal, firstItemIndex, lastItemIndex, currentPage, pagesTotal, pageURLMask); // Look for any communities or collections in the mix ReferenceSet referenceSet = null; for (SolrDocument doc : solrResults) { DSpaceObject resultDSO = SearchUtils.findDSpaceObject(context, doc); if (resultDSO instanceof Community || resultDSO instanceof Collection) { if (referenceSet == null) { referenceSet = results.addReferenceSet("search-results-repository", ReferenceSet.TYPE_SUMMARY_LIST, null, "repository-search-results"); // Set a heading showing that we will be listing containers that matched: referenceSet.setHead(T_head2); } referenceSet.addReference(resultDSO); } } // Put in palce top level referenceset referenceSet = results.addReferenceSet("search-results-repository", ReferenceSet.TYPE_SUMMARY_LIST, null, "repository-search-results"); for (SolrDocument doc : solrResults) { DSpaceObject resultDSO = SearchUtils.findDSpaceObject(context, doc); if (resultDSO instanceof Item) { referenceSet.addReference(resultDSO); } } } else { results.addPara(T_no_results); } //}// Empty query } /** * Add options to the search scope field. This field determines in what * communities or collections to search for the query. * <p/> * The scope list will depend upon the current search scope. There are three * cases: * <p/> * No current scope: All top level communities are listed. * <p/> * The current scope is a community: All collections contained within the * community are listed. * <p/> * The current scope is a collection: All parent communities are listed. * * @param scope The current scope field. */ protected void buildScopeList(Select scope) throws SQLException, WingException { DSpaceObject scopeDSO = getScope(); if (scopeDSO == null) { // No scope, display all root level communities scope.addOption("/", T_all_of_dspace); scope.setOptionSelected("/"); for (Community community : Community.findAllTop(context)) { scope.addOption(community.getHandle(), community.getMetadata("name")); } } else if (scopeDSO instanceof Community) { // The scope is a community, display all collections contained // within Community community = (Community) scopeDSO; scope.addOption("/", T_all_of_dspace); scope.addOption(community.getHandle(), community.getMetadata("name")); scope.setOptionSelected(community.getHandle()); for (Collection collection : community.getCollections()) { scope.addOption(collection.getHandle(), collection.getMetadata("name")); } } else if (scopeDSO instanceof Collection) { // The scope is a collection, display all parent collections. Collection collection = (Collection) scopeDSO; scope.addOption("/", T_all_of_dspace); scope.addOption(collection.getHandle(), collection.getMetadata("name")); scope.setOptionSelected(collection.getHandle()); Community[] communities = collection.getCommunities()[0] .getAllParents(); for (Community community : communities) { scope.addOption(community.getHandle(), community.getMetadata("name")); } } } /** * Query DSpace for a list of all items / collections / or communities that * match the given search query. * * @return The associated query results. */ public void performSearch(DSpaceObject scope) throws UIException, SearchServiceException { if (queryResults != null) { return; } String query = getQuery(); //DSpaceObject scope = getScope(); int page = getParameterPage(); List<String> filterQueries = new ArrayList<String>(); if (scope instanceof Community) { filterQueries.add("location:m" + scope.getID()); } else if (scope instanceof Collection) { filterQueries.add("location:l" + scope.getID()); } String[] fqs = getSolrFilterQueries(); if (fqs != null) { filterQueries.addAll(Arrays.asList(fqs)); } queryArgs = this.prepareDefaultFilters("search", filterQueries.toArray(new String[filterQueries.size()])); if (filterQueries.size() > 0) { queryArgs.addFilterQuery(filterQueries.toArray(new String[filterQueries.size()])); } queryArgs.setRows(getParameterRpp()); String sortBy = ObjectModelHelper.getRequest(objectModel).getParameter("sort_by"); String sortOrder = ObjectModelHelper.getRequest(objectModel).getParameter("order"); //webui.itemlist.sort-option.1 = title:dc.title:title //webui.itemlist.sort-option.2 = dateissued:dc.date.issued:date //webui.itemlist.sort-option.3 = dateaccessioned:dc.date.accessioned:date //webui.itemlist.sort-option.4 = ispartof:dc.relation.ispartof:text if (sortBy != null) { if (sortOrder == null || sortOrder.equals("DESC")) { queryArgs.addSortField(sortBy, SolrQuery.ORDER.desc); } else { queryArgs.addSortField(sortBy, SolrQuery.ORDER.asc); } } else { queryArgs.addSortField("score", SolrQuery.ORDER.asc); } String groupBy = ObjectModelHelper.getRequest(objectModel).getParameter("group_by"); // Enable groupBy collapsing if designated if (groupBy != null && !groupBy.equalsIgnoreCase("none")) { /** Construct a Collapse Field Query */ queryArgs.add("collapse.field", groupBy); queryArgs.add("collapse.threshold", "1"); queryArgs.add("collapse.includeCollapsedDocs.fl", "handle"); queryArgs.add("collapse.facet", "before"); //queryArgs.a type:Article^2 // TODO: This is a hack to get Publications (Articles) to always be at the top of Groups. // TODO: I think the can be more transparently done in the solr solrconfig.xml with DISMAX and boosting /** sort in groups to get publications to top */ queryArgs.addSortField("dc.type", SolrQuery.ORDER.asc); } queryArgs.setQuery(query != null && !query.trim().equals("") ? query : "*:*"); if (page > 1) { queryArgs.setStart((page - 1) * queryArgs.getRows()); } else { queryArgs.setStart(0); } // Use mlt // queryArgs.add("mlt", "true"); // The fields to use for similarity. NOTE: if possible, these should have a stored TermVector // queryArgs.add("mlt.fl", "author"); // Minimum Term Frequency - the frequency below which terms will be ignored in the source doc. // queryArgs.add("mlt.mintf", "1"); // Minimum Document Frequency - the frequency at which words will be ignored which do not occur in at least this many docs. // queryArgs.add("mlt.mindf", "1"); //queryArgs.add("mlt.q", ""); // mlt.minwl // minimum word length below which words will be ignored. // mlt.maxwl // maximum word length above which words will be ignored. // mlt.maxqt // maximum number of query terms that will be included in any generated query. // mlt.maxntp // maximum number of tokens to parse in each example doc field that is not stored with TermVector support. // mlt.boost // [true/false] set if the query will be boosted by the interesting term relevance. // mlt.qf // Query fields and their boosts using the same format as that used in DisMaxRequestHandler. These fields must also be specified in mlt.fl. //filePost.addParameter("fl", "handle, "search.resourcetype")"); //filePost.addParameter("field", "search.resourcetype"); //Set the default limit to 11 /* ClientUtils.escapeQueryChars(location) //f.category.facet.limit=5 for(Enumeration en = request.getParameterNames(); en.hasMoreElements();) { String key = (String)en.nextElement(); if(key.endsWith(".facet.limit")) { filePost.addParameter(key, request.getParameter(key)); } } */ this.queryResults = getSearchService().search(queryArgs); } /** * Returns a list of the filter queries for use in rendering pages, creating page more urls, .... * @return an array containing the filter queries */ protected String[] getParameterFilterQueries(){ try { return ObjectModelHelper.getRequest(objectModel).getParameterValues("fq"); } catch (Exception e) { return null; } } /** * Returns all the filter queries for use by solr * This method returns more expanded filter queries then the getParameterFilterQueries * @return an array containing the filter queries */ protected String[] getSolrFilterQueries() { try { return ObjectModelHelper.getRequest(objectModel).getParameterValues("fq"); } catch (Exception e) { return null; } } protected String[] getFacetsList() { try { return ObjectModelHelper.getRequest(objectModel).getParameterValues("fl"); } catch (Exception e) { return null; } } protected int getParameterPage() { try { return Integer.parseInt(ObjectModelHelper.getRequest(objectModel).getParameter("page")); } catch (Exception e) { return 1; } } protected int getParameterRpp() { try { return Integer.parseInt(ObjectModelHelper.getRequest(objectModel).getParameter("rpp")); } catch (Exception e) { return 10; } } protected String getParameterSortBy() { String s = ObjectModelHelper.getRequest(objectModel).getParameter("sort_by"); return s != null ? s : "score"; } protected String getParameterGroup() { String s = ObjectModelHelper.getRequest(objectModel).getParameter("group_by"); return s != null ? s : "none"; } protected String getParameterOrder() { String s = ObjectModelHelper.getRequest(objectModel).getParameter("order"); return s != null ? s : "DESC"; } protected int getParameterEtAl() { try { return Integer.parseInt(ObjectModelHelper.getRequest(objectModel).getParameter("etal")); } catch (Exception e) { return 0; } } /** * Determine if the scope of the search should fixed or is changeable by the * user. * <p/> * The search scope when preformed by url, i.e. they are at the url handle/xxxx/xx/search * then it is fixed. However at the global level the search is variable. * * @return true if the scope is variable, false otherwise. */ protected boolean variableScope() throws SQLException { return (HandleUtil.obtainHandle(objectModel) == null); } /** * Extract the query string. Under most implementations this will be derived * from the url parameters. * * @return The query string. */ protected abstract String getQuery() throws UIException; /** * Generate a url to the given search implementation with the associated * parameters included. * * @param parameters * @return The post URL */ protected abstract String generateURL(Map<String, String> parameters) throws UIException; /** * Recycle */ public void recycle() { this.validity = null; super.recycle(); } protected void buildSearchControls(Division div) throws WingException { Table controlsTable = div.addTable("search-controls", 1, 3); //Table controlsTable = div.addTable("search-controls", 1, 4); Row controlsRow = controlsTable.addRow(Row.ROLE_DATA); // Create a control for the number of records to display Cell rppCell = controlsRow.addCell(); rppCell.addContent(T_rpp); Select rppSelect = rppCell.addSelect("rpp"); for (int i : RESULTS_PER_PAGE_PROGRESSION) { rppSelect.addOption((i == getParameterRpp()), i, Integer.toString(i)); } /* Cell groupCell = controlsRow.addCell(); try { // Create a drop down of the different sort columns available groupCell.addContent(T_group_by); Select groupSelect = groupCell.addSelect("group_by"); groupSelect.addOption(false, "none", T_group_by_none); String[] groups = {"publication_grp"}; for (String group : groups) { groupSelect.addOption(group.equals(getParameterGroup()), group, message("xmlui.ArtifactBrowser.AbstractSearch.group_by." + group)); } } catch (Exception se) { throw new WingException("Unable to get group options", se); } */ Cell sortCell = controlsRow.addCell(); // Create a drop down of the different sort columns available sortCell.addContent(T_sort_by); Select sortSelect = sortCell.addSelect("sort_by"); sortSelect.addOption(false, "score", T_sort_by_relevance); for (String sortField : SearchUtils.getSortFields()) { sortField += "_sort"; sortSelect.addOption((sortField.equals(getParameterSortBy())), sortField, message("xmlui.ArtifactBrowser.AbstractSearch.sort_by." + sortField)); } // Create a control to changing ascending / descending order Cell orderCell = controlsRow.addCell(); orderCell.addContent(T_order); Select orderSelect = orderCell.addSelect("order"); orderSelect.addOption(SortOption.ASCENDING.equals(getParameterOrder()), SortOption.ASCENDING, T_order_asc); orderSelect.addOption(SortOption.DESCENDING.equals(getParameterOrder()), SortOption.DESCENDING, T_order_desc); // Create a control for the number of authors per item to display // FIXME This is currently disabled, as the supporting functionality // is not currently present in xmlui //if (isItemBrowse(info)) //{ // controlsForm.addContent(T_etal); // Select etalSelect = controlsForm.addSelect(BrowseParams.ETAL); // // etalSelect.addOption((info.getEtAl() < 0), 0, T_etal_all); // etalSelect.addOption(1 == info.getEtAl(), 1, Integer.toString(1)); // // for (int i = 5; i <= 50; i += 5) // { // etalSelect.addOption(i == info.getEtAl(), i, Integer.toString(i)); // } //} } protected void logSearch() { int countCommunities = 0; int countCollections = 0; int countItems = 0; /** * TODO: Maybe we can create a default "type" facet for this * will give results for Items, Communities and Collection types * benefits... no iteration over results at all to sum types * leaves it upto solr... for (Object type : queryResults.getHitTypes()) { if (type instanceof Integer) { switch (((Integer)type).intValue()) { case Constants.ITEM: countItems++; break; case Constants.COLLECTION: countCollections++; break; case Constants.COMMUNITY: countCommunities++; break; } } } */ String logInfo = ""; try { DSpaceObject dsoScope = getScope(); if (dsoScope instanceof Collection) { logInfo = "collection_id=" + dsoScope.getID() + ","; } else if (dsoScope instanceof Community) { logInfo = "community_id=" + dsoScope.getID() + ","; } } catch (SQLException sqle) { // Ignore, as we are only trying to get the scope to add detail to the log message } log.info(LogManager.getHeader(context, "search", logInfo + "query=\"" + queryArgs.getQuery() + "\",results=(" + countCommunities + "," + countCollections + "," + countItems + ")")); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.discovery; import java.io.IOException; import java.io.Serializable; import java.sql.SQLException; import org.apache.cocoon.caching.CacheableProcessingComponent; import org.apache.cocoon.util.HashUtil; import org.apache.excalibur.source.SourceValidity; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.DSpaceValidity; import org.dspace.app.xmlui.utils.HandleUtil; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.*; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.content.DSpaceObject; import org.dspace.core.ConfigurationManager; import org.xml.sax.SAXException; /** * Renders the search box for a collection * * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public class CollectionSearch extends AbstractDSpaceTransformer implements CacheableProcessingComponent { /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_full_text_search = message("xmlui.ArtifactBrowser.CollectionViewer.full_text_search"); private static final Message T_go = message("xmlui.general.go"); public static final Message T_untitled = message("xmlui.general.untitled"); /** Might implement browse links to activate views into search instead... private static final Message T_head_browse = message("xmlui.ArtifactBrowser.CollectionViewer.head_browse"); private static final Message T_browse_titles = message("xmlui.ArtifactBrowser.CollectionViewer.browse_titles"); private static final Message T_browse_authors = message("xmlui.ArtifactBrowser.CollectionViewer.browse_authors"); private static final Message T_browse_dates = message("xmlui.ArtifactBrowser.CollectionViewer.browse_dates"); private static final Message T_advanced_search_link= message("xmlui.ArtifactBrowser.CollectionViewer.advanced_search_link"); */ /** Cached validity object */ private SourceValidity validity; /** * Generate the unique caching key. * This key must be unique inside the space of this component. */ public Serializable getKey() { try { DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (dso == null) { return "0"; } return HashUtil.hash(dso.getHandle()); } catch (SQLException sqle) { // Ignore all errors and just return that the component is not // cachable. return "0"; } } /** * Generate the cache validity object. * * The validity object will include the collection being viewed and * all recently submitted items. This does not include the community / collection * hierarch, when this changes they will not be reflected in the cache. */ public SourceValidity getValidity() { if (this.validity == null) { Collection collection = null; try { DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (dso == null) { return null; } if (!(dso instanceof Collection)) { return null; } collection = (Collection) dso; DSpaceValidity validity = new DSpaceValidity(); // Add the actual collection; validity.add(collection); this.validity = validity.complete(); } catch (Exception e) { // Just ignore all errors and return an invalid cache. } } return this.validity; } /** * Add a page title and trail links. */ public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (!(dso instanceof Collection)) { return; } Collection collection = (Collection) dso; // Set the page title String name = collection.getMetadata("name"); if (name == null || name.length() == 0) { pageMeta.addMetadata("title").addContent(T_untitled); } else { pageMeta.addMetadata("title").addContent(name); } pageMeta.addTrailLink(contextPath + "/",T_dspace_home); HandleUtil.buildHandleTrail(collection,pageMeta,contextPath); // Add RSS links if available String formats = ConfigurationManager.getProperty("webui.feed.formats"); if ( formats != null ) { for (String format : formats.split(",")) { // Remove the protocol number, i.e. just list 'rss' or' atom' String[] parts = format.split("_"); if (parts.length < 1) { continue; } String feedFormat = parts[0].trim()+"+xml"; String feedURL = contextPath+"/feed/"+format.trim()+"/"+collection.getHandle(); pageMeta.addMetadata("feed", feedFormat).addContent(feedURL); } } } /** * Display a single collection */ public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (!(dso instanceof Collection)) { return; } // Set up the major variables Collection collection = (Collection) dso; // Build the collection viewer division. Division home = body.addDivision("collection-home", "primary repository collection"); String name = collection.getMetadata("name"); if (name == null || name.length() == 0) { home.setHead(T_untitled); } else { home.setHead(name); } // The search / browse box. { Division search = home.addDivision("collection-search-browse", "secondary search-browse"); // Search query Division query = search.addInteractiveDivision("collection-search", contextPath + "/handle/" + collection.getHandle() + "/discover", Division.METHOD_POST, "secondary search"); Para para = query.addPara("search-query", null); para.addContent(T_full_text_search); para.addContent(" "); para.addText("query"); para.addContent(" "); para.addButton("submit").setValue(T_go); //query.addPara().addXref(contextPath + "/handle/" + collection.getHandle()+ "/advanced-search", T_advanced_search_link); // Browse by list //Division browseDiv = search.addDivision("collection-browse","secondary browse"); //List browse = browseDiv.addList("collection-browse", List.TYPE_SIMPLE, // "collection-browse"); //browse.setHead(T_head_browse); //String url = contextPath + "/handle/" + collection.getHandle(); //browse.addItemXref(url + "/browse?type=title",T_browse_titles); //browse.addItemXref(url + "/browse?type=author",T_browse_authors); //browse.addItemXref(url + "/browse?type=dateissued",T_browse_dates); } } /** * Recycle */ public void recycle() { // Clear out our item's cache. this.validity = null; super.recycle(); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.discovery; import java.io.IOException; import java.io.Serializable; import java.sql.SQLException; import org.apache.cocoon.caching.CacheableProcessingComponent; import org.apache.excalibur.source.SourceValidity; import org.apache.excalibur.source.impl.validity.NOPValidity; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.authorize.AuthorizeException; import org.dspace.core.ConfigurationManager; import org.xml.sax.SAXException; /** * Adds a searchbox on the dspace home page * * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public class SiteViewer extends AbstractDSpaceTransformer implements CacheableProcessingComponent { /** Language Strings */ public static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_head = message("xmlui.ArtifactBrowser.FrontPageSearch.head"); private static final Message T_para1 = message("xmlui.ArtifactBrowser.FrontPageSearch.para1"); private static final Message T_go = message("xmlui.general.go"); /** * Generate the unique caching key. * This key must be unique inside the space of this component. */ public Serializable getKey() { return "1"; } /** * Generate the cache validity object. */ public SourceValidity getValidity() { return NOPValidity.SHARED_INSTANCE; } /** * Add a page title and trail links. */ public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { pageMeta.addMetadata("title").addContent(T_dspace_home); pageMeta.addTrailLink(contextPath, T_dspace_home); // Add RSS links if available String formats = ConfigurationManager.getProperty("webui.feed.formats"); if ( formats != null ) { for (String format : formats.split(",")) { // Remove the protocol number, i.e. just list 'rss' or' atom' String[] parts = format.split("_"); if (parts.length < 1) { continue; } String feedFormat = parts[0].trim()+"+xml"; String feedURL = contextPath+"/feed/"+format.trim()+"/site"; pageMeta.addMetadata("feed", feedFormat).addContent(feedURL); } } } public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { Division search = body.addInteractiveDivision("front-page-search",contextPath+"/discover",Division.METHOD_GET,"primary"); search.setHead(T_head); search.addPara(T_para1); Para fields = search.addPara(); fields.addText("query"); fields.addButton("submit").setValue(T_go); } }
Java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.discovery; import org.apache.cocoon.caching.CacheableProcessingComponent; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.apache.cocoon.util.HashUtil; import org.apache.excalibur.source.SourceValidity; import org.apache.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.params.FacetParams; import org.dspace.app.util.Util; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.DSpaceValidity; import org.dspace.app.xmlui.utils.HandleUtil; import org.dspace.app.xmlui.utils.RequestUtils; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.*; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DSpaceObject; import org.dspace.core.Constants; import org.dspace.discovery.SearchService; import org.dspace.discovery.SearchServiceException; import org.dspace.discovery.SearchUtils; import org.dspace.discovery.SolrServiceImpl; import org.dspace.services.ConfigurationService; import org.dspace.utils.DSpace; import org.xml.sax.SAXException; import java.io.IOException; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; /** * Filter which displays facets on which a user can filter his discovery search * * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public class SearchFacetFilter extends AbstractDSpaceTransformer implements CacheableProcessingComponent { private static final Logger log = Logger.getLogger(BrowseFacet.class); private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_starts_with = message("xmlui.Discovery.AbstractSearch.startswith"); private static final Message T_starts_with_help = message("xmlui.Discovery.AbstractSearch.startswith.help"); /** * The cache of recently submitted items */ protected QueryResponse queryResults; /** * Cached validity object */ protected SourceValidity validity; /** * Cached query arguments */ protected SolrQuery queryArgs; private int DEFAULT_PAGE_SIZE = 10; private ConfigurationService config = null; private SearchService searchService = null; private static final Message T_go = message("xmlui.general.go"); public SearchFacetFilter() { DSpace dspace = new DSpace(); config = dspace.getConfigurationService(); searchService = dspace.getServiceManager().getServiceByName(SearchService.class.getName(),SearchService.class); } /** * Generate the unique caching key. * This key must be unique inside the space of this component. */ public Serializable getKey() { try { DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (dso == null) { return "0"; } return HashUtil.hash(dso.getHandle()); } catch (SQLException sqle) { // Ignore all errors and just return that the component is not // cachable. return "0"; } } /** * Generate the cache validity object. * <p/> * The validity object will include the collection being viewed and * all recently submitted items. This does not include the community / collection * hierarch, when this changes they will not be reflected in the cache. */ public SourceValidity getValidity() { if (this.validity == null) { try { DSpaceValidity validity = new DSpaceValidity(); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (dso != null) { // Add the actual collection; validity.add(dso); } // add reciently submitted items, serialize solr query contents. QueryResponse response = getQueryResponse(dso); validity.add("numFound:" + response.getResults().getNumFound()); for (SolrDocument doc : response.getResults()) { validity.add(doc.toString()); } for (SolrDocument doc : response.getResults()) { validity.add(doc.toString()); } for (FacetField field : response.getFacetFields()) { validity.add(field.getName()); for (FacetField.Count count : field.getValues()) { validity.add(count.getName() + count.getCount()); } } this.validity = validity.complete(); } catch (Exception e) { // Just ignore all errors and return an invalid cache. } //TODO: dependent on tags as well :) } return this.validity; } /** * Get the recently submitted items for the given community or collection. * * @param scope The collection. */ protected QueryResponse getQueryResponse(DSpaceObject scope) { Request request = ObjectModelHelper.getRequest(objectModel); if (queryResults != null) { return queryResults; } queryArgs = new SolrQuery(); //Make sure we add our default filters queryArgs.addFilterQuery(SearchUtils.getDefaultFilters("search")); queryArgs.setQuery("search.resourcetype: " + Constants.ITEM + ((request.getParameter("query") != null && !"".equals(request.getParameter("query"))) ? " AND (" + request.getParameter("query") + ")" : "")); // queryArgs.setQuery("search.resourcetype:" + Constants.ITEM); queryArgs.setRows(0); queryArgs.addFilterQuery(getParameterFilterQueries()); //Set the default limit to 11 //query.setFacetLimit(11); queryArgs.setFacetMinCount(1); //sort //TODO: why this kind of sorting ? Should the sort not be on how many times the value appears like we do in the filter by sidebar ? queryArgs.setFacetSort(config.getPropertyAsType("solr.browse.sort","lex")); queryArgs.setFacet(true); String facetField = request.getParameter(SearchFilterParam.FACET_FIELD); int offset = RequestUtils.getIntParameter(request, SearchFilterParam.OFFSET); if (offset == -1) { offset = 0; } if(facetField.endsWith(".year")){ // TODO: dates are now handled in another way, throw this away? queryArgs.setParam(FacetParams.FACET_OFFSET, "0"); queryArgs.setParam(FacetParams.FACET_LIMIT, "1000000"); } else { queryArgs.setParam(FacetParams.FACET_OFFSET, String.valueOf(offset)); //We add +1 so we can use the extra one to make sure that we need to show the next page queryArgs.setParam(FacetParams.FACET_LIMIT, String.valueOf(DEFAULT_PAGE_SIZE + 1)); } if (scope != null) /* top level search / community */ { if (scope instanceof Community) { queryArgs.setFilterQueries("location:m" + scope.getID()); } else if (scope instanceof Collection) { queryArgs.setFilterQueries("location:l" + scope.getID()); } } boolean isDate = false; if(facetField.endsWith("_dt")){ facetField = facetField.split("_")[0]; isDate = true; } if (isDate) { queryArgs.setParam(FacetParams.FACET_DATE, facetField); queryArgs.setParam(FacetParams.FACET_DATE_GAP,"+1YEAR"); Date lowestDate = getLowestDateValue(queryArgs.getQuery(), facetField, queryArgs.getFilterQueries()); int thisYear = Calendar.getInstance().get(Calendar.YEAR); DateFormat formatter = new SimpleDateFormat("yyyy"); int maxEndYear = Integer.parseInt(formatter.format(lowestDate)); //Since we have a date, we need to find the last year String startDate = "NOW/YEAR-" + SearchUtils.getConfig().getString("solr.date.gap", "10") + "YEARS"; String endDate = "NOW"; int startYear = thisYear - (offset + DEFAULT_PAGE_SIZE); // We shouldn't go lower then our max bottom year // Make sure to substract one so the bottom year is also counted ! if(startYear < maxEndYear) { startYear = maxEndYear - 1; } if(0 < offset){ //Say that we have an offset of 10 years //we need to go back 10 years (2010 - (2010 - 10)) //(add one to compensate for the NOW in the start) int endYear = thisYear - offset + 1; endDate = "NOW/YEAR-" + (thisYear - endYear) + "YEARS"; //Add one to the startyear to get one more result //When we select NOW, the current year is also used (so auto+1) } startDate = "NOW/YEAR-" + (thisYear - startYear) + "YEARS"; queryArgs.setParam(FacetParams.FACET_DATE_START, startDate); queryArgs.setParam(FacetParams.FACET_DATE_END, endDate); System.out.println(startDate); System.out.println(endDate); } else { if(request.getParameter(SearchFilterParam.STARTS_WITH) != null) { queryArgs.setFacetPrefix(facetField, request.getParameter(SearchFilterParam.STARTS_WITH).toLowerCase()); } queryArgs.addFacetField(facetField); } try { queryResults = searchService.search(queryArgs); } catch (SearchServiceException e) { log.error(e.getMessage(), e); } return queryResults; } /** * Retrieves the lowest date value in the given field * @param query a solr query * @param dateField the field for which we want to retrieve our date * @param filterquery the filterqueries * @return the lowest date found, in a date object */ private Date getLowestDateValue(String query, String dateField, String... filterquery){ try { SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery(query); solrQuery.setFields(dateField); solrQuery.setRows(1); solrQuery.setSortField(dateField, SolrQuery.ORDER.asc); solrQuery.setFilterQueries(filterquery); QueryResponse rsp = searchService.search(solrQuery); if(0 < rsp.getResults().getNumFound()){ return (Date) rsp.getResults().get(0).getFieldValue(dateField); } }catch (Exception e){ e.printStackTrace(); } return null; } /** * Add a page title and trail links. */ public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, SQLException, IOException, AuthorizeException { Request request = ObjectModelHelper.getRequest(objectModel); String facetField = request.getParameter(SearchFilterParam.FACET_FIELD); pageMeta.addMetadata("title").addContent(message("xmlui.Discovery.AbstractSearch.type_" + facetField)); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if ((dso instanceof Collection) || (dso instanceof Community)) { HandleUtil.buildHandleTrail(dso, pageMeta, contextPath); } pageMeta.addTrail().addContent(message("xmlui.Discovery.AbstractSearch.type_" + facetField)); } @Override public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { Request request = ObjectModelHelper.getRequest(objectModel); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); SearchFilterParam browseParams = new SearchFilterParam(request); // Build the DRI Body Division div = body.addDivision("browse-by-" + request.getParameter(SearchFilterParam.FACET_FIELD), "primary"); addBrowseJumpNavigation(div, browseParams, request); // Set up the major variables //Collection collection = (Collection) dso; // Build the collection viewer division. //Make sure we get our results queryResults = getQueryResponse(dso); if (this.queryResults != null) { java.util.List<FacetField> facetFields = this.queryResults.getFacetFields(); if (facetFields == null) { facetFields = new ArrayList<FacetField>(); } facetFields.addAll(this.queryResults.getFacetDates()); if (facetFields.size() > 0) { FacetField field = facetFields.get(0); java.util.List<FacetField.Count> values = field.getValues(); if(field.getGap() != null){ //We are dealing with dates so flip em, top date comes first Collections.reverse(values); } Division results = body.addDivision("browse-by-" + field + "-results", "primary"); results.setHead(message("xmlui.Discovery.AbstractSearch.type_" + browseParams.getFacetField())); if (values != null && 0 < values.size()) { // Find our faceting offset int offSet = 0; try { offSet = Integer.parseInt(queryArgs.get(FacetParams.FACET_OFFSET)); } catch (NumberFormatException e) { //Ignore } //Only show the nextpageurl if we have at least one result following our current results String nextPageUrl = null; if(field.getName().endsWith(".year")){ offSet = Util.getIntParameter(request, SearchFilterParam.OFFSET); offSet = offSet == -1 ? 0 : offSet; if ((offSet + DEFAULT_PAGE_SIZE) < values.size()) { nextPageUrl = getNextPageURL(browseParams, request); } }else{ if (values.size() == (DEFAULT_PAGE_SIZE + 1)) { nextPageUrl = getNextPageURL(browseParams, request); } } int shownItemsMax; if(field.getName().endsWith(".year")){ if((values.size() - offSet) < DEFAULT_PAGE_SIZE) { shownItemsMax = values.size(); } else { shownItemsMax = DEFAULT_PAGE_SIZE; } }else{ shownItemsMax = offSet + (DEFAULT_PAGE_SIZE < values.size() ? values.size() - 1 : values.size()); } // We put our total results to -1 so this doesn't get shown in the results (will be hidden by the xsl) // The reason why we do this is because solr 1.4 can't retrieve the total number of facets found results.setSimplePagination(-1, offSet + 1, shownItemsMax, getPreviousPageURL(browseParams, request), nextPageUrl); Table singleTable = results.addTable("browse-by-" + field + "-results", (int) (queryResults.getResults().getNumFound() + 1), 1); List<String> filterQueries = new ArrayList<String>(); if(request.getParameterValues("fq") != null) { filterQueries = Arrays.asList(request.getParameterValues("fq")); } if(field.getName().endsWith(".year")){ int start = (values.size() - 1) - offSet; int end = start - DEFAULT_PAGE_SIZE; if(end < 0) { end = 0; } else { end++; } for(int i = start; end <= i; i--) { FacetField.Count value = values.get(i); renderFacetField(browseParams, dso, field, singleTable, filterQueries, value); } }else{ int end = values.size(); if(DEFAULT_PAGE_SIZE < end) { end = DEFAULT_PAGE_SIZE; } for (int i = 0; i < end; i++) { FacetField.Count value = values.get(i); renderFacetField(browseParams, dso, field, singleTable, filterQueries, value); } } }else{ results.addPara(message("xmlui.discovery.SearchFacetFilter.no-results")); } } } } private void addBrowseJumpNavigation(Division div, SearchFilterParam browseParams, Request request) throws WingException { Division jump = div.addInteractiveDivision("filter-navigation", contextPath + "/search-filter", Division.METHOD_POST, "secondary navigation"); Map<String, String> params = new HashMap<String, String>(); params.putAll(browseParams.getCommonBrowseParams()); // Add all the query parameters as hidden fields on the form for(Map.Entry<String, String> param : params.entrySet()){ jump.addHidden(param.getKey()).setValue(param.getValue()); } String[] filterQueries = getParameterFilterQueries(); for (String filterQuery : filterQueries) { jump.addHidden("fq").setValue(filterQuery); } //We cannot create a filter for dates if(!browseParams.getFacetField().endsWith(".year")){ // Create a clickable list of the alphabet org.dspace.app.xmlui.wing.element.List jumpList = jump.addList("jump-list", org.dspace.app.xmlui.wing.element.List.TYPE_SIMPLE, "alphabet"); //Create our basic url String basicUrl = generateURL("search-filter", params); //Add any filter queries basicUrl = addFilterQueriesToUrl(basicUrl); //TODO: put this back ! // jumpList.addItemXref(generateURL("browse", letterQuery), "0-9"); for (char c = 'A'; c <= 'Z'; c++) { String linkUrl = basicUrl + "&" + SearchFilterParam.STARTS_WITH + "=" + Character.toString(c).toLowerCase(); jumpList.addItemXref(linkUrl, Character .toString(c)); } // Create a free text field for the initial characters Para jumpForm = jump.addPara(); jumpForm.addContent(T_starts_with); jumpForm.addText("starts_with").setHelp(T_starts_with_help); jumpForm.addButton("submit").setValue(T_go); } } private void renderFacetField(SearchFilterParam browseParams, DSpaceObject dso, FacetField field, Table singleTable, List<String> filterQueries, FacetField.Count value) throws SQLException, WingException, UnsupportedEncodingException { String displayedValue = value.getName(); String filterQuery = value.getAsFilterQuery(); if (field.getName().equals("location.comm") || field.getName().equals("location.coll")) { //We have a community/collection, resolve it to a dspaceObject displayedValue = SolrServiceImpl.locationToName(context, field.getName(), displayedValue); } if(field.getGap() != null){ //We have a date get the year so we can display it DateFormat simpleDateformat = new SimpleDateFormat("yyyy"); displayedValue = simpleDateformat.format(SolrServiceImpl.toDate(displayedValue)); filterQuery = ClientUtils.escapeQueryChars(value.getFacetField().getName()) + ":" + displayedValue + "*"; } Cell cell = singleTable.addRow().addCell(); //No use in selecting the same filter twice if(filterQueries.contains(filterQuery)){ cell.addContent(SearchUtils.getFilterQueryDisplay(displayedValue) + " (" + value.getCount() + ")"); } else { //Add the basics Map<String, String> urlParams = new HashMap<String, String>(); urlParams.putAll(browseParams.getCommonBrowseParams()); String url = generateURL(contextPath + (dso == null ? "" : "/handle/" + dso.getHandle()) + "/discover", urlParams); //Add already existing filter queries url = addFilterQueriesToUrl(url); //Last add the current filter query url += "&fq=" + filterQuery; cell.addXref(url, SearchUtils.getFilterQueryDisplay(displayedValue) + " (" + value.getCount() + ")" ); } } private String getNextPageURL(SearchFilterParam browseParams, Request request) { int offSet = Util.getIntParameter(request, SearchFilterParam.OFFSET); if (offSet == -1) { offSet = 0; } Map<String, String> parameters = new HashMap<String, String>(); parameters.putAll(browseParams.getCommonBrowseParams()); parameters.putAll(browseParams.getControlParameters()); parameters.put(SearchFilterParam.OFFSET, String.valueOf(offSet + DEFAULT_PAGE_SIZE)); //TODO: correct comm/collection url // Add the filter queries String url = generateURL("search-filter", parameters); url = addFilterQueriesToUrl(url); return url; } private String getPreviousPageURL(SearchFilterParam browseParams, Request request) { //If our offset should be 0 then we shouldn't be able to view a previous page url if ("0".equals(queryArgs.get(FacetParams.FACET_OFFSET)) && Util.getIntParameter(request, "offset") == -1) { return null; } int offset = Util.getIntParameter(request, SearchFilterParam.OFFSET); if(offset == -1 || offset == 0) { return null; } Map<String, String> parameters = new HashMap<String, String>(); parameters.putAll(browseParams.getCommonBrowseParams()); parameters.putAll(browseParams.getControlParameters()); parameters.put(SearchFilterParam.OFFSET, String.valueOf(offset - DEFAULT_PAGE_SIZE)); //TODO: correct comm/collection url // Add the filter queries String url = generateURL("search-filter", parameters); url = addFilterQueriesToUrl(url); return url; } /** * Recycle */ public void recycle() { // Clear out our item's cache. this.queryResults = null; this.validity = null; super.recycle(); } public String addFilterQueriesToUrl(String url){ String[] fqs = getParameterFilterQueries(); if (fqs != null) { StringBuilder urlBuilder = new StringBuilder(url); for (String fq : fqs) { urlBuilder.append("&fq=").append(fq); } return urlBuilder.toString(); } return url; } private String[] getParameterFilterQueries() { Request request = ObjectModelHelper.getRequest(objectModel); return request.getParameterValues("fq") != null ? request.getParameterValues("fq") : new String[0]; } private static class SearchFilterParam { private Request request; /** The always present commond params **/ public static final String FACET_FIELD = "field"; /** The browse control params **/ public static final String OFFSET = "offset"; public static final String STARTS_WITH = "starts_with"; private SearchFilterParam(Request request){ this.request = request; } public String getFacetField(){ return request.getParameter(FACET_FIELD); } public Map<String, String> getCommonBrowseParams(){ Map<String, String> result = new HashMap<String, String>(); result.put(FACET_FIELD, request.getParameter(FACET_FIELD)); return result; } public Map<String, String> getControlParameters(){ Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put(OFFSET, request.getParameter(OFFSET)); if(request.getParameter(STARTS_WITH) != null) { paramMap.put(STARTS_WITH, request.getParameter(STARTS_WITH)); } return paramMap; } } }
Java
package org.json; /** * The JSONException is thrown by the JSON.org classes when things are amiss. * @author JSON.org * @version 2010-12-24 */ public class JSONException extends Exception { private static final long serialVersionUID = 0; private Throwable cause; /** * Constructs a JSONException with an explanatory message. * @param message Detail about the reason for the exception. */ public JSONException(String message) { super(message); } public JSONException(Throwable cause) { super(cause.getMessage()); this.cause = cause; } public Throwable getCause() { return this.cause; } }
Java
package org.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.util.Iterator; /** * This provides static methods to convert an XML text into a JSONObject, * and to covert a JSONObject into an XML text. * @author JSON.org * @version 2011-02-11 */ public class XML { /** The Character '&'. */ public static final Character AMP = new Character('&'); /** The Character '''. */ public static final Character APOS = new Character('\''); /** The Character '!'. */ public static final Character BANG = new Character('!'); /** The Character '='. */ public static final Character EQ = new Character('='); /** The Character '>'. */ public static final Character GT = new Character('>'); /** The Character '<'. */ public static final Character LT = new Character('<'); /** The Character '?'. */ public static final Character QUEST = new Character('?'); /** The Character '"'. */ public static final Character QUOT = new Character('"'); /** The Character '/'. */ public static final Character SLASH = new Character('/'); /** * Replace special characters with XML escapes: * <pre> * &amp; <small>(ampersand)</small> is replaced by &amp;amp; * &lt; <small>(less than)</small> is replaced by &amp;lt; * &gt; <small>(greater than)</small> is replaced by &amp;gt; * &quot; <small>(double quote)</small> is replaced by &amp;quot; * </pre> * @param string The string to be escaped. * @return The escaped string. */ public static String escape(String string) { StringBuffer sb = new StringBuffer(); for (int i = 0, length = string.length(); i < length; i++) { char c = string.charAt(i); switch (c) { case '&': sb.append("&amp;"); break; case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '"': sb.append("&quot;"); break; case '\'': sb.append("&apos;"); break; default: sb.append(c); } } return sb.toString(); } /** * Throw an exception if the string contains whitespace. * Whitespace is not allowed in tagNames and attributes. * @param string * @throws JSONException */ public static void noSpace(String string) throws JSONException { int i, length = string.length(); if (length == 0) { throw new JSONException("Empty string."); } for (i = 0; i < length; i += 1) { if (Character.isWhitespace(string.charAt(i))) { throw new JSONException("'" + string + "' contains a space character."); } } } /** * Scan the content following the named tag, attaching it to the context. * @param x The XMLTokener containing the source string. * @param context The JSONObject that will include the new material. * @param name The tag name. * @return true if the close tag is processed. * @throws JSONException */ private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException { char c; int i; JSONObject jsonobject = null; String string; String tagName; Object token; // Test for and skip past these forms: // <!-- ... --> // <! ... > // <![ ... ]]> // <? ... ?> // Report errors for these forms: // <> // <= // << token = x.nextToken(); // <! if (token == BANG) { c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); return false; } x.back(); } else if (c == '[') { token = x.nextToken(); if ("CDATA".equals(token)) { if (x.next() == '[') { string = x.nextCDATA(); if (string.length() > 0) { context.accumulate("content", string); } return false; } } throw x.syntaxError("Expected 'CDATA['"); } i = 1; do { token = x.nextMeta(); if (token == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (token == LT) { i += 1; } else if (token == GT) { i -= 1; } } while (i > 0); return false; } else if (token == QUEST) { // <? x.skipPast("?>"); return false; } else if (token == SLASH) { // Close tag </ token = x.nextToken(); if (name == null) { throw x.syntaxError("Mismatched close tag " + token); } if (!token.equals(name)) { throw x.syntaxError("Mismatched " + name + " and " + token); } if (x.nextToken() != GT) { throw x.syntaxError("Misshaped close tag"); } return true; } else if (token instanceof Character) { throw x.syntaxError("Misshaped tag"); // Open tag < } else { tagName = (String)token; token = null; jsonobject = new JSONObject(); for (;;) { if (token == null) { token = x.nextToken(); } // attribute = value if (token instanceof String) { string = (String)token; token = x.nextToken(); if (token == EQ) { token = x.nextToken(); if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } jsonobject.accumulate(string, XML.stringToValue((String)token)); token = null; } else { jsonobject.accumulate(string, ""); } // Empty tag <.../> } else if (token == SLASH) { if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); } if (jsonobject.length() > 0) { context.accumulate(tagName, jsonobject); } else { context.accumulate(tagName, ""); } return false; // Content, between <...> and </...> } else if (token == GT) { for (;;) { token = x.nextContent(); if (token == null) { if (tagName != null) { throw x.syntaxError("Unclosed tag " + tagName); } return false; } else if (token instanceof String) { string = (String)token; if (string.length() > 0) { jsonobject.accumulate("content", XML.stringToValue(string)); } // Nested element } else if (token == LT) { if (parse(x, jsonobject, tagName)) { if (jsonobject.length() == 0) { context.accumulate(tagName, ""); } else if (jsonobject.length() == 1 && jsonobject.opt("content") != null) { context.accumulate(tagName, jsonobject.opt("content")); } else { context.accumulate(tagName, jsonobject); } return false; } } } } else { throw x.syntaxError("Misshaped tag"); } } } } /** * Try to convert a string into a number, boolean, or null. If the string * can't be converted, return the string. This is much less ambitious than * JSONObject.stringToValue, especially because it does not attempt to * convert plus forms, octal forms, hex forms, or E forms lacking decimal * points. * @param string A String. * @return A simple JSON value. */ public static Object stringToValue(String string) { if ("".equals(string)) { return string; } if ("true".equalsIgnoreCase(string)) { return Boolean.TRUE; } if ("false".equalsIgnoreCase(string)) { return Boolean.FALSE; } if ("null".equalsIgnoreCase(string)) { return JSONObject.NULL; } if ("0".equals(string)) { return new Integer(0); } // If it might be a number, try converting it. If that doesn't work, // return the string. try { char initial = string.charAt(0); boolean negative = false; if (initial == '-') { initial = string.charAt(1); negative = true; } if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') { return string; } if ((initial >= '0' && initial <= '9')) { if (string.indexOf('.') >= 0) { return Double.valueOf(string); } else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) { Long myLong = new Long(string); if (myLong.longValue() == myLong.intValue()) { return new Integer(myLong.intValue()); } else { return myLong; } } } } catch (Exception ignore) { } return string; } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject. Some information may be lost in this transformation * because JSON is a data format and XML is a document format. XML uses * elements, attributes, and content text, while JSON uses unordered * collections of name/value pairs and arrays of values. JSON does not * does not like to distinguish between elements and attributes. * Sequences of similar elements are represented as JSONArrays. Content * text may be placed in a "content" member. Comments, prologs, DTDs, and * <code>&lt;[ [ ]]></code> are ignored. * @param string The source string. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); XMLTokener x = new XMLTokener(string); while (x.more() && x.skipPast("<")) { parse(x, jo, null); } return jo; } /** * Convert a JSONObject into a well-formed, element-normal XML string. * @param object A JSONObject. * @return A string. * @throws JSONException */ public static String toString(Object object) throws JSONException { return toString(object, null); } /** * Convert a JSONObject into a well-formed, element-normal XML string. * @param object A JSONObject. * @param tagName The optional name of the enclosing tag. * @return A string. * @throws JSONException */ public static String toString(Object object, String tagName) throws JSONException { StringBuffer sb = new StringBuffer(); int i; JSONArray ja; JSONObject jo; String key; Iterator keys; int length; String string; Object value; if (object instanceof JSONObject) { // Emit <tagName> if (tagName != null) { sb.append('<'); sb.append(tagName); sb.append('>'); } // Loop thru the keys. jo = (JSONObject)object; keys = jo.keys(); while (keys.hasNext()) { key = keys.next().toString(); value = jo.opt(key); if (value == null) { value = ""; } if (value instanceof String) { string = (String)value; } else { string = null; } // Emit content in body if ("content".equals(key)) { if (value instanceof JSONArray) { ja = (JSONArray)value; length = ja.length(); for (i = 0; i < length; i += 1) { if (i > 0) { sb.append('\n'); } sb.append(escape(ja.get(i).toString())); } } else { sb.append(escape(value.toString())); } // Emit an array of similar keys } else if (value instanceof JSONArray) { ja = (JSONArray)value; length = ja.length(); for (i = 0; i < length; i += 1) { value = ja.get(i); if (value instanceof JSONArray) { sb.append('<'); sb.append(key); sb.append('>'); sb.append(toString(value)); sb.append("</"); sb.append(key); sb.append('>'); } else { sb.append(toString(value, key)); } } } else if ("".equals(value)) { sb.append('<'); sb.append(key); sb.append("/>"); // Emit a new tag <k> } else { sb.append(toString(value, key)); } } if (tagName != null) { // Emit the </tagname> close tag sb.append("</"); sb.append(tagName); sb.append('>'); } return sb.toString(); // XML does not have good support for arrays. If an array appears in a place // where XML is lacking, synthesize an <array> element. } else { if (object.getClass().isArray()) { object = new JSONArray(object); } if (object instanceof JSONArray) { ja = (JSONArray)object; length = ja.length(); for (i = 0; i < length; i += 1) { sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); } return sb.toString(); } else { string = (object == null) ? "null" : escape(object.toString()); return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + "</" + tagName + ">"; } } } }
Java
package org.json; /* Copyright (c) 2008 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.util.Iterator; /** * This provides static methods to convert an XML text into a JSONArray or * JSONObject, and to covert a JSONArray or JSONObject into an XML text using * the JsonML transform. * @author JSON.org * @version 2011-11-24 */ public class JSONML { /** * Parse XML values and store them in a JSONArray. * @param x The XMLTokener containing the source string. * @param arrayForm true if array form, false if object form. * @param ja The JSONArray that is containing the current tag or null * if we are at the outermost level. * @return A JSONArray if the value is the outermost tag, otherwise null. * @throws JSONException */ private static Object parse( XMLTokener x, boolean arrayForm, JSONArray ja ) throws JSONException { String attribute; char c; String closeTag = null; int i; JSONArray newja = null; JSONObject newjo = null; Object token; String tagName = null; // Test for and skip past these forms: // <!-- ... --> // <![ ... ]]> // <! ... > // <? ... ?> while (true) { if (!x.more()) { throw x.syntaxError("Bad XML"); } token = x.nextContent(); if (token == XML.LT) { token = x.nextToken(); if (token instanceof Character) { if (token == XML.SLASH) { // Close tag </ token = x.nextToken(); if (!(token instanceof String)) { throw new JSONException( "Expected a closing name instead of '" + token + "'."); } if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped close tag"); } return token; } else if (token == XML.BANG) { // <! c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); } x.back(); } else if (c == '[') { token = x.nextToken(); if (token.equals("CDATA") && x.next() == '[') { if (ja != null) { ja.put(x.nextCDATA()); } } else { throw x.syntaxError("Expected 'CDATA['"); } } else { i = 1; do { token = x.nextMeta(); if (token == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (token == XML.LT) { i += 1; } else if (token == XML.GT) { i -= 1; } } while (i > 0); } } else if (token == XML.QUEST) { // <? x.skipPast("?>"); } else { throw x.syntaxError("Misshaped tag"); } // Open tag < } else { if (!(token instanceof String)) { throw x.syntaxError("Bad tagName '" + token + "'."); } tagName = (String)token; newja = new JSONArray(); newjo = new JSONObject(); if (arrayForm) { newja.put(tagName); if (ja != null) { ja.put(newja); } } else { newjo.put("tagName", tagName); if (ja != null) { ja.put(newjo); } } token = null; for (;;) { if (token == null) { token = x.nextToken(); } if (token == null) { throw x.syntaxError("Misshaped tag"); } if (!(token instanceof String)) { break; } // attribute = value attribute = (String)token; if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { throw x.syntaxError("Reserved attribute."); } token = x.nextToken(); if (token == XML.EQ) { token = x.nextToken(); if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } newjo.accumulate(attribute, XML.stringToValue((String)token)); token = null; } else { newjo.accumulate(attribute, ""); } } if (arrayForm && newjo.length() > 0) { newja.put(newjo); } // Empty tag <.../> if (token == XML.SLASH) { if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped tag"); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } // Content, between <...> and </...> } else { if (token != XML.GT) { throw x.syntaxError("Misshaped tag"); } closeTag = (String)parse(x, arrayForm, newja); if (closeTag != null) { if (!closeTag.equals(tagName)) { throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); } tagName = null; if (!arrayForm && newja.length() > 0) { newjo.put("childNodes", newja); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } } } } } else { if (ja != null) { ja.put(token instanceof String ? XML.stringToValue((String)token) : token); } } } } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONArray using the JsonML transform. Each XML tag is represented as * a JSONArray in which the first element is the tag name. If the tag has * attributes, then the second element will be JSONObject containing the * name/value pairs. If the tag contains children, then strings and * JSONArrays will represent the child tags. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param string The source string. * @return A JSONArray containing the structured data from the XML string. * @throws JSONException */ public static JSONArray toJSONArray(String string) throws JSONException { return toJSONArray(new XMLTokener(string)); } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONArray using the JsonML transform. Each XML tag is represented as * a JSONArray in which the first element is the tag name. If the tag has * attributes, then the second element will be JSONObject containing the * name/value pairs. If the tag contains children, then strings and * JSONArrays will represent the child content and tags. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param x An XMLTokener. * @return A JSONArray containing the structured data from the XML string. * @throws JSONException */ public static JSONArray toJSONArray(XMLTokener x) throws JSONException { return (JSONArray)parse(x, true, null); } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject using the JsonML transform. Each XML tag is represented as * a JSONObject with a "tagName" property. If the tag has attributes, then * the attributes will be in the JSONObject as properties. If the tag * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param x An XMLTokener of the XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(XMLTokener x) throws JSONException { return (JSONObject)parse(x, false, null); } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject using the JsonML transform. Each XML tag is represented as * a JSONObject with a "tagName" property. If the tag has attributes, then * the attributes will be in the JSONObject as properties. If the tag * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param string The XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { return toJSONObject(new XMLTokener(string)); } /** * Reverse the JSONML transformation, making an XML text from a JSONArray. * @param ja A JSONArray. * @return An XML string. * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { int i; JSONObject jo; String key; Iterator keys; int length; Object object; StringBuffer sb = new StringBuffer(); String tagName; String value; // Emit <tagName tagName = ja.getString(0); XML.noSpace(tagName); tagName = XML.escape(tagName); sb.append('<'); sb.append(tagName); object = ja.opt(1); if (object instanceof JSONObject) { i = 2; jo = (JSONObject)object; // Emit the attributes keys = jo.keys(); while (keys.hasNext()) { key = keys.next().toString(); XML.noSpace(key); value = jo.optString(key); if (value != null) { sb.append(' '); sb.append(XML.escape(key)); sb.append('='); sb.append('"'); sb.append(XML.escape(value)); sb.append('"'); } } } else { i = 1; } //Emit content in body length = ja.length(); if (i >= length) { sb.append('/'); sb.append('>'); } else { sb.append('>'); do { object = ja.get(i); i += 1; if (object != null) { if (object instanceof String) { sb.append(XML.escape(object.toString())); } else if (object instanceof JSONObject) { sb.append(toString((JSONObject)object)); } else if (object instanceof JSONArray) { sb.append(toString((JSONArray)object)); } } } while (i < length); sb.append('<'); sb.append('/'); sb.append(tagName); sb.append('>'); } return sb.toString(); } /** * Reverse the JSONML transformation, making an XML text from a JSONObject. * The JSONObject must contain a "tagName" property. If it has children, * then it must have a "childNodes" property containing an array of objects. * The other properties are attributes with string values. * @param jo A JSONObject. * @return An XML string. * @throws JSONException */ public static String toString(JSONObject jo) throws JSONException { StringBuffer sb = new StringBuffer(); int i; JSONArray ja; String key; Iterator keys; int length; Object object; String tagName; String value; //Emit <tagName tagName = jo.optString("tagName"); if (tagName == null) { return XML.escape(jo.toString()); } XML.noSpace(tagName); tagName = XML.escape(tagName); sb.append('<'); sb.append(tagName); //Emit the attributes keys = jo.keys(); while (keys.hasNext()) { key = keys.next().toString(); if (!"tagName".equals(key) && !"childNodes".equals(key)) { XML.noSpace(key); value = jo.optString(key); if (value != null) { sb.append(' '); sb.append(XML.escape(key)); sb.append('='); sb.append('"'); sb.append(XML.escape(value)); sb.append('"'); } } } //Emit content in body ja = jo.optJSONArray("childNodes"); if (ja == null) { sb.append('/'); sb.append('>'); } else { sb.append('>'); length = ja.length(); for (i = 0; i < length; i += 1) { object = ja.get(i); if (object != null) { if (object instanceof String) { sb.append(XML.escape(object.toString())); } else if (object instanceof JSONObject) { sb.append(toString((JSONObject)object)); } else if (object instanceof JSONArray) { sb.append(toString((JSONArray)object)); } else { sb.append(object.toString()); } } } sb.append('<'); sb.append('/'); sb.append(tagName); sb.append('>'); } return sb.toString(); } }
Java
package org.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * This provides static methods to convert comma delimited text into a * JSONArray, and to covert a JSONArray into comma delimited text. Comma * delimited text is a very popular format for data interchange. It is * understood by most database, spreadsheet, and organizer programs. * <p> * Each row of text represents a row in a table or a data record. Each row * ends with a NEWLINE character. Each row contains one or more values. * Values are separated by commas. A value can contain any character except * for comma, unless is is wrapped in single quotes or double quotes. * <p> * The first row usually contains the names of the columns. * <p> * A comma delimited list can be converted into a JSONArray of JSONObjects. * The names for the elements in the JSONObjects can be taken from the names * in the first row. * @author JSON.org * @version 2010-12-24 */ public class CDL { /** * Get the next value. The value can be wrapped in quotes. The value can * be empty. * @param x A JSONTokener of the source text. * @return The value string, or null if empty. * @throws JSONException if the quoted string is badly formed. */ private static String getValue(JSONTokener x) throws JSONException { char c; char q; StringBuffer sb; do { c = x.next(); } while (c == ' ' || c == '\t'); switch (c) { case 0: return null; case '"': case '\'': q = c; sb = new StringBuffer(); for (;;) { c = x.next(); if (c == q) { break; } if (c == 0 || c == '\n' || c == '\r') { throw x.syntaxError("Missing close quote '" + q + "'."); } sb.append(c); } return sb.toString(); case ',': x.back(); return ""; default: x.back(); return x.nextTo(','); } } /** * Produce a JSONArray of strings from a row of comma delimited values. * @param x A JSONTokener of the source text. * @return A JSONArray of strings. * @throws JSONException */ public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { JSONArray ja = new JSONArray(); for (;;) { String value = getValue(x); char c = x.next(); if (value == null || (ja.length() == 0 && value.length() == 0 && c != ',')) { return null; } ja.put(value); for (;;) { if (c == ',') { break; } if (c != ' ') { if (c == '\n' || c == '\r' || c == 0) { return ja; } throw x.syntaxError("Bad character '" + c + "' (" + (int)c + ")."); } c = x.next(); } } } /** * Produce a JSONObject from a row of comma delimited text, using a * parallel JSONArray of strings to provides the names of the elements. * @param names A JSONArray of names. This is commonly obtained from the * first row of a comma delimited text file using the rowToJSONArray * method. * @param x A JSONTokener of the source text. * @return A JSONObject combining the names and values. * @throws JSONException */ public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) throws JSONException { JSONArray ja = rowToJSONArray(x); return ja != null ? ja.toJSONObject(names) : null; } /** * Produce a comma delimited text row from a JSONArray. Values containing * the comma character will be quoted. Troublesome characters may be * removed. * @param ja A JSONArray of strings. * @return A string ending in NEWLINE. */ public static String rowToString(JSONArray ja) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < ja.length(); i += 1) { if (i > 0) { sb.append(','); } Object object = ja.opt(i); if (object != null) { String string = object.toString(); if (string.length() > 0 && (string.indexOf(',') >= 0 || string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 || string.indexOf(0) >= 0 || string.charAt(0) == '"')) { sb.append('"'); int length = string.length(); for (int j = 0; j < length; j += 1) { char c = string.charAt(j); if (c >= ' ' && c != '"') { sb.append(c); } } sb.append('"'); } else { sb.append(string); } } } sb.append('\n'); return sb.toString(); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string, * using the first row as a source of names. * @param string The comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException */ public static JSONArray toJSONArray(String string) throws JSONException { return toJSONArray(new JSONTokener(string)); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string, * using the first row as a source of names. * @param x The JSONTokener containing the comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException */ public static JSONArray toJSONArray(JSONTokener x) throws JSONException { return toJSONArray(rowToJSONArray(x), x); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string * using a supplied JSONArray as the source of element names. * @param names A JSONArray of strings. * @param string The comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException */ public static JSONArray toJSONArray(JSONArray names, String string) throws JSONException { return toJSONArray(names, new JSONTokener(string)); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string * using a supplied JSONArray as the source of element names. * @param names A JSONArray of strings. * @param x A JSONTokener of the source text. * @return A JSONArray of JSONObjects. * @throws JSONException */ public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws JSONException { if (names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); for (;;) { JSONObject jo = rowToJSONObject(names, x); if (jo == null) { break; } ja.put(jo); } if (ja.length() == 0) { return null; } return ja; } /** * Produce a comma delimited text from a JSONArray of JSONObjects. The * first row will be a list of names obtained by inspecting the first * JSONObject. * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { JSONObject jo = ja.optJSONObject(0); if (jo != null) { JSONArray names = jo.names(); if (names != null) { return rowToString(names) + toString(names, ja); } } return null; } /** * Produce a comma delimited text from a JSONArray of JSONObjects using * a provided list of names. The list of names is not included in the * output. * @param names A JSONArray of strings. * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException */ public static String toString(JSONArray names, JSONArray ja) throws JSONException { if (names == null || names.length() == 0) { return null; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < ja.length(); i += 1) { JSONObject jo = ja.optJSONObject(i); if (jo != null) { sb.append(rowToString(jo.toJSONArray(names))); } } return sb.toString(); } }
Java
package org.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.util.Iterator; /** * Convert an HTTP header to a JSONObject and back. * @author JSON.org * @version 2010-12-24 */ public class HTTP { /** Carriage return/line feed. */ public static final String CRLF = "\r\n"; /** * Convert an HTTP header string into a JSONObject. It can be a request * header or a response header. A request header will contain * <pre>{ * Method: "POST" (for example), * "Request-URI": "/" (for example), * "HTTP-Version": "HTTP/1.1" (for example) * }</pre> * A response header will contain * <pre>{ * "HTTP-Version": "HTTP/1.1" (for example), * "Status-Code": "200" (for example), * "Reason-Phrase": "OK" (for example) * }</pre> * In addition, the other parameters in the header will be captured, using * the HTTP field names as JSON names, so that <pre> * Date: Sun, 26 May 2002 18:06:04 GMT * Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s * Cache-Control: no-cache</pre> * become * <pre>{... * Date: "Sun, 26 May 2002 18:06:04 GMT", * Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s", * "Cache-Control": "no-cache", * ...}</pre> * It does no further checking or conversion. It does not parse dates. * It does not do '%' transforms on URLs. * @param string An HTTP header string. * @return A JSONObject containing the elements and attributes * of the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); HTTPTokener x = new HTTPTokener(string); String token; token = x.nextToken(); if (token.toUpperCase().startsWith("HTTP")) { // Response jo.put("HTTP-Version", token); jo.put("Status-Code", x.nextToken()); jo.put("Reason-Phrase", x.nextTo('\0')); x.next(); } else { // Request jo.put("Method", token); jo.put("Request-URI", x.nextToken()); jo.put("HTTP-Version", x.nextToken()); } // Fields while (x.more()) { String name = x.nextTo(':'); x.next(':'); jo.put(name, x.nextTo('\0')); x.next(); } return jo; } /** * Convert a JSONObject into an HTTP header. A request header must contain * <pre>{ * Method: "POST" (for example), * "Request-URI": "/" (for example), * "HTTP-Version": "HTTP/1.1" (for example) * }</pre> * A response header must contain * <pre>{ * "HTTP-Version": "HTTP/1.1" (for example), * "Status-Code": "200" (for example), * "Reason-Phrase": "OK" (for example) * }</pre> * Any other members of the JSONObject will be output as HTTP fields. * The result will end with two CRLF pairs. * @param jo A JSONObject * @return An HTTP header string. * @throws JSONException if the object does not contain enough * information. */ public static String toString(JSONObject jo) throws JSONException { Iterator keys = jo.keys(); String string; StringBuffer sb = new StringBuffer(); if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { sb.append(jo.getString("HTTP-Version")); sb.append(' '); sb.append(jo.getString("Status-Code")); sb.append(' '); sb.append(jo.getString("Reason-Phrase")); } else if (jo.has("Method") && jo.has("Request-URI")) { sb.append(jo.getString("Method")); sb.append(' '); sb.append('"'); sb.append(jo.getString("Request-URI")); sb.append('"'); sb.append(' '); sb.append(jo.getString("HTTP-Version")); } else { throw new JSONException("Not enough material for an HTTP header."); } sb.append(CRLF); while (keys.hasNext()) { string = keys.next().toString(); if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) { sb.append(string); sb.append(": "); sb.append(jo.getString(string)); sb.append(CRLF); } } sb.append(CRLF); return sb.toString(); } }
Java
package org.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Convert a web browser cookie specification to a JSONObject and back. * JSON and Cookies are both notations for name/value pairs. * @author JSON.org * @version 2010-12-24 */ public class Cookie { /** * Produce a copy of a string in which the characters '+', '%', '=', ';' * and control characters are replaced with "%hh". This is a gentle form * of URL encoding, attempting to cause as little distortion to the * string as possible. The characters '=' and ';' are meta characters in * cookies. By convention, they are escaped using the URL-encoding. This is * only a convention, not a standard. Often, cookies are expected to have * encoded values. We encode '=' and ';' because we must. We encode '%' and * '+' because they are meta characters in URL encoding. * @param string The source string. * @return The escaped result. */ public static String escape(String string) { char c; String s = string.trim(); StringBuffer sb = new StringBuffer(); int length = s.length(); for (int i = 0; i < length; i += 1) { c = s.charAt(i); if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { sb.append('%'); sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16)); sb.append(Character.forDigit((char)(c & 0x0f), 16)); } else { sb.append(c); } } return sb.toString(); } /** * Convert a cookie specification string into a JSONObject. The string * will contain a name value pair separated by '='. The name and the value * will be unescaped, possibly converting '+' and '%' sequences. The * cookie properties may follow, separated by ';', also represented as * name=value (except the secure property, which does not have a value). * The name will be stored under the key "name", and the value will be * stored under the key "value". This method does not do checking or * validation of the parameters. It only converts the cookie string into * a JSONObject. * @param string The cookie specification string. * @return A JSONObject containing "name", "value", and possibly other * members. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { String name; JSONObject jo = new JSONObject(); Object value; JSONTokener x = new JSONTokener(string); jo.put("name", x.nextTo('=')); x.next('='); jo.put("value", x.nextTo(';')); x.next(); while (x.more()) { name = unescape(x.nextTo("=;")); if (x.next() != '=') { if (name.equals("secure")) { value = Boolean.TRUE; } else { throw x.syntaxError("Missing '=' in cookie parameter."); } } else { value = unescape(x.nextTo(';')); x.next(); } jo.put(name, value); } return jo; } /** * Convert a JSONObject into a cookie specification string. The JSONObject * must contain "name" and "value" members. * If the JSONObject contains "expires", "domain", "path", or "secure" * members, they will be appended to the cookie specification string. * All other members are ignored. * @param jo A JSONObject * @return A cookie specification string * @throws JSONException */ public static String toString(JSONObject jo) throws JSONException { StringBuffer sb = new StringBuffer(); sb.append(escape(jo.getString("name"))); sb.append("="); sb.append(escape(jo.getString("value"))); if (jo.has("expires")) { sb.append(";expires="); sb.append(jo.getString("expires")); } if (jo.has("domain")) { sb.append(";domain="); sb.append(escape(jo.getString("domain"))); } if (jo.has("path")) { sb.append(";path="); sb.append(escape(jo.getString("path"))); } if (jo.optBoolean("secure")) { sb.append(";secure"); } return sb.toString(); } /** * Convert <code>%</code><i>hh</i> sequences to single characters, and * convert plus to space. * @param string A string that may contain * <code>+</code>&nbsp;<small>(plus)</small> and * <code>%</code><i>hh</i> sequences. * @return The unescaped string. */ public static String unescape(String string) { int length = string.length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; ++i) { char c = string.charAt(i); if (c == '+') { c = ' '; } else if (c == '%' && i + 2 < length) { int d = JSONTokener.dehexchar(string.charAt(i + 1)); int e = JSONTokener.dehexchar(string.charAt(i + 2)); if (d >= 0 && e >= 0) { c = (char)(d * 16 + e); i += 2; } } sb.append(c); } return sb.toString(); } }
Java
package org.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * The HTTPTokener extends the JSONTokener to provide additional methods * for the parsing of HTTP headers. * @author JSON.org * @version 2010-12-24 */ public class HTTPTokener extends JSONTokener { /** * Construct an HTTPTokener from a string. * @param string A source string. */ public HTTPTokener(String string) { super(string); } /** * Get the next token or string. This is used in parsing HTTP headers. * @throws JSONException * @return A String. */ public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } } }
Java
package org.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.io.IOException; import java.io.Writer; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.Method; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; /** * A JSONObject is an unordered collection of name/value pairs. Its * external form is a string wrapped in curly braces with colons between the * names and values, and commas between the values and names. The internal form * is an object having <code>get</code> and <code>opt</code> methods for * accessing the values by name, and <code>put</code> methods for adding or * replacing values by name. The values can be any of these types: * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>, * <code>Number</code>, <code>String</code>, or the <code>JSONObject.NULL</code> * object. A JSONObject constructor can be used to convert an external form * JSON text into an internal form whose values can be retrieved with the * <code>get</code> and <code>opt</code> methods, or to convert values into a * JSON text using the <code>put</code> and <code>toString</code> methods. * A <code>get</code> method returns a value if one can be found, and throws an * exception if one cannot be found. An <code>opt</code> method returns a * default value instead of throwing an exception, and so is useful for * obtaining optional values. * <p> * The generic <code>get()</code> and <code>opt()</code> methods return an * object, which you can cast or query for type. There are also typed * <code>get</code> and <code>opt</code> methods that do type checking and type * coercion for you. The opt methods differ from the get methods in that they * do not throw. Instead, they return a specified value, such as null. * <p> * The <code>put</code> methods add or replace values in an object. For example, * <pre>myString = new JSONObject().put("JSON", "Hello, World!").toString();</pre> * produces the string <code>{"JSON": "Hello, World"}</code>. * <p> * The texts produced by the <code>toString</code> methods strictly conform to * the JSON syntax rules. * The constructors are more forgiving in the texts they will accept: * <ul> * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just * before the closing brace.</li> * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single * quote)</small>.</li> * <li>Strings do not need to be quoted at all if they do not begin with a quote * or single quote, and if they do not contain leading or trailing spaces, * and if they do not contain any of these characters: * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers * and if they are not the reserved words <code>true</code>, * <code>false</code>, or <code>null</code>.</li> * <li>Keys can be followed by <code>=</code> or <code>=></code> as well as * by <code>:</code>.</li> * <li>Values can be followed by <code>;</code> <small>(semicolon)</small> as * well as by <code>,</code> <small>(comma)</small>.</li> * </ul> * @author JSON.org * @version 2011-11-24 */ public class JSONObject { /** * JSONObject.NULL is equivalent to the value that JavaScript calls null, * whilst Java's null is equivalent to the value that JavaScript calls * undefined. */ private static final class Null { /** * There is only intended to be a single instance of the NULL object, * so the clone method returns itself. * @return NULL. */ protected final Object clone() { return this; } /** * A Null object is equal to the null value and to itself. * @param object An object to test for nullness. * @return true if the object parameter is the JSONObject.NULL object * or null. */ public boolean equals(Object object) { return object == null || object == this; } /** * Get the "null" string value. * @return The string "null". */ public String toString() { return "null"; } } /** * The map where the JSONObject's properties are kept. */ private final Map map; /** * It is sometimes more convenient and less ambiguous to have a * <code>NULL</code> object than to use Java's <code>null</code> value. * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>. * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>. */ public static final Object NULL = new Null(); /** * Construct an empty JSONObject. */ public JSONObject() { this.map = new HashMap(); } /** * Construct a JSONObject from a subset of another JSONObject. * An array of strings is used to identify the keys that should be copied. * Missing keys are ignored. * @param jo A JSONObject. * @param names An array of strings. * @throws JSONException * @exception JSONException If a value is a non-finite number or if a name is duplicated. */ public JSONObject(JSONObject jo, String[] names) { this(); for (int i = 0; i < names.length; i += 1) { try { this.putOnce(names[i], jo.opt(names[i])); } catch (Exception ignore) { } } } /** * Construct a JSONObject from a JSONTokener. * @param x A JSONTokener object containing the source string. * @throws JSONException If there is a syntax error in the source string * or a duplicated key. */ public JSONObject(JSONTokener x) throws JSONException { this(); char c; String key; if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } for (;;) { c = x.nextClean(); switch (c) { case 0: throw x.syntaxError("A JSONObject text must end with '}'"); case '}': return; default: x.back(); key = x.nextValue().toString(); } // The key is followed by ':'. We will also tolerate '=' or '=>'. c = x.nextClean(); if (c == '=') { if (x.next() != '>') { x.back(); } } else if (c != ':') { throw x.syntaxError("Expected a ':' after a key"); } this.putOnce(key, x.nextValue()); // Pairs are separated by ','. We will also tolerate ';'. switch (x.nextClean()) { case ';': case ',': if (x.nextClean() == '}') { return; } x.back(); break; case '}': return; default: throw x.syntaxError("Expected a ',' or '}'"); } } } /** * Construct a JSONObject from a Map. * * @param map A map object that can be used to initialize the contents of * the JSONObject. * @throws JSONException */ public JSONObject(Map map) { this.map = new HashMap(); if (map != null) { Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry)i.next(); Object value = e.getValue(); if (value != null) { this.map.put(e.getKey(), wrap(value)); } } } } /** * Construct a JSONObject from an Object using bean getters. * It reflects on all of the public methods of the object. * For each of the methods with no parameters and a name starting * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter, * the method is invoked, and a key and the value returned from the getter method * are put into the new JSONObject. * * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. * If the second remaining character is not upper case, then the first * character is converted to lower case. * * For example, if an object has a method named <code>"getName"</code>, and * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>, * then the JSONObject will contain <code>"name": "Larry Fine"</code>. * * @param bean An object that has getter methods that should be used * to make a JSONObject. */ public JSONObject(Object bean) { this(); this.populateMap(bean); } /** * Construct a JSONObject from an Object, using reflection to find the * public members. The resulting JSONObject's keys will be the strings * from the names array, and the values will be the field values associated * with those keys in the object. If a key is not found or not visible, * then it will not be copied into the new JSONObject. * @param object An object that has fields that should be used to make a * JSONObject. * @param names An array of strings, the names of the fields to be obtained * from the object. */ public JSONObject(Object object, String names[]) { this(); Class c = object.getClass(); for (int i = 0; i < names.length; i += 1) { String name = names[i]; try { this.putOpt(name, c.getField(name).get(object)); } catch (Exception ignore) { } } } /** * Construct a JSONObject from a source JSON text string. * This is the most commonly used JSONObject constructor. * @param source A string beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @exception JSONException If there is a syntax error in the source * string or a duplicated key. */ public JSONObject(String source) throws JSONException { this(new JSONTokener(source)); } /** * Construct a JSONObject from a ResourceBundle. * @param baseName The ResourceBundle base name. * @param locale The Locale to load the ResourceBundle for. * @throws JSONException If any JSONExceptions are detected. */ public JSONObject(String baseName, Locale locale) throws JSONException { this(); ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); // Iterate through the keys in the bundle. Enumeration keys = bundle.getKeys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (key instanceof String) { // Go through the path, ensuring that there is a nested JSONObject for each // segment except the last. Add the value using the last segment's name into // the deepest nested JSONObject. String[] path = ((String)key).split("\\."); int last = path.length - 1; JSONObject target = this; for (int i = 0; i < last; i += 1) { String segment = path[i]; JSONObject nextTarget = target.optJSONObject(segment); if (nextTarget == null) { nextTarget = new JSONObject(); target.put(segment, nextTarget); } target = nextTarget; } target.put(path[last], bundle.getString((String)key)); } } } /** * Accumulate values under a key. It is similar to the put method except * that if there is already an object stored under the key then a * JSONArray is stored under the key to hold all of the accumulated values. * If there is already a JSONArray, then the new value is appended to it. * In contrast, the put method replaces the previous value. * * If only one value is accumulated that is not a JSONArray, then the * result will be the same as using put. But if multiple values are * accumulated, then the result will be like append. * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number * or if the key is null. */ public JSONObject accumulate( String key, Object value ) throws JSONException { testValidity(value); Object object = this.opt(key); if (object == null) { this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); } else if (object instanceof JSONArray) { ((JSONArray)object).put(value); } else { this.put(key, new JSONArray().put(object).put(value)); } return this; } /** * Append values to the array under a key. If the key does not exist in the * JSONObject, then the key is put in the JSONObject with its value being a * JSONArray containing the value parameter. If the key was already * associated with a JSONArray, then the value parameter is appended to it. * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the key is null or if the current value * associated with the key is not a JSONArray. */ public JSONObject append(String key, Object value) throws JSONException { testValidity(value); Object object = this.opt(key); if (object == null) { this.put(key, new JSONArray().put(value)); } else if (object instanceof JSONArray) { this.put(key, ((JSONArray)object).put(value)); } else { throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); } return this; } /** * Produce a string from a double. The string "null" will be returned if * the number is not finite. * @param d A double. * @return A String. */ public static String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String string = Double.toString(d); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; } /** * Get the value object associated with a key. * * @param key A key string. * @return The object associated with the key. * @throws JSONException if the key is not found. */ public Object get(String key) throws JSONException { if (key == null) { throw new JSONException("Null key."); } Object object = this.opt(key); if (object == null) { throw new JSONException("JSONObject[" + quote(key) + "] not found."); } return object; } /** * Get the boolean value associated with a key. * * @param key A key string. * @return The truth. * @throws JSONException * if the value is not a Boolean or the String "true" or "false". */ public boolean getBoolean(String key) throws JSONException { Object object = this.get(key); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); } /** * Get the double value associated with a key. * @param key A key string. * @return The numeric value. * @throws JSONException if the key is not found or * if the value is not a Number object and cannot be converted to a number. */ public double getDouble(String key) throws JSONException { Object object = this.get(key); try { return object instanceof Number ? ((Number)object).doubleValue() : Double.parseDouble((String)object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); } } /** * Get the int value associated with a key. * * @param key A key string. * @return The integer value. * @throws JSONException if the key is not found or if the value cannot * be converted to an integer. */ public int getInt(String key) throws JSONException { Object object = this.get(key); try { return object instanceof Number ? ((Number)object).intValue() : Integer.parseInt((String)object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not an int."); } } /** * Get the JSONArray value associated with a key. * * @param key A key string. * @return A JSONArray which is the value. * @throws JSONException if the key is not found or * if the value is not a JSONArray. */ public JSONArray getJSONArray(String key) throws JSONException { Object object = this.get(key); if (object instanceof JSONArray) { return (JSONArray)object; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); } /** * Get the JSONObject value associated with a key. * * @param key A key string. * @return A JSONObject which is the value. * @throws JSONException if the key is not found or * if the value is not a JSONObject. */ public JSONObject getJSONObject(String key) throws JSONException { Object object = this.get(key); if (object instanceof JSONObject) { return (JSONObject)object; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); } /** * Get the long value associated with a key. * * @param key A key string. * @return The long value. * @throws JSONException if the key is not found or if the value cannot * be converted to a long. */ public long getLong(String key) throws JSONException { Object object = this.get(key); try { return object instanceof Number ? ((Number)object).longValue() : Long.parseLong((String)object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not a long."); } } /** * Get an array of field names from a JSONObject. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(JSONObject jo) { int length = jo.length(); if (length == 0) { return null; } Iterator iterator = jo.keys(); String[] names = new String[length]; int i = 0; while (iterator.hasNext()) { names[i] = (String)iterator.next(); i += 1; } return names; } /** * Get an array of field names from an Object. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(Object object) { if (object == null) { return null; } Class klass = object.getClass(); Field[] fields = klass.getFields(); int length = fields.length; if (length == 0) { return null; } String[] names = new String[length]; for (int i = 0; i < length; i += 1) { names[i] = fields[i].getName(); } return names; } /** * Get the string associated with a key. * * @param key A key string. * @return A string which is the value. * @throws JSONException if there is no string value for the key. */ public String getString(String key) throws JSONException { Object object = this.get(key); if (object instanceof String) { return (String)object; } throw new JSONException("JSONObject[" + quote(key) + "] not a string."); } /** * Determine if the JSONObject contains a specific key. * @param key A key string. * @return true if the key exists in the JSONObject. */ public boolean has(String key) { return this.map.containsKey(key); } /** * Increment a property of a JSONObject. If there is no such property, * create one with a value of 1. If there is such a property, and if * it is an Integer, Long, Double, or Float, then add one to it. * @param key A key string. * @return this. * @throws JSONException If there is already a property with this name * that is not an Integer, Long, Double, or Float. */ public JSONObject increment(String key) throws JSONException { Object value = this.opt(key); if (value == null) { this.put(key, 1); } else if (value instanceof Integer) { this.put(key, ((Integer)value).intValue() + 1); } else if (value instanceof Long) { this.put(key, ((Long)value).longValue() + 1); } else if (value instanceof Double) { this.put(key, ((Double)value).doubleValue() + 1); } else if (value instanceof Float) { this.put(key, ((Float)value).floatValue() + 1); } else { throw new JSONException("Unable to increment [" + quote(key) + "]."); } return this; } /** * Determine if the value associated with the key is null or if there is * no value. * @param key A key string. * @return true if there is no value associated with the key or if * the value is the JSONObject.NULL object. */ public boolean isNull(String key) { return JSONObject.NULL.equals(this.opt(key)); } /** * Get an enumeration of the keys of the JSONObject. * * @return An iterator of the keys. */ public Iterator keys() { return this.map.keySet().iterator(); } /** * Get the number of keys stored in the JSONObject. * * @return The number of keys in the JSONObject. */ public int length() { return this.map.size(); } /** * Produce a JSONArray containing the names of the elements of this * JSONObject. * @return A JSONArray containing the key strings, or null if the JSONObject * is empty. */ public JSONArray names() { JSONArray ja = new JSONArray(); Iterator keys = this.keys(); while (keys.hasNext()) { ja.put(keys.next()); } return ja.length() == 0 ? null : ja; } /** * Produce a string from a Number. * @param number A Number * @return A String. * @throws JSONException If n is a non-finite number. */ public static String numberToString(Number number) throws JSONException { if (number == null) { throw new JSONException("Null pointer"); } testValidity(number); // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; } /** * Get an optional value associated with a key. * @param key A key string. * @return An object which is the value, or null if there is no value. */ public Object opt(String key) { return key == null ? null : this.map.get(key); } /** * Get an optional boolean associated with a key. * It returns false if there is no such key, or if the value is not * Boolean.TRUE or the String "true". * * @param key A key string. * @return The truth. */ public boolean optBoolean(String key) { return this.optBoolean(key, false); } /** * Get an optional boolean associated with a key. * It returns the defaultValue if there is no such key, or if it is not * a Boolean or the String "true" or "false" (case insensitive). * * @param key A key string. * @param defaultValue The default. * @return The truth. */ public boolean optBoolean(String key, boolean defaultValue) { try { return this.getBoolean(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional double associated with a key, * or NaN if there is no such key or if its value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A string which is the key. * @return An object which is the value. */ public double optDouble(String key) { return this.optDouble(key, Double.NaN); } /** * Get an optional double associated with a key, or the * defaultValue if there is no such key or if its value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public double optDouble(String key, double defaultValue) { try { return this.getDouble(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional int value associated with a key, * or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @return An object which is the value. */ public int optInt(String key) { return this.optInt(key, 0); } /** * Get an optional int value associated with a key, * or the default if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public int optInt(String key, int defaultValue) { try { return this.getInt(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional JSONArray associated with a key. * It returns null if there is no such key, or if its value is not a * JSONArray. * * @param key A key string. * @return A JSONArray which is the value. */ public JSONArray optJSONArray(String key) { Object o = this.opt(key); return o instanceof JSONArray ? (JSONArray)o : null; } /** * Get an optional JSONObject associated with a key. * It returns null if there is no such key, or if its value is not a * JSONObject. * * @param key A key string. * @return A JSONObject which is the value. */ public JSONObject optJSONObject(String key) { Object object = this.opt(key); return object instanceof JSONObject ? (JSONObject)object : null; } /** * Get an optional long value associated with a key, * or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @return An object which is the value. */ public long optLong(String key) { return this.optLong(key, 0); } /** * Get an optional long value associated with a key, * or the default if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public long optLong(String key, long defaultValue) { try { return this.getLong(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional string associated with a key. * It returns an empty string if there is no such key. If the value is not * a string and is not null, then it is converted to a string. * * @param key A key string. * @return A string which is the value. */ public String optString(String key) { return this.optString(key, ""); } /** * Get an optional string associated with a key. * It returns the defaultValue if there is no such key. * * @param key A key string. * @param defaultValue The default. * @return A string which is the value. */ public String optString(String key, String defaultValue) { Object object = this.opt(key); return NULL.equals(object) ? defaultValue : object.toString(); } private void populateMap(Object bean) { Class klass = bean.getClass(); // If klass is a System class then set includeSuperClass to false. boolean includeSuperClass = klass.getClassLoader() != null; Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); for (int i = 0; i < methods.length; i += 1) { try { Method method = methods[i]; if (Modifier.isPublic(method.getModifiers())) { String name = method.getName(); String key = ""; if (name.startsWith("get")) { if ("getClass".equals(name) || "getDeclaringClass".equals(name)) { key = ""; } else { key = name.substring(3); } } else if (name.startsWith("is")) { key = name.substring(2); } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } Object result = method.invoke(bean, (Object[])null); if (result != null) { this.map.put(key, wrap(result)); } } } } catch (Exception ignore) { } } } /** * Put a key/boolean pair in the JSONObject. * * @param key A key string. * @param value A boolean which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, boolean value) throws JSONException { this.put(key, value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONArray which is produced from a Collection. * @param key A key string. * @param value A Collection value. * @return this. * @throws JSONException */ public JSONObject put(String key, Collection value) throws JSONException { this.put(key, new JSONArray(value)); return this; } /** * Put a key/double pair in the JSONObject. * * @param key A key string. * @param value A double which is the value. * @return this. * @throws JSONException If the key is null or if the number is invalid. */ public JSONObject put(String key, double value) throws JSONException { this.put(key, new Double(value)); return this; } /** * Put a key/int pair in the JSONObject. * * @param key A key string. * @param value An int which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, int value) throws JSONException { this.put(key, new Integer(value)); return this; } /** * Put a key/long pair in the JSONObject. * * @param key A key string. * @param value A long which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, long value) throws JSONException { this.put(key, new Long(value)); return this; } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONObject which is produced from a Map. * @param key A key string. * @param value A Map value. * @return this. * @throws JSONException */ public JSONObject put(String key, Map value) throws JSONException { this.put(key, new JSONObject(value)); return this; } /** * Put a key/value pair in the JSONObject. If the value is null, * then the key will be removed from the JSONObject if it is present. * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is non-finite number * or if the key is null. */ public JSONObject put(String key, Object value) throws JSONException { if (key == null) { throw new JSONException("Null key."); } if (value != null) { testValidity(value); this.map.put(key, value); } else { this.remove(key); } return this; } /** * Put a key/value pair in the JSONObject, but only if the key and the * value are both non-null, and only if there is not already a member * with that name. * @param key * @param value * @return his. * @throws JSONException if the key is a duplicate */ public JSONObject putOnce(String key, Object value) throws JSONException { if (key != null && value != null) { if (this.opt(key) != null) { throw new JSONException("Duplicate key \"" + key + "\""); } this.put(key, value); } return this; } /** * Put a key/value pair in the JSONObject, but only if the * key and the value are both non-null. * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is a non-finite number. */ public JSONObject putOpt(String key, Object value) throws JSONException { if (key != null && value != null) { this.put(key, value); } return this; } /** * Produce a string in double quotes with backslash sequences in all the * right places. A backslash will be inserted within </, producing <\/, * allowing JSON text to be delivered in HTML. In JSON text, a string * cannot contain a control character or an unescaped quote or backslash. * @param string A String * @return A String correctly formatted for insertion in a JSON text. */ public static String quote(String string) { if (string == null || string.length() == 0) { return "\"\""; } char b; char c = 0; String hhhh; int i; int len = string.length(); StringBuffer sb = new StringBuffer(len + 4); sb.append('"'); for (i = 0; i < len; i += 1) { b = c; c = string.charAt(i); switch (c) { case '\\': case '"': sb.append('\\'); sb.append(c); break; case '/': if (b == '<') { sb.append('\\'); } sb.append(c); break; case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; default: if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { hhhh = "000" + Integer.toHexString(c); sb.append("\\u" + hhhh.substring(hhhh.length() - 4)); } else { sb.append(c); } } } sb.append('"'); return sb.toString(); } /** * Remove a name and its value, if present. * @param key The name to be removed. * @return The value that was associated with the name, * or null if there was no value. */ public Object remove(String key) { return this.map.remove(key); } /** * Try to convert a string into a number, boolean, or null. If the string * can't be converted, return the string. * @param string A String. * @return A simple JSON value. */ public static Object stringToValue(String string) { Double d; if (string.equals("")) { return string; } if (string.equalsIgnoreCase("true")) { return Boolean.TRUE; } if (string.equalsIgnoreCase("false")) { return Boolean.FALSE; } if (string.equalsIgnoreCase("null")) { return JSONObject.NULL; } /* * If it might be a number, try converting it. * If a number cannot be produced, then the value will just * be a string. Note that the plus and implied string * conventions are non-standard. A JSON parser may accept * non-JSON forms as long as it accepts all correct JSON forms. */ char b = string.charAt(0); if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { try { if (string.indexOf('.') > -1 || string.indexOf('e') > -1 || string.indexOf('E') > -1) { d = Double.valueOf(string); if (!d.isInfinite() && !d.isNaN()) { return d; } } else { Long myLong = new Long(string); if (myLong.longValue() == myLong.intValue()) { return new Integer(myLong.intValue()); } else { return myLong; } } } catch (Exception ignore) { } } return string; } /** * Throw an exception if the object is a NaN or infinite number. * @param o The object to test. * @throws JSONException If o is a non-finite number. */ public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } } /** * Produce a JSONArray containing the values of the members of this * JSONObject. * @param names A JSONArray containing a list of key strings. This * determines the sequence of the values in the result. * @return A JSONArray of values. * @throws JSONException If any of the values are non-finite numbers. */ public JSONArray toJSONArray(JSONArray names) throws JSONException { if (names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); for (int i = 0; i < names.length(); i += 1) { ja.put(this.opt(names.getString(i))); } return ja; } /** * Make a JSON text of this JSONObject. For compactness, no whitespace * is added. If this would not result in a syntactically correct JSON text, * then null will be returned instead. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, portable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. */ public String toString() { try { Iterator keys = this.keys(); StringBuffer sb = new StringBuffer("{"); while (keys.hasNext()) { if (sb.length() > 1) { sb.append(','); } Object o = keys.next(); sb.append(quote(o.toString())); sb.append(':'); sb.append(valueToString(this.map.get(o))); } sb.append('}'); return sb.toString(); } catch (Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONObject. * <p> * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @return a printable, displayable, portable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ public String toString(int indentFactor) throws JSONException { return this.toString(indentFactor, 0); } /** * Make a prettyprinted JSON text of this JSONObject. * <p> * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ String toString(int indentFactor, int indent) throws JSONException { int i; int length = this.length(); if (length == 0) { return "{}"; } Iterator keys = this.keys(); int newindent = indent + indentFactor; Object object; StringBuffer sb = new StringBuffer("{"); if (length == 1) { object = keys.next(); sb.append(quote(object.toString())); sb.append(": "); sb.append(valueToString(this.map.get(object), indentFactor, indent)); } else { while (keys.hasNext()) { object = keys.next(); if (sb.length() > 1) { sb.append(",\n"); } else { sb.append('\n'); } for (i = 0; i < newindent; i += 1) { sb.append(' '); } sb.append(quote(object.toString())); sb.append(": "); sb.append(valueToString(this.map.get(object), indentFactor, newindent)); } if (sb.length() > 1) { sb.append('\n'); for (i = 0; i < indent; i += 1) { sb.append(' '); } } } sb.append('}'); return sb.toString(); } /** * Make a JSON text of an Object value. If the object has an * value.toJSONString() method, then that method will be used to produce * the JSON text. The method is required to produce a strictly * conforming text. If the object does not contain a toJSONString * method (which is the most common case), then a text will be * produced by other means. If the value is an array or Collection, * then a JSONArray will be made from it and its toJSONString method * will be called. If the value is a MAP, then a JSONObject will be made * from it and its toJSONString method will be called. Otherwise, the * value's toString method will be called, and the result will be quoted. * * <p> * Warning: This method assumes that the data structure is acyclical. * @param value The value to be serialized. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the value is or contains an invalid number. */ public static String valueToString(Object value) throws JSONException { if (value == null || value.equals(null)) { return "null"; } if (value instanceof JSONString) { Object object; try { object = ((JSONString)value).toJSONString(); } catch (Exception e) { throw new JSONException(e); } if (object instanceof String) { return (String)object; } throw new JSONException("Bad value from toJSONString: " + object); } if (value instanceof Number) { return numberToString((Number) value); } if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { return value.toString(); } if (value instanceof Map) { return new JSONObject((Map)value).toString(); } if (value instanceof Collection) { return new JSONArray((Collection)value).toString(); } if (value.getClass().isArray()) { return new JSONArray(value).toString(); } return quote(value.toString()); } /** * Make a prettyprinted JSON text of an object value. * <p> * Warning: This method assumes that the data structure is acyclical. * @param value The value to be serialized. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ static String valueToString( Object value, int indentFactor, int indent ) throws JSONException { if (value == null || value.equals(null)) { return "null"; } try { if (value instanceof JSONString) { Object o = ((JSONString)value).toJSONString(); if (o instanceof String) { return (String)o; } } } catch (Exception ignore) { } if (value instanceof Number) { return numberToString((Number) value); } if (value instanceof Boolean) { return value.toString(); } if (value instanceof JSONObject) { return ((JSONObject)value).toString(indentFactor, indent); } if (value instanceof JSONArray) { return ((JSONArray)value).toString(indentFactor, indent); } if (value instanceof Map) { return new JSONObject((Map)value).toString(indentFactor, indent); } if (value instanceof Collection) { return new JSONArray((Collection)value).toString(indentFactor, indent); } if (value.getClass().isArray()) { return new JSONArray(value).toString(indentFactor, indent); } return quote(value.toString()); } /** * Wrap an object, if necessary. If the object is null, return the NULL * object. If it is an array or collection, wrap it in a JSONArray. If * it is a map, wrap it in a JSONObject. If it is a standard property * (Double, String, et al) then it is already wrapped. Otherwise, if it * comes from one of the java packages, turn it into a string. And if * it doesn't, try to wrap it in a JSONObject. If the wrapping fails, * then null is returned. * * @param object The object to wrap * @return The wrapped value */ public static Object wrap(Object object) { try { if (object == null) { return NULL; } if (object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object) || object instanceof JSONString || object instanceof Byte || object instanceof Character || object instanceof Short || object instanceof Integer || object instanceof Long || object instanceof Boolean || object instanceof Float || object instanceof Double || object instanceof String) { return object; } if (object instanceof Collection) { return new JSONArray((Collection)object); } if (object.getClass().isArray()) { return new JSONArray(object); } if (object instanceof Map) { return new JSONObject((Map)object); } Package objectPackage = object.getClass().getPackage(); String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; if ( objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || object.getClass().getClassLoader() == null ) { return object.toString(); } return new JSONObject(object); } catch(Exception exception) { return null; } } /** * Write the contents of the JSONObject as JSON text to a writer. * For compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { try { boolean commanate = false; Iterator keys = this.keys(); writer.write('{'); while (keys.hasNext()) { if (commanate) { writer.write(','); } Object key = keys.next(); writer.write(quote(key.toString())); writer.write(':'); Object value = this.map.get(key); if (value instanceof JSONObject) { ((JSONObject)value).write(writer); } else if (value instanceof JSONArray) { ((JSONArray)value).write(writer); } else { writer.write(valueToString(value)); } commanate = true; } writer.write('}'); return writer; } catch (IOException exception) { throw new JSONException(exception); } } }
Java
package org.json; /* Copyright (c) 2006 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.io.StringWriter; /** * JSONStringer provides a quick and convenient way of producing JSON text. * The texts produced strictly conform to JSON syntax rules. No whitespace is * added, so the results are ready for transmission or storage. Each instance of * JSONStringer can produce one JSON text. * <p> * A JSONStringer instance provides a <code>value</code> method for appending * values to the * text, and a <code>key</code> * method for adding keys before values in objects. There are <code>array</code> * and <code>endArray</code> methods that make and bound array values, and * <code>object</code> and <code>endObject</code> methods which make and bound * object values. All of these methods return the JSONWriter instance, * permitting cascade style. For example, <pre> * myString = new JSONStringer() * .object() * .key("JSON") * .value("Hello, World!") * .endObject() * .toString();</pre> which produces the string <pre> * {"JSON":"Hello, World!"}</pre> * <p> * The first method called must be <code>array</code> or <code>object</code>. * There are no methods for adding commas or colons. JSONStringer adds them for * you. Objects and arrays can be nested up to 20 levels deep. * <p> * This can sometimes be easier than using a JSONObject to build a string. * @author JSON.org * @version 2008-09-18 */ public class JSONStringer extends JSONWriter { /** * Make a fresh JSONStringer. It can be used to build one JSON text. */ public JSONStringer() { super(new StringWriter()); } /** * Return the JSON text. This method is used to obtain the product of the * JSONStringer instance. It will return <code>null</code> if there was a * problem in the construction of the JSON text (such as the calls to * <code>array</code> were not properly balanced with calls to * <code>endArray</code>). * @return The JSON text. */ public String toString() { return this.mode == 'd' ? this.writer.toString() : null; } }
Java
package org.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * The XMLTokener extends the JSONTokener to provide additional methods * for the parsing of XML texts. * @author JSON.org * @version 2010-12-24 */ public class XMLTokener extends JSONTokener { /** The table of entity values. It initially contains Character values for * amp, apos, gt, lt, quot. */ public static final java.util.HashMap entity; static { entity = new java.util.HashMap(8); entity.put("amp", XML.AMP); entity.put("apos", XML.APOS); entity.put("gt", XML.GT); entity.put("lt", XML.LT); entity.put("quot", XML.QUOT); } /** * Construct an XMLTokener from a string. * @param s A source string. */ public XMLTokener(String s) { super(s); } /** * Get the text in the CDATA block. * @return The string up to the <code>]]&gt;</code>. * @throws JSONException If the <code>]]&gt;</code> is not found. */ public String nextCDATA() throws JSONException { char c; int i; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); if (end()) { throw syntaxError("Unclosed CDATA"); } sb.append(c); i = sb.length() - 3; if (i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { sb.setLength(i); return sb.toString(); } } } /** * Get the next XML outer token, trimming whitespace. There are two kinds * of tokens: the '<' character which begins a markup tag, and the content * text between markup tags. * * @return A string, or a '<' Character, or null if there is no more * source text. * @throws JSONException */ public Object nextContent() throws JSONException { char c; StringBuffer sb; do { c = next(); } while (Character.isWhitespace(c)); if (c == 0) { return null; } if (c == '<') { return XML.LT; } sb = new StringBuffer(); for (;;) { if (c == '<' || c == 0) { back(); return sb.toString().trim(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } c = next(); } } /** * Return the next entity. These entities are translated to Characters: * <code>&amp; &apos; &gt; &lt; &quot;</code>. * @param ampersand An ampersand character. * @return A Character or an entity String if the entity is not recognized. * @throws JSONException If missing ';' in XML entity. */ public Object nextEntity(char ampersand) throws JSONException { StringBuffer sb = new StringBuffer(); for (;;) { char c = next(); if (Character.isLetterOrDigit(c) || c == '#') { sb.append(Character.toLowerCase(c)); } else if (c == ';') { break; } else { throw syntaxError("Missing ';' in XML entity: &" + sb); } } String string = sb.toString(); Object object = entity.get(string); return object != null ? object : ampersand + string + ";"; } /** * Returns the next XML meta token. This is used for skipping over <!...> * and <?...?> structures. * @return Syntax characters (<code>< > / = ! ?</code>) are returned as * Character, and strings and names are returned as Boolean. We don't care * what the values actually are. * @throws JSONException If a string is not properly closed or if the XML * is badly structured. */ public Object nextMeta() throws JSONException { char c; char q; do { c = next(); } while (Character.isWhitespace(c)); switch (c) { case 0: throw syntaxError("Misshaped meta tag"); case '<': return XML.LT; case '>': return XML.GT; case '/': return XML.SLASH; case '=': return XML.EQ; case '!': return XML.BANG; case '?': return XML.QUEST; case '"': case '\'': q = c; for (;;) { c = next(); if (c == 0) { throw syntaxError("Unterminated string"); } if (c == q) { return Boolean.TRUE; } } default: for (;;) { c = next(); if (Character.isWhitespace(c)) { return Boolean.TRUE; } switch (c) { case 0: case '<': case '>': case '/': case '=': case '!': case '?': case '"': case '\'': back(); return Boolean.TRUE; } } } } /** * Get the next XML Token. These tokens are found inside of angle * brackets. It may be one of these characters: <code>/ > = ! ?</code> or it * may be a string wrapped in single quotes or double quotes, or it may be a * name. * @return a String or a Character. * @throws JSONException If the XML is not well formed. */ public Object nextToken() throws JSONException { char c; char q; StringBuffer sb; do { c = next(); } while (Character.isWhitespace(c)); switch (c) { case 0: throw syntaxError("Misshaped element"); case '<': throw syntaxError("Misplaced '<'"); case '>': return XML.GT; case '/': return XML.SLASH; case '=': return XML.EQ; case '!': return XML.BANG; case '?': return XML.QUEST; // Quoted string case '"': case '\'': q = c; sb = new StringBuffer(); for (;;) { c = next(); if (c == 0) { throw syntaxError("Unterminated string"); } if (c == q) { return sb.toString(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } } default: // Name sb = new StringBuffer(); for (;;) { sb.append(c); c = next(); if (Character.isWhitespace(c)) { return sb.toString(); } switch (c) { case 0: return sb.toString(); case '>': case '/': case '=': case '!': case '?': case '[': case ']': back(); return sb.toString(); case '<': case '"': case '\'': throw syntaxError("Bad character in a name"); } } } } /** * Skip characters until past the requested string. * If it is not found, we are left at the end of the source with a result of false. * @param to A string to skip past. * @throws JSONException */ public boolean skipPast(String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; int length = to.length(); char[] circle = new char[length]; /* * First fill the circle buffer with as many characters as are in the * to string. If we reach an early end, bail. */ for (i = 0; i < length; i += 1) { c = next(); if (c == 0) { return false; } circle[i] = c; } /* * We will loop, possibly for all of the remaining characters. */ for (;;) { j = offset; b = true; /* * Compare the circle buffer with the to string. */ for (i = 0; i < length; i += 1) { if (circle[j] != to.charAt(i)) { b = false; break; } j += 1; if (j >= length) { j -= length; } } /* * If we exit the loop with b intact, then victory is ours. */ if (b) { return true; } /* * Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the * circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; if (offset >= length) { offset -= length; } } } }
Java
package org.json; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * A JSONTokener takes a source string and extracts characters and tokens from * it. It is used by the JSONObject and JSONArray constructors to parse * JSON source strings. * @author JSON.org * @version 2012-02-16 */ public class JSONTokener { private long character; private boolean eof; private long index; private long line; private char previous; private Reader reader; private boolean usePrevious; /** * Construct a JSONTokener from a Reader. * * @param reader A reader. */ public JSONTokener(Reader reader) { this.reader = reader.markSupported() ? reader : new BufferedReader(reader); this.eof = false; this.usePrevious = false; this.previous = 0; this.index = 0; this.character = 1; this.line = 1; } /** * Construct a JSONTokener from an InputStream. */ public JSONTokener(InputStream inputStream) throws JSONException { this(new InputStreamReader(inputStream)); } /** * Construct a JSONTokener from a string. * * @param s A source string. */ public JSONTokener(String s) { this(new StringReader(s)); } /** * Back up one character. This provides a sort of lookahead capability, * so that you can test for a digit or letter before attempting to parse * the next number or identifier. */ public void back() throws JSONException { if (this.usePrevious || this.index <= 0) { throw new JSONException("Stepping back two steps is not supported"); } this.index -= 1; this.character -= 1; this.usePrevious = true; this.eof = false; } /** * Get the hex value of a character (base16). * @param c A character between '0' and '9' or between 'A' and 'F' or * between 'a' and 'f'. * @return An int between 0 and 15, or -1 if c was not a hex digit. */ public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; } public boolean end() { return this.eof && !this.usePrevious; } /** * Determine if the source string still contains characters that next() * can consume. * @return true if not yet at the end of the source. */ public boolean more() throws JSONException { this.next(); if (this.end()) { return false; } this.back(); return true; } /** * Get the next character in the source string. * * @return The next character, or 0 if past the end of the source string. */ public char next() throws JSONException { int c; if (this.usePrevious) { this.usePrevious = false; c = this.previous; } else { try { c = this.reader.read(); } catch (IOException exception) { throw new JSONException(exception); } if (c <= 0) { // End of stream this.eof = true; c = 0; } } this.index += 1; if (this.previous == '\r') { this.line += 1; this.character = c == '\n' ? 0 : 1; } else if (c == '\n') { this.line += 1; this.character = 0; } else { this.character += 1; } this.previous = (char) c; return this.previous; } /** * Consume the next character, and check that it matches a specified * character. * @param c The character to match. * @return The character. * @throws JSONException if the character does not match. */ public char next(char c) throws JSONException { char n = this.next(); if (n != c) { throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); } return n; } /** * Get the next n characters. * * @param n The number of characters to take. * @return A string of n characters. * @throws JSONException * Substring bounds error if there are not * n characters remaining in the source string. */ public String next(int n) throws JSONException { if (n == 0) { return ""; } char[] chars = new char[n]; int pos = 0; while (pos < n) { chars[pos] = this.next(); if (this.end()) { throw this.syntaxError("Substring bounds error"); } pos += 1; } return new String(chars); } /** * Get the next char in the string, skipping whitespace. * @throws JSONException * @return A character, or 0 if there are no more characters. */ public char nextClean() throws JSONException { for (;;) { char c = this.next(); if (c == 0 || c > ' ') { return c; } } } /** * Return the characters up to the next close quote character. * Backslash processing is done. The formal JSON format does not * allow strings in single quotes, but an implementation is allowed to * accept them. * @param quote The quoting character, either * <code>"</code>&nbsp;<small>(double quote)</small> or * <code>'</code>&nbsp;<small>(single quote)</small>. * @return A String. * @throws JSONException Unterminated string. */ public String nextString(char quote) throws JSONException { char c; StringBuffer sb = new StringBuffer(); for (;;) { c = this.next(); switch (c) { case 0: case '\n': case '\r': throw this.syntaxError("Unterminated string"); case '\\': c = this.next(); switch (c) { case 'b': sb.append('\b'); break; case 't': sb.append('\t'); break; case 'n': sb.append('\n'); break; case 'f': sb.append('\f'); break; case 'r': sb.append('\r'); break; case 'u': sb.append((char)Integer.parseInt(this.next(4), 16)); break; case '"': case '\'': case '\\': case '/': sb.append(c); break; default: throw this.syntaxError("Illegal escape."); } break; default: if (c == quote) { return sb.toString(); } sb.append(c); } } } /** * Get the text up but not including the specified character or the * end of line, whichever comes first. * @param delimiter A delimiter character. * @return A string. */ public String nextTo(char delimiter) throws JSONException { StringBuffer sb = new StringBuffer(); for (;;) { char c = this.next(); if (c == delimiter || c == 0 || c == '\n' || c == '\r') { if (c != 0) { this.back(); } return sb.toString().trim(); } sb.append(c); } } /** * Get the text up but not including one of the specified delimiter * characters or the end of line, whichever comes first. * @param delimiters A set of delimiter characters. * @return A string, trimmed. */ public String nextTo(String delimiters) throws JSONException { char c; StringBuffer sb = new StringBuffer(); for (;;) { c = this.next(); if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { if (c != 0) { this.back(); } return sb.toString().trim(); } sb.append(c); } } /** * Get the next value. The value can be a Boolean, Double, Integer, * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. * @throws JSONException If syntax error. * * @return An object. */ public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { case '"': case '\'': return this.nextString(c); case '{': this.back(); return new JSONObject(this); case '[': this.back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = this.next(); } this.back(); string = sb.toString().trim(); if ("".equals(string)) { throw this.syntaxError("Missing value"); } return JSONObject.stringToValue(string); } /** * Skip characters until the next character is the requested character. * If the requested character is not found, no characters are skipped. * @param to A character to skip to. * @return The requested character, or zero if the requested character * is not found. */ public char skipTo(char to) throws JSONException { char c; try { long startIndex = this.index; long startCharacter = this.character; long startLine = this.line; this.reader.mark(1000000); do { c = this.next(); if (c == 0) { this.reader.reset(); this.index = startIndex; this.character = startCharacter; this.line = startLine; return c; } } while (c != to); } catch (IOException exc) { throw new JSONException(exc); } this.back(); return c; } /** * Make a JSONException to signal a syntax error. * * @param message The error message. * @return A JSONException object, suitable for throwing */ public JSONException syntaxError(String message) { return new JSONException(message + this.toString()); } /** * Make a printable string of this JSONTokener. * * @return " at {index} [character {character} line {line}]" */ public String toString() { return " at " + this.index + " [character " + this.character + " line " + this.line + "]"; } }
Java
package org.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.util.Iterator; /** * Convert a web browser cookie list string to a JSONObject and back. * @author JSON.org * @version 2010-12-24 */ public class CookieList { /** * Convert a cookie list into a JSONObject. A cookie list is a sequence * of name/value pairs. The names are separated from the values by '='. * The pairs are separated by ';'. The names and the values * will be unescaped, possibly converting '+' and '%' sequences. * * To add a cookie to a cooklist, * cookielistJSONObject.put(cookieJSONObject.getString("name"), * cookieJSONObject.getString("value")); * @param string A cookie list string * @return A JSONObject * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); JSONTokener x = new JSONTokener(string); while (x.more()) { String name = Cookie.unescape(x.nextTo('=')); x.next('='); jo.put(name, Cookie.unescape(x.nextTo(';'))); x.next(); } return jo; } /** * Convert a JSONObject into a cookie list. A cookie list is a sequence * of name/value pairs. The names are separated from the values by '='. * The pairs are separated by ';'. The characters '%', '+', '=', and ';' * in the names and values are replaced by "%hh". * @param jo A JSONObject * @return A cookie list string * @throws JSONException */ public static String toString(JSONObject jo) throws JSONException { boolean b = false; Iterator keys = jo.keys(); String string; StringBuffer sb = new StringBuffer(); while (keys.hasNext()) { string = keys.next().toString(); if (!jo.isNull(string)) { if (b) { sb.append(';'); } sb.append(Cookie.escape(string)); sb.append("="); sb.append(Cookie.escape(jo.getString(string))); b = true; } } return sb.toString(); } }
Java
package org.json; /** * The <code>JSONString</code> interface allows a <code>toJSONString()</code> * method so that a class can change the behavior of * <code>JSONObject.toString()</code>, <code>JSONArray.toString()</code>, * and <code>JSONWriter.value(</code>Object<code>)</code>. The * <code>toJSONString</code> method will be used instead of the default behavior * of using the Object's <code>toString()</code> method and quoting the result. */ public interface JSONString { /** * The <code>toJSONString</code> method allows a class to produce its own JSON * serialization. * * @return A strictly syntactically correct JSON text. */ public String toJSONString(); }
Java
package org.json; import java.io.IOException; import java.io.Writer; /* Copyright (c) 2006 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * JSONWriter provides a quick and convenient way of producing JSON text. * The texts produced strictly conform to JSON syntax rules. No whitespace is * added, so the results are ready for transmission or storage. Each instance of * JSONWriter can produce one JSON text. * <p> * A JSONWriter instance provides a <code>value</code> method for appending * values to the * text, and a <code>key</code> * method for adding keys before values in objects. There are <code>array</code> * and <code>endArray</code> methods that make and bound array values, and * <code>object</code> and <code>endObject</code> methods which make and bound * object values. All of these methods return the JSONWriter instance, * permitting a cascade style. For example, <pre> * new JSONWriter(myWriter) * .object() * .key("JSON") * .value("Hello, World!") * .endObject();</pre> which writes <pre> * {"JSON":"Hello, World!"}</pre> * <p> * The first method called must be <code>array</code> or <code>object</code>. * There are no methods for adding commas or colons. JSONWriter adds them for * you. Objects and arrays can be nested up to 20 levels deep. * <p> * This can sometimes be easier than using a JSONObject to build a string. * @author JSON.org * @version 2011-11-24 */ public class JSONWriter { private static final int maxdepth = 200; /** * The comma flag determines if a comma should be output before the next * value. */ private boolean comma; /** * The current mode. Values: * 'a' (array), * 'd' (done), * 'i' (initial), * 'k' (key), * 'o' (object). */ protected char mode; /** * The object/array stack. */ private final JSONObject stack[]; /** * The stack top index. A value of 0 indicates that the stack is empty. */ private int top; /** * The writer that will receive the output. */ protected Writer writer; /** * Make a fresh JSONWriter. It can be used to build one JSON text. */ public JSONWriter(Writer w) { this.comma = false; this.mode = 'i'; this.stack = new JSONObject[maxdepth]; this.top = 0; this.writer = w; } /** * Append a value. * @param string A string value. * @return this * @throws JSONException If the value is out of sequence. */ private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); } /** * Begin appending a new array. All values until the balancing * <code>endArray</code> will be appended to this array. The * <code>endArray</code> method must be called to mark the array's end. * @return this * @throws JSONException If the nesting is too deep, or if the object is * started in the wrong place (for example as a key or after the end of the * outermost array or object). */ public JSONWriter array() throws JSONException { if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { this.push(null); this.append("["); this.comma = false; return this; } throw new JSONException("Misplaced array."); } /** * End something. * @param mode Mode * @param c Closing character * @return this * @throws JSONException If unbalanced. */ private JSONWriter end(char mode, char c) throws JSONException { if (this.mode != mode) { throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); } this.pop(mode); try { this.writer.write(c); } catch (IOException e) { throw new JSONException(e); } this.comma = true; return this; } /** * End an array. This method most be called to balance calls to * <code>array</code>. * @return this * @throws JSONException If incorrectly nested. */ public JSONWriter endArray() throws JSONException { return this.end('a', ']'); } /** * End an object. This method most be called to balance calls to * <code>object</code>. * @return this * @throws JSONException If incorrectly nested. */ public JSONWriter endObject() throws JSONException { return this.end('k', '}'); } /** * Append a key. The key will be associated with the next value. In an * object, every value must be preceded by a key. * @param string A key string. * @return this * @throws JSONException If the key is out of place. For example, keys * do not belong in arrays or if the key is null. */ public JSONWriter key(String string) throws JSONException { if (string == null) { throw new JSONException("Null key."); } if (this.mode == 'k') { try { this.stack[this.top - 1].putOnce(string, Boolean.TRUE); if (this.comma) { this.writer.write(','); } this.writer.write(JSONObject.quote(string)); this.writer.write(':'); this.comma = false; this.mode = 'o'; return this; } catch (IOException e) { throw new JSONException(e); } } throw new JSONException("Misplaced key."); } /** * Begin appending a new object. All keys and values until the balancing * <code>endObject</code> will be appended to this object. The * <code>endObject</code> method must be called to mark the object's end. * @return this * @throws JSONException If the nesting is too deep, or if the object is * started in the wrong place (for example as a key or after the end of the * outermost array or object). */ public JSONWriter object() throws JSONException { if (this.mode == 'i') { this.mode = 'o'; } if (this.mode == 'o' || this.mode == 'a') { this.append("{"); this.push(new JSONObject()); this.comma = false; return this; } throw new JSONException("Misplaced object."); } /** * Pop an array or object scope. * @param c The scope to close. * @throws JSONException If nesting is wrong. */ private void pop(char c) throws JSONException { if (this.top <= 0) { throw new JSONException("Nesting error."); } char m = this.stack[this.top - 1] == null ? 'a' : 'k'; if (m != c) { throw new JSONException("Nesting error."); } this.top -= 1; this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; } /** * Push an array or object scope. * @param c The scope to open. * @throws JSONException If nesting is too deep. */ private void push(JSONObject jo) throws JSONException { if (this.top >= maxdepth) { throw new JSONException("Nesting too deep."); } this.stack[this.top] = jo; this.mode = jo == null ? 'a' : 'k'; this.top += 1; } /** * Append either the value <code>true</code> or the value * <code>false</code>. * @param b A boolean. * @return this * @throws JSONException */ public JSONWriter value(boolean b) throws JSONException { return this.append(b ? "true" : "false"); } /** * Append a double value. * @param d A double. * @return this * @throws JSONException If the number is not finite. */ public JSONWriter value(double d) throws JSONException { return this.value(new Double(d)); } /** * Append a long value. * @param l A long. * @return this * @throws JSONException */ public JSONWriter value(long l) throws JSONException { return this.append(Long.toString(l)); } /** * Append an object value. * @param object The object to append. It can be null, or a Boolean, Number, * String, JSONObject, or JSONArray, or an object that implements JSONString. * @return this * @throws JSONException If the value is out of sequence. */ public JSONWriter value(Object object) throws JSONException { return this.append(JSONObject.valueToString(object)); } }
Java
package org.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.io.IOException; import java.io.Writer; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * A JSONArray is an ordered sequence of values. Its external text form is a * string wrapped in square brackets with commas separating the values. The * internal form is an object having <code>get</code> and <code>opt</code> * methods for accessing the values by index, and <code>put</code> methods for * adding or replacing values. The values can be any of these types: * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>, * <code>Number</code>, <code>String</code>, or the * <code>JSONObject.NULL object</code>. * <p> * The constructor can convert a JSON text into a Java object. The * <code>toString</code> method converts to JSON text. * <p> * A <code>get</code> method returns a value if one can be found, and throws an * exception if one cannot be found. An <code>opt</code> method returns a * default value instead of throwing an exception, and so is useful for * obtaining optional values. * <p> * The generic <code>get()</code> and <code>opt()</code> methods return an * object which you can cast or query for type. There are also typed * <code>get</code> and <code>opt</code> methods that do type checking and type * coercion for you. * <p> * The texts produced by the <code>toString</code> methods strictly conform to * JSON syntax rules. The constructors are more forgiving in the texts they will * accept: * <ul> * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just * before the closing bracket.</li> * <li>The <code>null</code> value will be inserted when there * is <code>,</code>&nbsp;<small>(comma)</small> elision.</li> * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single * quote)</small>.</li> * <li>Strings do not need to be quoted at all if they do not begin with a quote * or single quote, and if they do not contain leading or trailing spaces, * and if they do not contain any of these characters: * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers * and if they are not the reserved words <code>true</code>, * <code>false</code>, or <code>null</code>.</li> * <li>Values can be separated by <code>;</code> <small>(semicolon)</small> as * well as by <code>,</code> <small>(comma)</small>.</li> * </ul> * @author JSON.org * @version 2011-12-19 */ public class JSONArray { /** * The arrayList where the JSONArray's properties are kept. */ private final ArrayList myArrayList; /** * Construct an empty JSONArray. */ public JSONArray() { this.myArrayList = new ArrayList(); } /** * Construct a JSONArray from a JSONTokener. * @param x A JSONTokener * @throws JSONException If there is a syntax error. */ public JSONArray(JSONTokener x) throws JSONException { this(); if (x.nextClean() != '[') { throw x.syntaxError("A JSONArray text must start with '['"); } if (x.nextClean() != ']') { x.back(); for (;;) { if (x.nextClean() == ',') { x.back(); this.myArrayList.add(JSONObject.NULL); } else { x.back(); this.myArrayList.add(x.nextValue()); } switch (x.nextClean()) { case ';': case ',': if (x.nextClean() == ']') { return; } x.back(); break; case ']': return; default: throw x.syntaxError("Expected a ',' or ']'"); } } } } /** * Construct a JSONArray from a source JSON text. * @param source A string that begins with * <code>[</code>&nbsp;<small>(left bracket)</small> * and ends with <code>]</code>&nbsp;<small>(right bracket)</small>. * @throws JSONException If there is a syntax error. */ public JSONArray(String source) throws JSONException { this(new JSONTokener(source)); } /** * Construct a JSONArray from a Collection. * @param collection A Collection. */ public JSONArray(Collection collection) { this.myArrayList = new ArrayList(); if (collection != null) { Iterator iter = collection.iterator(); while (iter.hasNext()) { this.myArrayList.add(JSONObject.wrap(iter.next())); } } } /** * Construct a JSONArray from an array * @throws JSONException If not an array. */ public JSONArray(Object array) throws JSONException { this(); if (array.getClass().isArray()) { int length = Array.getLength(array); for (int i = 0; i < length; i += 1) { this.put(JSONObject.wrap(Array.get(array, i))); } } else { throw new JSONException( "JSONArray initial value should be a string or collection or array."); } } /** * Get the object value associated with an index. * @param index * The index must be between 0 and length() - 1. * @return An object value. * @throws JSONException If there is no value for the index. */ public Object get(int index) throws JSONException { Object object = this.opt(index); if (object == null) { throw new JSONException("JSONArray[" + index + "] not found."); } return object; } /** * Get the boolean value associated with an index. * The string values "true" and "false" are converted to boolean. * * @param index The index must be between 0 and length() - 1. * @return The truth. * @throws JSONException If there is no value for the index or if the * value is not convertible to boolean. */ public boolean getBoolean(int index) throws JSONException { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); } /** * Get the double value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. * @throws JSONException If the key is not found or if the value cannot * be converted to a number. */ public double getDouble(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number)object).doubleValue() : Double.parseDouble((String)object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the int value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. * @throws JSONException If the key is not found or if the value is not a number. */ public int getInt(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number)object).intValue() : Integer.parseInt((String)object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the JSONArray associated with an index. * @param index The index must be between 0 and length() - 1. * @return A JSONArray value. * @throws JSONException If there is no value for the index. or if the * value is not a JSONArray */ public JSONArray getJSONArray(int index) throws JSONException { Object object = this.get(index); if (object instanceof JSONArray) { return (JSONArray)object; } throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); } /** * Get the JSONObject associated with an index. * @param index subscript * @return A JSONObject value. * @throws JSONException If there is no value for the index or if the * value is not a JSONObject */ public JSONObject getJSONObject(int index) throws JSONException { Object object = this.get(index); if (object instanceof JSONObject) { return (JSONObject)object; } throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); } /** * Get the long value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. * @throws JSONException If the key is not found or if the value cannot * be converted to a number. */ public long getLong(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number)object).longValue() : Long.parseLong((String)object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the string associated with an index. * @param index The index must be between 0 and length() - 1. * @return A string value. * @throws JSONException If there is no string value for the index. */ public String getString(int index) throws JSONException { Object object = this.get(index); if (object instanceof String) { return (String)object; } throw new JSONException("JSONArray[" + index + "] not a string."); } /** * Determine if the value is null. * @param index The index must be between 0 and length() - 1. * @return true if the value at the index is null, or if there is no value. */ public boolean isNull(int index) { return JSONObject.NULL.equals(this.opt(index)); } /** * Make a string from the contents of this JSONArray. The * <code>separator</code> string is inserted between each element. * Warning: This method assumes that the data structure is acyclical. * @param separator A string that will be inserted between the elements. * @return a string. * @throws JSONException If the array contains an invalid number. */ public String join(String separator) throws JSONException { int len = this.length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < len; i += 1) { if (i > 0) { sb.append(separator); } sb.append(JSONObject.valueToString(this.myArrayList.get(i))); } return sb.toString(); } /** * Get the number of elements in the JSONArray, included nulls. * * @return The length (or size). */ public int length() { return this.myArrayList.size(); } /** * Get the optional object value associated with an index. * @param index The index must be between 0 and length() - 1. * @return An object value, or null if there is no * object at that index. */ public Object opt(int index) { return (index < 0 || index >= this.length()) ? null : this.myArrayList.get(index); } /** * Get the optional boolean value associated with an index. * It returns false if there is no value at that index, * or if the value is not Boolean.TRUE or the String "true". * * @param index The index must be between 0 and length() - 1. * @return The truth. */ public boolean optBoolean(int index) { return this.optBoolean(index, false); } /** * Get the optional boolean value associated with an index. * It returns the defaultValue if there is no value at that index or if * it is not a Boolean or the String "true" or "false" (case insensitive). * * @param index The index must be between 0 and length() - 1. * @param defaultValue A boolean default. * @return The truth. */ public boolean optBoolean(int index, boolean defaultValue) { try { return this.getBoolean(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional double value associated with an index. * NaN is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public double optDouble(int index) { return this.optDouble(index, Double.NaN); } /** * Get the optional double value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index subscript * @param defaultValue The default value. * @return The value. */ public double optDouble(int index, double defaultValue) { try { return this.getDouble(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional int value associated with an index. * Zero is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public int optInt(int index) { return this.optInt(index, 0); } /** * Get the optional int value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. * @return The value. */ public int optInt(int index, int defaultValue) { try { return this.getInt(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional JSONArray associated with an index. * @param index subscript * @return A JSONArray value, or null if the index has no value, * or if the value is not a JSONArray. */ public JSONArray optJSONArray(int index) { Object o = this.opt(index); return o instanceof JSONArray ? (JSONArray)o : null; } /** * Get the optional JSONObject associated with an index. * Null is returned if the key is not found, or null if the index has * no value, or if the value is not a JSONObject. * * @param index The index must be between 0 and length() - 1. * @return A JSONObject value. */ public JSONObject optJSONObject(int index) { Object o = this.opt(index); return o instanceof JSONObject ? (JSONObject)o : null; } /** * Get the optional long value associated with an index. * Zero is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public long optLong(int index) { return this.optLong(index, 0); } /** * Get the optional long value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. * @return The value. */ public long optLong(int index, long defaultValue) { try { return this.getLong(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional string value associated with an index. It returns an * empty string if there is no value at that index. If the value * is not a string and is not null, then it is coverted to a string. * * @param index The index must be between 0 and length() - 1. * @return A String value. */ public String optString(int index) { return this.optString(index, ""); } /** * Get the optional string associated with an index. * The defaultValue is returned if the key is not found. * * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. * @return A String value. */ public String optString(int index, String defaultValue) { Object object = this.opt(index); return JSONObject.NULL.equals(object) ? defaultValue : object.toString(); } /** * Append a boolean value. This increases the array's length by one. * * @param value A boolean value. * @return this. */ public JSONArray put(boolean value) { this.put(value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONArray which is produced from a Collection. * @param value A Collection value. * @return this. */ public JSONArray put(Collection value) { this.put(new JSONArray(value)); return this; } /** * Append a double value. This increases the array's length by one. * * @param value A double value. * @throws JSONException if the value is not finite. * @return this. */ public JSONArray put(double value) throws JSONException { Double d = new Double(value); JSONObject.testValidity(d); this.put(d); return this; } /** * Append an int value. This increases the array's length by one. * * @param value An int value. * @return this. */ public JSONArray put(int value) { this.put(new Integer(value)); return this; } /** * Append an long value. This increases the array's length by one. * * @param value A long value. * @return this. */ public JSONArray put(long value) { this.put(new Long(value)); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONObject which is produced from a Map. * @param value A Map value. * @return this. */ public JSONArray put(Map value) { this.put(new JSONObject(value)); return this; } /** * Append an object value. This increases the array's length by one. * @param value An object value. The value should be a * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * @return this. */ public JSONArray put(Object value) { this.myArrayList.add(value); return this; } /** * Put or replace a boolean value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * @param index The subscript. * @param value A boolean value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray put(int index, boolean value) throws JSONException { this.put(index, value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONArray which is produced from a Collection. * @param index The subscript. * @param value A Collection value. * @return this. * @throws JSONException If the index is negative or if the value is * not finite. */ public JSONArray put(int index, Collection value) throws JSONException { this.put(index, new JSONArray(value)); return this; } /** * Put or replace a double value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad * it out. * @param index The subscript. * @param value A double value. * @return this. * @throws JSONException If the index is negative or if the value is * not finite. */ public JSONArray put(int index, double value) throws JSONException { this.put(index, new Double(value)); return this; } /** * Put or replace an int value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad * it out. * @param index The subscript. * @param value An int value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray put(int index, int value) throws JSONException { this.put(index, new Integer(value)); return this; } /** * Put or replace a long value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad * it out. * @param index The subscript. * @param value A long value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray put(int index, long value) throws JSONException { this.put(index, new Long(value)); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONObject that is produced from a Map. * @param index The subscript. * @param value The Map value. * @return this. * @throws JSONException If the index is negative or if the the value is * an invalid number. */ public JSONArray put(int index, Map value) throws JSONException { this.put(index, new JSONObject(value)); return this; } /** * Put or replace an object value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * @param index The subscript. * @param value The value to put into the array. The value should be a * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * @return this. * @throws JSONException If the index is negative or if the the value is * an invalid number. */ public JSONArray put(int index, Object value) throws JSONException { JSONObject.testValidity(value); if (index < 0) { throw new JSONException("JSONArray[" + index + "] not found."); } if (index < this.length()) { this.myArrayList.set(index, value); } else { while (index != this.length()) { this.put(JSONObject.NULL); } this.put(value); } return this; } /** * Remove an index and close the hole. * @param index The index of the element to be removed. * @return The value that was associated with the index, * or null if there was no value. */ public Object remove(int index) { Object o = this.opt(index); this.myArrayList.remove(index); return o; } /** * Produce a JSONObject by combining a JSONArray of names with the values * of this JSONArray. * @param names A JSONArray containing a list of key strings. These will be * paired with the values. * @return A JSONObject, or null if there are no names or if this JSONArray * has no values. * @throws JSONException If any of the names are null. */ public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || this.length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; } /** * Make a JSON text of this JSONArray. For compactness, no * unnecessary whitespace is added. If it is not possible to produce a * syntactically correct JSON text then null will be returned instead. This * could occur if the array contains an invalid number. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, transmittable * representation of the array. */ public String toString() { try { return '[' + this.join(",") + ']'; } catch (Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONArray. * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>[</code>&nbsp;<small>(left bracket)</small> and ending * with <code>]</code>&nbsp;<small>(right bracket)</small>. * @throws JSONException */ public String toString(int indentFactor) throws JSONException { return this.toString(indentFactor, 0); } /** * Make a prettyprinted JSON text of this JSONArray. * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indention of the top level. * @return a printable, displayable, transmittable * representation of the array. * @throws JSONException */ String toString(int indentFactor, int indent) throws JSONException { int len = this.length(); if (len == 0) { return "[]"; } int i; StringBuffer sb = new StringBuffer("["); if (len == 1) { sb.append(JSONObject.valueToString(this.myArrayList.get(0), indentFactor, indent)); } else { int newindent = indent + indentFactor; sb.append('\n'); for (i = 0; i < len; i += 1) { if (i > 0) { sb.append(",\n"); } for (int j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(JSONObject.valueToString(this.myArrayList.get(i), indentFactor, newindent)); } sb.append('\n'); for (i = 0; i < indent; i += 1) { sb.append(' '); } } sb.append(']'); return sb.toString(); } /** * Write the contents of the JSONArray as JSON text to a writer. * For compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { try { boolean b = false; int len = this.length(); writer.write('['); for (int i = 0; i < len; i += 1) { if (b) { writer.write(','); } Object v = this.myArrayList.get(i); if (v instanceof JSONObject) { ((JSONObject)v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray)v).write(writer); } else { writer.write(JSONObject.valueToString(v)); } b = true; } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } } }
Java
package com.hundred.home.module.screen; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.turbine.Context; import com.alibaba.citrus.turbine.Navigator; import com.alibaba.citrus.util.StringUtil; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.item.manager.ItemCompareManager; import com.hundred.item.manager.ItemManager; import com.hundred.item.manager.TopItemManager; public class WebIndex { private static final Logger logger = LoggerFactory.getLogger(Index.class); @Autowired private HttpServletRequest request; @Autowired private ItemManager itemManager; @Autowired private TopItemManager topItemManager; @Autowired private ItemCompareManager itemCompareManager; public void execute(Context context, Navigator nav) { String command = request.getParameter("syn"); if(command!=null && "true".equals(command)){ logger.error("---syn---templetes--"); synTemplete(); } String tagStr = request.getParameter("tag"); int tag = 100; if(!StringUtil.isBlank(tagStr)){ tag=Integer.parseInt(tagStr); } List<ItemDO> itemList = itemCompareManager.selectCompareItems(2,tag); context.put("leftItem", itemList.get(0)); context.put("rightItem", itemList.get(1)); List<ItemDO> topItems = topItemManager.getTopItemList(10L); if(topItems!=null && topItems.size()>0){ context.put("topItem", topItems.get(0)); context.put("topItemList",topItems); } context.put("result", "ok"); context.put("closeTime", getCloserTime()); } private String getCloserTime(){ Calendar cpcalendar = new GregorianCalendar(); long nowTime=cpcalendar.getTimeInMillis(); cpcalendar.add(Calendar.DAY_OF_MONTH,1); cpcalendar.set(Calendar.HOUR_OF_DAY, 0); cpcalendar.set(Calendar.MINUTE, 0); cpcalendar.set(Calendar.SECOND, 0); long targetTime=cpcalendar.getTimeInMillis(); int expireTime=(int) ((targetTime-nowTime)/1000); int hours = expireTime/3600; int minute = (expireTime%3600)/60; String closeTime = String.valueOf(hours)+"小时"+String.valueOf(minute)+"分"; return closeTime; } public ItemManager getItemManager() { return itemManager; } public void setItemManager(ItemManager itemManager) { this.itemManager = itemManager; } public TopItemManager getTopItemManager() { return topItemManager; } public void setTopItemManager(TopItemManager topItemManager) { this.topItemManager = topItemManager; } public ItemCompareManager getItemCompareManager() { return itemCompareManager; } public void setItemCompareManager(ItemCompareManager itemCompareManager) { this.itemCompareManager = itemCompareManager; } private void synTemplete(){ Process process=null; try { process = Runtime.getRuntime().exec("/home/admin/script/syntemplete.sh"); process.waitFor(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if (process != null) { process.destroy(); } } }
Java
package com.hundred.home.module.screen; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.turbine.Context; import com.alibaba.citrus.turbine.Navigator; public class PointsPlan { private static final Logger logger = LoggerFactory.getLogger(Index.class); @Autowired private HttpServletRequest request; public void execute(Context context, Navigator nav) {} }
Java
package com.hundred.home.module.screen; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.turbine.Context; import com.alibaba.citrus.turbine.Navigator; import com.alibaba.citrus.util.StringUtil; import com.hundred.comment.dao.dataobject.AppCommentDO; import com.hundred.comment.manager.CommentManager; import com.hundred.item.dao.dataobject.AppItemDO; import com.hundred.item.manager.AppItemManager; import com.hundred.user.dao.dataobject.AppUserDO; import com.hundred.user.manager.UserManager; public class Index { private static final Logger logger = LoggerFactory.getLogger(Index.class); @Autowired private HttpServletRequest request; @Autowired private AppItemManager itemManager; @Autowired private CommentManager commentManager; @Autowired private UserManager userManager; public void execute(Context context, Navigator nav) { String tagStr = request.getParameter("tag"); int tag = 1; if(!StringUtil.isBlank(tagStr)){ tag=Integer.parseInt(tagStr); } List<AppItemDO> resultList = itemManager.getAppItemList(tag); List<AppCommentDO> commentList = commentManager.getAppCommentList(tag); if(resultList!=null && resultList.size()>0){ int k=20; for(int i=0;i<resultList.size();i++){ for(int j=0;j<4;j++){ k+=1; AppItemDO itemDO = resultList.get(i); itemDO.getCommentUserIcons().put("icon0"+k, commentList.get(j).getCommentContent()); } } } context.put("resultList", resultList); for(AppItemDO item:resultList){ logger.error("------"+item.getItemName()); } String openIdStr = request.getParameter("openid"); String openkeyStr = request.getParameter("openkey"); context.put("openIdStr", openIdStr); context.put("openkeyStr", openkeyStr); AppUserDO userDO = userManager.getAppUser4Open(openIdStr, openkeyStr); String jifenOntheWay = "0"; if(userDO!=null){ context.put("userDO", userDO); if(userDO.getLastLoginIp().split("_0")!=null){ String[] temp = userDO.getLastLoginIp().split("_0"); int points = 100*temp.length; jifenOntheWay = String.valueOf(points); } context.put("jifenOntheWay", jifenOntheWay); } } public AppItemManager getItemManager() { return itemManager; } public void setItemManager(AppItemManager itemManager) { this.itemManager = itemManager; } public CommentManager getCommentManager() { return commentManager; } public void setCommentManager(CommentManager commentManager) { this.commentManager = commentManager; } public UserManager getUserManager() { return userManager; } public void setUserManager(UserManager userManager) { this.userManager = userManager; } }
Java
package com.hundred.home.module.screen; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.turbine.Context; import com.alibaba.citrus.turbine.Navigator; import com.alibaba.citrus.util.StringUtil; import com.hundred.item.dao.dataobject.AppItemDO; import com.hundred.item.manager.AppItemManager; public class AppIndex { private static final Logger logger = LoggerFactory.getLogger(AppIndex.class); @Autowired private HttpServletRequest request; @Autowired private AppItemManager itemManager; public void execute(Context context, Navigator nav) { String tagStr = request.getParameter("tag"); int tag = 100; if(!StringUtil.isBlank(tagStr)){ tag=Integer.parseInt(tagStr); } List<AppItemDO> resultList = itemManager.getAppItemList(tag); context.put("resultList", resultList); } public AppItemManager getItemManager() { return itemManager; } public void setItemManager(AppItemManager itemManager) { this.itemManager = itemManager; } }
Java
package com.hundred.home.module.screen; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.turbine.Context; import com.alibaba.citrus.turbine.Navigator; import com.alibaba.citrus.util.StringUtil; import com.hundred.comment.manager.CommentManager; import com.hundred.item.dao.dataobject.AppItemDO; import com.hundred.item.manager.AppItemManager; import com.hundred.user.dao.dataobject.AppUserDO; import com.hundred.user.manager.UserManager; public class AbtainPoints { private static final Logger logger = LoggerFactory.getLogger(AbtainPoints.class); @Autowired private HttpServletRequest request; @Autowired private AppItemManager itemManager; @Autowired private CommentManager commentManager; @Autowired private UserManager userManager; public void execute(Context context, Navigator nav) { String pointStr = request.getParameter("point_num"); String taskIdStr = request.getParameter("task_id"); String itemIdStr = request.getParameter("item_id"); int points = 0; if(!StringUtil.isBlank(pointStr)){ points=Integer.parseInt(pointStr); } int taskId = 0; if(!StringUtil.isBlank(taskIdStr)){ taskId=Integer.parseInt(taskIdStr); } if(taskId == 0){ return; } int itemId = 0; if(!StringUtil.isBlank(itemIdStr)){ itemId=Integer.parseInt(itemIdStr); } String userIdStr = request.getParameter("userid"); logger.error(userIdStr); if(userIdStr!=null){ AppUserDO updateUserDO = userManager.getAppUserByUserId(userIdStr); if(updateUserDO==null){ logger.error("user is null! check the get method!"); return; } constructPointsStamp(taskId,updateUserDO); AppItemDO appItemDO = itemManager.getAppItemById(itemId); if(taskId==1){ appItemDO.setLikeNum(appItemDO.getLikeNum()+1); itemManager.updateAppItemInfo(appItemDO); } if(taskId==2){ appItemDO.setCollectNum(appItemDO.getCollectNum()+1); itemManager.updateAppItemInfo(appItemDO); } context.put("userDO", updateUserDO); } } private String getTimeStamp(){ StringBuffer sb = new StringBuffer(); Calendar c = Calendar.getInstance(); sb.append(c.get(Calendar.DAY_OF_YEAR)); return sb.toString(); } private String constructPointsStamp(int stampId,AppUserDO updateUserDO){ String originalStamp = updateUserDO.getLastLoginIp(); if(originalStamp==null || originalStamp.length()<1){ return "a:1_0;b:1_0;c:1_0;d:1_0;e:1_0"; } Map<String,Integer> limitMap = new HashMap<String,Integer>(); String[] pointArray = originalStamp.split(";"); for(String one:pointArray){ String[] singlePoint = one.split("_"); limitMap.put(singlePoint[0], Integer.parseInt(singlePoint[1])); } String needRemove = ""; switch(stampId){ case 1: if(limitMap.get("b:"+getTimeStamp())!=null){ int count = limitMap.get("b:"+getTimeStamp()); count+=1; limitMap.put("b:"+getTimeStamp(), count); } else{ for(String key:limitMap.keySet()){ if(key.startsWith("b")){ needRemove= key; } } limitMap.remove(needRemove); limitMap.put("b:"+getTimeStamp(), 1); } updateUserDO.setPoints(updateUserDO.getPoints()+10); break; case 2: if(limitMap.get("b:"+getTimeStamp())!=null){ int count = limitMap.get("b:"+getTimeStamp()); count+=1; limitMap.put("b:"+getTimeStamp(), count); } else{ for(String key:limitMap.keySet()){ if(key.startsWith("b")){ needRemove= key; } } limitMap.remove(needRemove); limitMap.put("b:"+getTimeStamp(), 1); } break; case 3: if(limitMap.get("c:"+getTimeStamp())!=null){ int count = limitMap.get("c:"+getTimeStamp()); count+=1; limitMap.put("c:"+getTimeStamp(), count); } else{ for(String key:limitMap.keySet()){ if(key.startsWith("c")){ needRemove= key; } } limitMap.remove(needRemove); limitMap.put("c:"+getTimeStamp(), 1); } break; case 4: if(limitMap.get("d:"+getTimeStamp())!=null){ int count = limitMap.get("d:"+getTimeStamp()); count+=1; limitMap.put("d:"+getTimeStamp(), count); } else{ for(String key:limitMap.keySet()){ if(key.startsWith("d")){ needRemove= key; } } limitMap.remove(needRemove); limitMap.put("d:"+getTimeStamp(), 1); } break; case 5: if(limitMap.get("e:"+getTimeStamp())!=null){ int count = limitMap.get("e:"+getTimeStamp()); count+=1; limitMap.put("e:"+getTimeStamp(), count); } else{ for(String key:limitMap.keySet()){ if(key.startsWith("e")){ needRemove= key; } } limitMap.remove(needRemove); limitMap.put("e:"+getTimeStamp(), 1); } break; default: ; } String resultFinalStr = convertMap2String(limitMap); updateUserDO.setLastLoginIp(resultFinalStr); userManager.updateUserInfo(updateUserDO); return resultFinalStr; } private String convertMap2String(Map<String,Integer> limitMap ){ StringBuffer sb = new StringBuffer(); if(limitMap!=null && limitMap.size()>0){ int m = limitMap.size(); for(String key:limitMap.keySet()){ sb.append(key); sb.append("_"); sb.append(limitMap.get(key)); if(m>1){ sb.append(";"); } m--; } } return sb.toString(); } public AppItemManager getItemManager() { return itemManager; } public void setItemManager(AppItemManager itemManager) { this.itemManager = itemManager; } public CommentManager getCommentManager() { return commentManager; } public void setCommentManager(CommentManager commentManager) { this.commentManager = commentManager; } public UserManager getUserManager() { return userManager; } public void setUserManager(UserManager userManager) { this.userManager = userManager; } }
Java
package com.hundred.home.module.screen; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.turbine.Context; import com.alibaba.citrus.turbine.Navigator; import com.hundred.item.manager.AppItemManager; public class AttendanceBook { private static final Logger logger = LoggerFactory.getLogger(AttendanceBook.class); @Autowired private HttpServletRequest request; @Autowired private AppItemManager itemManager; public void execute(Context context, Navigator nav) { context.put("result", true); String errorMessage = ""; context.put("errorMessage",errorMessage); } public AppItemManager getItemManager() { return itemManager; } public void setItemManager(AppItemManager itemManager) { this.itemManager = itemManager; } }
Java
package com.hundred.home.module.screen; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.turbine.Context; import com.alibaba.citrus.turbine.Navigator; import com.alibaba.citrus.util.StringUtil; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.item.manager.ItemCompareManager; import com.hundred.item.manager.ItemManager; import com.hundred.item.manager.TopItemManager; public class RealIndexPage { private static final Logger logger = LoggerFactory.getLogger(RealIndexPage.class); @Autowired private HttpServletRequest request; @Autowired private ItemManager itemManager; @Autowired private TopItemManager topItemManager; @Autowired private ItemCompareManager itemCompareManager; public void execute(Context context, Navigator nav) { String command = request.getParameter("syn"); if(command!=null && "true".equals(command)){ logger.error("---syn---templetes--"); synTemplete(); } if(command!=null && "checkdata963".equals(command)){ checkData(); } String tagStr = request.getParameter("tag"); int tag = 100; if(!StringUtil.isBlank(tagStr)){ tag=Integer.parseInt(tagStr); } List<ItemDO> itemList = itemCompareManager.selectCompareItems(2,tag); context.put("leftItem", itemList.get(0)); context.put("rightItem", itemList.get(1)); List<ItemDO> topItems = topItemManager.getTopItemList(10L); if(topItems!=null && topItems.size()>0){ context.put("topItem", topItems.get(0)); context.put("topItemList",topItems); } context.put("result", "ok"); context.put("closeTime", getCloserTime()); } private String getCloserTime(){ Calendar cpcalendar = new GregorianCalendar(); long nowTime=cpcalendar.getTimeInMillis(); cpcalendar.add(Calendar.DAY_OF_MONTH,1); cpcalendar.set(Calendar.HOUR_OF_DAY, 0); cpcalendar.set(Calendar.MINUTE, 0); cpcalendar.set(Calendar.SECOND, 0); long targetTime=cpcalendar.getTimeInMillis(); int expireTime=(int) ((targetTime-nowTime)/1000); int hours = expireTime/3600; int minute = (expireTime%3600)/60; String closeTime = String.valueOf(hours)+"小时"+String.valueOf(minute)+"分"; return closeTime; } public ItemManager getItemManager() { return itemManager; } public void setItemManager(ItemManager itemManager) { this.itemManager = itemManager; } public TopItemManager getTopItemManager() { return topItemManager; } public void setTopItemManager(TopItemManager topItemManager) { this.topItemManager = topItemManager; } public ItemCompareManager getItemCompareManager() { return itemCompareManager; } public void setItemCompareManager(ItemCompareManager itemCompareManager) { this.itemCompareManager = itemCompareManager; } private void synTemplete(){ Process process=null; try { process = Runtime.getRuntime().exec("/home/admin/script/syntemplete.sh"); process.waitFor(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if (process != null) { process.destroy(); } } private void checkData(){ //itemOnlineInfoChecker.process(); } }
Java
package com.hundred.user.dao; import com.hundred.user.dao.dataobject.AppUserDO; /** * * @author hengheng * */ public interface UserDAO { /** * Get user info by UserID * @param userId * @return */ public AppUserDO getAppUserByUserId(String userId); /** * * @param appUserDO * @return */ public boolean updateUserInfo(AppUserDO appUserDO); public boolean insertUser(AppUserDO appUserDO); }
Java
package com.hundred.user.dao.impl; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.user.dao.UserDAO; import com.hundred.user.dao.dataobject.AppUserDO; public class UserDAOImpl extends SqlMapClientDaoSupport implements UserDAO { public AppUserDO getAppUserByUserId(String userId) { return (AppUserDO) this.getSqlMapClientTemplate().queryForObject("AppUser.querySingleAppUserById",userId); } public boolean updateUserInfo(AppUserDO appUserDO) { return this.getSqlMapClientTemplate().update("AppUser.updateUser", appUserDO)>0; } public boolean insertUser(AppUserDO appUserDO) { this.getSqlMapClientTemplate().insert("AppUser.insertUser", appUserDO); return true; } }
Java
package com.hundred.user.dao.dataobject; import java.util.Date; public class AppUserDO { private String userId; private int appId; private String appName; private String userNick; private long points; private String lastLoginIp; private String password; private int status; private int loginStatus; private Date lastLoginTime; private Date gmtCreate; private Date gmtModified; private String headPic; public int getAppId() { return appId; } public void setAppId(int appId) { this.appId = appId; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getUserNick() { return userNick; } public void setUserNick(String userNick) { this.userNick = userNick; } public long getPoints() { return points; } public void setPoints(long points) { this.points = points; } public String getLastLoginIp() { return lastLoginIp; } public void setLastLoginIp(String lastLoginIp) { this.lastLoginIp = lastLoginIp; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getLastLoginTime() { return lastLoginTime; } public void setLastLoginTime(Date lastLoginTime) { this.lastLoginTime = lastLoginTime; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public int getLoginStatus() { return loginStatus; } public void setLoginStatus(int loginStatus) { this.loginStatus = loginStatus; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getHeadPic() { return headPic; } public void setHeadPic(String headPic) { this.headPic = headPic; } }
Java
package com.hundred.user.manager.impl; import java.util.HashMap; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.hundred.home.module.screen.Index; import com.hundred.user.dao.UserDAO; import com.hundred.user.dao.dataobject.AppUserDO; import com.hundred.user.manager.UserManager; import com.qq.open.ErrorCode; import com.qq.open.OpenApiV3; import com.qq.open.OpensnsException; public class UserManagerImpl implements UserManager{ private static final Logger logger = LoggerFactory.getLogger(UserManagerImpl.class); @Autowired private UserDAO userDAO; public AppUserDO getAppUserByUserId(String userId) { return userDAO.getAppUserByUserId(userId); } public boolean updateUserInfo(AppUserDO appUserDO) { return userDAO.updateUserInfo(appUserDO); } public UserDAO getUserDAO() { return userDAO; } public void setUserDAO(UserDAO userDAO) { this.userDAO = userDAO; } public AppUserDO getAppUser4Open(String openId,String openKey) { AppUserDO curUser = this.getAppUserByUserId(openId); if(curUser==null){ AppUserDO appUserDO = new AppUserDO(); appUserDO.setUserId(openId); appUserDO.setUserNick(""); appUserDO.setLastLoginIp("a:1_0;b:1_0;c:1_0;d:1_0;e:1_0"); this.userDAO.insertUser(appUserDO); } String userInterface = "/v3/user/get_info"; AppUserDO userDO = new AppUserDO(); userDO.setLastLoginIp(curUser.getLastLoginIp()); userDO.setUserId(openId); HashMap<String,String> params = new HashMap<String,String>(); params.put("openid", openId); params.put("openkey", openKey); params.put("appid", String.valueOf(100678863)); params.put("pf", "qzone"); OpenApiV3 openApi = new OpenApiV3(String.valueOf(100678863), String.valueOf("3d7842f9c6b39977bf4e9526f881d1ba")); openApi.setServerName("119.147.19.43"); try { String reqStr = openApi.api(userInterface, params, "http"); logger.error(reqStr); JSONObject jo = new JSONObject(reqStr); userDO.setHeadPic((String)(jo.get("figureurl"))); userDO.setUserNick((String)(jo.get("nickname"))); logger.error(userDO.getUserNick()); logger.error(userDO.getHeadPic()); } catch (Exception e) { logger.error(e.toString()); } return userDO; } }
Java
package com.hundred.user.manager; import com.hundred.user.dao.dataobject.AppUserDO; public interface UserManager { /** * Get user info by UserID * @param userId * @return */ public AppUserDO getAppUserByUserId(String userId); /** * * @param appUserDO * @return */ public boolean updateUserInfo(AppUserDO appUserDO); public AppUserDO getAppUser4Open(String openId,String openKey); }
Java
package com.hundred.data.spider; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; //import org.apache.commons.httpclient.HttpClient; //import org.apache.commons.httpclient.HttpException; //import org.apache.commons.httpclient.HttpMethod; //import org.apache.commons.httpclient.methods.GetMethod; public class DataSpiderService { // public static void main(String args[]){ // // long beginTime = System.currentTimeMillis(); // // //////////////////////////////// // // FileOutputStream outSTr = null; // BufferedOutputStream Buff = null; // try { // outSTr = new FileOutputStream(new File("D:/gkresult.txt")); // Buff = new BufferedOutputStream(outSTr); // // ///***************** // // int number = 1100; // // while(number<43252){ // // String numberStr = String.valueOf(number); // // HttpClient client = new HttpClient(); // // HttpMethod method=new GetMethod("http://i.guoku.com/present/"+numberStr+"/"); // // try { // client.executeMethod(method); // } catch (HttpException e) { // // TODO Auto-generated catch block // //e.printStackTrace(); // } catch (IOException e) { // //e.printStackTrace(); // } // // //打印服务器返回的状态 // //System.out.println(method.getStatusLine()); // //打印返回的信息 // String content = method.getResponseBodyAsString(); // //System.out.println(content); // //释放连接 // method.releaseConnection(); // ContentAbstract contentAbstract = new ContentAbstract(content); // // Map<String,String> resultMap = contentAbstract.process(); // // if(resultMap.size()>0){ // System.out.print(number); // System.out.print("\t"); // //Buff.write(number); // //Buff.write("\t".getBytes()); // for(String key:resultMap.keySet()){ // System.out.print(resultMap.get(key)); // System.out.print("\t"); // Buff.write(resultMap.get(key).getBytes()); // Buff.write("\t".getBytes()); // } // System.out.println(""); // Buff.write("\n".getBytes()); // } // number++; // } // long endTime = System.currentTimeMillis(); // System.out.println(endTime-beginTime); // // //****************** // Buff.flush(); // Buff.close(); // // } catch (Exception e) { // e.printStackTrace(); // } finally { // try { // Buff.close(); // outSTr.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // /////////////////////////////// // // // } }
Java
package com.hundred.data.spider; import java.util.HashMap; import java.util.Map; public class ContentAbstract { private String content; public ContentAbstract(String content){ this.content = content; } public Map<String,String> process(){ boolean isWant=false; if(this.content!=null && this.content.length()>0){ Map<String,String> result = new HashMap<String,String>(); int titleIndex = content.indexOf("class=\"context\">"); int titleIndexEnd = content.indexOf("</div>",titleIndex+1); if(titleIndex>0 && titleIndexEnd>0){ result.put("title",content.substring(titleIndex+16, titleIndexEnd)); } int priceIndex = content.indexOf("present-price"); int priceIndexEnd = content.indexOf("</div>", priceIndex+1); if(priceIndex>0 && priceIndexEnd>0){ result.put("price", content.substring(priceIndex+16, priceIndexEnd)); } int itemIndex = content.indexOf("http://item.taobao.com/item.htm"); int itemIndexEnd = content.indexOf("\"",itemIndex+1); if(itemIndex>0 && itemIndexEnd >0){ result.put("itemUrl", content.substring(itemIndex, itemIndexEnd)); } else{ int nitemIndex = content.indexOf("http://s.click.taobao.com"); int nitemIndexEnd = content.indexOf("\"",nitemIndex+1); if(nitemIndex>0 && nitemIndexEnd >0){ result.put("itemUrl", content.substring(nitemIndex, nitemIndexEnd)); } } int picIndex = content.indexOf("http://img"); int picIndexEnd = content.indexOf("\"",picIndex+1); if(picIndex>0 && picIndexEnd>0){ result.put("itemPic", content.substring(picIndex, picIndexEnd)); } if(result!=null && result.containsKey("price")){ String priceStr = result.get("price"); System.out.println(priceStr); double priceDouble = Double.parseDouble(priceStr); if(priceDouble>50 && priceDouble<=105){ isWant = true; } } if(!isWant){ return new HashMap<String ,String>(); } return result; } return new HashMap<String ,String>(); } }
Java
package com.hundred.data.check; import java.io.IOException; import java.util.List; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.hundred.item.dao.ItemDao; import com.hundred.item.dao.dataobject.ItemDO; public class ItemOnlineInfoChecker { private static final Logger logger = LoggerFactory.getLogger(ItemOnlineInfoChecker.class); @Autowired private ItemDao itemDao; public void process(){ List<ItemDO> itemList = itemDao.getInitCacheItems(0); for(ItemDO itemDO:itemList){ String itemUrl = itemDO.getItemUrl(); logger.error("Processing URL:"+itemUrl); HttpClient client = new HttpClient(); HttpMethod method=new GetMethod(itemUrl); try { client.executeMethod(method); } catch (HttpException e) { // TODO Auto-generated catch block //e.printStackTrace(); } catch (IOException e) { //e.printStackTrace(); } //打印服务器返回的状态 //System.out.println(method.getStatusLine()); //打印返回的信息 String content=null; try { Thread.sleep(1000); content = method.getResponseBodyAsString(); if(content!=null && content.indexOf("此宝贝已下架")>-1){ logger.error("宝贝已下架:"+itemUrl); itemDO.setItemStatus(2); itemDao.updateItem(itemDO); } if(content!=null && content.indexOf("此商品已下架")>-1){ logger.error("宝贝已下架:"+itemUrl); itemDO.setItemStatus(2); itemDao.updateItem(itemDO); } if(content!=null && content.indexOf("可能已下架或者被转移")>-1){ logger.error("宝贝可能已下架或者被转移:"+itemUrl); itemDO.setItemStatus(2); itemDao.updateItem(itemDO); } } catch (Exception e) { logger.error(e.toString()); } } } public ItemDao getItemDao() { return itemDao; } public void setItemDao(ItemDao itemDao) { this.itemDao = itemDao; } }
Java
package com.hundred.data.transfer; import java.io.File; import java.util.List; import com.hundred.item.dao.dataobject.ItemDO; public interface TransferOutDataToStdItems { public List<ItemDO> transferFileToStdItems(File file); }
Java
package com.hundred.time.job; public class ItemSpiderJob { // // public static final String FILE = "/home/admin/dataflag.txt"; // // private static final Logger logger = LoggerFactory.getLogger(ItemSpiderJob.class); // // public void spideData(){ // // long beginTime = System.currentTimeMillis(); // FileOutputStream outSTr = null; // BufferedOutputStream Buff = null; // try { // outSTr = new FileOutputStream(new File("D:/data_result.txt")); // Buff = new BufferedOutputStream(outSTr); // long number = getDataStartFlag(); // setDataStartFlag(number+200); // while(number<number+200){ // String numberStr = String.valueOf(number); // HttpClient client = new HttpClient(); // HttpMethod method=new GetMethod("http://i.guoku.com/present/"+numberStr+"/"); // try { // client.executeMethod(method); // }catch (Exception e) { // } // String content = method.getResponseBodyAsString(); // method.releaseConnection(); // ContentAbstract contentAbstract = new ContentAbstract(content); // Map<String,String> resultMap = contentAbstract.process(); // if(resultMap.size()>0){ // System.out.print(number); // System.out.print("\t"); // //Buff.write(number); // //Buff.write("\t".getBytes()); // for(String key:resultMap.keySet()){ // System.out.print(resultMap.get(key)); // System.out.print("\t"); // Buff.write(resultMap.get(key).getBytes()); // Buff.write("\t".getBytes()); // } // logger.error(""); // Buff.write("\n".getBytes()); // } // number++; // } // long endTime = System.currentTimeMillis(); // logger.error((endTime-beginTime)+""); // Buff.flush(); // Buff.close(); // } catch (Exception e) { // e.printStackTrace(); // } finally { // try { // Buff.close(); // outSTr.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // // private long getDataStartFlag(){ // File file = new File(FILE); // if(! file.exists()) { // return 0; // } // FileReader fr = null; // BufferedReader buf = null; // try { // fr = new FileReader(FILE); // buf = new BufferedReader(fr); // String line; // while((line = buf.readLine()) != null) { // if(line!=null && line.length()>1 && line.indexOf("start-line")>-1){ // String[] value = line.trim().split("="); // String name = value[0].trim(); // String start = value[1].trim(); // if(name.equalsIgnoreCase("start-line")){ // return Long.parseLong(start); // } // } // } // } catch (IOException e) { // } finally { // try { // buf.close(); // fr.close(); // } catch (IOException e) { // } // } // return 0L; // } // // private void setDataStartFlag(long number){ // FileOutputStream outStr = null; // try { // outStr = new FileOutputStream(new File(FILE)); // outStr.write(("start-line" + "=" + number + "\n").getBytes()); // } catch (Exception e) { // } finally { // try { // outStr.close(); // } catch (IOException e) { // } // } // } // }
Java
package com.hundred.category.dao; import java.sql.SQLException; import java.util.List; import com.hundred.category.dao.dataobject.CategoryDo; public interface CategoryDao { int insertCategory(CategoryDo cateDo) throws SQLException; int updateCategory(CategoryDo cateDo) throws SQLException; List<CategoryDo> queryAllEnableCategoryByParentId(Long cParentid) throws SQLException; CategoryDo queryCategoryById(Long cateId) throws SQLException; List<CategoryDo> queryAllEnableCategory() throws SQLException; }
Java
package com.hundred.category.dao.impl; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.hundred.category.dao.CategoryDao; import com.hundred.category.dao.dataobject.CategoryDo; public class CategoryDaoImpl extends SqlMapClientDaoSupport implements CategoryDao { public int insertCategory(CategoryDo cateDo) throws SQLException { return getSqlMapClient().update("Category.insertCategory",cateDo); } public int updateCategory(CategoryDo cateDo) throws SQLException { return getSqlMapClient().update("Category.updateCategory",cateDo); } @SuppressWarnings("unchecked") public List<CategoryDo> queryAllEnableCategoryByParentId(Long cParentid) throws SQLException { Map<String,Long> param = new HashMap<String, Long>(); param.put("cParentid", cParentid); return getSqlMapClient().queryForList("Category.queryAllEnableCategoryByParentId",param); } @SuppressWarnings("unchecked") public List<CategoryDo> queryAllEnableCategory() throws SQLException { return getSqlMapClient().queryForList("Category.queryAllEnableCategory"); } public CategoryDo queryCategoryById(Long cateId) throws SQLException { return (CategoryDo) getSqlMapClient().queryForObject("Category.queryCategoryById",cateId); } }
Java
package com.hundred.category.dao.dataobject; import java.util.Date; /** * 类目 * @author Administrator */ public class CategoryDo { private Long cId; private String cName; /** * 类目编号 */ private String cCode; /** * 类目顺序 */ private Integer cSeq; private Long cParentid; /** * 1为可用 0为不可用 */ private Integer cStatus; private String cNotes; private Date gmtCreate; private Date gmtModified; public Long getcId() { return cId; } public void setcId(Long cId) { this.cId = cId; } public String getcName() { return cName; } public void setcName(String cName) { this.cName = cName; } public String getcCode() { return cCode; } public void setcCode(String cCode) { this.cCode = cCode; } public Integer getcSeq() { return cSeq; } public void setcSeq(Integer cSeq) { this.cSeq = cSeq; } public Long getcParentid() { return cParentid; } public void setcParentid(Long cParentid) { this.cParentid = cParentid; } public Integer getcStatus() { return cStatus; } public void setcStatus(Integer cStatus) { this.cStatus = cStatus; } public String getcNotes() { return cNotes; } public void setcNotes(String cNotes) { this.cNotes = cNotes; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } @Override public String toString() { return "CategoryDo [cId=" + cId + ", cName=" + cName + ", cCode=" + cCode + ", cSeq=" + cSeq + ", cParentid=" + cParentid + ", cStatus=" + cStatus + ", cNotes=" + cNotes + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + "]"; } }
Java
package com.hundred.category.module.screen; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.hundred.category.dao.CategoryDao; import com.hundred.category.dao.dataobject.CategoryDo; /** * 类目列表JSON * * @author Administrator */ public class Catelistjson { private static final Logger log = LoggerFactory.getLogger(Catelistjson.class); private CategoryDao categoryDao; @Autowired private HttpServletRequest request; @Autowired private HttpServletResponse response; public void execute() { response.addHeader("Cache-Control", "no-cache"); response.setContentType("application/json"); String parentIdStr = request.getParameter("id"); try { List<CategoryDo> pCate = categoryDao.queryAllEnableCategoryByParentId(Long.valueOf(parentIdStr)); ObjectMapper mapper = new ObjectMapper(); PrintWriter pw = response.getWriter(); mapper.writeValue(pw, pCate); pw.flush(); pw.close(); } catch (Exception e) { log.error("Catelistjson error . parentIdStr=" + parentIdStr, e); } return; } }
Java
package com.hundred.category.module.vo; import com.hundred.category.dao.dataobject.CategoryDo; public class CategoryVo extends CategoryDo{ private String parentCateName; public String getParentCateName() { return parentCateName; } public void setParentCateName(String parentCateName) { this.parentCateName = parentCateName; } }
Java
package com.hundred.comment.dao; import java.util.List; import com.hundred.comment.dao.dataobject.AppCommentDO; public interface AppCommentDAO { /** * GET Comment by tagId * @param tagId * @return */ public List<AppCommentDO> getAppCommentList(int tagId); /** * Modified App comment info * @param appCommentDO * @return */ public boolean updateCommentInfo(AppCommentDO appCommentDO); /** * * @param id * @return */ public AppCommentDO getAppCommentByCommentId(long id); }
Java
package com.hundred.comment.dao.impl; import java.util.List; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.hundred.comment.dao.AppCommentDAO; import com.hundred.comment.dao.dataobject.AppCommentDO; import com.hundred.item.dao.dataobject.AppItemDO; public class AppCommentDAOImpl extends SqlMapClientDaoSupport implements AppCommentDAO{ public List<AppCommentDO> getAppCommentList(int tagId) { @SuppressWarnings("unchecked") List<AppCommentDO> commentList = this.getSqlMapClientTemplate().queryForList("AppComment.queryAppCommentsByTagId", (long)(tagId)); return commentList; } public boolean updateCommentInfo(AppCommentDO appCommentDO) { // TODO Auto-generated method stub return false; } public AppCommentDO getAppCommentByCommentId(long id) { return (AppCommentDO) this.getSqlMapClientTemplate().queryForObject("AppComment.queryAppCommentsById",id); } }
Java
package com.hundred.comment.dao.dataobject; import java.util.Date; public class AppCommentDO { private long commentId; private String commentContent; private int status; private int tagId; private Date gmtCreate; private Date gmtModified; public long getCommentId() { return commentId; } public void setCommentId(long commentId) { this.commentId = commentId; } public String getCommentContent() { return commentContent; } public void setCommentContent(String commentContent) { this.commentContent = commentContent; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getTagId() { return tagId; } public void setTagId(int tagId) { this.tagId = tagId; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } }
Java
package com.hundred.comment.manager; import java.util.List; import com.hundred.comment.dao.dataobject.AppCommentDO; public interface CommentManager { /** * GET Comment by tagId * @param tagId * @return */ public List<AppCommentDO> getAppCommentList(int tagId); /** * Modified App comment info * @param appCommentDO * @return */ public boolean updateCommentInfo(AppCommentDO appCommentDO); /** * * @param id * @return */ public AppCommentDO getAppCommentByCommentId(long id); }
Java
package com.hundred.comment.manager.impl; import java.util.List; import com.hundred.comment.dao.AppCommentDAO; import com.hundred.comment.dao.dataobject.AppCommentDO; import com.hundred.comment.manager.CommentManager; public class CommentManagerImpl implements CommentManager { private AppCommentDAO appCommentDAO; public List<AppCommentDO> getAppCommentList(int tagId) { return appCommentDAO.getAppCommentList(tagId); } public boolean updateCommentInfo(AppCommentDO appCommentDO) { return appCommentDAO.updateCommentInfo(appCommentDO); } public AppCommentDAO getAppCommentDAO() { return appCommentDAO; } public void setAppCommentDAO(AppCommentDAO appCommentDAO) { this.appCommentDAO = appCommentDAO; } public AppCommentDO getAppCommentByCommentId(long id) { return appCommentDAO.getAppCommentByCommentId(id); } }
Java
package com.hundred.permission.exceptions; public class DepartmentErrorException extends RuntimeException { private static final long serialVersionUID = 2777316889341195168L; public DepartmentErrorException(String msg) { super(msg); } public DepartmentErrorException(String msg, Throwable cause) { super(msg, cause); } public DepartmentErrorException(Throwable cause) { super(cause); } }
Java
package com.hundred.permission.exceptions; public class RoleEditException extends RuntimeException { private static final long serialVersionUID = -2984110404350162539L; public RoleEditException(String msg) { super(msg); } public RoleEditException(String msg, Throwable cause) { super(msg, cause); } public RoleEditException(Throwable cause) { super(cause); } }
Java
package com.hundred.permission.dao.dataobject; import java.util.Date; public class FunctionDO { /** * 数据id */ private long id; /** * 功能编号 */ private String functionId; /** * 功能信息 */ private String functionInfo; /** * 可操作角色列表 */ private String roleList; /** * 备注 */ private String note; /** * 状态:0正常1不可用 */ private int status; private Date gmtCreate; private Date gmtModified; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getFunctionId() { return functionId; } public void setFunctionId(String functionId) { this.functionId = functionId; } public String getFunctionInfo() { return functionInfo; } public void setFunctionInfo(String functionInfo) { this.functionInfo = functionInfo; } public String getRoleList() { return roleList; } public void setRoleList(String roleList) { this.roleList = roleList; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } }
Java
package com.hundred.permission.dao.dataobject; import java.util.Date; import org.apache.commons.lang.StringEscapeUtils; public class UserDO { /** * 用户id */ private Long userId; /** * 用户名 */ private String userName; /** * 真名 */ private String realName; /** * 密码 */ private String password; /** * 移动电话 */ private String mobilePhone; /** * 固定电话 */ private String telephone ; /** * E-mail */ private String eMail; /** * 部门 */ private String department; /** * 部门id */ private long departmentId; /** * 所属组 */ private String groupName; /** * 所属组id */ private long groupId; /** * 角色id列表 */ private String roleIdList; /** * 角色名列表 */ private String roleNameList; /** * 备注 */ private String note; /** * 状态:0正常1不可用 */ private int status; private Date gmtCreate; private Date gmtModified; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUserName() { return userName; } public String getUserNameForJs() { return StringEscapeUtils.escapeJavaScript(userName); } public void setUserName(String userName) { this.userName = userName; } public String getRealName() { return realName; } public String getRealNameForJs() { return StringEscapeUtils.escapeJavaScript(realName); } public void setRealName(String realName) { this.realName = realName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getMobilePhone() { return mobilePhone; } public String getMobilePhoneForJs() { return StringEscapeUtils.escapeJavaScript(mobilePhone); } public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } public String getTelephone() { return telephone; } public String getTelephoneForJs() { return StringEscapeUtils.escapeJavaScript(telephone); } public void setTelephone(String telephone) { this.telephone = telephone; } public String geteMail() { return eMail; } public void seteMail(String eMail) { this.eMail = eMail; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public long getDepartmentId() { return departmentId; } public void setDepartmentId(long departmentId) { this.departmentId = departmentId; } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } public long getGroupId() { return groupId; } public void setGroupId(long groupId) { this.groupId = groupId; } public String getRoleIdList() { return roleIdList; } public void setRoleIdList(String roleIdList) { this.roleIdList = roleIdList; } public String getRoleNameList() { return roleNameList; } public void setRoleNameList(String roleNameList) { this.roleNameList = roleNameList; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } }
Java
package com.hundred.permission.dao.dataobject; import java.util.Date; public class TargetDO { /** * 数据id */ private long id; /** * 目标编号 */ private String targetId; /** * 目标信息 */ private String targetInfo; /** * 可访问角色列表 */ private String roleList; /** * 备注 */ private String note; /** * 状态:0正常1不可用 */ private int status; private Date gmtCreate; private Date gmtModified; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTargetId() { return targetId; } public void setTargetId(String targetId) { this.targetId = targetId; } public String getTargetInfo() { return targetInfo; } public void setTargetInfo(String targetInfo) { this.targetInfo = targetInfo; } public String getRoleList() { return roleList; } public void setRoleList(String roleList) { this.roleList = roleList; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } }
Java
package com.hundred.permission.dao.dataobject; import java.util.Date; public class DepartmentDO { /** * 部门id */ private long departmentId; /** * 部门名 */ private String departmentName; /** * 上级部门id */ private long superiorDepartmentId; /** * 上级部门名 */ private String superiorDepartmentName; /** * 部门基础角色id列表 */ private String roleList; private String roleNameList; /** * 备注 */ private String note; /** * 状态:0正常1不可用 */ private int status; private Date gmtCreate; private Date gmtModified; public long getDepartmentId() { return departmentId; } public void setDepartmentId(long departmentId) { this.departmentId = departmentId; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public long getSuperiorDepartmentId() { return superiorDepartmentId; } public void setSuperiorDepartmentId(long superiorDepartmentId) { this.superiorDepartmentId = superiorDepartmentId; } public String getSuperiorDepartmentName() { return superiorDepartmentName; } public void setSuperiorDepartmentName(String superiorDepartmentName) { this.superiorDepartmentName = superiorDepartmentName; } public String getRoleList() { return roleList; } public void setRoleList(String roleList) { this.roleList = roleList; } public String getRoleNameList() { return roleNameList; } public void setRoleNameList(String roleNameList) { this.roleNameList = roleNameList; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } }
Java
package com.hundred.permission.dao.dataobject; import java.util.Date; public class RoleDO { /** * 角色id */ private long roleId; /** * 角色名 */ private String roleName; /** * 该角色能访问的页面列表 */ private String targetList; /** * 该角色能访问的页面列表 */ private String targetNameList; /** * 该角色能操作的功能列表 */ private String functionList; /** * 该角色能操作的功能列表 */ private String functionNameList; /** * 备注 */ private String note; /** * 状态:0正常1不可用 */ private int status; private Date gmtCreate; private Date gmtModified; public long getRoleId() { return roleId; } public void setRoleId(long roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getTargetList() { return targetList; } public void setTargetList(String targetList) { this.targetList = targetList; } public String getFunctionList() { return functionList; } public void setFunctionList(String functionList) { this.functionList = functionList; } public String getTargetNameList() { return targetNameList; } public void setTargetNameList(String targetNameList) { this.targetNameList = targetNameList; } public String getFunctionNameList() { return functionNameList; } public void setFunctionNameList(String functionNameList) { this.functionNameList = functionNameList; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } }
Java
package com.hundred.permission.module.screen; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.turbine.Context; import com.alibaba.citrus.turbine.Navigator; public class UserInfoProcess { private static final Logger logger = LoggerFactory.getLogger(UserInfoProcess.class); @Autowired private HttpServletRequest request; public void execute(Context context, Navigator nav) { } }
Java
package com.hundred.permission.module.screen; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.turbine.Context; import com.alibaba.citrus.turbine.Navigator; public class CorpLoginProcess { @Autowired private HttpServletRequest request; private static final Logger logger = LoggerFactory.getLogger(CorpLoginProcess.class); private static final String qqOpenApiUrl = "https://graph.qq.com/oauth2.0/authorize?" + "response_type=code" + "&client_id=" +"100312390" + "&redirect_uri=" +"100msm.com/permission/userInfoProcess.htm"; public void execute(Context context, Navigator nav) { nav.redirectToLocation(qqOpenApiUrl); } }
Java
package com.hundred.permission.module.vo; import com.hundred.permission.dao.dataobject.UserDO; /** */ public class UserVO extends UserDO { }
Java
package com.hundred.permission.util; public class PagePermissionUtil { }
Java
package com.hundred.common.exception; public class ManagerException extends Exception { private static final long serialVersionUID = -8582786964348665874L; /** * 构造函数 * @param c */ public ManagerException(String c) { super(c); } /** * 构造函数 * @param c * @param t */ public ManagerException(String c, Throwable t) { super(c, t); } /** * 构造函数 * @param t */ public ManagerException(Throwable t) { super(t); } }
Java
package com.hundred.common; import static org.apache.commons.lang.StringUtils.defaultIfEmpty; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.apache.commons.lang.StringUtils.trim; import com.alibaba.citrus.service.form.Field; import com.alibaba.citrus.service.form.Group; public class GroupUtils{ private final Group group; public GroupUtils(Group group) { this.group = group; } public void setMessage(String fieldName, String msgId) { Field field = group.getField(fieldName); if (field != null) { field.setMessage(msgId); } } public void setValue(String fieldName, String val) { Field field = group.getField(fieldName); if (field != null) { field.setValue(val == null ? "" : val); } } public void setObjectValue(String fieldName, Object val) { Field field = group.getField(fieldName); if (field != null) { field.setValue(val); } } public String getDisplayName(String fieldName) { Field field = group.getField(fieldName); if (field == null) { return ""; } return group.getField(fieldName).getDisplayName(); } public String getString(String fieldName) { Field field = group.getField(fieldName); if (field == null) { return ""; } return defaultIfEmpty(trim(field.getStringValue()), ""); } public String getString(String fieldName, String defaultVal) { checkState(isNotBlank(defaultVal)); Field field = group.getField(fieldName); if (field == null) { return defaultVal; } return defaultIfEmpty(trim(field.getStringValue(defaultVal)), ""); } public long getLong(String fieldName) { Field field = group.getField(fieldName); if (field == null) { return 0; } return field.getLongValue(); } public long getLong(String fieldName, long defaultVal) { Field field = group.getField(fieldName); if (field == null) { return defaultVal; } return field.getLongValue(defaultVal); } public int getInt(String fieldName) { Field field = group.getField(fieldName); if (field == null) { return 0; } return field.getIntegerValue(); } public int getInt(String fieldName, int defaultVal) { Field field = group.getField(fieldName); if (field == null) { return defaultVal; } return field.getIntegerValue(defaultVal); } public Group getGroup() { return group; } public boolean isValidated() { return group.isValidated(); } private void checkState(boolean expr) { if (!expr) { throw new IllegalStateException(); } } }
Java
package com.hundred.common; import java.io.Serializable; public class Result<T> implements Serializable{ private static final long serialVersionUID = -5592371478635944394L; private boolean success = false; // 执行是否成功 private String resultCode; protected String errorMassage; private T module; // 实际的返回结果 public Result() { } public Result(T module) { this.module = module; } public static <T> Result<T> getResult(){ return new Result<T>(); } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getResultCode() { return resultCode; } public void setResultCode(String resultCode) { this.resultCode = resultCode; } public String getErrorMassage() { return errorMassage; } public void setErrorMassage(String errorMassage) { this.errorMassage = errorMassage; } public T getModule() { return module; } public void setModule(T module) { this.module = module; } }
Java
package com.hundred.common; import java.io.File; public class WebConstant { /** 在session中保存用户对象的key。 */ public static String SYS_USER_SESSION_KEY = "sysUser"; /** * 文件上传根目录 */ public static String FILE_UPLOAD_PATH = File.separator + "data" + File.separator + "pics"; /** * 产品图片文件夹 */ public static String ITEM_PIC_FOLDER = File.separator + "itempics"; /** * 文件分隔符 */ public static String ITEM_PIC_SEPARATOR = "|"; }
Java
package com.hundred.item.dao; import java.util.List; import com.hundred.item.dao.dataobject.AppItemDO; /** * APP Item DAO * @author hengheng * */ public interface AppItemDAO { /** * GET items by tag id * @param tagId * @return */ public List<AppItemDO> getAppItemByTagId(int tagId); /** * GET item by id * @param itemId * @return */ public AppItemDO getAppItemById(long itemId); public int updateAppItem(AppItemDO appItemDO); }
Java
package com.hundred.item.dao; import java.util.List; import com.hundred.item.dao.dataobject.ItemCompareDO; public interface ItemCompareDAO { /** * * @param itemCompareDO * @return */ public int insertCompareModel(ItemCompareDO itemCompareDO); /** * * @param itemCompareDO * @return */ public int updateCompareModel(ItemCompareDO itemCompareDO); /** * * @param id * @return */ public ItemCompareDO getCompareModelById(long id); /** * * @param userId * @return */ public List<ItemCompareDO> getCompareModelByUserId(long userId); /** * * @param winnerItemId * @return */ public List<ItemCompareDO> getCompareModelByWinnerItemId(long winnerItemId); /** * * @param winnerItemId * @param status * @return */ public List<ItemCompareDO> getCompareModelByWinnerItemIdAndStatus(long winnerItemId,int status); /** * * @param id * @return */ public int deleteCompareModelById(long id); /** * * @param userId * @return */ public int deleteCompareModelByUserId(long userId); }
Java
package com.hundred.item.dao; import java.util.List; import com.hundred.item.dao.dataobject.TopItemDO; public interface TopItemDAO { /** * * @param topItemDO * @return */ public long insertTopItem(TopItemDO topItemDO); /** * * @param limitNum * @return */ public List<TopItemDO> queryTopItemList(long limitNum); }
Java
package com.hundred.item.dao.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.hundred.item.dao.ItemCompareDAO; import com.hundred.item.dao.dataobject.ItemCompareDO; public class ItemCompareDAOImpl extends SqlMapClientDaoSupport implements ItemCompareDAO { public int insertCompareModel(ItemCompareDO itemCompareDO) { this.getSqlMapClientTemplate().insert("ItemCompareDAO.insertItemCompareRes", itemCompareDO); return 1; } public int updateCompareModel(ItemCompareDO itemCompareDO) { return this.getSqlMapClientTemplate().update("ItemCompareDAO.updateItemCompareModel", itemCompareDO); } public ItemCompareDO getCompareModelById(long id) { return (ItemCompareDO) this.getSqlMapClientTemplate().queryForObject("ItemCompareDAO.getItemCompareModelById",id); } public List<ItemCompareDO> getCompareModelByUserId(long userId) { List<ItemCompareDO> result = new ArrayList<ItemCompareDO>(); @SuppressWarnings("unchecked") List<ItemCompareDO> queryResult = this.getSqlMapClientTemplate().queryForList("ItemCompareDAO.selectUserCompareRes",userId); if(queryResult!=null && queryResult.size()>0){ result = queryResult; } return result; } public List<ItemCompareDO> getCompareModelByWinnerItemId(long winnerItemId) { List<ItemCompareDO> result = new ArrayList<ItemCompareDO>(); @SuppressWarnings("unchecked") List<ItemCompareDO> queryResult = this.getSqlMapClientTemplate().queryForList("ItemCompareDAO.getItemCompareModelByWinnerItemId",winnerItemId); if(queryResult!=null && queryResult.size()>0){ result = queryResult; } return result; } public List<ItemCompareDO> getCompareModelByWinnerItemIdAndStatus( long winnerItemId, int status) { Map<String, Long> parameterMap = new HashMap<String , Long>(); parameterMap.put("winnerItemId", winnerItemId); parameterMap.put("status", (long) status); List<ItemCompareDO> result = new ArrayList<ItemCompareDO>(); @SuppressWarnings("unchecked") List<ItemCompareDO> queryResult = this.getSqlMapClientTemplate().queryForList("ItemCompareDAO.getItemCompareModelByWinnerItemIdAndStatus",parameterMap); if(queryResult!=null && queryResult.size()>0){ result = queryResult; } return result; } public int deleteCompareModelById(long id) { return this.getSqlMapClientTemplate().update("ItemCompareDAO.deleteItemCompareModelById", id); } public int deleteCompareModelByUserId(long userId) { // TODO Auto-generated method stub return 0; } }
Java
package com.hundred.item.dao.impl; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.hundred.item.dao.ItemDao; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.item.dao.dataobject.ItemReqDO; import com.hundred.item.manager.impl.ItemManagerImpl; public class ItemDaoImpl extends SqlMapClientDaoSupport implements ItemDao { private static final Logger logger = LoggerFactory.getLogger(ItemDaoImpl.class); public long insertItem(ItemDO itemDo) throws SQLException { return (Long) this.getSqlMapClientTemplate().insert("Item.insertItem", itemDo); } public int updateItem(ItemDO itemDo) throws SQLException { return this.getSqlMapClientTemplate().update("Item.updateItem", itemDo); } public int deleteItem(long itemId) throws SQLException { ItemDO itemDo = new ItemDO(); itemDo.setItemId(itemId); itemDo.setItemStatus(0); return this.getSqlMapClientTemplate().update("Item.deleteItem", itemDo); } public ItemDO getItemById(ItemReqDO itemReq) { Map<String,Object> map = new HashMap<String,Object>(); map.put("itemId", itemReq.getItemId()); map.put("tagId", itemReq.getTagId()); logger.error("itemId:"+itemReq.getItemId()+"|"+"tagId:"+itemReq.getTagId()); return (ItemDO) this.getSqlMapClientTemplate().queryForObject("Item.querySingleItem",map); } public List<ItemDO> getTopItemsList(int status, long startRow, long endRow) { Map<String,Long> param = new HashMap<String,Long>(); param.put("status", (long)(status)); param.put("startRow", startRow); param.put("endRow", endRow); @SuppressWarnings("unchecked") List<ItemDO> topList = this.getSqlMapClientTemplate().queryForList("Item.getTopItemList", param); return topList; } public long countTotalOnlineItems(int status) { return (Long) this.getSqlMapClientTemplate().queryForObject("Item.countTotalOnlineItems",status); } public ItemDO getHistoryItemById(long itemId) { return (ItemDO) this.getSqlMapClientTemplate().queryForObject("Item.querySingleHistoryItem",itemId); } public List<ItemDO> getInitCacheItems(int status) { @SuppressWarnings("unchecked") List<ItemDO> itemList = this.getSqlMapClientTemplate().queryForList("Item.cacheInitItem", status); return itemList; } }
Java
package com.hundred.item.dao.impl; import java.util.List; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.hundred.item.dao.AppItemDAO; import com.hundred.item.dao.dataobject.AppItemDO; import com.hundred.item.dao.dataobject.ItemDO; public class AppItemDAOImpl extends SqlMapClientDaoSupport implements AppItemDAO { public List<AppItemDO> getAppItemByTagId(int tagId) { @SuppressWarnings("unchecked") List<AppItemDO> itemList = this.getSqlMapClientTemplate().queryForList("AppItem.queryAppItemByTagId", (long)(tagId)); return itemList; } public AppItemDO getAppItemById(long itemId) { return (AppItemDO) this.getSqlMapClientTemplate().queryForObject("Item.querySingleAppItem",itemId); } public int updateAppItem(AppItemDO appItemDO) { return this.getSqlMapClientTemplate().update("AppItem.updateAppItem", appItemDO); } }
Java
package com.hundred.item.dao.impl; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import com.hundred.item.dao.TopItemDAO; import com.hundred.item.dao.dataobject.TopItemDO; import com.hundred.item.manager.impl.TopItemManagerImpl; public class TopItemDAOImpl extends SqlMapClientDaoSupport implements TopItemDAO { private static final Logger logger = LoggerFactory.getLogger(TopItemDAOImpl.class); public long insertTopItem(TopItemDO topItemDO) { // TODO Auto-generated method stub return 0; } public List<TopItemDO> queryTopItemList(long limitNum) { @SuppressWarnings("unchecked") List<TopItemDO> topItems = this.getSqlMapClientTemplate().queryForList("TopItemDAO.selectTopItemList", limitNum); if(topItems!=null){ return topItems; } logger.error("Top-item-Null"); return new ArrayList<TopItemDO>(); } }
Java
package com.hundred.item.dao.dataobject; import java.util.Date; /** * 宝贝单元 * @author YUTONG * */ public class ItemDO { private long id; private long itemId; private String itemName; private String itemPic; private String itemUrl; private long itemPrice; private long userId; private long betterCount; private String itemQuantity; private int originId; private int itemStatus; private String attributes; private long categoryId; private String description; private Date gmtCreate; private Date gmtModified; private int tagId; private String priceStr; public long getItemId() { return itemId; } public void setItemId(long itemId) { this.itemId = itemId; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public String getItemPic() { return itemPic; } public void setItemPic(String itemPic) { this.itemPic = itemPic; } public long getItemPrice() { return itemPrice; } public void setItemPrice(long itemPrice) { this.itemPrice = itemPrice; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public long getBetterCount() { return betterCount; } public void setBetterCount(long betterCount) { this.betterCount = betterCount; } public String getItemQuantity() { return itemQuantity; } public void setItemQuantity(String itemQuantity) { this.itemQuantity = itemQuantity; } public int getOriginId() { return originId; } public void setOriginId(int originId) { this.originId = originId; } public int getItemStatus() { return itemStatus; } public void setItemStatus(int itemStatus) { this.itemStatus = itemStatus; } public long getCategoryId() { return categoryId; } public void setCategoryId(long categoryId) { this.categoryId = categoryId; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getAttributes() { return attributes; } public void setAttributes(String attributes) { this.attributes = attributes; } public String getItemUrl() { return itemUrl; } public void setItemUrl(String itemUrl) { this.itemUrl = itemUrl; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPriceStr() { return priceStr; } public void setPriceStr(String priceStr) { this.priceStr = priceStr; } public int getTagId() { return tagId; } public void setTagId(int tagId) { this.tagId = tagId; } }
Java
package com.hundred.item.dao.dataobject; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class AppItemDO { private long itemId; private String itemName; private String itemPic; private String itemUrl; private String itemDescription; private int tagId; private long itemPrice; private long likeNum; private long collectNum; private int status; private String attributes; private int appId; private String appName; private Date gmtCreate; private Map<String,String> commentUserIcons = new HashMap<String,String> (); private String priceStr; public long getItemId() { return itemId; } public void setItemId(long itemId) { this.itemId = itemId; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public String getItemPic() { return itemPic; } public void setItemPic(String itemPic) { this.itemPic = itemPic; } public String getItemUrl() { return itemUrl; } public void setItemUrl(String itemUrl) { this.itemUrl = itemUrl; } public String getItemDescription() { return itemDescription; } public void setItemDescription(String itemDescription) { this.itemDescription = itemDescription; } public int getTagId() { return tagId; } public void setTagId(int tagId) { this.tagId = tagId; } public long getItemPrice() { return itemPrice; } public void setItemPrice(long itemPrice) { this.itemPrice = itemPrice; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getAttributes() { return attributes; } public void setAttributes(String attributes) { this.attributes = attributes; } public int getAppId() { return appId; } public void setAppId(int appId) { this.appId = appId; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public long getLikeNum() { return likeNum; } public void setLikeNum(long likeNum) { this.likeNum = likeNum; } public long getCollectNum() { return collectNum; } public void setCollectNum(long collectNum) { this.collectNum = collectNum; } public Map<String,String> getCommentUserIcons() { return commentUserIcons; } public void setCommentUserIcons(Map<String,String> commentUserIcons) { this.commentUserIcons = commentUserIcons; } public String getPriceStr() { return priceStr; } public void setPriceStr(String priceStr) { this.priceStr = priceStr; } private Date gmtModified; }
Java
package com.hundred.item.dao.dataobject; public class ItemReqDO { private long itemId; private int status=0; private int tagId=0; public long getItemId() { return itemId; } public void setItemId(long itemId) { this.itemId = itemId; } public int getTagId() { return tagId; } public void setTagId(int tagId) { this.tagId = tagId; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } }
Java
package com.hundred.item.dao.dataobject; import java.util.Date; public class ItemCompareDO { private long id; private long userId; private long winnerItemId; private long loserItemId; private int status; private String ip; private Date gmtCreate; private Date gmtModified; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public long getWinnerItemId() { return winnerItemId; } public void setWinnerItemId(long winnerItemId) { this.winnerItemId = winnerItemId; } public long getLoserItemId() { return loserItemId; } public void setLoserItemId(long loserItemId) { this.loserItemId = loserItemId; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } }
Java
package com.hundred.item.dao.dataobject; import java.util.Date; public class TopItemDO { private long id; private long userId; private long itemId; private long finalScore; private int rank; private int phaseNo; private int status; private String xiaobianMessage; private Date startDate; private Date endDate; private Date gmtCreate; private Date gmtModified; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getItemId() { return itemId; } public void setItemId(long itemId) { this.itemId = itemId; } public long getFinalScore() { return finalScore; } public void setFinalScore(long finalScore) { this.finalScore = finalScore; } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } public int getPhaseNo() { return phaseNo; } public void setPhaseNo(int phaseNo) { this.phaseNo = phaseNo; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public String getXiaobianMessage() { return xiaobianMessage; } public void setXiaobianMessage(String xiaobianMessage) { this.xiaobianMessage = xiaobianMessage; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } }
Java
package com.hundred.item.dao; import java.sql.SQLException; import java.util.List; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.item.dao.dataobject.ItemReqDO; /** * ITEM-DAO * @author YUTONG * */ public interface ItemDao { /** * * @param itemDo * @throws SQLException */ public long insertItem(ItemDO itemDo) throws SQLException; /** * * @param itemDo * @return * @throws SQLException */ public int updateItem(ItemDO itemDo) throws SQLException; /** * * @param itemId * @return * @throws SQLException */ public int deleteItem(long itemId) throws SQLException; /** * * @param itemId * @return */ public ItemDO getItemById(ItemReqDO itemReq); /** * * @param itemId * @return */ public ItemDO getHistoryItemById(long itemId); /** * * @param status * @param startRow * @param endRow * @return */ public List<ItemDO> getTopItemsList(int status,long startRow,long endRow); /** * * @param status * @return */ public long countTotalOnlineItems(int status); public List<ItemDO> getInitCacheItems(int status); }
Java
package com.hundred.item.manager; import java.util.List; import com.hundred.item.dao.dataobject.ItemDO; public interface TopItemManager { /** * * @param number * @return */ public List<ItemDO> getTopItemList(long number); }
Java
package com.hundred.item.manager; import java.util.List; import com.hundred.item.dao.dataobject.AppItemDO; /** * * Manager For App Items. * * @author hengheng * */ public interface AppItemManager { public List<AppItemDO> getAppItemList(int tagId); public AppItemDO getAppItemById(long itemId); public boolean updateAppItemInfo(AppItemDO appItemDO); }
Java
package com.hundred.item.manager; import java.util.List; import com.hundred.item.dao.dataobject.ItemCompareDO; import com.hundred.item.dao.dataobject.ItemDO; public interface ItemCompareManager { /** * 增加用户比较的信息 * @param itemCompareDO * @return */ public boolean addNewItemCompareModel(ItemCompareDO itemCompareDO); /** * 查询单个用户的比较信息 * @param userId * @return */ public List<ItemCompareDO> selectSingleUserCompareResult(long userId); /** * * @param num * @return */ public List<ItemDO> selectCompareItems (int num,int tagId); }
Java
package com.hundred.item.manager; import java.sql.SQLException; import java.util.List; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.item.dao.dataobject.ItemReqDO; public interface ItemManager { boolean addItem(ItemDO itemVo) throws Exception; boolean deleteItem(ItemDO itemVo) throws Exception; /** * * @param itemDo * @throws SQLException */ public void insertItem(ItemDO itemDo) throws Exception; /** * * @param itemDo * @return * @throws SQLException */ public int updateItem(ItemDO itemDo) throws Exception; /** * * @param itemId * @return * @throws SQLException */ public int deleteItem(long itemId) throws Exception; /** * * @param itemId * @return */ public ItemDO getItemById(ItemReqDO itemReq); /** * * @param itemId * @return */ public ItemDO getHistoryItemById(long itemId); /** * * @return */ public long countTotalItemNumber(int status); /** * * @param status * @param startRow * @param endRow * @return */ public List<ItemDO> getTopItemList(int status,long startRow,long endRow); }
Java
package com.hundred.item.manager.impl; import java.util.List; import com.hundred.item.dao.AppItemDAO; import com.hundred.item.dao.dataobject.AppItemDO; import com.hundred.item.manager.AppItemManager; public class AppItemManagerImpl implements AppItemManager { private AppItemDAO appItemDAO; public List<AppItemDO> getAppItemList(int tagId) { List<AppItemDO> result = appItemDAO.getAppItemByTagId(tagId); if(result!=null){ for(AppItemDO itemDO :result){ setAppItemAdditionalStr(itemDO); } } return result; } public AppItemDO getAppItemById(long itemId) { return appItemDAO.getAppItemById(itemId); } public AppItemDAO getAppItemDAO() { return appItemDAO; } public void setAppItemDAO(AppItemDAO appItemDAO) { this.appItemDAO = appItemDAO; } public boolean updateAppItemInfo(AppItemDO appItemDO) { return appItemDAO.updateAppItem(appItemDO)>0; } private void setAppItemAdditionalStr(AppItemDO appItemDO){ long price = appItemDO.getItemPrice(); double priced = price/100.00; appItemDO.setPriceStr(String.format("%.2f", priced)); } }
Java
package com.hundred.item.manager.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.hundred.item.dao.ItemCompareDAO; import com.hundred.item.dao.ItemDao; import com.hundred.item.dao.dataobject.ItemCompareDO; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.item.dao.dataobject.ItemReqDO; import com.hundred.item.manager.ItemCompareManager; import com.hundred.item.manager.ItemManager; public class ItemCompareManagerImpl implements ItemCompareManager { private ItemCompareDAO itemCompareDAO; private ItemDao itemDao; @Autowired private ItemManager itemManager; private static final Logger logger = LoggerFactory.getLogger(ItemCompareManagerImpl.class); private Map<Integer, ArrayList<Long>> itemListMap = new HashMap <Integer,ArrayList<Long>>(); public boolean addNewItemCompareModel(ItemCompareDO itemCompareDO) { this.itemCompareDAO.insertCompareModel(itemCompareDO); return true; } public List<ItemCompareDO> selectSingleUserCompareResult(long userId) { return this.itemCompareDAO.getCompareModelByUserId(userId); } public ItemCompareDAO getItemCompareDAO() { return itemCompareDAO; } public void setItemCompareDAO(ItemCompareDAO itemCompareDAO) { this.itemCompareDAO = itemCompareDAO; } public void init(){ List<ItemDO> itemDOList = itemDao.getInitCacheItems(0); for(ItemDO itemDO:itemDOList){ if(itemListMap.get(itemDO.getTagId())==null){ ArrayList<Long> itemIdList= new ArrayList<Long> (); itemIdList.add(itemDO.getItemId()); itemListMap.put(itemDO.getTagId(), itemIdList); } else{ ArrayList<Long> itemIdList = itemListMap.get(itemDO.getTagId()); itemIdList.add(itemDO.getItemId()); itemListMap.put(itemDO.getTagId(), itemIdList); } } } public List<ItemDO> selectCompareItems(int num,int tagId) { int totalNum = itemListMap.get(tagId).size()-2; long item1 = itemListMap.get(tagId).get((int)(Math.random()*(totalNum))); long item2 = itemListMap.get(tagId).get((int)(Math.random()*(totalNum))); ItemReqDO itemReq= new ItemReqDO(); itemReq.setItemId(item1); itemReq.setTagId(tagId); ItemReqDO itemReq2= new ItemReqDO(); itemReq2.setItemId(item2); itemReq2.setTagId(tagId); ItemDO leftItem = itemManager.getItemById(itemReq); ItemDO rightItem = itemManager.getItemById(itemReq2); if(leftItem!=null && rightItem!=null){ List<ItemDO> itemList = new ArrayList<ItemDO>(); itemList.add(leftItem); itemList.add(rightItem); logger.error("Two-Item-Found"); return itemList; } itemReq.setItemId(12); leftItem = itemManager.getItemById(itemReq); itemReq2.setItemId(17); rightItem = itemManager.getItemById(itemReq2); if(leftItem!=null && rightItem!=null){ List<ItemDO> itemList = new ArrayList<ItemDO>(); itemList.add(leftItem); itemList.add(rightItem); logger.error("Two-Item-Found2"); return itemList; } logger.error("sorry!!!!!!!!!!!!"); return new ArrayList<ItemDO>(); } public ItemManager getItemManager() { return itemManager; } public void setItemManager(ItemManager itemManager) { this.itemManager = itemManager; } public ItemDao getItemDao() { return itemDao; } public void setItemDao(ItemDao itemDao) { this.itemDao = itemDao; } }
Java
package com.hundred.item.manager.impl; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hundred.item.dao.ItemDao; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.item.dao.dataobject.ItemReqDO; import com.hundred.item.manager.ItemManager; public class ItemManagerImpl implements ItemManager { private static final Logger log = LoggerFactory.getLogger(ItemManagerImpl.class); private ItemDao itemDao; private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); public boolean addItem(ItemDO itemVo) throws Exception {return true;} public boolean deleteItem(ItemDO itemVo) throws Exception { if(itemDao.deleteItem(itemVo.getItemId())>0){ return true; }else{ return false; } } public void setItemDao(ItemDao itemDao) { this.itemDao = itemDao; } public void insertItem(ItemDO itemDo) throws Exception { long itemId = itemDao.insertItem(itemDo); if(itemId<=0){ return; } itemDo.setItemId(itemId); this.updateItem(itemDo); } public int updateItem(ItemDO itemDo) throws Exception { return itemDao.updateItem(itemDo); } public int deleteItem(long itemId) throws Exception { // TODO Auto-generated method stub return 0; } public ItemDO getItemById(ItemReqDO itemReq) { ItemDO itemDO = itemDao.getItemById(itemReq); if(itemDO!=null){ titleProcess(itemDO); priceProcess(itemDO); itemUrlProcess(itemDO); } return itemDO; } public long countTotalItemNumber(int status) { return itemDao.countTotalOnlineItems(status); } public List<ItemDO> getTopItemList(int status, long startRow, long endRow) { List<ItemDO> listItems = itemDao.getTopItemsList(status, startRow, endRow); if(listItems!=null && listItems.size()>0){ for(ItemDO item:listItems){ titleProcess(item); priceProcess(item); itemUrlProcess(item); } } return listItems; } public ItemDO getHistoryItemById(long itemId) { ItemDO itemDO = itemDao.getHistoryItemById(itemId); if(itemDO!=null){ titleProcess(itemDO); priceProcess(itemDO); itemUrlProcess(itemDO); } return itemDO; } private void titleProcess(ItemDO itemDO){ if(itemDO!=null && itemDO.getItemName()!=null){ String[] titleStrArray = itemDO.getItemName().split("。"); String[] titleStrArray2 = itemDO.getItemName().split(","); if(titleStrArray.length>=1 && titleStrArray2.length>=1){ String oneStr = titleStrArray[0]; String twoStr = titleStrArray2[0]; String newTitle = oneStr.length()<=twoStr.length()?oneStr:twoStr; itemDO.setItemName(newTitle); } else if(titleStrArray.length>=1){ String newTitle = titleStrArray[0]; itemDO.setItemName(newTitle); } } } private void priceProcess(ItemDO itemDO){ if(itemDO.getItemPrice()>0){ BigDecimal bg = new BigDecimal((itemDO.getItemPrice())/100.00); double newprice = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); itemDO.setPriceStr(String.valueOf(newprice)); } } private void itemUrlProcess(ItemDO itemDO){ String ourTrackId="10037056"; String trackId = "&ali_trackid=2:mm_10037056_0_0:1353977147_4k2_691519382"; if(itemDO!=null && itemDO.getItemUrl()!=null){ String itemUrlTemp = itemDO.getItemUrl().replaceAll("amp;", ""); String finalItemUrl = itemUrlTemp; if(itemUrlTemp.indexOf("mm_")>-1){ int aliIndex = itemUrlTemp.indexOf("mm_"); finalItemUrl = itemUrlTemp.substring(0, aliIndex+3) +ourTrackId +itemUrlTemp.substring(itemUrlTemp.indexOf("_",aliIndex+4)); } else{ finalItemUrl=finalItemUrl+trackId; } itemDO.setItemUrl(finalItemUrl); log.error("item-url:"+itemUrlTemp); } if(itemDO!=null && itemDO.getItemPic()!=null){ log.error("URL-Prossesing----"+itemDO.getItemPic()); String itemPicStr = itemDO.getItemPic(); if(itemPicStr.indexOf("_310x310.jpg")>-1){ itemPicStr=itemPicStr.replaceAll("_310x310.jpg", ""); itemDO.setItemPic(itemPicStr); } } } public static void main(String args[]){ ItemManagerImpl dd= new ItemManagerImpl(); ItemDO item = new ItemDO(); item.setItemUrl("http://s.click.taobao.com/t_8?e=7HZ6jHSTZPhc3yRJRF%2Fa6cZZYIwKZaWVLo%2BoWLPHtjyxLKii7iwH8IooOwVdnXSY3e93m4dqYVta2Jfat%2F7Ik%2Ftw9LJB3xNNfl2ybcSjSgdJ3ac%3D&p=mm_28514026_0_0&n=19"); item.setItemUrl("http://item.taobao.com/item.htm?id=9892769239&ali_trackid=2:mm_28514026_0_0:1353944393_310_42855049"); dd.itemUrlProcess(item); System.out.println(item.getItemUrl()); } }
Java
package com.hundred.item.manager.impl; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hundred.home.module.screen.Index; import com.hundred.item.dao.TopItemDAO; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.item.dao.dataobject.TopItemDO; import com.hundred.item.manager.ItemManager; import com.hundred.item.manager.TopItemManager; public class TopItemManagerImpl implements TopItemManager { private static final Logger logger = LoggerFactory.getLogger(TopItemManagerImpl.class); private TopItemDAO topItemDAO; private ItemManager itemManager; public List<ItemDO> getTopItemList(long number) { List<TopItemDO> topItemList = this.topItemDAO.queryTopItemList(number); if(topItemList!=null && topItemList.size()>0){ List<ItemDO> resultList = new ArrayList<ItemDO> (); for(TopItemDO topItem:topItemList){ ItemDO itemDO = itemManager.getHistoryItemById(topItem.getItemId()); resultList.add(itemDO); } logger.error("(=@__@=)---->Top:"+resultList.size()); return resultList; } return new ArrayList<ItemDO> (); } public TopItemDAO getTopItemDAO() { return topItemDAO; } public void setTopItemDAO(TopItemDAO topItemDAO) { this.topItemDAO = topItemDAO; } public ItemManager getItemManager() { return itemManager; } public void setItemManager(ItemManager itemManager) { this.itemManager = itemManager; } }
Java
package com.hundred.item.module.screen; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.service.requestcontext.parser.ParameterParser; import com.alibaba.citrus.turbine.Context; import com.alibaba.citrus.turbine.Navigator; import com.alibaba.citrus.turbine.util.TurbineUtil; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.item.dao.dataobject.ItemReqDO; import com.hundred.item.manager.ItemManager; public class AysnProcessSelected { private static final Logger log = LoggerFactory.getLogger(AysnProcessSelected.class); @Autowired private HttpServletRequest request; @Autowired private ItemManager itemManager; public void execute(Context context, Navigator nav) { log.error("log-success!"); final ParameterParser rundata = TurbineUtil.getTurbineRunData(request).getParameters(); String winnerItemIdStr = rundata.getString("winnerItemId", "0"); String loserItemIdStr = rundata.getString("winnerItemId", "0"); if("0".equals(winnerItemIdStr)){ return; } long winnerItemId = Long.parseLong(winnerItemIdStr); long loserItemId = Long.parseLong(loserItemIdStr); ItemReqDO itemReq= new ItemReqDO(); itemReq.setItemId(winnerItemId); itemReq.setTagId(0); ItemDO winnerItem = itemManager.getItemById(itemReq); long betterCount = winnerItem.getBetterCount()+1; winnerItem.setBetterCount(betterCount); try { int result = itemManager.updateItem(winnerItem); if(result==0){ } } catch (Exception e) { } //这里加上商品比较的记录,winnerItemId和loserItemId } public ItemManager getItemManager() { return itemManager; } public void setItemManager(ItemManager itemManager) { this.itemManager = itemManager; } }
Java
package com.hundred.item.module.screen; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.hundred.common.WebConstant; public class Itempic { private static final Logger log = LoggerFactory.getLogger(Itempic.class); @Autowired private HttpServletRequest request; @Autowired private HttpServletResponse response; public void execute() { InputStream inputStream = null; OutputStream outputStream = null; try { String path = request.getParameter("p"); inputStream = new FileInputStream(new File(WebConstant.FILE_UPLOAD_PATH + path)); int i = inputStream.available(); byte data[] = new byte[i]; inputStream.read(data); inputStream.close(); response.setContentType("image/*"); outputStream = response.getOutputStream(); outputStream.write(data); outputStream.close(); } catch (Exception e) {// 错误处理 try { inputStream = new FileInputStream(new File(WebConstant.FILE_UPLOAD_PATH + WebConstant.ITEM_PIC_FOLDER + File.separator + "default.png")); int i = inputStream.available(); byte data[] = new byte[i]; inputStream.read(data); inputStream.close(); response.setContentType("image/*"); outputStream = response.getOutputStream(); outputStream.write(data); outputStream.close(); } catch (Exception e1) { log.error("默认文件异常 ", e1); } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.error("关闭异常 ", e); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { log.error("关闭异常 ", e); } } } } }
Java
package com.hundred.item.module.screen; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.turbine.Context; import com.alibaba.citrus.turbine.Navigator; import com.hundred.item.dao.ItemDao; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.item.dao.dataobject.ItemReqDO; public class Itemlist { private static final Logger log = LoggerFactory.getLogger(Itemlist.class); @Autowired private ItemDao itemDao; public void execute(Context context, Navigator nav) { ItemReqDO itemReq = new ItemReqDO(); ItemDO itemDO = itemDao.getItemById(itemReq); if(itemDO==null){ context.put("result", "noitem"); } else{ context.put("result", "ok"); context.put("resultItem", itemDO); } } public ItemDao getItemDao() { return itemDao; } public void setItemDao(ItemDao itemDao) { this.itemDao = itemDao; } }
Java
package com.hundred.item.module.screen; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.turbine.Context; import com.alibaba.citrus.turbine.Navigator; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.item.manager.ItemManager; public class TopItemsList { private static final Logger logger = LoggerFactory.getLogger(TopItemsList.class); @Autowired private ItemManager itemManager; public void execute(Context context, Navigator nav) { List<ItemDO> topList = itemManager.getTopItemList(0, 0, 5); for(ItemDO item:topList){ titleProcess(item); logger.error(""); } context.put("items", topList); logger.error("------------------TopItemList:"+topList.size()); } private void titleProcess(ItemDO itemDO){ if(itemDO!=null && itemDO.getItemName()!=null){ String[] titleStrArray = itemDO.getItemName().split("。"); String[] titleStrArray2 = itemDO.getItemName().split(","); if(titleStrArray.length>=1 && titleStrArray2.length>=1){ String oneStr = titleStrArray[0]; String twoStr = titleStrArray2[0]; String newTitle = oneStr.length()<=twoStr.length()?oneStr:twoStr; itemDO.setItemName(newTitle); } else if(titleStrArray.length>=1){ String newTitle = titleStrArray[0]; itemDO.setItemName(newTitle); } } } public ItemManager getItemManager() { return itemManager; } public void setItemManager(ItemManager itemManager) { this.itemManager = itemManager; } }
Java
package com.hundred.item.module.screen; import java.util.List; import java.util.Random; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.turbine.Context; import com.alibaba.citrus.turbine.Navigator; import com.alibaba.citrus.util.StringUtil; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.item.manager.ItemCompareManager; import com.hundred.item.manager.ItemManager; public class SelectCompareItems { private static final Logger logger = LoggerFactory.getLogger(SelectCompareItems.class); @Autowired private HttpServletRequest request; @Autowired private ItemManager itemManager; @Autowired private ItemCompareManager itemCompareManager; public void execute(Context context, Navigator nav) { String tagStr = request.getParameter("tag"); int tag = 100; if(!StringUtil.isBlank(tagStr)){ tag=Integer.parseInt(tagStr); } logger.error("用户选择标签:"+tag); List<ItemDO> itemList = itemCompareManager.selectCompareItems(2,tag); context.put("leftItem", itemList.get(0)); context.put("rightItem", itemList.get(1)); } public ItemManager getItemManager() { return itemManager; } public void setItemManager(ItemManager itemManager) { this.itemManager = itemManager; } public ItemCompareManager getItemCompareManager() { return itemCompareManager; } public void setItemCompareManager(ItemCompareManager itemCompareManager) { this.itemCompareManager = itemCompareManager; } }
Java
package com.hundred.item.module.action; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.citrus.turbine.Navigator; import com.alibaba.citrus.turbine.dataresolver.FormGroup; import com.hundred.item.dao.dataobject.ItemDO; import com.hundred.item.manager.ItemManager; public class ItemAction { private static final Logger log = LoggerFactory.getLogger(ItemAction.class); @Autowired private ItemManager itemManager; public void doAddItem(@FormGroup("additem") ItemDO itemVo, Navigator nav) { try { itemManager.addItem(itemVo); } catch (Exception e) { log.error("add item error. " + itemVo, e); } nav.redirectTo("itemLink").withTarget("itemlist").withParameter("sId", String.valueOf(itemVo.getItemId())); } public void doDelItem(@FormGroup("delitem") ItemDO itemVo, Navigator nav) { try { itemManager.deleteItem(itemVo); } catch (Exception e) { log.error("del item error. " + itemVo, e); } nav.redirectTo("itemLink").withTarget("itemlist").withParameter("sId", String.valueOf(itemVo.getItemId())); } }
Java
// Copyright 2003-2010 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland // www.source-code.biz, www.inventec.ch/chdh // // This module is multi-licensed and may be used under the terms // of any of the following licenses: // // EPL, Eclipse Public License, V1.0 or later, http://www.eclipse.org/legal // LGPL, GNU Lesser General Public License, V2.1 or later, http://www.gnu.org/licenses/lgpl.html // GPL, GNU General Public License, V2 or later, http://www.gnu.org/licenses/gpl.html // AL, Apache License, V2.0 or later, http://www.apache.org/licenses // BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php // MIT, MIT License, http://www.opensource.org/licenses/MIT // // Please contact the author if you need another license. // This module is provided "as is", without warranties of any kind. package com.qq.open; /** * A Base64 encoder/decoder. * * <p> * This class is used to encode and decode data in Base64 format as described in RFC 1521. * * <p> * Project home page: <a href="http://www.source-code.biz/base64coder/java/">www.source-code.biz/base64coder/java</a><br> * Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br> * Multi-licensed: EPL / LGPL / GPL / AL / BSD / MIT. */ public class Base64Coder { // The line separator string of the operating system. private static final String systemLineSeparator = System.getProperty("line.separator"); // Mapping table from 6-bit nibbles to Base64 characters. private static final char[] map1 = new char[64]; static { int i=0; for (char c='A'; c<='Z'; c++) map1[i++] = c; for (char c='a'; c<='z'; c++) map1[i++] = c; for (char c='0'; c<='9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; } // Mapping table from Base64 characters to 6-bit nibbles. private static final byte[] map2 = new byte[128]; static { for (int i=0; i<map2.length; i++) map2[i] = -1; for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; } /** * Encodes a string into Base64 format. * No blanks or line breaks are inserted. * @param s A String to be encoded. * @return A String containing the Base64 encoded data. */ public static String encodeString (String s) { return new String(encode(s.getBytes())); } /** * Encodes a byte array into Base 64 format and breaks the output into lines of 76 characters. * This method is compatible with <code>sun.misc.BASE64Encoder.encodeBuffer(byte[])</code>. * @param in An array containing the data bytes to be encoded. * @return A String containing the Base64 encoded data, broken into lines. */ public static String encodeLines (byte[] in) { return encodeLines(in, 0, in.length, 76, systemLineSeparator); } /** * Encodes a byte array into Base 64 format and breaks the output into lines. * @param in An array containing the data bytes to be encoded. * @param iOff Offset of the first byte in <code>in</code> to be processed. * @param iLen Number of bytes to be processed in <code>in</code>, starting at <code>iOff</code>. * @param lineLen Line length for the output data. Should be a multiple of 4. * @param lineSeparator The line separator to be used to separate the output lines. * @return A String containing the Base64 encoded data, broken into lines. */ public static String encodeLines (byte[] in, int iOff, int iLen, int lineLen, String lineSeparator) { int blockLen = (lineLen*3) / 4; if (blockLen <= 0) throw new IllegalArgumentException(); int lines = (iLen+blockLen-1) / blockLen; int bufLen = ((iLen+2)/3)*4 + lines*lineSeparator.length(); StringBuilder buf = new StringBuilder(bufLen); int ip = 0; while (ip < iLen) { int l = Math.min(iLen-ip, blockLen); buf.append (encode(in, iOff+ip, l)); buf.append (lineSeparator); ip += l; } return buf.toString(); } /** * Encodes a byte array into Base64 format. * No blanks or line breaks are inserted in the output. * @param in An array containing the data bytes to be encoded. * @return A character array containing the Base64 encoded data. */ public static char[] encode (byte[] in) { return encode(in, 0, in.length); } /** * Encodes a byte array into Base64 format. * No blanks or line breaks are inserted in the output. * @param in An array containing the data bytes to be encoded. * @param iLen Number of bytes to process in <code>in</code>. * @return A character array containing the Base64 encoded data. */ public static char[] encode (byte[] in, int iLen) { return encode(in, 0, iLen); } /** * Encodes a byte array into Base64 format. * No blanks or line breaks are inserted in the output. * @param in An array containing the data bytes to be encoded. * @param iOff Offset of the first byte in <code>in</code> to be processed. * @param iLen Number of bytes to process in <code>in</code>, starting at <code>iOff</code>. * @return A character array containing the Base64 encoded data. */ public static char[] encode (byte[] in, int iOff, int iLen) { int oDataLen = (iLen*4+2)/3; // output length without padding int oLen = ((iLen+2)/3)*4; // output length including padding char[] out = new char[oLen]; int ip = iOff; int iEnd = iOff + iLen; int op = 0; while (ip < iEnd) { int i0 = in[ip++] & 0xff; int i1 = ip < iEnd ? in[ip++] & 0xff : 0; int i2 = ip < iEnd ? in[ip++] & 0xff : 0; int o0 = i0 >>> 2; int o1 = ((i0 & 3) << 4) | (i1 >>> 4); int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); int o3 = i2 & 0x3F; out[op++] = map1[o0]; out[op++] = map1[o1]; out[op] = op < oDataLen ? map1[o2] : '='; op++; out[op] = op < oDataLen ? map1[o3] : '='; op++; } return out; } /** * Decodes a string from Base64 format. * No blanks or line breaks are allowed within the Base64 encoded input data. * @param s A Base64 String to be decoded. * @return A String containing the decoded data. * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ public static String decodeString (String s) { return new String(decode(s)); } /** * Decodes a byte array from Base64 format and ignores line separators, tabs and blanks. * CR, LF, Tab and Space characters are ignored in the input data. * This method is compatible with <code>sun.misc.BASE64Decoder.decodeBuffer(String)</code>. * @param s A Base64 String to be decoded. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ public static byte[] decodeLines (String s) { char[] buf = new char[s.length()]; int p = 0; for (int ip = 0; ip < s.length(); ip++) { char c = s.charAt(ip); if (c != ' ' && c != '\r' && c != '\n' && c != '\t') buf[p++] = c; } return decode(buf, 0, p); } /** * Decodes a byte array from Base64 format. * No blanks or line breaks are allowed within the Base64 encoded input data. * @param s A Base64 String to be decoded. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ public static byte[] decode (String s) { return decode(s.toCharArray()); } /** * Decodes a byte array from Base64 format. * No blanks or line breaks are allowed within the Base64 encoded input data. * @param in A character array containing the Base64 encoded data. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ public static byte[] decode (char[] in) { return decode(in, 0, in.length); } /** * Decodes a byte array from Base64 format. * No blanks or line breaks are allowed within the Base64 encoded input data. * @param in A character array containing the Base64 encoded data. * @param iOff Offset of the first character in <code>in</code> to be processed. * @param iLen Number of characters to process in <code>in</code>, starting at <code>iOff</code>. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ public static byte[] decode (char[] in, int iOff, int iLen) { if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4."); while (iLen > 0 && in[iOff+iLen-1] == '=') iLen--; int oLen = (iLen*3) / 4; byte[] out = new byte[oLen]; int ip = iOff; int iEnd = iOff + iLen; int op = 0; while (ip < iEnd) { int i0 = in[ip++]; int i1 = in[ip++]; int i2 = ip < iEnd ? in[ip++] : 'A'; int i3 = ip < iEnd ? in[ip++] : 'A'; if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); int b0 = map2[i0]; int b1 = map2[i1]; int b2 = map2[i2]; int b3 = map2[i3]; if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); int o0 = ( b0 <<2) | (b1>>>4); int o1 = ((b1 & 0xf)<<4) | (b2>>>2); int o2 = ((b2 & 3)<<6) | b3; out[op++] = (byte)o0; if (op<oLen) out[op++] = (byte)o1; if (op<oLen) out[op++] = (byte)o2; } return out; } // Dummy constructor. private Base64Coder() {} } // end class Base64Coder
Java
package com.qq.open.https; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.HttpClientError; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; /** * 自定义SecureProtocolSocketFactory类 (辅助https实现接受任意来源证书) * * @version 3.0.0 * @since jdk1.5 * @author open.qq.com * @copyright © 2012, Tencent Corporation. All rights reserved. * @History: * 3.0.0 | nemozhang | 2012-03-21 12:01:05 | initialization */ public class MySecureProtocolSocketFactory implements ProtocolSocketFactory { private SSLContext sslContext = null; /** * Constructor for MySecureProtocolSocketFactory. */ public MySecureProtocolSocketFactory() { } /** * * @return */ private static SSLContext createEasySSLContext() { try { SSLContext context = SSLContext.getInstance("SSL"); context.init(null, new TrustManager[] { new MyX509TrustManager() }, null); return context; } catch (Exception e) { throw new HttpClientError(e.toString()); } } /** * * @return */ private SSLContext getSSLContext() { if (this.sslContext == null) { this.sslContext = createEasySSLContext(); } return this.sslContext; } /* * (non-Javadoc) * * @see org.apache.commons.httpclient.protocol.ProtocolSocketFactory#createSocket(java.lang.String, * int, java.net.InetAddress, int) */ public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort); } /* * (non-Javadoc) * * @see org.apache.commons.httpclient.protocol.ProtocolSocketFactory#createSocket(java.lang.String, * int, java.net.InetAddress, int, * org.apache.commons.httpclient.params.HttpConnectionParams) */ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); if (timeout == 0) { return createSocket(host, port, localAddress, localPort); } else { return ControllerThreadSocketFactory.createSocket(this, host, port, localAddress, localPort, timeout); } } /* * (non-Javadoc) * * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int) */ public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(host, port); } /* * (non-Javadoc) * * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean) */ public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); } }
Java
package com.qq.open.https; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; /** * 自定义签名证书管理类 (接受任意来源证书) * * @version 3.0.0 * @since jdk1.5 * @author open.qq.com * @copyright © 2012, Tencent Corporation. All rights reserved. * @History: * 3.0.0 | nemozhang | 2012-03-21 12:01:05 | initialization */ public class MyX509TrustManager implements X509TrustManager { /* (non-Javadoc) * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], java.lang.String) */ public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } /* (non-Javadoc) * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], java.lang.String) */ public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } /* (non-Javadoc) * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() */ public X509Certificate[] getAcceptedIssuers() { return null; } }
Java
package com.qq.open; /** * 定义错误码。 * * @version 3.0.0 * @since jdk1.5 * @author open.qq.com * @copyright © 2012, Tencent Corporation. All rights reserved. * @History: * 3.0.0 | nemozhang | 2012-03-21 12:01:05 | initialization * */ public class ErrorCode { // 序列化UID private static final long serialVersionUID = -1679458253208555786L; /** * 必填参数为空。 */ public final static int PARAMETER_EMPTY = 2001; /** * 必填参数无效。 */ public final static int PARAMETER_INVALID = 2002; /** * 服务器响应数据无效。 */ public final static int RESPONSE_DATA_INVALID = 2003; /** * 生成签名失败。 */ public final static int MAKE_SIGNATURE_ERROR = 2004; /** * 网络错误。 */ public final static int NETWORK_ERROR = 3000; }
Java
package com.qq.open; import java.util.*; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.*; import java.net.URI; import java.net.URISyntaxException; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.MultipartPostMethod; import org.apache.commons.httpclient.methods.multipart.StringPart; import com.qq.open.OpensnsException; import com.qq.open.ErrorCode; import com.qq.open.https.MySecureProtocolSocketFactory; /** * 发送HTTP网络请求类 * * @version 3.0.0 * @since jdk1.5 * @author open.qq.com * @copyright © 2012, Tencent Corporation. All rights reserved. * @History: * 3.0.1 | coolinchen| 2012-11-07 11:20:12 | support POST request in "multipart/form-data" format * 3.0.0 | nemozhang | 2012-03-21 12:01:05 | initialization * */ public class SnsNetwork { /** * 发送POST请求 * * @param url 请求URL地址 * @param params 请求参数 * @param protocol 请求协议 "http" / "https" * @return 服务器响应的请求结果 * @throws OpensnsException 网络故障时抛出异常。 */ public static String postRequest( String url, HashMap<String, String> params, HashMap<String, String> cookies, String protocol) throws OpensnsException { if (protocol.equalsIgnoreCase("https")) { Protocol httpsProtocol = new Protocol("https", new MySecureProtocolSocketFactory(), 443); Protocol.registerProtocol("https", httpsProtocol); } HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url); // 设置请求参数 if (params != null && !params.isEmpty()) { NameValuePair[] data = new NameValuePair[params.size()]; Iterator iter = params.entrySet().iterator(); int i=0; while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); data[i] = new NameValuePair((String)entry.getKey(), (String)entry.getValue()); ++i; } postMethod.setRequestBody(data); } // 设置cookie if (cookies !=null && !cookies.isEmpty()) { Iterator iter = cookies.entrySet().iterator(); StringBuilder buffer = new StringBuilder(128); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); buffer.append((String)entry.getKey()).append("=").append((String)entry.getValue()).append("; "); } // 设置cookie策略 postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); // 设置cookie内容 postMethod.setRequestHeader("Cookie", buffer.toString()); } // 设置User-Agent postMethod.setRequestHeader("User-Agent", "Java OpenApiV3 SDK Client"); // 设置建立连接超时时间 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT); // 设置读数据超时时间 httpClient.getHttpConnectionManager().getParams().setSoTimeout(READ_DATA_TIMEOUT); // 设置编码 postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, CONTENT_CHARSET); //使用系统提供的默认的恢复策略 postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); try { try { int statusCode = httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { throw new OpensnsException(ErrorCode.NETWORK_ERROR, "Request [" + url + "] failed:" + postMethod.getStatusLine()); } //读取内容 byte[] responseBody = postMethod.getResponseBody(); return new String(responseBody, CONTENT_CHARSET); } finally { //释放链接 postMethod.releaseConnection(); } } catch (HttpException e) { //发生致命的异常,可能是协议不对或者返回的内容有问题 throw new OpensnsException(ErrorCode.NETWORK_ERROR, "Request [" + url + "] failed:" + e.getMessage()); } catch (IOException e) { //发生网络异常 throw new OpensnsException(ErrorCode.NETWORK_ERROR, "Request [" + url + "] failed:" + e.getMessage()); } } /** * 发送POST请求 * * @param url 请求URL地址 * @param params 请求参数 * @param protocol 请求协议 "http" / "https" * @param fp 上传的文件 * @return 服务器响应的请求结果 * @throws OpensnsException 网络故障时抛出异常。 */ public static String postRequestWithFile( String url, HashMap<String, String> params, HashMap<String, String> cookies, FilePart fp, String protocol) throws OpensnsException { if (protocol.equalsIgnoreCase("https")) { Protocol httpsProtocol = new Protocol("https", new MySecureProtocolSocketFactory(), 443); Protocol.registerProtocol("https", httpsProtocol); } HttpClient httpClient = new HttpClient(); //上传文件要使用MultipartPostMethod类 MultipartPostMethod postMethod = new MultipartPostMethod(url); //将FilePart类型的文件加到参数里 postMethod.addPart(fp); // 设置请求参数 if (params != null && !params.isEmpty()) { Iterator iter = params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); //设置参数为UTF-8编码集,解决中文乱码问题,并且将参数加到post中 postMethod.addPart(new StringPart((String)entry.getKey(), (String)entry.getValue(), CONTENT_CHARSET)); } } // 设置cookie if (cookies !=null && !cookies.isEmpty()) { Iterator iter = cookies.entrySet().iterator(); StringBuilder buffer = new StringBuilder(128); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); buffer.append((String)entry.getKey()).append("=").append((String)entry.getValue()).append("; "); } // 设置cookie策略 postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); // 设置cookie内容 postMethod.setRequestHeader("Cookie", buffer.toString()); } // 设置User-Agent postMethod.setRequestHeader("User-Agent", "Java OpenApiV3 SDK Client"); // 设置建立连接超时时间 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT); // 设置读数据超时时间 httpClient.getHttpConnectionManager().getParams().setSoTimeout(READ_DATA_TIMEOUT); //使用系统提供的默认的恢复策略 postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //发送请求 try { try { postMethod.getParams().setContentCharset("UTF-8"); int statusCode = httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { throw new OpensnsException(ErrorCode.NETWORK_ERROR, "Request [" + url + "] failed:" + postMethod.getStatusLine()); } //读取内容 byte[] responseBody = postMethod.getResponseBody(); return new String(responseBody, CONTENT_CHARSET); } finally { //释放链接 postMethod.releaseConnection(); } } catch (HttpException e) { //发生致命的异常,可能是协议不对或者返回的内容有问题 throw new OpensnsException(ErrorCode.NETWORK_ERROR, "Request [" + url + "] failed:" + e.getMessage()); } catch (IOException e) { //发生网络异常 throw new OpensnsException(ErrorCode.NETWORK_ERROR, "Request [" + url + "] failed:" + e.getMessage()); } } // 编码方式 private static final String CONTENT_CHARSET = "UTF-8"; // 连接超时时间 private static final int CONNECTION_TIMEOUT = 3000; // 读数据超时时间 private static final int READ_DATA_TIMEOUT = 3000; }
Java