answer
stringlengths
17
10.2M
package edu.cornell.mannlib.vitro.webapp.search.controller; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.MultiFieldQueryParser; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.WildcardQuery; import edu.cornell.mannlib.vitro.webapp.beans.DataProperty; import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement; import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.IndividualImpl; import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty; import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement; import edu.cornell.mannlib.vitro.webapp.beans.Portal; import edu.cornell.mannlib.vitro.webapp.beans.VClass; import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.ParamMap; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ExceptionResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao; import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao; import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao; import edu.cornell.mannlib.vitro.webapp.dao.VClassDao; import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.flags.PortalFlag; import edu.cornell.mannlib.vitro.webapp.search.SearchException; import edu.cornell.mannlib.vitro.webapp.search.beans.Searcher; import edu.cornell.mannlib.vitro.webapp.search.beans.VitroHighlighter; import edu.cornell.mannlib.vitro.webapp.search.beans.VitroQuery; import edu.cornell.mannlib.vitro.webapp.search.beans.VitroQueryFactory; import edu.cornell.mannlib.vitro.webapp.search.lucene.Entity2LuceneDoc; import edu.cornell.mannlib.vitro.webapp.search.lucene.LuceneIndexFactory; import edu.cornell.mannlib.vitro.webapp.search.lucene.LuceneSetup; import edu.cornell.mannlib.vitro.webapp.utils.FlagMathUtils; import edu.cornell.mannlib.vitro.webapp.utils.Html2Text; import edu.cornell.mannlib.vitro.webapp.utils.StringUtils; import edu.cornell.mannlib.vitro.webapp.web.templatemodels.LinkTemplateModel; import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.ListedIndividualTemplateModel; import freemarker.template.Configuration; /** * PagedSearchController is the new search controller that interacts * directly with the lucene API and returns paged, relevance ranked results. * * @author bdc34 * * Rewritten to use Freemarker: rjy7 * */ public class PagedSearchController extends FreemarkerHttpServlet implements Searcher { private static final long serialVersionUID = 1L; private static final Log log = LogFactory.getLog(PagedSearchController.class.getName()); private static final String XML_REQUEST_PARAM = "xml"; private IndexSearcher searcher = null; private int defaultHitsPerPage = 25; private int defaultMaxSearchSize= 1000; protected static final Map<Format,Map<Result,String>> templateTable; private static final float QUERY_BOOST = 2.0F; protected enum Format{ HTML, XML; } protected enum Result{ PAGED, FORM, ERROR, BAD_QUERY } static{ templateTable = setupTemplateTable(); } // protected enum SearchTemplate { // PAGED_RESULTS("search-pagedResults.ftl"), // FORM("search-form.ftl"), // ERROR("search-error.ftl"), // BAD_QUERY("search-badQuery.ftl"), // XML_RESULT("search-xmlResults.ftl"); // private final String filename; // SearchTemplate(String filename) { // this.filename = filename; // public String toString() { // return filename; /** * Overriding doGet from FreemarkerHttpController to do a page template (as * opposed to body template) style output for XML requests. * * This follows the pattern in AutocompleteController.java. */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { boolean wasXmlRequested = isRequesedFormatXml(request); if( ! wasXmlRequested ){ super.doGet(request,response); }else{ try { VitroRequest vreq = new VitroRequest(request); Configuration config = getConfig(vreq); ResponseValues rvalues = processRequest(vreq); response.setCharacterEncoding("UTF-8"); response.setContentType("text/xml;charset=UTF-8"); writeTemplate(rvalues.getTemplateName(), rvalues.getMap(), config, request, response); } catch (Exception e) { log.error(e, e); } } } @Override protected ResponseValues processRequest(VitroRequest vreq) { log.info("All parameters present in the request: "+ vreq.getParameterMap().toString()); //There may be other non-html formats in the future Format format = getFormat(vreq); boolean wasXmlRequested = Format.XML == format; log.debug("xml was the requested format"); boolean wasHtmlRequested = ! wasXmlRequested; try { Portal portal = vreq.getPortal(); PortalFlag portalFlag = vreq.getPortalFlag(); //make sure an IndividualDao is available if( vreq.getWebappDaoFactory() == null || vreq.getWebappDaoFactory().getIndividualDao() == null ){ log.error("Could not get webappDaoFactory or IndividualDao"); throw new Exception("Could not access model."); } IndividualDao iDao = vreq.getWebappDaoFactory().getIndividualDao(); VClassGroupDao grpDao = vreq.getWebappDaoFactory().getVClassGroupDao(); VClassDao vclassDao = vreq.getWebappDaoFactory().getVClassDao(); String alphaFilter = vreq.getParameter("alpha"); log.info("IndividualDao is " + iDao.toString() + " Public classes in the classgroup are " + grpDao.getPublicGroupsWithVClasses().toString()); log.info("VClassDao is "+ vclassDao.toString() ); int startIndex = 0; try{ startIndex = Integer.parseInt(vreq.getParameter("startIndex")); }catch (Throwable e) { startIndex = 0; } log.debug("startIndex is " + startIndex); int hitsPerPage = defaultHitsPerPage; try{ hitsPerPage = Integer.parseInt(vreq.getParameter("hitsPerPage")); } catch (Throwable e) { hitsPerPage = defaultHitsPerPage; } log.debug("hitsPerPage is " + hitsPerPage); int maxHitSize = defaultMaxSearchSize; if( startIndex >= defaultMaxSearchSize - hitsPerPage ) maxHitSize = startIndex + defaultMaxSearchSize; if( alphaFilter != null ){ maxHitSize = maxHitSize * 2; hitsPerPage = maxHitSize; } log.debug("maxHitSize is " + maxHitSize); String qtxt = vreq.getParameter(VitroQuery.QUERY_PARAMETER_NAME); Analyzer analyzer = getAnalyzer(getServletContext()); log.info("Query text is "+ qtxt + " Analyzer is "+ analyzer.toString()); Query query = null; try { query = getQuery(vreq, portalFlag, analyzer, qtxt); log.debug("query for '" + qtxt +"' is " + query.toString()); } catch (ParseException e) { return doBadQuery(portal, qtxt,format); } IndexSearcher searcherForRequest = LuceneIndexFactory.getIndexSearcher(getServletContext()); TopDocs topDocs = null; try{ log.info("Searching for query term in the Index with maxHitSize "+ maxHitSize); log.info("Query is "+ query.toString()); //sets the query boost for the query. the lucene docs matching this query term //are multiplied by QUERY_BOOST to get their total score query.setBoost(QUERY_BOOST); topDocs = searcherForRequest.search(query,null,maxHitSize); }catch(Throwable t){ log.error("in first pass at search: " + t); // this is a hack to deal with odd cases where search and index threads interact try{ wait(150); topDocs = searcherForRequest.search(query,null,maxHitSize); }catch (Exception ex){ log.error(ex); String msg = makeBadSearchMessage(qtxt,ex.getMessage()); if (msg == null) { msg = "The search request contained errors."; } return doFailedSearch(msg, qtxt,format); } } if( topDocs == null || topDocs.scoreDocs == null){ log.error("topDocs for a search was null"); String msg = "The search request contained errors."; return doFailedSearch(msg, qtxt,format); } int hitsLength = topDocs.scoreDocs.length; log.info("No. of hits "+ hitsLength); if ( hitsLength < 1 ){ return doNoHits(qtxt,format); } log.debug("found "+hitsLength+" hits"); int lastHitToShow = 0; if((startIndex + hitsPerPage) > hitsLength ) { lastHitToShow = hitsLength; } else { lastHitToShow = startIndex + hitsPerPage - 1; } List<Individual> beans = new LinkedList<Individual>(); for(int i=startIndex; i<topDocs.scoreDocs.length ;i++){ try{ if( (i >= startIndex) && (i <= lastHitToShow) ){ Document doc = searcherForRequest.doc(topDocs.scoreDocs[i].doc); String uri = doc.get(Entity2LuceneDoc.term.URI); log.info("Retrieving entity with uri "+ uri); Individual ent = new IndividualImpl(); ent.setURI(uri); ent = iDao.getIndividualByURI(uri); if(ent!=null) beans.add(ent); } }catch(Exception e){ log.error("problem getting usable Individuals from search " + "hits" + e.getMessage()); } } ParamMap pagingLinkParams = new ParamMap(); pagingLinkParams.put("querytext", qtxt); pagingLinkParams.put("hitsPerPage", String.valueOf(hitsPerPage)); if( wasXmlRequested ){ pagingLinkParams.put(XML_REQUEST_PARAM,"1"); } /* Start putting together the data for the templates */ Map<String, Object> body = new HashMap<String, Object>(); String classGroupParam = vreq.getParameter("classgroup"); boolean classGroupFilterRequested = false; if (!StringUtils.isEmpty(classGroupParam)) { VClassGroup grp = grpDao.getGroupByURI(classGroupParam); classGroupFilterRequested = true; if (grp != null && grp.getPublicName() != null) body.put("classGroupName", grp.getPublicName()); } String typeParam = vreq.getParameter("type"); boolean typeFiltereRequested = false; if (!StringUtils.isEmpty(typeParam)) { VClass type = vclassDao.getVClassByURI(typeParam); typeFiltereRequested = true; if (type != null && type.getName() != null) body.put("typeName", type.getName()); } /* Add classgroup and type refinement links to body */ if( wasHtmlRequested ){ // Search request includes no classgroup and no type, so add classgroup search refinement links. if ( !classGroupFilterRequested && !typeFiltereRequested ) { List<VClassGroup> classgroups = getClassGroups(grpDao, topDocs, searcherForRequest); List<VClassGroupSearchLink> classGroupLinks = new ArrayList<VClassGroupSearchLink>(classgroups.size()); for (VClassGroup vcg : classgroups) { classGroupLinks.add(new VClassGroupSearchLink(qtxt, vcg)); } body.put("classGroupLinks", classGroupLinks); // Search request is for a classgroup, so add rdf:type search refinement links // but try to filter out classes that are subclasses } else if ( classGroupFilterRequested && !typeFiltereRequested ) { List<VClass> vClasses = getVClasses(vclassDao,topDocs,searcherForRequest); List<VClassSearchLink> vClassLinks = new ArrayList<VClassSearchLink>(vClasses.size()); for (VClass vc : vClasses) { vClassLinks.add(new VClassSearchLink(qtxt, vc)); } body.put("classLinks", vClassLinks); pagingLinkParams.put("classgroup", classGroupParam); // This case is never displayed } else if (!StringUtils.isEmpty(alphaFilter)) { body.put("alphas", getAlphas(topDocs, searcherForRequest)); alphaSortIndividuals(beans); } else { pagingLinkParams.put("type", typeParam); } } // Convert search result individuals to template model objects body.put("individuals", ListedIndividualTemplateModel .getIndividualTemplateModelList(beans, vreq)); body.put("querytext", qtxt); body.put("title", qtxt + " - " + portal.getAppName() + " Search Results"); body.put("hitsLength",hitsLength); body.put("startIndex", startIndex); body.put("pagingLinks", getPagingLinks(startIndex, hitsPerPage, hitsLength, maxHitSize, vreq.getServletPath(), pagingLinkParams)); if (startIndex != 0) { body.put("prevPage", getPreviousPageLink(startIndex, hitsPerPage, vreq.getServletPath(), pagingLinkParams)); } if (startIndex < (hitsLength - hitsPerPage)) { body.put("nextPage", getNextPageLink(startIndex, hitsPerPage, vreq.getServletPath(), pagingLinkParams)); } String template = templateTable.get(format).get(Result.PAGED); return new TemplateResponseValues(template, body); } catch (Throwable e) { return doSearchError(e,format); } } private void alphaSortIndividuals(List<Individual> beans) { Collections.sort(beans, new Comparator< Individual >(){ public int compare(Individual o1, Individual o2) { if( o1 == null || o1.getName() == null ) return 1; else return o1.getName().compareTo(o2.getName()); }}); } private List<String> getAlphas(TopDocs topDocs, IndexSearcher searcher) { Set<String> alphas = new HashSet<String>(); for(int i=0;i<topDocs.scoreDocs.length; i++){ Document doc; try { doc = searcher.doc(topDocs.scoreDocs[i].doc); String name =doc.get(Entity2LuceneDoc.term.NAME); if( name != null && name.length() > 0) alphas.add( name.substring(0, 1)); } catch (CorruptIndexException e) { log.debug("Could not get alphas for document",e); } catch (IOException e) { log.debug("Could not get alphas for document",e); } } return new ArrayList<String>(alphas); } /** * Get the class groups represented for the individuals in the topDocs. */ private List<VClassGroup> getClassGroups(VClassGroupDao grpDao, TopDocs topDocs, IndexSearcher searcherForRequest) { LinkedHashMap<String,VClassGroup> grpMap = grpDao.getClassGroupMap(); int n = grpMap.size(); HashSet<String> classGroupsInHits = new HashSet<String>(n); int grpsFound = 0; for(int i=0; i<topDocs.scoreDocs.length && n > grpsFound ;i++){ try{ Document doc = searcherForRequest.doc(topDocs.scoreDocs[i].doc); Field[] grps = doc.getFields(Entity2LuceneDoc.term.CLASSGROUP_URI); if(grps != null || grps.length > 0){ for(int j=0;j<grps.length;j++){ String groupUri = grps[j].stringValue(); if( groupUri != null && ! classGroupsInHits.contains(groupUri)){ classGroupsInHits.add(groupUri); grpsFound++; if( grpsFound >= n ) break; } } } }catch(Exception e){ log.error("problem getting VClassGroups from search hits " + e.getMessage()); } } List<String> classgroupURIs= Collections.list(Collections.enumeration(classGroupsInHits)); List<VClassGroup> classgroups = new ArrayList<VClassGroup>( classgroupURIs.size() ); for(String cgUri: classgroupURIs){ if( cgUri != null && ! "".equals(cgUri) ){ VClassGroup vcg = grpDao.getGroupByURI( cgUri ); if( vcg == null ){ log.debug("could not get classgroup for URI " + cgUri); }else{ classgroups.add(vcg); } } } grpDao.sortGroupList(classgroups); return classgroups; } private class VClassGroupSearchLink extends LinkTemplateModel { VClassGroupSearchLink(String querytext, VClassGroup classgroup) { super(classgroup.getPublicName(), "/search", "querytext", querytext, "classgroup", classgroup.getURI()); } } private class VClassSearchLink extends LinkTemplateModel { VClassSearchLink(String querytext, VClass type) { super(type.getName(), "/search", "querytext", querytext, "type", type.getURI()); } } private List<PagingLink> getPagingLinks(int startIndex, int hitsPerPage, int hitsLength, int maxHitSize, String baseUrl, ParamMap params) { List<PagingLink> pagingLinks = new ArrayList<PagingLink>(); // No paging links if only one page of results if (hitsLength <= hitsPerPage) { return pagingLinks; } for (int i = 0; i < hitsLength; i += hitsPerPage) { params.put("startIndex", String.valueOf(i)); if ( i < maxHitSize - hitsPerPage) { int pageNumber = i/hitsPerPage + 1; if (i >= startIndex && i < (startIndex + hitsPerPage)) { pagingLinks.add(new PagingLink(pageNumber)); } else { pagingLinks.add(new PagingLink(pageNumber, baseUrl, params)); } } else { pagingLinks.add(new PagingLink("more...", baseUrl, params)); } } return pagingLinks; } private String getPreviousPageLink(int startIndex, int hitsPerPage, String baseUrl, ParamMap params) { params.put("startIndex", String.valueOf(startIndex-hitsPerPage)); //return new PagingLink("Previous", baseUrl, params); return UrlBuilder.getUrl(baseUrl, params); } private String getNextPageLink(int startIndex, int hitsPerPage, String baseUrl, ParamMap params) { params.put("startIndex", String.valueOf(startIndex+hitsPerPage)); //return new PagingLink("Next", baseUrl, params); return UrlBuilder.getUrl(baseUrl, params); } private class PagingLink extends LinkTemplateModel { PagingLink(int pageNumber, String baseUrl, ParamMap params) { super(String.valueOf(pageNumber), baseUrl, params); } // Constructor for current page item: not a link, so no url value. PagingLink(int pageNumber) { setText(String.valueOf(pageNumber)); } // Constructor for "more..." item PagingLink(String text, String baseUrl, ParamMap params) { super(text, baseUrl, params); } } private List<VClass> getVClasses(VClassDao vclassDao, TopDocs topDocs, IndexSearcher searherForRequest){ HashSet<String> typesInHits = getVClassUrisForHits(topDocs,searherForRequest); List<VClass> classes = new ArrayList<VClass>(typesInHits.size()); Iterator<String> it = typesInHits.iterator(); while(it.hasNext()){ String typeUri = it.next(); try{ if( VitroVocabulary.OWL_THING.equals(typeUri)) continue; VClass type = vclassDao.getVClassByURI(typeUri); if( ! type.isAnonymous() && type.getName() != null && !"".equals(type.getName()) && type.getGroupURI() != null ) //don't display classes that aren't in classgroups classes.add(type); }catch(Exception ex){ if( log.isDebugEnabled() ) log.debug("could not add type " + typeUri, ex); } } Collections.sort(classes, new Comparator<VClass>(){ public int compare(VClass o1, VClass o2) { return o1.compareTo(o2); }}); return classes; } private HashSet<String> getVClassUrisForHits(TopDocs topDocs, IndexSearcher searcherForRequest){ HashSet<String> typesInHits = new HashSet<String>(); for(int i=0; i<topDocs.scoreDocs.length; i++){ try{ Document doc=searcherForRequest.doc(topDocs.scoreDocs[i].doc); Field[] types = doc.getFields(Entity2LuceneDoc.term.RDFTYPE); if(types != null ){ for(int j=0;j<types.length;j++){ String typeUri = types[j].stringValue(); typesInHits.add(typeUri); } } }catch(Exception e){ log.error("problems getting rdf:type for search hits",e); } } return typesInHits; } private Analyzer getAnalyzer(ServletContext servletContext) throws SearchException { Object obj = servletContext.getAttribute(LuceneSetup.ANALYZER); if( obj == null || !(obj instanceof Analyzer) ) throw new SearchException("Could not get analyzer"); else return (Analyzer)obj; } private Query getQuery(VitroRequest request, PortalFlag portalState, Analyzer analyzer, String querystr ) throws SearchException, ParseException { Query query = null; try{ //String querystr = request.getParameter(VitroQuery.QUERY_PARAMETER_NAME); if( querystr == null){ log.error("There was no Parameter '"+VitroQuery.QUERY_PARAMETER_NAME +"' in the request."); return null; }else if( querystr.length() > MAX_QUERY_LENGTH ){ log.debug("The search was too long. The maximum " + "query length is " + MAX_QUERY_LENGTH ); return null; } log.info("Parsing query using QueryParser "); QueryParser parser = getQueryParser(analyzer); query = parser.parse(querystr); String alpha = request.getParameter("alpha"); if( alpha != null && !"".equals(alpha) && alpha.length() == 1){ log.info("Firing alpha query "); log.info("request.getParameter(alpha) is " + alpha); BooleanQuery boolQuery = new BooleanQuery(); boolQuery.add( query, BooleanClause.Occur.MUST ); boolQuery.add( new WildcardQuery(new Term(Entity2LuceneDoc.term.NAME, alpha+'*')), BooleanClause.Occur.MUST); query = boolQuery; } //check if this is classgroup filtered Object param = request.getParameter("classgroup"); if( param != null && !"".equals(param)){ log.info("Firing classgroup query "); log.info("request.getParameter(classgroup) is "+ param.toString()); BooleanQuery boolQuery = new BooleanQuery(); boolQuery.add( query, BooleanClause.Occur.MUST); boolQuery.add( new TermQuery( new Term(Entity2LuceneDoc.term.CLASSGROUP_URI, (String)param)), BooleanClause.Occur.MUST); query = boolQuery; } //check if this is rdf:type filtered param = request.getParameter("type"); if( param != null && !"".equals(param)){ log.info("Firing type query "); log.info("request.getParameter(type) is "+ param.toString()); BooleanQuery boolQuery = new BooleanQuery(); boolQuery.add( query, BooleanClause.Occur.MUST); boolQuery.add( new TermQuery( new Term(Entity2LuceneDoc.term.RDFTYPE, (String)param)), BooleanClause.Occur.MUST); query = boolQuery; } //if we have a flag/portal query then we add //it by making a BooelanQuery. Query flagQuery = makeFlagQuery( portalState ); if( flagQuery != null ){ log.info("Firing Flag query "); BooleanQuery boolQuery = new BooleanQuery(); boolQuery.add( query, BooleanClause.Occur.MUST); boolQuery.add( flagQuery, BooleanClause.Occur.MUST); query = boolQuery; } log.debug("Query: " + query); } catch (ParseException e) { throw new ParseException(e.getMessage()); } catch (Exception ex){ throw new SearchException(ex.getMessage()); } return query; } @SuppressWarnings("static-access") private QueryParser getQueryParser(Analyzer analyzer){ //defaultSearchField indicates which field search against when there is no term //indicated in the query string. //The analyzer is needed so that we use the same analyzer on the search queries as //was used on the text that was indexed. //QueryParser qp = new QueryParser("NAME",analyzer); //this sets the query parser to AND all of the query terms it finds. //qp.setDefaultOperator(QueryParser.AND_OPERATOR); //set up the map of stemmed field names -> unstemmed field names // HashMap<String,String> map = new HashMap<String, String>(); // map.put(Entity2LuceneDoc.term.ALLTEXT,Entity2LuceneDoc.term.ALLTEXTUNSTEMMED); // qp.setStemmedToUnstemmed(map); MultiFieldQueryParser qp = new MultiFieldQueryParser(new String[]{"ALLTEXT", "name", "type"}, analyzer); return qp; } /** * Makes a flag based query clause. This is where searches can filtered * by portal. * * If you think that search is not working correctly with protals and * all that kruft then this is a method you want to look at. * * It only takes into account "the portal flag" and flag1Exclusive must * be set. Where does that stuff get set? Look in vitro.flags.PortalFlag * * One thing to keep in mind with portal filtering and search is that if * you want to search a portal that is different then the portal the user * is 'in' then the home parameter should be set to force the user into * the new portal. * * Ex. Bob requests the search page for vivo in portal 3. You want to * have a drop down menu so bob can search the all CALS protal, id 60. * You need to have a home=60 on your search form. If you don't set * home=60 with your search query, then the search will not be in the * all portal AND the WebappDaoFactory will be filtered to only show * things in portal 3. * * Notice: flag1 as a parameter is ignored. bdc34 2009-05-22. */ @SuppressWarnings("static-access") private Query makeFlagQuery( PortalFlag flag){ if( flag == null || !flag.isFilteringActive() || flag.getFlag1DisplayStatus() == flag.SHOW_ALL_PORTALS ) return null; // make one term for each bit in the numeric flag that is set Collection<TermQuery> terms = new LinkedList<TermQuery>(); int portalNumericId = flag.getFlag1Numeric(); Long[] bits = FlagMathUtils.numeric2numerics(portalNumericId); for (Long bit : bits) { terms.add(new TermQuery(new Term(Entity2LuceneDoc.term.PORTAL, Long .toString(bit)))); } // make a boolean OR query for all of those terms BooleanQuery boolQuery = new BooleanQuery(); if (terms.size() > 0) { for (TermQuery term : terms) { boolQuery.add(term, BooleanClause.Occur.SHOULD); } return boolQuery; } else { //we have no flags set, so no flag filtering return null; } } private ExceptionResponseValues doSearchError(Throwable e, Format f) { Map<String, Object> body = new HashMap<String, Object>(); body.put("message", "Search failed: " + e.getMessage()); return new ExceptionResponseValues(getTemplate(f,Result.ERROR), body, e); } private TemplateResponseValues doBadQuery(Portal portal, String query, Format f) { Map<String, Object> body = new HashMap<String, Object>(); body.put("title", "Search " + portal.getAppName()); body.put("query", query); return new TemplateResponseValues(getTemplate(f,Result.BAD_QUERY), body); } private TemplateResponseValues doFailedSearch(String message, String querytext, Format f) { Map<String, Object> body = new HashMap<String, Object>(); body.put("title", "Search for '" + querytext + "'"); if ( StringUtils.isEmpty(message) ) { message = "Search failed."; } body.put("message", message); return new TemplateResponseValues(getTemplate(f,Result.ERROR), body); } private TemplateResponseValues doNoHits(String querytext, Format f) { Map<String, Object> body = new HashMap<String, Object>(); body.put("title", "Search for '" + querytext + "'"); body.put("message", "No matching results."); return new TemplateResponseValues(getTemplate(f,Result.ERROR), body); } /** * Makes a message to display to user for a bad search term. * @param query * @param exceptionMsg */ private String makeBadSearchMessage(String querytext, String exceptionMsg){ String rv = ""; try{ //try to get the column in the search term that is causing the problems int coli = exceptionMsg.indexOf("column"); if( coli == -1) return ""; int numi = exceptionMsg.indexOf(".", coli+7); if( numi == -1 ) return ""; String part = exceptionMsg.substring(coli+7,numi ); int i = Integer.parseInt(part) - 1; // figure out where to cut preview and post-view int errorWindow = 5; int pre = i - errorWindow; if (pre < 0) pre = 0; int post = i + errorWindow; if (post > querytext.length()) post = querytext.length(); // log.warn("pre: " + pre + " post: " + post + " term len: // " + term.length()); // get part of the search term before the error and after String before = querytext.substring(pre, i); String after = ""; if (post > i) after = querytext.substring(i + 1, post); rv = "The search term had an error near <span class='searchQuote'>" + before + "<span class='searchError'>" + querytext.charAt(i) + "</span>" + after + "</span>"; } catch (Throwable ex) { return ""; } return rv; } @SuppressWarnings("unchecked") private HashSet<String> getDataPropertyBlacklist(){ HashSet<String>dpBlacklist = (HashSet<String>) getServletContext().getAttribute(LuceneSetup.SEARCH_DATAPROPERTY_BLACKLIST); return dpBlacklist; } @SuppressWarnings("unchecked") private HashSet<String> getObjectPropertyBlacklist(){ HashSet<String>opBlacklist = (HashSet<String>) getServletContext().getAttribute(LuceneSetup.SEARCH_OBJECTPROPERTY_BLACKLIST); return opBlacklist; } private final String defaultSearchField = "ALLTEXT"; public static final int MAX_QUERY_LENGTH = 500; /** * Need to accept notification from indexer that the index has been changed. */ public void close() { searcher = null; } public VitroHighlighter getHighlighter(VitroQuery q) { throw new Error("PagedSearchController.getHighlighter() is unimplemented"); } public VitroQueryFactory getQueryFactory() { throw new Error("PagedSearchController.getQueryFactory() is unimplemented"); } public List search(VitroQuery query) throws SearchException { throw new Error("PagedSearchController.search() is unimplemented"); } protected boolean isRequesedFormatXml(HttpServletRequest req){ if( req != null ){ String param = req.getParameter(XML_REQUEST_PARAM); if( param != null && "1".equals(param)){ return true; }else{ return false; } }else{ return false; } } protected Format getFormat(HttpServletRequest req){ if( req != null && req.getParameter("xml") != null && "1".equals(req.getParameter("xml"))) return Format.XML; else return Format.HTML; } protected static String getTemplate(Format format, Result result){ if( format != null && result != null) return templateTable.get(format).get(result); else{ log.error("getTemplate() must not have a null format or result."); return templateTable.get(Format.HTML).get(Result.ERROR); } } protected static Map<Format,Map<Result,String>> setupTemplateTable(){ Map<Format,Map<Result,String>> templateTable = new HashMap<Format,Map<Result,String>>(); HashMap<Result,String> resultsToTemplates = new HashMap<Result,String>(); //setup HTML format resultsToTemplates.put(Result.PAGED, "search-pagedResults.ftl"); resultsToTemplates.put(Result.FORM, "search-form.ftl"); resultsToTemplates.put(Result.ERROR, "search-error.ftl"); resultsToTemplates.put(Result.BAD_QUERY, "search-badQuery.ftl"); templateTable.put(Format.HTML, Collections.unmodifiableMap(resultsToTemplates)); //setup XML format resultsToTemplates = new HashMap<Result,String>(); resultsToTemplates.put(Result.PAGED, "search-xmlResults.ftl"); resultsToTemplates.put(Result.FORM, "search-xmlForm.ftl"); resultsToTemplates.put(Result.ERROR, "search-xmlError.ftl"); resultsToTemplates.put(Result.BAD_QUERY, "search-xmlBadQuery.ftl"); templateTable.put(Format.XML, Collections.unmodifiableMap(resultsToTemplates)); return Collections.unmodifiableMap(templateTable); } }
package io.javadog.cws.core.jce; import io.javadog.cws.core.enums.KeyAlgorithm; import io.javadog.cws.core.model.Settings; import javax.security.auth.DestroyFailedException; import javax.security.auth.Destroyable; import java.security.Key; import java.util.logging.Logger; /** * @author Kim Jensen * @since CWS 1.0 */ public abstract class CWSKey<T extends Key> { private static final Logger log = Logger.getLogger(CWSKey.class.getName()); protected boolean destroyed = false; private final KeyAlgorithm algorithm; protected final T key; /** * Default Constructor. * * @param algorithm Key Algorithm * @param key Key */ protected CWSKey(final KeyAlgorithm algorithm, final T key) { this.algorithm = algorithm; this.key = key; } public abstract T getKey(); public byte[] getEncoded() { return key.getEncoded(); } public KeyAlgorithm getAlgorithm() { return algorithm; } public boolean isDestroyed() { return destroyed; } /** * <p>The Secret &amp; Private Keys both extend the {@link Destroyable } * interface, which means that they in theory can be destroyed. However, * many of the implementations only have the default behaviour, which is to * simply throw a {@link DestroyFailedException }. Hence this method will * simply ignore this exception by logging it as a debug message. Hopefully * the debug logs will be reduced in the future, once the implementation has * been added.</p> * * <p>Unfortunately, it seems that the functionality is not implemented in * Java 8, so to avoid large stacktrace in the logs, the code to destroy * the keys is revoked and listed as pending..</p> */ protected void destroyKey() { // From the OpenJDK bugs: // - No way to clean the memory for a java.security.Key // - Clean memory in JCE implementations of private key and secret key // - java.security.KeyPair should implement Destroyable // - SecretKeySpec should implement destroy() log.log(Settings.DEBUG, "Java support for destroying keys is not yet implemented."); } }
package com.hortonworks.iotas.webservice; import com.codahale.metrics.annotation.Timed; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.ByteStreams; import com.hortonworks.iotas.catalog.ParserInfo; import com.hortonworks.iotas.storage.StorageManager; import com.hortonworks.util.JarStorage; import com.hortonworks.util.ReflectionHelper; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.StreamingOutput; import java.io.*; import java.nio.file.FileSystems; import java.util.Collection; @Path("/api/v1/catalog") @Produces(MediaType.APPLICATION_JSON) public class ParserInfoCatalogResource { // TODO should probably make namespace static private static final String PARSER_INFO_NAMESPACE = new ParserInfo().getNameSpace(); private static final ObjectMapper objectMapper = new ObjectMapper(); private StorageManager dao; private IotasConfiguration configuration; private JarStorage jarStorage; public ParserInfoCatalogResource(StorageManager manager, IotasConfiguration configuration) { this.dao = manager; this.configuration = configuration; try { this.jarStorage = ReflectionHelper.newInstance(this.configuration .getJarStorageImplementationClass()); } catch (Exception ex) { throw new RuntimeException(ex); } } @GET @Path("/parsers") @Timed // TODO add a way to query/filter and/or page results public Collection<ParserInfo> listParsers() { return this.dao.<ParserInfo>list(PARSER_INFO_NAMESPACE); } @GET @Path("/parsers/{id}") @Timed public ParserInfo getParserInfoById(@PathParam("id") Long parserId) { ParserInfo parserInfo = new ParserInfo(); parserInfo.setParserId(parserId); return this.dao.<ParserInfo>get(PARSER_INFO_NAMESPACE, parserInfo.getPrimaryKey()); } @DELETE @Path("/parsers/{id}") @Timed public ParserInfo removeParser(@PathParam("id") Long parserId) { ParserInfo parserInfo = new ParserInfo(); parserInfo.setParserId(parserId); return this.dao.remove(PARSER_INFO_NAMESPACE, parserInfo.getPrimaryKey()); } @Timed @POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Path("/parsers") public ParserInfo addParser(@FormDataParam("parserJar") final InputStream inputStream, @FormDataParam("parserJar") final FormDataContentDisposition contentDispositionHeader, @FormDataParam("parserInfo") final String parserInfoStr) throws IOException { String name = ""; if(contentDispositionHeader != null && contentDispositionHeader.getFileName() != null) { name = contentDispositionHeader.getFileName(); this.jarStorage.uploadJar(inputStream, name); inputStream.close(); } //TODO something special about multipart request so it wont let me pass just a ParserInfo json object, instead we must pass ParserInfo as a json string. ParserInfo parserInfo = objectMapper.readValue(new StringReader(parserInfoStr), ParserInfo.class); if (parserInfo.getParserId() == null) { parserInfo.setParserId(this.dao.nextId(PARSER_INFO_NAMESPACE)); } if (parserInfo.getTimestamp() == null) { parserInfo.setTimestamp(System.currentTimeMillis()); } parserInfo.setJarStoragePath(name); this.dao.add(parserInfo); return parserInfo; } //TODO Still need to implement update/PUT //TODO, is it better to expect that clients will know the parserId or the jarStoragePath? I like parserId as it //hides the storage details from clients. @Timed @GET @Consumes(MediaType.MULTIPART_FORM_DATA) @Path("/parsers/download/{parserId}") public StreamingOutput downloadParserJar(@PathParam("parserId") Long parserId) throws IOException { ParserInfo parserInfo = getParserInfoById(parserId); final InputStream inputStream = this.jarStorage.downloadJar(parserInfo.getJarStoragePath()); StreamingOutput streamOutput = new StreamingOutput() { public void write(OutputStream os) throws IOException, WebApplicationException { ByteStreams.copy(inputStream, os); } }; return streamOutput; } }
package org.cobbzilla.wizard.model.entityconfig; import com.fasterxml.jackson.annotation.JsonCreator; import lombok.AllArgsConstructor; import org.cobbzilla.wizard.model.entityconfig.validation.*; import org.cobbzilla.wizard.validation.ValidationResult; import org.cobbzilla.wizard.validation.Validator; import javax.persistence.Column; import java.lang.reflect.Field; import java.util.Locale; import static org.cobbzilla.util.daemon.ZillaRuntime.empty; @AllArgsConstructor public enum EntityFieldType { /** a string of characters */ string (new EntityConfigFieldValidator_string()), /** a string containing an email address */ email (new EntityConfigFieldValidator_email()), /** an integer-valued number */ integer (new EntityConfigFieldValidator_integer()), /** a real number */ decimal (new EntityConfigFieldValidator_decimal()), /** an integer-valued monetary amount */ money_integer (null), /** a real-valued monetary amount */ money_decimal (null), /** a boolean value */ flag (new EntityConfigFieldValidator_boolean()), /** a date value */ date (null), /** a date value in the past (before current date) */ date_past (null), /** a date value in the future (or current date) */ date_future (null), /** a field for age */ age (null), /** a 4-digit year field */ year (null), /** a 4-digit year field that starts with the current year and goes into the past */ year_past (null), /** a 4-digit year field that starts with the current year and goes into the future */ year_future (null), /** a 4-digit year and 2-digit month field (YYYY-MM) */ year_and_month (null), /** a 4-digit year and 2-digit month field (YYYY-MM) field that starts with the current year and goes into the past */ year_and_month_past (null), /** a 4-digit year and 2-digit month field (YYYY-MM) field that starts with the current year and goes into the future */ year_and_month_future (null), /** a date or date/time value (null), represented as milliseconds since 1/1/1970 */ epoch_time (new EntityConfigFieldValidator_integer()), /** a time-zone (for example America/New York) */ time_zone (null), /** a locale (for example en_US) */ locale (null), /** an IPv4 address */ ip4 (null), /** an IPv6 address */ ip6 (null), /** a 2-letter US state abbreviation */ us_state (null), /** a US ZIP code */ us_zip (null), /** HTTP URL */ http_url (new EntityConfigFieldValidator_httpUrl()), /** a reference to another EntityConfig instance */ reference (null), /** a base64-encoded PNG image */ base64_png (null), /** an embedded sub-object */ embedded (new EntityConfigFieldValidator_embedded()), /** a US phone number */ us_phone (new EntityConfigFieldValidator_USPhone()); private EntityConfigFieldValidator fieldValidator; /** Jackson-hook to create a new instance based on a string, case-insensitively */ @JsonCreator public static EntityFieldType fromString(String val) { return valueOf(val.toLowerCase()); } public static EntityFieldType safeFromString(String val) { try { return valueOf(val.toLowerCase()); } catch (Exception e) { return null; } } public static boolean isNullable(Field f) { final Column column = f.getAnnotation(Column.class); if (column == null) return !f.getType().isPrimitive(); if (!column.nullable()) return false; if (!empty(column.columnDefinition()) && column.columnDefinition().toUpperCase().contains("NOT NULL")) return false; return true; } public static int safeColumnLength(Field f) { final Integer val = columnLength(f); return val == null ? -1 : val; } public static Integer columnLength(Field f) { final Column column = f.getAnnotation(Column.class); return column == null ? null : column.length(); } public Object toObject(Locale locale, String value) { return fieldValidator == null ? value : fieldValidator.toObject(locale, value); } public ValidationResult validate(Locale locale, Validator validator, EntityFieldConfig fieldConfig, Object value) { return fieldValidator == null ? null : fieldValidator.validate(locale, validator, fieldConfig, value); } }
package com.sothree.slidinguppanel.demo; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.text.Html; import android.text.method.LinkMovementMethod; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Interpolator; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.nineoldandroids.animation.ArgbEvaluator; import com.sothree.slidinguppanel.SlidingUpPanelLayout; import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelSlideListener; import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState; public class DemoActivity extends ActionBarActivity { private static final String TAG = "DemoActivity"; private SlidingUpPanelLayout mLayout; //private LinearLayout mTitleLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_demo); setSupportActionBar((Toolbar)findViewById(R.id.main_toolbar)); mLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout); //mTitleLayout = (LinearLayout) findViewById(R.id.titlebar); //final ArgbEvaluator colorEvaluator = new ArgbEvaluator(); mLayout.setPanelSlideListener(new PanelSlideListener() { @Override public void onPanelSlide(View panel, float slideOffset) { Log.i(TAG, "onPanelSlide, offset " + slideOffset); //mTitleLayout.setBackgroundColor((int) colorEvaluator.evaluate(slideOffset, Color.WHITE, Color.parseColor("#ffff9431"))); } @Override public void onPanelExpanded(View panel) { Log.i(TAG, "onPanelExpanded"); } @Override public void onPanelCollapsed(View panel) { Log.i(TAG, "onPanelCollapsed"); } @Override public void onPanelAnchored(View panel) { Log.i(TAG, "onPanelAnchored"); } @Override public void onPanelHidden(View panel) { Log.i(TAG, "onPanelHidden"); } @Override public void onPanelHiddenExecuted(View panel, Interpolator interpolator, int duration) { Log.i(TAG, "onPanelHiddenExecuted"); } @Override public void onPanelShownExecuted(View panel, Interpolator interpolator, int duration) { Log.i(TAG, "onPanelShownExecuted"); } @Override public void onPanelExpandedStateY(View panel, boolean reached) { Log.i(TAG, "onPanelExpandedStateY" + (reached ? "reached" : "left")); } @Override public void onPanelCollapsedStateY(View panel, boolean reached) { Log.i(TAG, "onPanelCollapsedStateY" + (reached ? "reached" : "left")); LinearLayout titleBar = (LinearLayout) findViewById(R.id.titlebar); if (reached) { titleBar.setBackgroundColor(Color.WHITE); } else { titleBar.setBackgroundColor(Color.parseColor("#ffff9431")); } } @Override public void onPanelLayout(View panel, SlidingUpPanelLayout.PanelState state) { LinearLayout titleBar = (LinearLayout) findViewById(R.id.titlebar); if(state == SlidingUpPanelLayout.PanelState.COLLAPSED){ titleBar.setBackgroundColor(Color.WHITE); } else if (state == SlidingUpPanelLayout.PanelState.EXPANDED || state == SlidingUpPanelLayout.PanelState.ANCHORED){ titleBar.setBackgroundColor(Color.parseColor("#ffff9431")); } } }); TextView t = (TextView) findViewById(R.id.main); t.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mLayout.setPanelState(PanelState.COLLAPSED); } }); t = (TextView) findViewById(R.id.name); t.setText(Html.fromHtml(getString(R.string.hello))); Button f = (Button) findViewById(R.id.follow); f.setText(Html.fromHtml(getString(R.string.follow))); f.setMovementMethod(LinkMovementMethod.getInstance()); f.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("http: startActivity(i); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.demo, menu); MenuItem item = menu.findItem(R.id.action_toggle); if (mLayout != null) { if (mLayout.getPanelState() == PanelState.HIDDEN) { item.setTitle(R.string.action_show); } else { item.setTitle(R.string.action_hide); } } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.action_toggle: { if (mLayout != null) { if (mLayout.getPanelState() != PanelState.HIDDEN) { mLayout.setPanelState(PanelState.HIDDEN); item.setTitle(R.string.action_show); } else { mLayout.setPanelState(PanelState.COLLAPSED); item.setTitle(R.string.action_hide); } } return true; } case R.id.action_anchor: { if (mLayout != null) { if (mLayout.getAnchorPoint() == 1.0f) { mLayout.setAnchorPoint(0.7f); mLayout.setPanelState(PanelState.ANCHORED); item.setTitle(R.string.action_anchor_disable); } else { mLayout.setAnchorPoint(1.0f); mLayout.setPanelState(PanelState.COLLAPSED); item.setTitle(R.string.action_anchor_enable); } } return true; } } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (mLayout != null && (mLayout.getPanelState() == PanelState.EXPANDED || mLayout.getPanelState() == PanelState.ANCHORED)) { mLayout.setPanelState(PanelState.COLLAPSED); } else { super.onBackPressed(); } } }
package nl.mpi.kinnate.export; import java.awt.Component; import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.arbil.ui.GuiHelper; import nl.mpi.kinnate.KinTermSavePanel; import nl.mpi.kinnate.userstorage.KinSessionStorage; public class ExportToR { public void doExport(Component mainFrame, KinTermSavePanel savePanel) { // todo: modify this to use the ArbilWindowManager and update the ArbilWindowManager file select to support save file actions JFileChooser fc = new JFileChooser(); String lastSavedFileString = KinSessionStorage.getSingleInstance().loadString("kinoath.ExportToR"); if (lastSavedFileString != null) { fc.setSelectedFile(new File(lastSavedFileString)); } fc.addChoosableFileFilter(new FileFilter() { @Override public boolean accept(File file) { if (file.isDirectory()) { return true; } return (file.getName().toLowerCase().endsWith(".csv")); } @Override public String getDescription() { return "Data Frame (CSV)"; } }); int returnVal = fc.showSaveDialog(mainFrame); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); PedigreePackageExport packageExport = new PedigreePackageExport(); KinSessionStorage.getSingleInstance().saveString("kinoath.ExportToR", file.getPath()); try { FileWriter fileWriter = new FileWriter(file, false); fileWriter.write(packageExport.createCsvContents(savePanel.getGraphEntities())); fileWriter.close(); // ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("File saved", "Export"); } catch (IOException exception) { ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("Error, could not save file", "Export"); GuiHelper.linorgBugCatcher.logError(exception); } } } // example usage: // install.packages() // pid id momid dadid sex affected // 24 1 0 0 1 1 // 24 2 0 0 2 1 // 24 3 1 2 1 2 // 24 4 0 0 2 2 // 24 5 3 4 1 3 // // dataFrame <- read.table("~/kinship-r.csv",header=T) // library(kinship) // attach(dataFrame) // pedigreeObj <- pedigree(id,momid,dadid,sex, affected) // plot(pedigreeObj) // Suggestion from Dan on R package to look into in detail }
package org.apache.james.nntpserver; import org.apache.avalon.cornerstone.services.connection.ConnectionHandler; import org.apache.avalon.excalibur.pool.Poolable; import org.apache.avalon.framework.activity.Disposable; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.component.ComponentManager; import org.apache.avalon.framework.component.Composable; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.logger.AbstractLogEnabled; import org.apache.avalon.framework.logger.Logger; import org.apache.james.nntpserver.repository.NNTPArticle; import org.apache.james.nntpserver.repository.NNTPGroup; import org.apache.james.nntpserver.repository.NNTPLineReaderImpl; import org.apache.james.nntpserver.repository.NNTPRepository; import org.apache.james.services.UsersRepository; import org.apache.james.services.UsersStore; import org.apache.james.util.InternetPrintWriter; import org.apache.james.util.RFC977DateFormat; import org.apache.james.util.RFC2980DateFormat; import org.apache.james.util.SimplifiedDateFormat; import org.apache.james.util.watchdog.Watchdog; import org.apache.james.util.watchdog.WatchdogTarget; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.text.DateFormat; import java.text.ParseException; import java.util.*; public class NNTPHandler extends AbstractLogEnabled implements ConnectionHandler, Poolable { /** * used to calculate DATE from - see 11.3 */ private static final SimplifiedDateFormat DF_RFC977 = new RFC977DateFormat(); /** * Date format for the DATE keyword - see 11.1.1 */ private static final SimplifiedDateFormat DF_RFC2980 = new RFC2980DateFormat(); /** * The UTC offset for this time zone. */ public static final long UTC_OFFSET = Calendar.getInstance().get(Calendar.ZONE_OFFSET); /** * The text string for the NNTP MODE command. */ private final static String COMMAND_MODE = "MODE"; /** * The text string for the NNTP LIST command. */ private final static String COMMAND_LIST = "LIST"; /** * The text string for the NNTP GROUP command. */ private final static String COMMAND_GROUP = "GROUP"; /** * The text string for the NNTP NEXT command. */ private final static String COMMAND_NEXT = "NEXT"; /** * The text string for the NNTP LAST command. */ private final static String COMMAND_LAST = "LAST"; /** * The text string for the NNTP ARTICLE command. */ private final static String COMMAND_ARTICLE = "ARTICLE"; /** * The text string for the NNTP HEAD command. */ private final static String COMMAND_HEAD = "HEAD"; /** * The text string for the NNTP BODY command. */ private final static String COMMAND_BODY = "BODY"; /** * The text string for the NNTP STAT command. */ private final static String COMMAND_STAT = "STAT"; /** * The text string for the NNTP POST command. */ private final static String COMMAND_POST = "POST"; /** * The text string for the NNTP IHAVE command. */ private final static String COMMAND_IHAVE = "IHAVE"; /** * The text string for the NNTP QUIT command. */ private final static String COMMAND_QUIT = "QUIT"; /** * The text string for the NNTP DATE command. */ private final static String COMMAND_DATE = "DATE"; /** * The text string for the NNTP HELP command. */ private final static String COMMAND_HELP = "HELP"; /** * The text string for the NNTP NEWGROUPS command. */ private final static String COMMAND_NEWGROUPS = "NEWGROUPS"; /** * The text string for the NNTP NEWNEWS command. */ private final static String COMMAND_NEWNEWS = "NEWNEWS"; /** * The text string for the NNTP LISTGROUP command. */ private final static String COMMAND_LISTGROUP = "LISTGROUP"; /** * The text string for the NNTP OVER command. */ private final static String COMMAND_OVER = "OVER"; /** * The text string for the NNTP XOVER command. */ private final static String COMMAND_XOVER = "XOVER"; /** * The text string for the NNTP HDR command. */ private final static String COMMAND_HDR = "HDR"; /** * The text string for the NNTP XHDR command. */ private final static String COMMAND_XHDR = "XHDR"; /** * The text string for the NNTP AUTHINFO command. */ private final static String COMMAND_AUTHINFO = "AUTHINFO"; /** * The text string for the NNTP MODE READER parameter. */ private final static String MODE_TYPE_READER = "READER"; /** * The text string for the NNTP MODE STREAM parameter. */ private final static String MODE_TYPE_STREAM = "STREAM"; /** * The text string for the NNTP AUTHINFO USER parameter. */ private final static String AUTHINFO_PARAM_USER = "USER"; /** * The text string for the NNTP AUTHINFO PASS parameter. */ private final static String AUTHINFO_PARAM_PASS = "PASS"; /** * The TCP/IP socket over which the POP3 interaction * is occurring */ private Socket socket; /** * The reader associated with incoming characters. */ private BufferedReader reader; /** * The writer to which outgoing messages are written. */ private PrintWriter writer; /** * The current newsgroup. */ private NNTPGroup group; /** * The current newsgroup. */ private int currentArticleNumber = -1; /** * Per-service configuration data that applies to all handlers * associated with the service. */ private NNTPHandlerConfigurationData theConfigData; /** * The user id associated with the NNTP dialogue */ private String user; /** * The password associated with the NNTP dialogue */ private String password; /** * Whether the user for this session has already authenticated. * Used to optimize authentication checks */ boolean isAlreadyAuthenticated = false; /** * The watchdog being used by this handler to deal with idle timeouts. */ private Watchdog theWatchdog; /** * The watchdog target that idles out this handler. */ private WatchdogTarget theWatchdogTarget = new NNTPWatchdogTarget(); /** * Set the configuration data for the handler * * @param theData configuration data for the handler */ void setConfigurationData(NNTPHandlerConfigurationData theData) { theConfigData = theData; } /** * Set the Watchdog for use by this handler. * * @param theWatchdog the watchdog */ void setWatchdog(Watchdog theWatchdog) { this.theWatchdog = theWatchdog; } /** * Gets the Watchdog Target that should be used by Watchdogs managing * this connection. * * @return the WatchdogTarget */ WatchdogTarget getWatchdogTarget() { return theWatchdogTarget; } /** * Idle out this connection */ void idleClose() { if (getLogger() != null) { getLogger().error("Remote Manager Connection has idled out."); } try { if (socket != null) { socket.close(); } } catch (Exception e) { // ignored } } /** * @see org.apache.avalon.cornerstone.services.connection.ConnectionHandler#handleConnection(Socket) */ public void handleConnection( Socket connection ) throws IOException { try { this.socket = connection; reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "ASCII"), 1024); writer = new InternetPrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()), 1024), true); } catch (Exception e) { getLogger().error( "Cannot open connection from: " + e.getMessage(), e ); } try { // section 7.1 if ( theConfigData.getNNTPRepository().isReadOnly() ) { StringBuffer respBuffer = new StringBuffer(128) .append("201 ") .append(theConfigData.getHelloName()) .append(" NNTP Service Ready, posting prohibited"); writer.println(respBuffer.toString()); } else { StringBuffer respBuffer = new StringBuffer(128) .append("200 ") .append(theConfigData.getHelloName()) .append(" NNTP Service Ready, posting permitted"); writer.println(respBuffer.toString()); } theWatchdog.start(); while (parseCommand(reader.readLine())) { theWatchdog.reset(); } theWatchdog.stop(); getLogger().info("Connection closed"); } catch (Exception e) { doQUIT(null); getLogger().error( "Exception during connection:" + e.getMessage(), e ); } finally { resetHandler(); } } /** * Resets the handler data to a basic state. */ private void resetHandler() { // Clear the Watchdog if (theWatchdog != null) { if (theWatchdog instanceof Disposable) { ((Disposable)theWatchdog).dispose(); } theWatchdog = null; } // Clear the streams try { if (reader != null) { reader.close(); } } catch (IOException ioe) { getLogger().warn("NNTPHandler: Unexpected exception occurred while closing reader: " + ioe); } finally { reader = null; } if (writer != null) { writer.close(); writer = null; } try { if (socket != null) { socket.close(); } } catch (IOException ioe) { getLogger().warn("NNTPHandler: Unexpected exception occurred while closing socket: " + ioe); } finally { socket = null; } // Clear the selected group, article info group = null; currentArticleNumber = -1; // Clear the authentication info user = null; password = null; isAlreadyAuthenticated = false; // Clear the config data theConfigData = null; } /** * This method parses NNTP commands read off the wire in handleConnection. * Actual processing of the command (possibly including additional back and * forth communication with the client) is delegated to one of a number of * command specific handler methods. The primary purpose of this method is * to parse the raw command string to determine exactly which handler should * be called. It returns true if expecting additional commands, false otherwise. * * @param commandRaw the raw command string passed in over the socket * * @return whether additional commands are expected. */ private boolean parseCommand(String commandRaw) { if (commandRaw == null) { return false; } if (getLogger().isDebugEnabled()) { getLogger().debug("Command received: " + commandRaw); } String command = commandRaw.trim(); String argument = null; int spaceIndex = command.indexOf(" "); if (spaceIndex >= 0) { argument = command.substring(spaceIndex + 1); command = command.substring(0, spaceIndex); } command = command.toUpperCase(Locale.US); if (!isAuthorized(command) ) { writer.println("502 User is not authenticated"); getLogger().debug("Command not allowed."); return true; } if ((command.equals(COMMAND_MODE)) && (argument != null) && argument.toUpperCase(Locale.US).equals(MODE_TYPE_READER)) { doMODEREADER(argument); } else if ( command.equals(COMMAND_LIST)) { doLIST(argument); } else if ( command.equals(COMMAND_GROUP) ) { doGROUP(argument); } else if ( command.equals(COMMAND_NEXT) ) { doNEXT(argument); } else if ( command.equals(COMMAND_LAST) ) { doLAST(argument); } else if ( command.equals(COMMAND_ARTICLE) ) { doARTICLE(argument); } else if ( command.equals(COMMAND_HEAD) ) { doHEAD(argument); } else if ( command.equals(COMMAND_BODY) ) { doBODY(argument); } else if ( command.equals(COMMAND_STAT) ) { doSTAT(argument); } else if ( command.equals(COMMAND_POST) ) { doPOST(argument); } else if ( command.equals(COMMAND_IHAVE) ) { doIHAVE(argument); } else if ( command.equals(COMMAND_QUIT) ) { doQUIT(argument); } else if ( command.equals(COMMAND_DATE) ) { doDATE(argument); } else if ( command.equals(COMMAND_HELP) ) { doHELP(argument); } else if ( command.equals(COMMAND_NEWGROUPS) ) { doNEWGROUPS(argument); } else if ( command.equals(COMMAND_NEWNEWS) ) { doNEWNEWS(argument); } else if ( command.equals(COMMAND_LISTGROUP) ) { doLISTGROUP(argument); } else if ( command.equals(COMMAND_OVER) ) { doOVER(argument); } else if ( command.equals(COMMAND_XOVER) ) { doXOVER(argument); } else if ( command.equals(COMMAND_HDR) ) { doHDR(argument); } else if ( command.equals(COMMAND_XHDR) ) { doXHDR(argument); } else if ( command.equals(COMMAND_AUTHINFO) ) { doAUTHINFO(argument); } else if ( command.equals("PAT") ) { doPAT(argument); } else { doUnknownCommand(command, argument); } return (command.equals(COMMAND_QUIT) == false); } /** * Handles an unrecognized command, logging that. * * @param command the command received from the client * @param argument the argument passed in with the command */ private void doUnknownCommand(String command, String argument) { if (getLogger().isDebugEnabled()) { StringBuffer logBuffer = new StringBuffer(128) .append("Received unknown command ") .append(command) .append(" with argument ") .append(argument); getLogger().debug(logBuffer.toString()); } writer.println("500 Unknown command"); } /** * Implements only the originnal AUTHINFO. * for simple and generic AUTHINFO, 501 is sent back. This is as * per article 3.1.3 of RFC 2980 * * @param argument the argument passed in with the AUTHINFO command */ private void doAUTHINFO(String argument) { String command = null; String value = null; if (argument != null) { int spaceIndex = argument.indexOf(" "); if (spaceIndex >= 0) { command = argument.substring(0, spaceIndex); value = argument.substring(spaceIndex + 1); } } if (command == null) { writer.println("501 Syntax error"); return; } if ( command.equals(AUTHINFO_PARAM_USER) ) { user = value; writer.println("381 More authentication information required"); } else if ( command.equals(AUTHINFO_PARAM_PASS) ) { password = value; if ( isAuthenticated() ) { writer.println("281 Authentication accepted"); } else { writer.println("482 Authentication rejected"); // Clear bad authentication user = null; password = null; } } } /** * Lists the articles posted since the date passed in as * an argument. * * @param argument the argument passed in with the NEWNEWS command. * Should be a date. */ private void doNEWNEWS(String argument) { // see section 11.4 Date theDate = null; try { theDate = getDateFrom(argument); } catch (NNTPException nntpe) { getLogger().error("NEWNEWS had an invalid argument", nntpe); writer.println("501 Syntax error"); return; } Iterator iter = theConfigData.getNNTPRepository().getArticlesSince(theDate); writer.println("230 list of new articles by message-id follows"); while ( iter.hasNext() ) { StringBuffer iterBuffer = new StringBuffer(64) .append("<") .append(((NNTPArticle)iter.next()).getUniqueID()) .append(">"); writer.println(iterBuffer.toString()); } writer.println("."); } /** * Lists the groups added since the date passed in as * an argument. * * @param argument the argument passed in with the NEWNEWS command. * Should be a date. */ private void doNEWGROUPS(String argument) { // see section 11.3 // both draft-ietf-nntpext-base-15.txt and rfc977 have only group names // in response lines, but INN sends // '<group name> <last article> <first article> <posting allowed>' // NOTE: following INN over either document. // doesn't mention the supposed discrepancy. Consider changing code to // be in line with spec. Date theDate = null; try { theDate = getDateFrom(argument); } catch (NNTPException nntpe) { getLogger().error("NEWGROUPS had an invalid argument", nntpe); writer.println("501 Syntax error"); return; } Iterator iter = theConfigData.getNNTPRepository().getGroupsSince(theDate); writer.println("231 list of new newsgroups follows"); while ( iter.hasNext() ) { NNTPGroup currentGroup = (NNTPGroup)iter.next(); StringBuffer iterBuffer = new StringBuffer(128) .append(currentGroup.getName()) .append(" ") .append(currentGroup.getLastArticleNumber()) .append(" ") .append(currentGroup.getFirstArticleNumber()) .append(" ") .append((currentGroup.isPostAllowed()?"y":"n")); writer.println(iterBuffer.toString()); } writer.println("."); } /** * Lists the help text for the service. * * @param argument the argument passed in with the HELP command. */ private void doHELP(String argument) { writer.println("100 Help text follows"); writer.println("."); } /** * Returns the current date according to the news server. * * @param argument the argument passed in with the DATE command */ private void doDATE(String argument) { Date dt = new Date(System.currentTimeMillis()-UTC_OFFSET); String dtStr = DF_RFC2980.format(new Date(dt.getTime() - UTC_OFFSET)); writer.println("111 "+dtStr); } /** * Quits the transaction. * * @param argument the argument passed in with the QUIT command */ private void doQUIT(String argument) { writer.println("205 closing connection"); } /** * Handles the LIST command and its assorted extensions. * * @param argument the argument passed in with the LIST command. */ private void doLIST(String argument) { // see section 9.4.1 String wildmat = "*"; boolean isListNewsgroups = false; String extension = argument; if (argument != null) { int spaceIndex = argument.indexOf(" "); if (spaceIndex >= 0) { wildmat = argument.substring(spaceIndex + 1); extension = argument.substring(0, spaceIndex); } extension = extension.toUpperCase(Locale.US); } if (extension != null) { if (extension.equals("ACTIVE")) { isListNewsgroups = false; } else if (extension.equals("NEWSGROUPS") ) { isListNewsgroups = true; } else if (extension.equals("EXTENSIONS") ) { doLISTEXTENSIONS(); return; } else if (extension.equals("OVERVIEW.FMT") ) { doLISTOVERVIEWFMT(); return; } else if (extension.equals("ACTIVE.TIMES") ) { // not supported - 9.4.2.1, 9.4.3.1, 9.4.4.1 writer.println("503 program error, function not performed"); return; } else if (extension.equals("DISTRIBUTIONS") ) { // not supported - 9.4.2.1, 9.4.3.1, 9.4.4.1 writer.println("503 program error, function not performed"); return; } else if (extension.equals("DISTRIB.PATS") ) { // not supported - 9.4.2.1, 9.4.3.1, 9.4.4.1 writer.println("503 program error, function not performed"); return; } else { writer.println("501 Syntax error"); return; } } Iterator iter = theConfigData.getNNTPRepository().getMatchedGroups(wildmat); writer.println("215 list of newsgroups follows"); while ( iter.hasNext() ) { NNTPGroup theGroup = (NNTPGroup)iter.next(); if (isListNewsgroups) { writer.println(theGroup.getListNewsgroupsFormat()); } else { writer.println(theGroup.getListFormat()); } } writer.println("."); } /** * Informs the server that the client has an article with the specified * message-ID. * * @param id the message id */ private void doIHAVE(String id) { // see section 9.3.2.1 if (!isMessageId(id)) { writer.println("501 command syntax error"); return; } NNTPArticle article = theConfigData.getNNTPRepository().getArticleFromID(id); if ( article != null ) { writer.println("435 article not wanted - do not send it"); } else { writer.println("335 send article to be transferred. End with <CR-LF>.<CR-LF>"); createArticle(); writer.println("235 article received ok"); } } /** * Posts an article to the news server. * * @param argument the argument passed in with the POST command */ private void doPOST(String argument) { // see section 9.3.1.1 if ( argument != null ) { writer.println("501 Syntax error - unexpected parameter"); } writer.println("340 send article to be posted. End with <CR-LF>.<CR-LF>"); createArticle(); writer.println("240 article received ok"); } /** * Executes the STAT command. Sets the current article pointer, * returns article information. * * @param the argument passed in to the STAT command, * which should be an article number or message id. * If no parameter is provided, the current selected * article is used. */ private void doSTAT(String param) { // section 9.2.4 NNTPArticle article = null; if (isMessageId(param)) { article = theConfigData.getNNTPRepository().getArticleFromID(param); if ( article == null ) { writer.println("430 no such article"); return; } else { StringBuffer respBuffer = new StringBuffer(64) .append("223 0 ") .append(param); writer.println(respBuffer.toString()); } } else { int newArticleNumber = currentArticleNumber; if ( group == null ) { writer.println("412 no newsgroup selected"); return; } else { if ( param == null ) { if ( currentArticleNumber < 0 ) { writer.println("420 no current article selected"); return; } else { article = group.getArticle(currentArticleNumber); } } else { newArticleNumber = Integer.parseInt(param); article = group.getArticle(newArticleNumber); } if ( article == null ) { writer.println("423 no such article number in this group"); return; } else { currentArticleNumber = newArticleNumber; String articleID = article.getUniqueID(); if (articleID == null) { articleID = "<0>"; } StringBuffer respBuffer = new StringBuffer(128) .append("223 ") .append(article.getArticleNumber()) .append(" ") .append(articleID); writer.println(respBuffer.toString()); } } } } /** * Executes the BODY command. Sets the current article pointer, * returns article information and body. * * @param the argument passed in to the BODY command, * which should be an article number or message id. * If no parameter is provided, the current selected * article is used. */ private void doBODY(String param) { // section 9.2.3 NNTPArticle article = null; if (isMessageId(param)) { article = theConfigData.getNNTPRepository().getArticleFromID(param); if ( article == null ) { writer.println("430 no such article"); return; } else { StringBuffer respBuffer = new StringBuffer(64) .append("222 0 ") .append(param); writer.println(respBuffer.toString()); } } else { int newArticleNumber = currentArticleNumber; if ( group == null ) { writer.println("412 no newsgroup selected"); return; } else { if ( param == null ) { if ( currentArticleNumber < 0 ) { writer.println("420 no current article selected"); return; } else { article = group.getArticle(currentArticleNumber); } } else { newArticleNumber = Integer.parseInt(param); article = group.getArticle(newArticleNumber); } if ( article == null ) { writer.println("423 no such article number in this group"); } else { currentArticleNumber = newArticleNumber; String articleID = article.getUniqueID(); if (articleID == null) { articleID = "<0>"; } StringBuffer respBuffer = new StringBuffer(128) .append("222 ") .append(article.getArticleNumber()) .append(" ") .append(articleID); writer.println(respBuffer.toString()); } } } if (article != null) { article.writeBody(writer); writer.println("."); } } /** * Executes the HEAD command. Sets the current article pointer, * returns article information and headers. * * @param the argument passed in to the HEAD command, * which should be an article number or message id. * If no parameter is provided, the current selected * article is used. */ private void doHEAD(String param) { // section 9.2.2 NNTPArticle article = null; if (isMessageId(param)) { article = theConfigData.getNNTPRepository().getArticleFromID(param); if ( article == null ) { writer.println("430 no such article"); return; } else { StringBuffer respBuffer = new StringBuffer(64) .append("221 0 ") .append(param); writer.println(respBuffer.toString()); } } else { int newArticleNumber = currentArticleNumber; if ( group == null ) { writer.println("412 no newsgroup selected"); return; } else { if ( param == null ) { if ( currentArticleNumber < 0 ) { writer.println("420 no current article selected"); return; } else { article = group.getArticle(currentArticleNumber); } } else { newArticleNumber = Integer.parseInt(param); article = group.getArticle(newArticleNumber); } if ( article == null ) { writer.println("423 no such article number in this group"); } else { currentArticleNumber = newArticleNumber; String articleID = article.getUniqueID(); if (articleID == null) { articleID = "<0>"; } StringBuffer respBuffer = new StringBuffer(128) .append("221 ") .append(article.getArticleNumber()) .append(" ") .append(articleID); writer.println(respBuffer.toString()); } } } if (article != null) { article.writeHead(writer); writer.println("."); } } /** * Executes the ARTICLE command. Sets the current article pointer, * returns article information and contents. * * @param the argument passed in to the ARTICLE command, * which should be an article number or message id. * If no parameter is provided, the current selected * article is used. */ private void doARTICLE(String param) { // section 9.2.1 NNTPArticle article = null; if (isMessageId(param)) { article = theConfigData.getNNTPRepository().getArticleFromID(param); if ( article == null ) { writer.println("430 no such article"); return; } else { StringBuffer respBuffer = new StringBuffer(64) .append("220 0 ") .append(param); writer.println(respBuffer.toString()); } } else { int newArticleNumber = currentArticleNumber; if ( group == null ) { writer.println("412 no newsgroup selected"); return; } else { if ( param == null ) { if ( currentArticleNumber < 0 ) { writer.println("420 no current article selected"); return; } else { article = group.getArticle(currentArticleNumber); } } else { newArticleNumber = Integer.parseInt(param); article = group.getArticle(newArticleNumber); } if ( article == null ) { writer.println("423 no such article number in this group"); } else { currentArticleNumber = newArticleNumber; String articleID = article.getUniqueID(); if (articleID == null) { articleID = "<0>"; } StringBuffer respBuffer = new StringBuffer(128) .append("220 ") .append(article.getArticleNumber()) .append(" ") .append(articleID); writer.println(respBuffer.toString()); } } } if (article != null) { article.writeArticle(writer); writer.println("."); } } /** * Advances the current article pointer to the next article in the group. * * @param argument the argument passed in with the NEXT command */ private void doNEXT(String argument) { // section 9.1.1.3.1 if ( argument != null ) { writer.println("501 Syntax error - unexpected parameter"); } else if ( group == null ) { writer.println("412 no newsgroup selected"); } else if ( currentArticleNumber < 0 ) { writer.println("420 no current article has been selected"); } else if ( currentArticleNumber >= group.getLastArticleNumber() ) { writer.println("421 no next article in this group"); } else { currentArticleNumber++; NNTPArticle article = group.getArticle(currentArticleNumber); StringBuffer respBuffer = new StringBuffer(64) .append("223 ") .append(article.getArticleNumber()) .append(" ") .append(article.getUniqueID()); writer.println(respBuffer.toString()); } } /** * Moves the currently selected article pointer to the article * previous to the currently selected article in the selected group. * * @param argument the argument passed in with the LAST command */ private void doLAST(String argument) { // section 9.1.1.2.1 if ( argument != null ) { writer.println("501 Syntax error - unexpected parameter"); } else if ( group == null ) { writer.println("412 no newsgroup selected"); } else if ( currentArticleNumber < 0 ) { writer.println("420 no current article has been selected"); } else if ( currentArticleNumber <= group.getFirstArticleNumber() ) { writer.println("422 no previous article in this group"); } else { currentArticleNumber NNTPArticle article = group.getArticle(currentArticleNumber); StringBuffer respBuffer = new StringBuffer(64) .append("223 ") .append(article.getArticleNumber()) .append(" ") .append(article.getUniqueID()); writer.println(respBuffer.toString()); } } /** * Selects a group to be the current newsgroup. * * @param group the name of the group being selected. */ private void doGROUP(String groupName) { if (groupName == null) { writer.println("501 Syntax error - missing required parameter"); return; } NNTPGroup newGroup = theConfigData.getNNTPRepository().getGroup(groupName); // section 9.1.1.1 if ( newGroup == null ) { writer.println("411 no such newsgroup"); } else { group = newGroup; // if the number of articles in group == 0 // then the server may return this information in 3 ways, // The clients must honor all those 3 ways. // our response is: // highWaterMark == lowWaterMark and number of articles == 0 int articleCount = group.getNumberOfArticles(); int lowWaterMark = group.getFirstArticleNumber(); int highWaterMark = group.getLastArticleNumber(); // Set the current article pointer. If no // articles are in the group, the current article // pointer should be explicitly unset. if (articleCount != 0) { currentArticleNumber = lowWaterMark; } else { currentArticleNumber = -1; } StringBuffer respBuffer = new StringBuffer(128) .append("211 ") .append(articleCount) .append(" ") .append(lowWaterMark) .append(" ") .append(highWaterMark) .append(" ") .append(group.getName()) .append(" group selected"); writer.println(respBuffer.toString()); } } /** * Lists the extensions supported by this news server. */ private void doLISTEXTENSIONS() { // 8.1.1 writer.println("202 Extensions supported:"); writer.println("LISTGROUP"); writer.println("AUTHINFO"); writer.println("OVER"); writer.println("XOVER"); writer.println("HDR"); writer.println("XHDR"); writer.println("."); } /** * Informs the server that the client is a newsreader. * * @param argument the argument passed in with the MODE READER command */ private void doMODEREADER(String argument) { if ( argument != null ) { writer.println("501 Syntax error - unexpected parameter"); } writer.println(theConfigData.getNNTPRepository().isReadOnly() ? "201 Posting Not Permitted" : "200 Posting Permitted"); } /** * Gets a listing of article numbers in specified group name * or in the already selected group if the groupName is null. * * @param groupName the name of the group to list */ private void doLISTGROUP(String groupName) { // 9.5.1.1.1 if (groupName==null) { if ( group == null) { writer.println("412 no news group currently selected"); return; } } else { group = theConfigData.getNNTPRepository().getGroup(groupName); if ( group == null ) { writer.println("411 no such newsgroup"); return; } } if ( group != null ) { this.group = group; // Set the current article pointer. If no // articles are in the group, the current article // pointer should be explicitly unset. if (group.getNumberOfArticles() > 0) { currentArticleNumber = group.getFirstArticleNumber(); } else { currentArticleNumber = -1; } writer.println("211 list of article numbers follow"); Iterator iter = group.getArticles(); while (iter.hasNext()) { NNTPArticle article = (NNTPArticle)iter.next(); writer.println(article.getArticleNumber()); } writer.println("."); } } /** * Handles the LIST OVERVIEW.FMT command. Not supported. */ private void doLISTOVERVIEWFMT() { // 9.5.3.1.1 writer.println("215 Information follows"); String[] overviewHeaders = theConfigData.getNNTPRepository().getOverviewFormat(); for (int i = 0; i < overviewHeaders.length; i++) { writer.println(overviewHeaders[i]); } writer.println("."); } /** * Handles the PAT command. Not supported. * * @param argument the argument passed in with the PAT command */ private void doPAT(String argument) { // 9.5.3.1.1 in draft-12 writer.println("500 Command not recognized"); } /** * Get the values of the headers for the selected newsgroup, * with an optional range modifier. * * @param argument the argument passed in with the XHDR command. */ private void doXHDR(String argument) { doHDR(argument); } /** * Get the values of the headers for the selected newsgroup, * with an optional range modifier. * * @param argument the argument passed in with the HDR command. */ private void doHDR(String argument) { // 9.5.3 if (argument == null) { writer.println("501 Syntax error - missing required parameter"); } String hdr = argument; String range = null; int spaceIndex = hdr.indexOf(" "); if (spaceIndex >= 0 ) { range = hdr.substring(spaceIndex + 1); hdr = hdr.substring(0, spaceIndex); } if (group == null ) { writer.println("412 No news group currently selected."); return; } if ((range == null) && (currentArticleNumber < 0)) { writer.println("420 No current article selected"); return; } NNTPArticle[] article = getRange(range); if ( article == null ) { writer.println("412 no newsgroup selected"); } else if ( article.length == 0 ) { writer.println("430 no such article"); } else { writer.println("221 Header follows"); for ( int i = 0 ; i < article.length ; i++ ) { String val = article[i].getHeader(hdr); if ( val == null ) { val = ""; } StringBuffer hdrBuffer = new StringBuffer(128) .append(article[i].getArticleNumber()) .append(" ") .append(val); writer.println(hdrBuffer.toString()); } writer.println("."); } } /** * Returns information from the overview database regarding the * current article, or a range of articles. * * @param range the optional article range. */ private void doXOVER(String range) { doOVER(range); } /** * Returns information from the overview database regarding the * current article, or a range of articles. * * @param range the optional article range. */ private void doOVER(String range) { // 9.5.2.2.1 if ( group == null ) { writer.println("412 No newsgroup selected"); return; } if ((range == null) && (currentArticleNumber < 0)) { writer.println("420 No current article selected"); return; } NNTPArticle[] article = getRange(range); if ( article.length == 0 ) { writer.println("420 No article(s) selected"); } else { writer.println("224 Overview information follows"); for ( int i = 0 ; i < article.length ; i++ ) { article[i].writeOverview(writer); if (i % 100 == 0) { // Reset the watchdog ever hundred headers or so // to ensure the connection doesn't timeout for slow // clients theWatchdog.reset(); } } writer.println("."); } } /** * Handles the transaction for getting the article data. */ private void createArticle() { theConfigData.getNNTPRepository().createArticle(new NNTPLineReaderImpl(reader)); } /** * Returns the date from @param input. * The input tokens are assumed to be in format date time [GMT|UTC] . * 'date' is in format [XX]YYMMDD. 'time' is in format 'HHMMSS' * NOTE: This routine could do with some format checks. * * @param argument the date string */ private Date getDateFrom(String argument) { if (argument == null) { throw new NNTPException("Date argument was absent."); } StringTokenizer tok = new StringTokenizer(argument, " "); if (tok.countTokens() < 2) { throw new NNTPException("Date argument was ill-formed."); } String date = tok.nextToken(); String time = tok.nextToken(); boolean utc = ( tok.hasMoreTokens() ); Date d = new Date(); try { StringBuffer dateStringBuffer = new StringBuffer(64) .append(date) .append(" ") .append(time); Date dt = DF_RFC977.parse(dateStringBuffer.toString()); if ( utc ) { dt = new Date(dt.getTime()+UTC_OFFSET); } return dt; } catch ( ParseException pe ) { StringBuffer exceptionBuffer = new StringBuffer(128) .append("Date extraction failed: ") .append(date) .append(",") .append(time) .append(",") .append(utc); throw new NNTPException(exceptionBuffer.toString()); } } /** * Returns the list of articles that match the range. * * A precondition of this method is that the selected * group be non-null. The current article pointer must * be valid if no range is explicitly provided. * * @return null indicates insufficient information to * fetch the list of articles */ private NNTPArticle[] getRange(String range) { // check for msg id if ( isMessageId(range)) { NNTPArticle article = theConfigData.getNNTPRepository().getArticleFromID(range); return ( article == null ) ? new NNTPArticle[0] : new NNTPArticle[] { article }; } if ( range == null ) { range = "" + currentArticleNumber; } int start = -1; int end = -1; int idx = range.indexOf('-'); if ( idx == -1 ) { start = Integer.parseInt(range); end = start; } else { start = Integer.parseInt(range.substring(0,idx)); if ( (idx + 1) == range.length() ) { end = group.getLastArticleNumber(); } else { end = Integer.parseInt(range.substring(idx + 1)); } } List list = new ArrayList(); for ( int i = start ; i <= end ; i++ ) { NNTPArticle article = group.getArticle(i); if ( article != null ) { list.add(article); } } return (NNTPArticle[])list.toArray(new NNTPArticle[0]); } /** * Return whether the user associated with the connection (possibly no * user) is authorized to execute the command. * * @param the command being tested * @return whether the command is authorized */ private boolean isAuthorized(String command) { boolean allowed = isAlreadyAuthenticated || isAuthenticated(); if (allowed) { return true; } // some commands are authorized, even if the user is not authenticated allowed = allowed || command.equals("AUTHINFO"); allowed = allowed || command.equals("MODE"); allowed = allowed || command.equals("QUIT"); return allowed; } /** * Return whether the connection has been authenticated. * * @return whether the connection has been authenticated. */ private boolean isAuthenticated() { if ( theConfigData.isAuthRequired() ) { if ((user != null) && (password != null) && (theConfigData.getUsersRepository() != null)) { return theConfigData.getUsersRepository().test(user,password); } else { return false; } } else { return true; } } /** * Tests a string to see whether it is formatted as a message * ID. * * @param testString the string to test * * @return whether the string is a candidate message ID */ private static boolean isMessageId(String testString) { if ((testString != null) && (testString.startsWith("<")) && (testString.endsWith(">"))) { return true; } else { return false; } } /** * A private inner class which serves as an adaptor * between the WatchdogTarget interface and this * handler class. */ private class NNTPWatchdogTarget implements WatchdogTarget { /** * @see org.apache.james.util.watchdog.WatchdogTarget#execute() */ public void execute() { NNTPHandler.this.idleClose(); } } }
package com.intellij.openapi.wm.impl; import com.intellij.Patches; import com.intellij.ide.DataManager; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.impl.DataManagerImpl; import com.intellij.ide.ui.UISettings; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.util.NamedJDOMExternalizable; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.ex.StatusBarEx; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.util.Alarm; import com.sun.jna.examples.WindowUtils; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Set; /** * @author Anton Katilin * @author Vladimir Kondratyev */ public final class WindowManagerImpl extends WindowManagerEx implements ApplicationComponent, NamedJDOMExternalizable { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.wm.impl.WindowManagerImpl"); private static boolean ourAlphaModeLibraryLoaded; @NonNls private static final String FOCUSED_WINDOW_PROPERTY_NAME = "focusedWindow"; @NonNls private static final String X_ATTR = "x"; @NonNls private static final String FRAME_ELEMENT = "frame"; @NonNls private static final String Y_ATTR = "y"; @NonNls private static final String WIDTH_ATTR = "width"; @NonNls private static final String HEIGHT_ATTR = "height"; @NonNls private static final String EXTENDED_STATE_ATTR = "extended-state"; private Boolean myAlphaModeSupported = null; static { initialize(); } @SuppressWarnings({"HardCodedStringLiteral"}) private static void initialize() { try { System.loadLibrary("jawt"); ourAlphaModeLibraryLoaded = true; } catch (Throwable exc) { ourAlphaModeLibraryLoaded = false; } } /** * Union of bounds of all available default screen devices. */ private Rectangle myScreenBounds; private final CommandProcessor myCommandProcessor; private final WindowWatcher myWindowWatcher; /** * That is the default layout. */ private DesktopLayout myLayout; private final HashMap<Project, IdeFrameImpl> myProject2Frame; private final HashMap<Project, Set<JDialog>> myDialogsToDispose; /** * This members is needed to read frame's bounds from XML. * <code>myFrameBounds</code> can be <code>null</code>. */ private Rectangle myFrameBounds; private int myFrameExtendedState; private WindowAdapter myActivationListener; private final ApplicationInfoEx myApplicationInfoEx; private final DataManager myDataManager; private final ActionManager myActionManager; private final UISettings myUiSettings; private final KeymapManager myKeymapManager; /** * invoked by reflection * @param dataManager * @param applicationInfoEx * @param actionManager * @param uiSettings * @param keymapManager */ public WindowManagerImpl(DataManager dataManager, ApplicationInfoEx applicationInfoEx, ActionManager actionManager, UISettings uiSettings, KeymapManager keymapManager) { myApplicationInfoEx = applicationInfoEx; myDataManager = dataManager; myActionManager = actionManager; myUiSettings = uiSettings; myKeymapManager = keymapManager; if (myDataManager instanceof DataManagerImpl) { ((DataManagerImpl)myDataManager).setWindowManager(this); } myCommandProcessor = new CommandProcessor(); myWindowWatcher = new WindowWatcher(); final KeyboardFocusManager keyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); keyboardFocusManager.addPropertyChangeListener(FOCUSED_WINDOW_PROPERTY_NAME, myWindowWatcher); if (Patches.SUN_BUG_ID_4218084) { keyboardFocusManager.addPropertyChangeListener(FOCUSED_WINDOW_PROPERTY_NAME, new SUN_BUG_ID_4218084_Patch()); } myLayout = new DesktopLayout(); myProject2Frame = new HashMap<Project, IdeFrameImpl>(); myDialogsToDispose = new HashMap<Project, Set<JDialog>>(); myFrameExtendedState = Frame.NORMAL; // Calculate screen bounds. myScreenBounds = new Rectangle(); if (!ApplicationManager.getApplication().isHeadlessEnvironment()) { final GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); final GraphicsDevice[] devices = env.getScreenDevices(); for (final GraphicsDevice device : devices) { myScreenBounds = myScreenBounds.union(device.getDefaultConfiguration().getBounds()); } } myActivationListener = new WindowAdapter() { public void windowActivated(WindowEvent e) { Window activeWindow = e.getWindow(); if (activeWindow instanceof IdeFrameImpl) { // must be proceedDialogDisposalQueue(((IdeFrameImpl)activeWindow).getProject()); } } }; } public void showFrame() { IdeEventQueue.getInstance().setWindowManager(this); final IdeFrameImpl frame = new IdeFrameImpl(myApplicationInfoEx, myActionManager, myUiSettings, myDataManager, myKeymapManager, ApplicationManager.getApplication()); myProject2Frame.put(null, frame); if (myFrameBounds != null) { frame.setBounds(myFrameBounds); } frame.setVisible(true); frame.setExtendedState(myFrameExtendedState); } public IdeFrameImpl[] getAllFrames() { final Collection<IdeFrameImpl> ideFrames = myProject2Frame.values(); return ideFrames.toArray(new IdeFrameImpl[ideFrames.size()]); } public final Rectangle getScreenBounds() { return myScreenBounds; } public final boolean isInsideScreenBounds(final int x, final int y, final int width) { return x >= myScreenBounds.x + 50 - width && y >= myScreenBounds.y - 50 && x <= myScreenBounds.x + myScreenBounds.width - 50 && y <= myScreenBounds.y + myScreenBounds.height - 50; } public final boolean isInsideScreenBounds(final int x, final int y) { return myScreenBounds.contains(x, y); } public final boolean isAlphaModeSupported() { if (myAlphaModeSupported == null) { myAlphaModeSupported = calcAlphaModelSupported(); } return myAlphaModeSupported.booleanValue(); } private static boolean calcAlphaModelSupported() { try { return WindowUtils.isWindowAlphaSupported(); } catch (Throwable e) { return false; } } public final void setAlphaModeRatio(final Window window, final float ratio) { if (!window.isDisplayable() || !window.isShowing()) { throw new IllegalArgumentException("window must be displayable and showing. window=" + window); } if (ratio < 0.0f || ratio > 1.0f) { throw new IllegalArgumentException("ratio must be in [0..1] range. ratio=" + ratio); } if (!isAlphaModeSupported() || !isAlphaModeEnabled(window)) { return; } setAlphaMode(window, ratio); } private void setAlphaMode(Window window, float ratio) { WindowUtils.setWindowAlpha(window, 1.0f - ratio); } public void setWindowMask(final Window window, final Shape mask) { WindowUtils.setWindowMask(window, mask); } public void resetWindow(final Window window) { WindowUtils.setWindowMask(window, (Shape)null); setAlphaMode(window, 0f); } public final boolean isAlphaModeEnabled(final Window window) { if (!window.isDisplayable() || !window.isShowing()) { throw new IllegalArgumentException("window must be displayable and showing. window=" + window); } return isAlphaModeSupported(); } public final void setAlphaModeEnabled(final Window window, final boolean state) { if (!window.isDisplayable() || !window.isShowing()) { throw new IllegalArgumentException("window must be displayable and showing. window=" + window); } } public void hideDialog(JDialog dialog, Project project) { if (project == null) { dialog.dispose(); } else { IdeFrameImpl frame = getFrame(project); if (frame.isActive()) { dialog.dispose(); } else { queueForDisposal(dialog, project); dialog.setVisible(false); } } } public final void disposeComponent() {} public final void initComponent() { } public final void doNotSuggestAsParent(final Window window) { myWindowWatcher.doNotSuggestAsParent(window); } public final void dispatchComponentEvent(final ComponentEvent e) { myWindowWatcher.dispatchComponentEvent(e); } public final Window suggestParentWindow(final Project project) { return myWindowWatcher.suggestParentWindow(project); } public final StatusBar getStatusBar(final Project project) { if (!myProject2Frame.containsKey(project)) { return null; } final IdeFrameImpl frame = getFrame(project); LOG.assertTrue(frame != null); return frame.getStatusBar(); } public IdeFrame findFrameFor(@Nullable final Project project) { IdeFrameImpl frame = null; if (project != null) { frame = getFrame(project); } else { Container eachParent = getMostRecentFocusedWindow(); while(eachParent != null) { if (eachParent instanceof IdeFrameImpl) { frame = (IdeFrameImpl)eachParent; break; } eachParent = eachParent.getParent(); } if (frame == null) { frame = tryToFindTheOnlyFrame(); } } LOG.assertTrue(frame != null, "Project: " + project); return frame; } private IdeFrameImpl tryToFindTheOnlyFrame() { IdeFrameImpl candidate = null; final Frame[] all = Frame.getFrames(); for (Frame each : all) { if (each instanceof IdeFrameImpl) { if (candidate == null) { candidate = (IdeFrameImpl)each; } else { candidate = null; break; } } } return candidate; } public final IdeFrameImpl getFrame(final Project project) { // no assert! otherwise WindowWatcher.suggestParentWindow fails for default project //LOG.assertTrue(myProject2Frame.containsKey(project)); return myProject2Frame.get(project); } public IdeFrame getIdeFrame(final Project project) { return getFrame(project); } public final IdeFrameImpl allocateFrame(final Project project) { LOG.assertTrue(!myProject2Frame.containsKey(project)); final IdeFrameImpl frame; if (myProject2Frame.containsKey(null)) { frame = myProject2Frame.get(null); myProject2Frame.remove(null); myProject2Frame.put(project, frame); frame.setProject(project); } else { frame = new IdeFrameImpl((ApplicationInfoEx)ApplicationInfo.getInstance(), ActionManager.getInstance(), UISettings.getInstance(), DataManager.getInstance(), KeymapManager.getInstance(), ApplicationManager.getApplication()); if (myFrameBounds != null) { frame.setBounds(myFrameBounds); } frame.setProject(project); myProject2Frame.put(project, frame); frame.setVisible(true); } frame.addWindowListener(myActivationListener); return frame; } private void proceedDialogDisposalQueue(Project project) { Set<JDialog> dialogs = myDialogsToDispose.get(project); if (dialogs == null) return; for (JDialog dialog : dialogs) { dialog.dispose(); } myDialogsToDispose.put(project, null); } private void queueForDisposal(JDialog dialog, Project project) { Set<JDialog> dialogs = myDialogsToDispose.get(project); if (dialogs == null) { dialogs = new HashSet<JDialog>(); myDialogsToDispose.put(project, dialogs); } dialogs.add(dialog); } public final void releaseFrame(final IdeFrameImpl frame) { final Project project = frame.getProject(); LOG.assertTrue(project != null); frame.removeWindowListener(myActivationListener); proceedDialogDisposalQueue(project); frame.setProject(null); frame.setTitle(null); frame.setFileTitle(null); final StatusBarEx statusBar = frame.getStatusBar(); statusBar.setStatus(null); statusBar.setWriteStatus(false); statusBar.setPosition(null); statusBar.updateEditorHighlightingStatus(true); myProject2Frame.remove(project); if (myProject2Frame.isEmpty()) { myProject2Frame.put(null, frame); } else { frame.dispose(); } } public final Window getMostRecentFocusedWindow() { return myWindowWatcher.getFocusedWindow(); } public final Component getFocusedComponent(@NotNull final Window window) { return myWindowWatcher.getFocusedComponent(window); } public final Component getFocusedComponent(final Project project) { return myWindowWatcher.getFocusedComponent(project); } /** * Private part */ public final CommandProcessor getCommandProcessor() { return myCommandProcessor; } public final String getExternalFileName() { return "window.manager"; } public final void readExternal(final Element element) { final Element frameElement = element.getChild(FRAME_ELEMENT); if (frameElement != null) { myFrameBounds = loadFrameBounds(frameElement); try { myFrameExtendedState = Integer.parseInt(frameElement.getAttributeValue(EXTENDED_STATE_ATTR)); if ((myFrameExtendedState & Frame.ICONIFIED) > 0) { myFrameExtendedState = Frame.NORMAL; } } catch (NumberFormatException ignored) { myFrameExtendedState = Frame.NORMAL; } } final Element desktopElement = element.getChild(DesktopLayout.TAG); if (desktopElement != null) { myLayout.readExternal(desktopElement); } } private static Rectangle loadFrameBounds(final Element frameElement) { Rectangle bounds = new Rectangle(); try { bounds.x = Integer.parseInt(frameElement.getAttributeValue(X_ATTR)); } catch (NumberFormatException ignored) { return null; } try { bounds.y = Integer.parseInt(frameElement.getAttributeValue(Y_ATTR)); } catch (NumberFormatException ignored) { return null; } try { bounds.width = Integer.parseInt(frameElement.getAttributeValue(WIDTH_ATTR)); } catch (NumberFormatException ignored) { return null; } try { bounds.height = Integer.parseInt(frameElement.getAttributeValue(HEIGHT_ATTR)); } catch (NumberFormatException ignored) { return null; } return bounds; } public final void writeExternal(final Element element) { // Save frame bounds final Element frameElement = new Element(FRAME_ELEMENT); element.addContent(frameElement); final Project[] projects = ProjectManager.getInstance().getOpenProjects(); final Project project; if (projects.length > 0) { project = projects[projects.length - 1]; } else { project = null; } final IdeFrameImpl frame = getFrame(project); if (frame != null) { final Rectangle rectangle = frame.getBounds(); frameElement.setAttribute(X_ATTR, Integer.toString(rectangle.x)); frameElement.setAttribute(Y_ATTR, Integer.toString(rectangle.y)); frameElement.setAttribute(WIDTH_ATTR, Integer.toString(rectangle.width)); frameElement.setAttribute(HEIGHT_ATTR, Integer.toString(rectangle.height)); frameElement.setAttribute(EXTENDED_STATE_ATTR, Integer.toString(frame.getExtendedState())); // Save default layout final Element layoutElement = new Element(DesktopLayout.TAG); element.addContent(layoutElement); myLayout.writeExternal(layoutElement); } } public final DesktopLayout getLayout() { return myLayout; } public final void setLayout(final DesktopLayout layout) { myLayout.copyFrom(layout); } @NotNull public final String getComponentName() { return "WindowManager"; } /** * We cannot clear selected menu path just by changing of focused window. Under Windows LAF * focused window changes sporadically when user clickes on menu item or submenu. The problem * is that all popups under Windows LAF always has native window ancestor. This window isn't * focusable but by mouse click focused window changes in this manner: * InitialFocusedWindow->null * null->InitialFocusedWindow * To fix this problem we use alarm to accumulate such focus events. */ private static final class SUN_BUG_ID_4218084_Patch implements PropertyChangeListener { private final Alarm myAlarm; private Window myInitialFocusedWindow; private Window myLastFocusedWindow; private final Runnable myClearSelectedPathRunnable; public SUN_BUG_ID_4218084_Patch() { myAlarm = new Alarm(); myClearSelectedPathRunnable = new Runnable() { public void run() { if (myInitialFocusedWindow != myLastFocusedWindow) { MenuSelectionManager.defaultManager().clearSelectedPath(); } } }; } public void propertyChange(final PropertyChangeEvent e) { if (myAlarm.getActiveRequestCount() == 0) { myInitialFocusedWindow = (Window)e.getOldValue(); final MenuElement[] selectedPath = MenuSelectionManager.defaultManager().getSelectedPath(); if (selectedPath.length == 0) { // there is no visible popup return; } Component firstComponent = null; for (final MenuElement menuElement : selectedPath) { final Component component = menuElement.getComponent(); if (component instanceof JMenuBar) { firstComponent = component; break; } else if (component instanceof JPopupMenu) { firstComponent = ((JPopupMenu) component).getInvoker(); break; } } if (firstComponent == null) { return; } final Window window = SwingUtilities.getWindowAncestor(firstComponent); if (window != myInitialFocusedWindow) { // focused window doesn't have popup return; } } myLastFocusedWindow = (Window)e.getNewValue(); myAlarm.cancelAllRequests(); myAlarm.addRequest(myClearSelectedPathRunnable, 150); } } public WindowWatcher getWindowWatcher() { return myWindowWatcher; } }
package com.artursworld.reactiontest.view.user; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.InputType; import android.view.View; import android.widget.EditText; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.artursworld.reactiontest.R; import com.artursworld.reactiontest.controller.helper.Gender; import com.artursworld.reactiontest.controller.util.UtilsRG; import com.artursworld.reactiontest.model.entity.InOpEvent; import com.artursworld.reactiontest.model.entity.MedicalUser; import com.artursworld.reactiontest.model.persistence.manager.InOpEventManager; import com.artursworld.reactiontest.model.persistence.manager.MedicalUserManager; import com.artursworld.reactiontest.view.StartMenu; import com.artursworld.reactiontest.view.dialogs.DialogHelper; import com.artursworld.reactiontest.view.games.StartGameSettings; import com.rengwuxian.materialedittext.MaterialEditText; import com.sdsmdg.tastytoast.TastyToast; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Displays view to add a new user */ public class AddMedicalUser extends AppCompatActivity { private MedicalUserManager medUserDb; private Activity activity; private int selectedGenderIndex = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_medical_user); } @Override protected void onResume() { super.onResume(); activity = this; new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... unusedParams) { medUserDb = new MedicalUserManager(activity); return null; } }.execute(); addBirthDatePicker(); addGenderSingleChoiceDialog(); } /** * Initializes birthDate picker and sets on focus listener */ private void addBirthDatePicker() { final EditText editText = (EditText) findViewById(R.id.add_medical_user_birthdate_txt); editText.setInputType(InputType.TYPE_NULL); DialogHelper.onFocusOpenDatePicker(activity, editText); } /** * Opens gender choise dialog on focus edit text */ private void addGenderSingleChoiceDialog() { final EditText genderEditText = (EditText) findViewById(R.id.start_game_settings_operation_issue_selector); genderEditText.setInputType(InputType.TYPE_NULL); final String titleGender = getResources().getString(R.string.gender); final CharSequence[] maleOrFemaleList = {getResources().getString(R.string.male), getResources().getString(R.string.female)}; Runnable task = new Runnable() { @Override public void run() { AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(activity); singleChoiceDialog.setTitle(titleGender); singleChoiceDialog.setSingleChoiceItems(maleOrFemaleList, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int clickedPosition) { selectedGenderIndex = clickedPosition; String value = maleOrFemaleList[clickedPosition].toString(); genderEditText.setText(value); UtilsRG.info("checked gender at position: " +clickedPosition); dialog.cancel(); } }); AlertDialog alert_dialog = singleChoiceDialog.create(); alert_dialog.show(); alert_dialog.getListView().setItemChecked(selectedGenderIndex, true); } }; DialogHelper.onFocusOpenSingleChoiceDialog(activity, genderEditText, titleGender, maleOrFemaleList, task); } /** * Adds user via database on button clicK and switch back to user management view */ public void onAddUserButtonClick(View view) { String medicalId = ((MaterialEditText) findViewById(R.id.add_medical_user_medico_id)).getText().toString(); boolean isEmptyId = medicalId.trim().equals(""); double bmi = 0; Date birthdate = null; if (!isEmptyId) { String birthdateString = ((EditText) findViewById(R.id.add_medical_user_birthdate_txt)).getText().toString(); try { birthdate = UtilsRG.germanDateFormat.parse(birthdateString); EditText bmiText = (EditText) findViewById(R.id.add_medical_user_bmi_txt); if (bmiText != null) { if (bmiText.getText() != null) if (!bmiText.getText().toString().trim().equals("")) bmi = Double.parseDouble(bmiText.getText().toString().trim()); } } catch (ParseException e) { UtilsRG.error("Could not parse date input to date: " + e.getLocalizedMessage()); } String gender; if (selectedGenderIndex == 0) gender = Gender.MALE.name(); else gender = Gender.FEMALE.name(); final MedicalUser medicalUser = new MedicalUser(medicalId, birthdate, Gender.valueOf(gender), bmi); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... unusedParams) { medUserDb.insert(medicalUser); return null; } }.execute(); try { String hasNoUserInDBKey = getResources().getString(R.string.no_user_in_the_database); boolean hasStartedAppFirstTime = getIntent().getExtras().getBoolean(hasNoUserInDBKey); if(hasStartedAppFirstTime){ UtilsRG.info("Start game settings"); Intent intent = new Intent(activity, StartMenu.class); startActivity(intent); } else{ finish(); } }catch (Exception e){ UtilsRG.info("could not detect that no user in db, so close this activity"); finish(); } } else { try { String warningMessage = getResources().getString(R.string.no_medical_id); TastyToast.makeText(getApplicationContext(), warningMessage, TastyToast.LENGTH_LONG, TastyToast.WARNING); } catch (Exception e) { UtilsRG.error("Could not display Tasty Toast"); } } } @Override public void onBackPressed() { try{ String hasNoUserInDBKey = getResources().getString(R.string.no_user_in_the_database); boolean hasStartedAppFirstTime = getIntent().getExtras().getBoolean(hasNoUserInDBKey); if(hasStartedAppFirstTime){ UtilsRG.info("No user in database, so no way to go back"); new MaterialDialog.Builder(activity) .title(R.string.attention) .positiveText(R.string.ok) .content(R.string.please_create_user_before_use_app) .show(); return; } }catch (Exception e){ UtilsRG.error("Unexpected Exception:" +e.getLocalizedMessage()); } super.onBackPressed(); } }
package com.groupon.seleniumgridextras.utilities; import java.io.IOException; import sun.misc.BASE64Encoder; import sun.misc.BASE64Decoder; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class ImageUtils { /** * Decode string to image * @param imageString The string to decode * @return decoded image */ public static BufferedImage decodeToImage(String imageString) { BufferedImage image = null; byte[] imageByte; try { BASE64Decoder decoder = new BASE64Decoder(); imageByte = decoder.decodeBuffer(imageString); ByteArrayInputStream bis = new ByteArrayInputStream(imageByte); image = ImageIO.read(bis); bis.close(); } catch (Exception e) { e.printStackTrace(); } return image; } /** * Encode image to string * @param image The image to encode * @param type jpeg, bmp, ... * @return encoded string */ public static String encodeToString(BufferedImage image, String type) { String imageString = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ImageIO.write(image, type, bos); byte[] imageBytes = bos.toByteArray(); BASE64Encoder encoder = new BASE64Encoder(); imageString = encoder.encode(imageBytes); bos.close(); } catch (IOException e) { e.printStackTrace(); } return imageString; } public static BufferedImage readImage(File image) throws IOException { return ImageIO.read(image); } public static void saveImage(File filename, BufferedImage image) throws IOException { ImageIO.write(image, "png", filename.getAbsoluteFile()); } }
package com.compomics.toolbox.json.converters; /** * * @author Kenneth Verheggen */ import com.compomics.toolbox.json.DefaultJsonConverter; import com.compomics.util.experiment.biology.Atom; import com.compomics.util.experiment.identification.identification_parameters.IdentificationAlgorithmParameter; /** * This class is a convenience class to have a DefaultJsonConverter with the search parameter interfaces * @author Kenneth Verheggen */ public class SearchParameterConverter extends DefaultJsonConverter { /** * Default constructor */ public SearchParameterConverter() { super(IdentificationAlgorithmParameter.class, Atom.class); } }
package com.psddev.dari.db; import com.psddev.dari.util.ObjectUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Internal representation of an SQL query based on a Dari one. */ class SqlQuery { private static final Pattern QUERY_KEY_PATTERN = Pattern.compile("\\$\\{([^}]+)\\}"); private final SqlDatabase database; private final Query<?> query; private final String aliasPrefix; private final SqlVendor vendor; private final String recordIdField; private final String recordTypeIdField; private final String recordInRowIndexField; private final Map<String, Query.MappedKey> mappedKeys; private final Map<String, ObjectIndex> selectedIndexes; private String fromClause; private String whereClause; private String havingClause; private String orderByClause; private String extraSourceColumns; private List<String> orderBySelectColumns = new ArrayList<String>(); private final List<Join> joins = new ArrayList<Join>(); private final Map<Query<?>, String> subQueries = new LinkedHashMap<Query<?>, String>(); private final Map<Query<?>, SqlQuery> subSqlQueries = new HashMap<Query<?>, SqlQuery>(); private boolean needsDistinct; private Join mysqlIndexHint; private boolean forceLeftJoins; /** * Creates an instance that can translate the given {@code query} * with the given {@code database}. */ public SqlQuery( SqlDatabase initialDatabase, Query<?> initialQuery, String initialAliasPrefix) { database = initialDatabase; query = initialQuery; aliasPrefix = initialAliasPrefix; vendor = database.getVendor(); recordIdField = aliasedField("r", SqlDatabase.ID_COLUMN); recordTypeIdField = aliasedField("r", SqlDatabase.TYPE_ID_COLUMN); recordInRowIndexField = aliasedField("r", SqlDatabase.IN_ROW_INDEX_COLUMN); mappedKeys = query.mapEmbeddedKeys(database.getEnvironment()); selectedIndexes = new HashMap<String, ObjectIndex>(); for (Map.Entry<String, Query.MappedKey> entry : mappedKeys.entrySet()) { selectIndex(entry.getKey(), entry.getValue()); } } private void selectIndex(String queryKey, Query.MappedKey mappedKey) { ObjectIndex selectedIndex = null; int maxMatchCount = 0; for (ObjectIndex index : mappedKey.getIndexes()) { List<String> indexFields = index.getFields(); int matchCount = 0; for (Query.MappedKey mk : mappedKeys.values()) { ObjectField mkf = mk.getField(); if (mkf != null && indexFields.contains(mkf.getInternalName())) { ++ matchCount; } } if (matchCount > maxMatchCount) { selectedIndex = index; maxMatchCount = matchCount; } } if (selectedIndex != null) { if (maxMatchCount == 1) { for (ObjectIndex index : mappedKey.getIndexes()) { if (index.getFields().size() == 1) { selectedIndex = index; break; } } } selectedIndexes.put(queryKey, selectedIndex); } } public SqlQuery(SqlDatabase initialDatabase, Query<?> initialQuery) { this(initialDatabase, initialQuery, ""); } private String aliasedField(String alias, String field) { StringBuilder fieldBuilder = new StringBuilder(); fieldBuilder.append(aliasPrefix); fieldBuilder.append(alias); fieldBuilder.append("."); vendor.appendIdentifier(fieldBuilder, field); return fieldBuilder.toString(); } private SqlQuery getOrCreateSubSqlQuery(Query<?> subQuery, boolean forceLeftJoins) { SqlQuery subSqlQuery = subSqlQueries.get(subQuery); if (subSqlQuery == null) { subSqlQuery = new SqlQuery(database, subQuery, aliasPrefix + "s" + subSqlQueries.size()); subSqlQuery.forceLeftJoins = forceLeftJoins; subSqlQuery.initializeClauses(); subSqlQueries.put(subQuery, subSqlQuery); } return subSqlQuery; } /** Initializes FROM, WHERE, and ORDER BY clauses. */ private void initializeClauses() { // Determine whether any of the fields are sourced somewhere else. HashMap<String, ObjectField> sourceTables = new HashMap<String, ObjectField>(); Set<ObjectType> queryTypes = query.getConcreteTypes(database.getEnvironment()); if (queryTypes != null) { for (ObjectType type : queryTypes) { for (ObjectField field : type.getFields()) { SqlDatabase.FieldData fieldData = field.as(SqlDatabase.FieldData.class); if (fieldData.isIndexTableSource()) { sourceTables.put(fieldData.getIndexTable(), field); } } } } String extraJoins = ObjectUtils.to(String.class, query.getOptions().get(SqlDatabase.EXTRA_JOINS_QUERY_OPTION)); if (extraJoins != null) { Matcher queryKeyMatcher = QUERY_KEY_PATTERN.matcher(extraJoins); int lastEnd = 0; StringBuilder newExtraJoinsBuilder = new StringBuilder(); while (queryKeyMatcher.find()) { newExtraJoinsBuilder.append(extraJoins.substring(lastEnd, queryKeyMatcher.start())); lastEnd = queryKeyMatcher.end(); String queryKey = queryKeyMatcher.group(1); Query.MappedKey mappedKey = query.mapEmbeddedKey(database.getEnvironment(), queryKey); mappedKeys.put(queryKey, mappedKey); selectIndex(queryKey, mappedKey); Join join = getJoin(queryKey); join.type = JoinType.LEFT_OUTER; newExtraJoinsBuilder.append(join.getValueField(queryKey, null)); } newExtraJoinsBuilder.append(extraJoins.substring(lastEnd)); extraJoins = newExtraJoinsBuilder.toString(); } // Builds the WHERE clause. StringBuilder whereBuilder = new StringBuilder(); whereBuilder.append("\nWHERE "); String extraWhere = ObjectUtils.to(String.class, query.getOptions().get(SqlDatabase.EXTRA_WHERE_QUERY_OPTION)); if (!ObjectUtils.isBlank(extraWhere)) { whereBuilder.append("("); } whereBuilder.append("1 = 1"); if (!query.isFromAll()) { Set<ObjectType> types = query.getConcreteTypes(database.getEnvironment()); whereBuilder.append("\nAND "); if (types.isEmpty()) { whereBuilder.append("0 = 1"); } else { whereBuilder.append(recordTypeIdField); whereBuilder.append(" IN ("); for (ObjectType type : types) { vendor.appendValue(whereBuilder, type.getId()); whereBuilder.append(", "); } whereBuilder.setLength(whereBuilder.length() - 2); whereBuilder.append(")"); } } Predicate predicate = query.getPredicate(); if (predicate != null) { whereBuilder.append("\nAND ("); addWherePredicate(whereBuilder, predicate, null, false); whereBuilder.append(')'); } if (!ObjectUtils.isBlank(extraWhere)) { whereBuilder.append(") "); whereBuilder.append(extraWhere); } // Builds the ORDER BY clause. StringBuilder orderByBuilder = new StringBuilder(); for (Sorter sorter : query.getSorters()) { String operator = sorter.getOperator(); boolean ascending = Sorter.ASCENDING_OPERATOR.equals(operator); boolean descending = Sorter.DESCENDING_OPERATOR.equals(operator); boolean closest = Sorter.CLOSEST_OPERATOR.equals(operator); boolean farthest = Sorter.CLOSEST_OPERATOR.equals(operator); if (ascending || descending || closest || farthest) { String queryKey = (String) sorter.getOptions().get(0); String joinValueField = getSortFieldJoin(queryKey).getValueField(queryKey, null); Query<?> subQuery = mappedKeys.get(queryKey).getSubQueryWithSorter(sorter, 0); if (subQuery != null) { SqlQuery subSqlQuery = getOrCreateSubSqlQuery(subQuery, true); subQueries.put(subQuery, joinValueField + " = "); orderByBuilder.append(subSqlQuery.orderByClause.substring(9)); orderByBuilder.append(", "); continue; } if (ascending || descending) { orderByBuilder.append(joinValueField); orderBySelectColumns.add(joinValueField); } else if (closest || farthest) { Location location = (Location) sorter.getOptions().get(1); StringBuilder selectBuilder = new StringBuilder(); try { vendor.appendNearestLocation(orderByBuilder, selectBuilder, whereBuilder, location, joinValueField); orderBySelectColumns.add(selectBuilder.toString()); } catch(UnsupportedIndexException uie) { throw new UnsupportedIndexException(vendor, queryKey); } } orderByBuilder.append(' '); orderByBuilder.append(ascending || closest ? "ASC" : "DESC"); orderByBuilder.append(", "); continue; } throw new UnsupportedSorterException(database, sorter); } if (orderByBuilder.length() > 0) { orderByBuilder.setLength(orderByBuilder.length() - 2); orderByBuilder.insert(0, "\nORDER BY "); } // Builds the FROM clause. StringBuilder fromBuilder = new StringBuilder(); HashMap<String, String> joinTableAliases = new HashMap<String, String>(); for (Join join : joins) { if (join.indexKeys.isEmpty()) { continue; } joinTableAliases.put(join.getTableName().toLowerCase(), join.getAlias()); // e.g. JOIN RecordIndex AS i fromBuilder.append("\n"); fromBuilder.append((forceLeftJoins ? JoinType.LEFT_OUTER : join.type).token); fromBuilder.append(" "); fromBuilder.append(join.table); if (join.type == JoinType.INNER && join.equals(mysqlIndexHint)) { fromBuilder.append(" /*! USE INDEX (k_name_value) */"); } else if (join.sqlIndex == SqlIndex.LOCATION && join.sqlIndexTable.getVersion() >= 2) { fromBuilder.append(" /*! IGNORE INDEX (PRIMARY) */"); } // e.g. ON i#.recordId = r.id AND i#.name = ... fromBuilder.append(" ON "); fromBuilder.append(join.idField); fromBuilder.append(" = "); fromBuilder.append(aliasPrefix); fromBuilder.append("r."); vendor.appendIdentifier(fromBuilder, "id"); fromBuilder.append(" AND "); fromBuilder.append(join.keyField); fromBuilder.append(" IN ("); for (String indexKey : join.indexKeys) { fromBuilder.append(join.quoteIndexKey(indexKey)); fromBuilder.append(", "); } fromBuilder.setLength(fromBuilder.length() - 2); fromBuilder.append(")"); } for (Map.Entry<String, ObjectField> entry: sourceTables.entrySet()) { StringBuilder sourceTableNameBuilder = new StringBuilder(); vendor.appendIdentifier(sourceTableNameBuilder, entry.getKey()); String sourceTableName = sourceTableNameBuilder.toString(); ObjectField field = entry.getValue(); String sourceTableAlias; StringBuilder keyNameBuilder = new StringBuilder(field.getParentType().getInternalName()); keyNameBuilder.append("/"); keyNameBuilder.append(field.getInternalName()); Query.MappedKey key = query.mapEmbeddedKey(database.getEnvironment(), keyNameBuilder.toString()); ObjectIndex useIndex = null; for (ObjectIndex index : key.getIndexes()) { if (index.getFields().get(0) == field.getInternalName()) { useIndex = index; break; } } if (useIndex == null) { continue; } SqlIndex useSqlIndex = SqlIndex.Static.getByIndex(useIndex); SqlIndex.Table indexTable = useSqlIndex.getReadTable(database, useIndex); // This table hasn't been joined to yet. if (!joinTableAliases.containsKey(sourceTableName.toLowerCase())) { sourceTableAlias = sourceTableName; int symbolId = database.getSymbolId(key.getIndexKey(useIndex)); fromBuilder.append(" LEFT OUTER JOIN "); fromBuilder.append(sourceTableName); fromBuilder.append(" ON "); fromBuilder.append(sourceTableName); fromBuilder.append("."); vendor.appendIdentifier(fromBuilder, "id"); fromBuilder.append(" = "); fromBuilder.append(aliasPrefix); fromBuilder.append("r."); vendor.appendIdentifier(fromBuilder, "id"); fromBuilder.append(" AND "); fromBuilder.append(sourceTableName); fromBuilder.append("."); vendor.appendIdentifier(fromBuilder, "symbolId"); fromBuilder.append(" = "); fromBuilder.append(symbolId); } else { sourceTableAlias = joinTableAliases.get(sourceTableName.toLowerCase()); } // Add columns to select. int fieldIndex = 0; StringBuilder extraColumnsBuilder = new StringBuilder(); for (String indexFieldName : useIndex.getFields()) { String indexColumnName; query.getExtraSourceColumns().add(indexFieldName); indexColumnName = indexTable.getValueField(database, useIndex, fieldIndex); fieldIndex++; extraColumnsBuilder.append(sourceTableAlias); extraColumnsBuilder.append("."); vendor.appendIdentifier(extraColumnsBuilder, indexColumnName); extraColumnsBuilder.append(" AS "); vendor.appendIdentifier(extraColumnsBuilder, indexFieldName); extraColumnsBuilder.append(", "); } extraColumnsBuilder.setLength(extraColumnsBuilder.length() - 2); this.extraSourceColumns = extraColumnsBuilder.toString(); } for (Map.Entry<Query<?>, String> entry : subQueries.entrySet()) { Query<?> subQuery = entry.getKey(); SqlQuery subSqlQuery = getOrCreateSubSqlQuery(subQuery, false); if (subSqlQuery.needsDistinct) { needsDistinct = true; } fromBuilder.append("\nINNER JOIN "); vendor.appendIdentifier(fromBuilder, "Record"); fromBuilder.append(" "); fromBuilder.append(subSqlQuery.aliasPrefix); fromBuilder.append("r ON "); fromBuilder.append(entry.getValue()); fromBuilder.append(subSqlQuery.aliasPrefix); fromBuilder.append("r."); vendor.appendIdentifier(fromBuilder, "id"); fromBuilder.append(subSqlQuery.fromClause); } if (extraJoins != null) { fromBuilder.append(' '); fromBuilder.append(extraJoins); } this.whereClause = whereBuilder.toString(); String extraHaving = ObjectUtils.to(String.class, query.getOptions().get(SqlDatabase.EXTRA_HAVING_QUERY_OPTION)); this.havingClause = ObjectUtils.isBlank(extraHaving) ? "" : "\nHAVING " + extraHaving; this.orderByClause = orderByBuilder.toString(); this.fromClause = fromBuilder.toString(); } /** Adds the given {@code predicate} to the {@code WHERE} clause. */ private void addWherePredicate( StringBuilder whereBuilder, Predicate predicate, Predicate parentPredicate, boolean usesLeftJoin) { if (predicate instanceof CompoundPredicate) { CompoundPredicate compoundPredicate = (CompoundPredicate) predicate; String operator = compoundPredicate.getOperator(); boolean isNot = PredicateParser.NOT_OPERATOR.equals(operator); // e.g. (child1) OR (child2) OR ... (child if (isNot || PredicateParser.OR_OPERATOR.equals(operator)) { StringBuilder compoundBuilder = new StringBuilder(); List<Predicate> children = compoundPredicate.getChildren(); boolean usesLeftJoinChildren; if (children.size() > 1) { usesLeftJoinChildren = true; needsDistinct = true; } else { usesLeftJoinChildren = isNot; } for (Predicate child : children) { compoundBuilder.append("("); addWherePredicate(compoundBuilder, child, predicate, usesLeftJoinChildren); compoundBuilder.append(")\nOR "); } if (compoundBuilder.length() > 0) { compoundBuilder.setLength(compoundBuilder.length() - 4); // e.g. NOT ((child1) OR (child2) OR ... (child if (isNot) { whereBuilder.append("NOT ("); whereBuilder.append(compoundBuilder); whereBuilder.append(")"); } else { whereBuilder.append(compoundBuilder); } } return; // e.g. (child1) AND (child2) AND .... (child } else if (PredicateParser.AND_OPERATOR.equals(operator)) { StringBuilder compoundBuilder = new StringBuilder(); for (Predicate child : compoundPredicate.getChildren()) { compoundBuilder.append("("); addWherePredicate(compoundBuilder, child, predicate, usesLeftJoin); compoundBuilder.append(")\nAND "); } if (compoundBuilder.length() > 0) { compoundBuilder.setLength(compoundBuilder.length() - 5); whereBuilder.append(compoundBuilder); } return; } } else if (predicate instanceof ComparisonPredicate) { ComparisonPredicate comparisonPredicate = (ComparisonPredicate) predicate; String queryKey = comparisonPredicate.getKey(); Query.MappedKey mappedKey = mappedKeys.get(queryKey); boolean isFieldCollection = mappedKey.isInternalCollectionType(); Join join = null; if (mappedKey.getField() != null && parentPredicate instanceof CompoundPredicate && PredicateParser.OR_OPERATOR.equals(((CompoundPredicate) parentPredicate).getOperator())) { for (Join j : joins) { if (j.parent == parentPredicate && j.sqlIndex.equals(SqlIndex.Static.getByType(mappedKeys.get(queryKey).getInternalType()))) { join = j; join.addIndexKey(queryKey); needsDistinct = true; break; } } if (join == null) { join = getJoin(queryKey); join.parent = parentPredicate; } } else if (isFieldCollection) { join = createJoin(queryKey); } else { join = getJoin(queryKey); } if (usesLeftJoin) { join.type = JoinType.LEFT_OUTER; } if (isFieldCollection && (join.sqlIndexTable == null || join.sqlIndexTable.getVersion() < 2)) { needsDistinct = true; } String joinValueField = join.getValueField(queryKey, comparisonPredicate); String operator = comparisonPredicate.getOperator(); StringBuilder comparisonBuilder = new StringBuilder(); boolean hasMissing = false; int subClauseCount = 0; boolean isNotEqualsAll = PredicateParser.NOT_EQUALS_ALL_OPERATOR.equals(operator); if (isNotEqualsAll || PredicateParser.EQUALS_ANY_OPERATOR.equals(operator)) { Query<?> valueQuery = mappedKey.getSubQueryWithComparison(comparisonPredicate); // e.g. field IN (SELECT ...) if (valueQuery != null) { if (isNotEqualsAll || isFieldCollection) { needsDistinct = true; } if (findSimilarComparison(mappedKey.getField(), query.getPredicate())) { whereBuilder.append(joinValueField); if (isNotEqualsAll) { whereBuilder.append(" NOT"); } whereBuilder.append(" IN ("); whereBuilder.append(new SqlQuery(database, valueQuery).subQueryStatement()); whereBuilder.append(")"); } else { SqlQuery subSqlQuery = getOrCreateSubSqlQuery(valueQuery, join.type == JoinType.LEFT_OUTER); subQueries.put(valueQuery, joinValueField + (isNotEqualsAll ? " != " : " = ")); whereBuilder.append(subSqlQuery.whereClause.substring(7)); } return; } for (Object value : comparisonPredicate.resolveValues(database)) { if (value == null) { ++ subClauseCount; comparisonBuilder.append("0 = 1"); } else if (value == Query.MISSING_VALUE) { ++ subClauseCount; hasMissing = true; join.type = JoinType.LEFT_OUTER; comparisonBuilder.append(joinValueField); if (isNotEqualsAll) { if (isFieldCollection) { needsDistinct = true; } comparisonBuilder.append(" IS NOT NULL"); } else { comparisonBuilder.append(" IS NULL"); } } else if (value instanceof Region) { List<Location> locations = ((Region) value).getLocations(); if (!locations.isEmpty()) { ++ subClauseCount; if (isNotEqualsAll) { comparisonBuilder.append("NOT "); } try { vendor.appendWhereRegion(comparisonBuilder, (Region) value, joinValueField); } catch (UnsupportedIndexException uie) { throw new UnsupportedIndexException(vendor, queryKey); } } } else { ++ subClauseCount; if (isNotEqualsAll) { join.type = JoinType.LEFT_OUTER; needsDistinct = true; hasMissing = true; comparisonBuilder.append("("); comparisonBuilder.append(joinValueField); comparisonBuilder.append(" IS NULL OR "); comparisonBuilder.append(joinValueField); if (join.likeValuePrefix != null) { comparisonBuilder.append(" NOT LIKE "); join.appendValue(comparisonBuilder, comparisonPredicate, join.likeValuePrefix + database.getSymbolId(value.toString()) + ";%"); } else { comparisonBuilder.append(" != "); join.appendValue(comparisonBuilder, comparisonPredicate, value); } comparisonBuilder.append(")"); } else { comparisonBuilder.append(joinValueField); if (join.likeValuePrefix != null) { comparisonBuilder.append(" LIKE "); join.appendValue(comparisonBuilder, comparisonPredicate, join.likeValuePrefix + database.getSymbolId(value.toString()) + ";%"); } else { comparisonBuilder.append(" = "); join.appendValue(comparisonBuilder, comparisonPredicate, value); } } } comparisonBuilder.append(isNotEqualsAll ? " AND " : " OR "); } if (comparisonBuilder.length() == 0) { whereBuilder.append(isNotEqualsAll ? "1 = 1" : "0 = 1"); return; } } else { boolean isStartsWith = PredicateParser.STARTS_WITH_OPERATOR.equals(operator); String sqlOperator = isStartsWith ? "LIKE" : PredicateParser.LESS_THAN_OPERATOR.equals(operator) ? "<" : PredicateParser.LESS_THAN_OR_EQUALS_OPERATOR.equals(operator) ? "<=" : PredicateParser.GREATER_THAN_OPERATOR.equals(operator) ? ">" : PredicateParser.GREATER_THAN_OR_EQUALS_OPERATOR.equals(operator) ? ">=" : null; // e.g. field OP value1 OR field OP value2 OR ... field OP value if (sqlOperator != null) { for (Object value : comparisonPredicate.resolveValues(database)) { ++ subClauseCount; if (value == null) { comparisonBuilder.append("0 = 1"); } else if (value == Query.MISSING_VALUE) { hasMissing = true; join.type = JoinType.LEFT_OUTER; comparisonBuilder.append(joinValueField); comparisonBuilder.append(" IS NULL"); } else { comparisonBuilder.append(joinValueField); comparisonBuilder.append(" "); comparisonBuilder.append(sqlOperator); comparisonBuilder.append(" "); if (isStartsWith) { value = value.toString() + "%"; } join.appendValue(comparisonBuilder, comparisonPredicate, value); } comparisonBuilder.append(" OR "); } if (comparisonBuilder.length() == 0) { whereBuilder.append("0 = 1"); return; } } } if (comparisonBuilder.length() > 0) { comparisonBuilder.setLength(comparisonBuilder.length() - 5); if (!hasMissing) { if (join.needsIndexTable) { String indexKey = mappedKeys.get(queryKey).getIndexKey(selectedIndexes.get(queryKey)); if (indexKey != null) { whereBuilder.append(join.keyField); whereBuilder.append(" = "); whereBuilder.append(join.quoteIndexKey(indexKey)); whereBuilder.append(" AND "); } } whereBuilder.append(joinValueField); whereBuilder.append(" IS NOT NULL AND "); if (subClauseCount > 1) { needsDistinct = true; whereBuilder.append("("); comparisonBuilder.append(")"); } } whereBuilder.append(comparisonBuilder); return; } } throw new UnsupportedPredicateException(this, predicate); } private boolean findSimilarComparison(ObjectField field, Predicate predicate) { if (field != null) { if (predicate instanceof CompoundPredicate) { for (Predicate child : ((CompoundPredicate) predicate).getChildren()) { if (findSimilarComparison(field, child)) { return true; } } } else if (predicate instanceof ComparisonPredicate) { ComparisonPredicate comparison = (ComparisonPredicate) predicate; Query.MappedKey mappedKey = mappedKeys.get(comparison.getKey()); if (field.equals(mappedKey.getField()) && mappedKey.getSubQueryWithComparison(comparison) == null) { return true; } } } return false; } /** * Returns an SQL statement that can be used to get a count * of all rows matching the query. */ public String countStatement() { StringBuilder statementBuilder = new StringBuilder(); initializeClauses(); statementBuilder.append("SELECT COUNT("); if (needsDistinct) { statementBuilder.append("DISTINCT "); } statementBuilder.append(recordIdField); statementBuilder.append(")\nFROM "); vendor.appendIdentifier(statementBuilder, "Record"); statementBuilder.append(" "); statementBuilder.append(aliasPrefix); statementBuilder.append("r"); statementBuilder.append(fromClause.replace(" /*! USE INDEX (k_name_value) */", "")); statementBuilder.append(whereClause); return statementBuilder.toString(); } /** * Returns an SQL statement that can be used to delete all rows * matching the query. */ public String deleteStatement() { StringBuilder statementBuilder = new StringBuilder(); initializeClauses(); statementBuilder.append("DELETE r\nFROM "); vendor.appendIdentifier(statementBuilder, "Record"); statementBuilder.append(" "); statementBuilder.append(aliasPrefix); statementBuilder.append("r"); statementBuilder.append(fromClause); statementBuilder.append(whereClause); statementBuilder.append(havingClause); statementBuilder.append(orderByClause); return statementBuilder.toString(); } /** * Returns an SQL statement that can be used to get all objects * grouped by the values of the given {@code groupFields}. */ public String groupStatement(String[] groupFields) { Map<String, Join> groupJoins = new LinkedHashMap<String, Join>(); if (groupFields != null) { for (String groupField : groupFields) { Query.MappedKey mappedKey = query.mapEmbeddedKey(database.getEnvironment(), groupField); mappedKeys.put(groupField, mappedKey); Iterator<ObjectIndex> indexesIterator = mappedKey.getIndexes().iterator(); if (indexesIterator.hasNext()) { ObjectIndex selectedIndex = indexesIterator.next(); while (indexesIterator.hasNext()) { ObjectIndex index = indexesIterator.next(); if (selectedIndex.getFields().size() < index.getFields().size()) { selectedIndex = index; } } selectedIndexes.put(groupField, selectedIndex); } groupJoins.put(groupField, getJoin(groupField)); } } StringBuilder statementBuilder = new StringBuilder(); initializeClauses(); statementBuilder.append("SELECT COUNT("); if (needsDistinct) { statementBuilder.append("DISTINCT "); } statementBuilder.append(recordIdField); statementBuilder.append(")"); for (Map.Entry<String, Join> entry : groupJoins.entrySet()) { statementBuilder.append(", "); statementBuilder.append(entry.getValue().getValueField(entry.getKey(), null)); } for (String field : orderBySelectColumns) { statementBuilder.append(", "); statementBuilder.append(field); } statementBuilder.append("\nFROM "); vendor.appendIdentifier(statementBuilder, "Record"); statementBuilder.append(" "); statementBuilder.append(aliasPrefix); statementBuilder.append("r"); statementBuilder.append(fromClause.replace(" /*! USE INDEX (k_name_value) */", "")); statementBuilder.append(whereClause); StringBuilder groupBy = new StringBuilder(); for (Map.Entry<String, Join> entry : groupJoins.entrySet()) { groupBy.append(entry.getValue().getValueField(entry.getKey(), null)); groupBy.append(", "); } if (groupBy.length() > 0) { groupBy.setLength(groupBy.length() - 2); statementBuilder.append(" GROUP BY "); statementBuilder.append(groupBy); } for (String field : orderBySelectColumns) { statementBuilder.append(", "); statementBuilder.append(field); } if (orderBySelectColumns.size() > 0) { statementBuilder.append(" ORDER BY "); int i = 0; for (Map.Entry<String, Join> entry : groupJoins.entrySet()) { if (i++ == 1) { statementBuilder.append(", "); } statementBuilder.append(entry.getValue().getValueField(entry.getKey(), null)); } for (String field : orderBySelectColumns) { if (i++ == 1) { statementBuilder.append(", "); } statementBuilder.append(field); } } statementBuilder.append(havingClause); return statementBuilder.toString(); } /** * Returns an SQL statement that can be used to get when the rows * matching the query were last updated. */ public String lastUpdateStatement() { StringBuilder statementBuilder = new StringBuilder(); initializeClauses(); statementBuilder.append("SELECT MAX(r."); vendor.appendIdentifier(statementBuilder, "updateDate"); statementBuilder.append(")\nFROM "); vendor.appendIdentifier(statementBuilder, "RecordUpdate"); statementBuilder.append(" "); statementBuilder.append(aliasPrefix); statementBuilder.append("r"); statementBuilder.append(fromClause); statementBuilder.append(whereClause); return statementBuilder.toString(); } /** * Returns an SQL statement that can be used to list all rows * matching the query. */ public String selectStatement() { StringBuilder statementBuilder = new StringBuilder(); initializeClauses(); statementBuilder.append("SELECT"); if (needsDistinct && vendor.supportsDistinctBlob()) { statementBuilder.append(" DISTINCT"); } statementBuilder.append(" r."); vendor.appendIdentifier(statementBuilder, "id"); statementBuilder.append(", r."); vendor.appendIdentifier(statementBuilder, "typeId"); List<String> fields = query.getFields(); if (fields == null) { if (!needsDistinct || vendor.supportsDistinctBlob()) { statementBuilder.append(", r."); vendor.appendIdentifier(statementBuilder, "data"); } } else if (!fields.isEmpty()) { statementBuilder.append(", "); vendor.appendSelectFields(statementBuilder, fields); } if (!orderBySelectColumns.isEmpty()) { for (String joinValueField : orderBySelectColumns) { statementBuilder.append(", "); statementBuilder.append(joinValueField); } } String extraColumns = ObjectUtils.to(String.class, query.getOptions().get(SqlDatabase.EXTRA_COLUMNS_QUERY_OPTION)); if (extraColumns != null) { statementBuilder.append(", "); statementBuilder.append(extraColumns); } if (extraSourceColumns != null) { statementBuilder.append(", "); statementBuilder.append(extraSourceColumns); } statementBuilder.append("\nFROM "); vendor.appendIdentifier(statementBuilder, "Record"); statementBuilder.append(" "); statementBuilder.append(aliasPrefix); statementBuilder.append("r"); statementBuilder.append(fromClause); statementBuilder.append(whereClause); statementBuilder.append(havingClause); statementBuilder.append(orderByClause); if (needsDistinct && !vendor.supportsDistinctBlob()) { StringBuilder distinctBuilder = new StringBuilder(); distinctBuilder.append("SELECT"); distinctBuilder.append(" r."); vendor.appendIdentifier(distinctBuilder, "id"); distinctBuilder.append(", r."); vendor.appendIdentifier(distinctBuilder, "typeId"); if (fields == null) { distinctBuilder.append(", r."); vendor.appendIdentifier(distinctBuilder, "data"); } else if (!fields.isEmpty()) { distinctBuilder.append(", "); vendor.appendSelectFields(distinctBuilder, fields); } distinctBuilder.append(" FROM "); vendor.appendIdentifier(distinctBuilder, SqlDatabase.RECORD_TABLE); distinctBuilder.append(" r INNER JOIN ("); distinctBuilder.append(statementBuilder.toString()); distinctBuilder.append(") d0 ON (r.id = d0.id)"); return distinctBuilder.toString(); } return statementBuilder.toString(); } /** Returns an SQL statement that can be used as a sub-query. */ public String subQueryStatement() { StringBuilder statementBuilder = new StringBuilder(); initializeClauses(); statementBuilder.append("SELECT"); if (needsDistinct) { statementBuilder.append(" DISTINCT"); } statementBuilder.append(" r."); vendor.appendIdentifier(statementBuilder, "id"); statementBuilder.append("\nFROM "); vendor.appendIdentifier(statementBuilder, "Record"); statementBuilder.append(" "); statementBuilder.append(aliasPrefix); statementBuilder.append("r"); statementBuilder.append(fromClause); statementBuilder.append(whereClause); statementBuilder.append(havingClause); statementBuilder.append(orderByClause); return statementBuilder.toString(); } private enum JoinType { INNER("INNER JOIN"), LEFT_OUTER("LEFT OUTER JOIN"); public final String token; private JoinType(String token) { this.token = token; } } private Join createJoin(String queryKey) { Join join = new Join("i" + joins.size(), queryKey); joins.add(join); if (queryKey.equals(query.getOptions().get(SqlDatabase.MYSQL_INDEX_HINT_QUERY_OPTION))) { mysqlIndexHint = join; } return join; } /** Returns the column alias for the given {@code queryKey}. */ private Join getJoin(String queryKey) { ObjectIndex index = selectedIndexes.get(queryKey); for (Join join : joins) { if (queryKey.equals(join.queryKey)) { return join; } else { String indexKey = mappedKeys.get(queryKey).getIndexKey(index); if (indexKey != null && indexKey.equals(mappedKeys.get(join.queryKey).getIndexKey(join.index))) { return join; } } } return createJoin(queryKey); } /** Returns the column alias for the given field-based {@code sorter}. */ private Join getSortFieldJoin(String queryKey) { ObjectIndex index = selectedIndexes.get(queryKey); for (Join join : joins) { if (queryKey.equals(join.queryKey)) { return join; } else { String indexKey = mappedKeys.get(queryKey).getIndexKey(index); if (indexKey != null && indexKey.equals(mappedKeys.get(join.queryKey).getIndexKey(join.index))) { return join; } } } Join join = createJoin(queryKey); join.type = JoinType.LEFT_OUTER; return join; } private class Join { public Predicate parent; public JoinType type = JoinType.INNER; public final boolean needsIndexTable; public final String likeValuePrefix; public final String queryKey; public final String indexType; public final String table; public final String idField; public final String keyField; public final List<String> indexKeys = new ArrayList<String>(); private final String alias; private final String tableName; private final ObjectIndex index; private final SqlIndex sqlIndex; private final SqlIndex.Table sqlIndexTable; private final String valueField; public Join(String alias, String queryKey) { this.alias = alias; this.queryKey = queryKey; Query.MappedKey mappedKey = mappedKeys.get(queryKey); this.index = selectedIndexes.get(queryKey); this.indexType = mappedKey.getInternalType(); this.sqlIndex = this.index != null ? SqlIndex.Static.getByIndex(this.index) : SqlIndex.Static.getByType(this.indexType); if (Query.ID_KEY.equals(queryKey)) { needsIndexTable = false; likeValuePrefix = null; valueField = recordIdField; sqlIndexTable = null; table = null; tableName = null; idField = null; keyField = null; } else if (Query.TYPE_KEY.equals(queryKey)) { needsIndexTable = false; likeValuePrefix = null; valueField = recordTypeIdField; sqlIndexTable = null; table = null; tableName = null; idField = null; keyField = null; } else if (Query.ANY_KEY.equals(queryKey)) { throw new UnsupportedIndexException(database, queryKey); } else if (database.hasInRowIndex() && index.isShortConstant()) { needsIndexTable = false; likeValuePrefix = "%;" + database.getSymbolId(mappedKeys.get(queryKey).getIndexKey(selectedIndexes.get(queryKey))) + "="; valueField = recordInRowIndexField; sqlIndexTable = this.sqlIndex.getReadTable(database, index); table = null; tableName = null; idField = null; keyField = null; } else { needsIndexTable = true; likeValuePrefix = null; addIndexKey(queryKey); valueField = null; sqlIndexTable = this.sqlIndex.getReadTable(database, index); StringBuilder tableBuilder = new StringBuilder(); vendor.appendIdentifier(tableBuilder, sqlIndexTable.getName(database, index)); tableName = tableBuilder.toString(); tableBuilder.append(" "); tableBuilder.append(aliasPrefix); tableBuilder.append(alias); table = tableBuilder.toString(); idField = aliasedField(alias, sqlIndexTable.getIdField(database, index)); keyField = aliasedField(alias, sqlIndexTable.getKeyField(database, index)); } } public String getAlias() { return this.alias; } public String getTableName() { return this.tableName; } public void addIndexKey(String queryKey) { String indexKey = mappedKeys.get(queryKey).getIndexKey(selectedIndexes.get(queryKey)); if (ObjectUtils.isBlank(indexKey)) { throw new UnsupportedIndexException(database, indexKey); } if (needsIndexTable) { indexKeys.add(indexKey); } } public Object quoteIndexKey(String indexKey) { return SqlDatabase.quoteValue(sqlIndexTable.convertKey(database, index, indexKey)); } public void appendValue(StringBuilder builder, ComparisonPredicate comparison, Object value) { ObjectField field = mappedKeys.get(comparison.getKey()).getField(); SqlIndex fieldSqlIndex = field != null ? SqlIndex.Static.getByType(field.getInternalItemType()) : sqlIndex; if (fieldSqlIndex == SqlIndex.UUID) { value = ObjectUtils.to(UUID.class, value); } else if (fieldSqlIndex == SqlIndex.NUMBER && !PredicateParser.STARTS_WITH_OPERATOR.equals(comparison.getOperator())) { if (value != null) { Long valueLong = ObjectUtils.to(Long.class, value); if (valueLong != null) { value = valueLong; } else { value = ObjectUtils.to(Double.class, value); } } } else if (fieldSqlIndex == SqlIndex.STRING) { if (comparison.isIgnoreCase()) { value = value.toString().toLowerCase(Locale.ENGLISH); } else if (database.comparesIgnoreCase()) { String valueString = value.toString().trim(); if (!index.isCaseSensitive()) { valueString = valueString.toLowerCase(Locale.ENGLISH); } value = valueString; } } vendor.appendValue(builder, value); } public String getValueField(String queryKey, ComparisonPredicate comparison) { String field; if (valueField != null) { field = valueField; } else if (sqlIndex != SqlIndex.CUSTOM) { field = aliasedField(alias, sqlIndexTable.getValueField(database, index, 0)); } else { String valueFieldName = mappedKeys.get(queryKey).getField().getInternalName(); List<String> fieldNames = index.getFields(); int fieldIndex = 0; for (int size = fieldNames.size(); fieldIndex < size; ++ fieldIndex) { if (valueFieldName.equals(fieldNames.get(fieldIndex))) { break; } } field = aliasedField(alias, sqlIndexTable.getValueField(database, index, fieldIndex)); } if (comparison != null && comparison.isIgnoreCase()) { field = "LOWER(CONVERT(" + field + " USING utf8))"; } return field; } } }
package VASSAL.tools.image; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import VASSAL.tools.swing.SwingUtils; public class LabelUtils { private LabelUtils() {} public static final int CENTER = 0; public static final int RIGHT = 1; public static final int LEFT = 2; public static final int TOP = 3; public static final int BOTTOM = 4; public static void drawLabel(Graphics g, String text, int x, int y, int hAlign, int vAlign, Color fgColor, Color bgColor) { drawLabel(g, text, x, y, new Font("Dialog", Font.PLAIN, 10), hAlign, vAlign, fgColor, bgColor, null); } public static void drawLabel(Graphics g, String text, int x, int y, Font f, int hAlign, int vAlign, Color fgColor, Color bgColor, Color borderColor) { ((Graphics2D) g).addRenderingHints(SwingUtils.FONT_HINTS); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setFont(f); final int width = g.getFontMetrics().stringWidth(text + " "); final int height = g.getFontMetrics().getHeight(); int x0 = x; int y0 = y; switch (hAlign) { case CENTER: x0 = x - width / 2; break; case LEFT: x0 = x - width; break; } switch (vAlign) { case CENTER: y0 = y - height / 2; break; case BOTTOM: y0 = y - height; break; } if (bgColor != null) { g.setColor(bgColor); g.fillRect(x0, y0, width, height); } if (borderColor != null) { g.setColor(borderColor); g.drawRect(x0, y0, width, height); } g.setColor(fgColor); g.drawString(" " + text + " ", x0, y0 + g.getFontMetrics().getHeight() - g.getFontMetrics().getDescent()); } }
package org.mozartoz.truffle.nodes.builtins; import java.math.BigInteger; import org.mozartoz.truffle.nodes.DerefNodeGen; import org.mozartoz.truffle.nodes.OzNode; import com.oracle.truffle.api.ExactMath; import com.oracle.truffle.api.dsl.CreateCast; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.NodeChildren; import com.oracle.truffle.api.dsl.Specialization; public abstract class IntBuiltins { private static final BigInteger ONE = BigInteger.valueOf(1); @Builtin(name = "is") @GenerateNodeFactory @NodeChild("value") public static abstract class IsIntNode extends OzNode { @Specialization Object isInt(Object value) { return unimplemented(); } } @Builtin(name = "+1") @GenerateNodeFactory @NodeChild("value") public static abstract class AddOneNode extends OzNode { @CreateCast("value") protected OzNode derefValue(OzNode var) { return DerefNodeGen.create(var); } @Specialization(rewriteOn = ArithmeticException.class) protected long addOne(long n) { return ExactMath.addExact(n, 1); } @Specialization protected BigInteger addOne(BigInteger n) { return n.add(ONE); } } @Builtin(name = "-1") @GenerateNodeFactory @NodeChild("value") public static abstract class SubOneNode extends OzNode { @CreateCast("value") protected OzNode derefValue(OzNode var) { return DerefNodeGen.create(var); } @Specialization(rewriteOn = ArithmeticException.class) protected long subOne(long n) { return ExactMath.subtractExact(n, 1); } @Specialization protected BigInteger subOne(BigInteger n) { return n.subtract(ONE); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("left"), @NodeChild("right") }) public static abstract class DivNode extends OzNode { @CreateCast("left") protected OzNode derefLeft(OzNode var) { return DerefNodeGen.create(var); } @CreateCast("right") protected OzNode derefRight(OzNode var) { return DerefNodeGen.create(var); } @Specialization(rewriteOn = ArithmeticException.class) protected long div(long a, long b) { return a / b; } @Specialization protected BigInteger div(BigInteger a, BigInteger b) { return a.divide(b); } } @GenerateNodeFactory @NodeChildren({ @NodeChild("left"), @NodeChild("right") }) public static abstract class ModNode extends OzNode { @CreateCast("left") protected OzNode derefLeft(OzNode var) { return DerefNodeGen.create(var); } @CreateCast("right") protected OzNode derefRight(OzNode var) { return DerefNodeGen.create(var); } @Specialization(rewriteOn = ArithmeticException.class) protected long mod(long a, long b) { return a % b; } @Specialization protected BigInteger mod(BigInteger a, BigInteger b) { return a.mod(b); } } }
package org.flymine.util; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.beans.IntrospectionException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.net.URL; import java.net.MalformedURLException; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Date; import org.flymine.objectstore.proxy.ProxyReference; /** * Provides utility methods for working with Java types and reflection * * @author Mark Woodbridge * @author Richard Smith * @author Matthew Wakeling */ public class TypeUtil { private TypeUtil() { } private static Map classToFieldToGetter = new HashMap(); private static Map classToFieldToSetter = new HashMap(); private static Map classToFieldnameToFieldInfo = new HashMap(); /** * Returns the package name from a fully qualified class name * * @param className the fully qualified class name * @return the package name */ public static String packageName(String className) { if (className.lastIndexOf(".") >= 0) { return className.substring(0, className.lastIndexOf(".")); } else { return ""; } } /** * Returns the unqualifed class name from a fully qualified class name * * @param className the fully qualified class name * @return the unqualified name */ public static String unqualifiedName(String className) { if (className.lastIndexOf(".") >= 0) { return className.substring(className.lastIndexOf(".") + 1); } else { return className; } } public static Object getFieldValue(Object o, String fieldName) throws IllegalAccessException { try { return getGetter(o.getClass(), fieldName).invoke(o, new Object[] {}); } catch (Exception e) { String type = ""; try { type = " (a " + getFieldInfo(o.getClass(), fieldName).getGetter().getReturnType() .getName() + ")"; } catch (Exception e3) { type = " (available fields are " + getFieldInfos(o.getClass()).keySet() + ")"; } IllegalAccessException e2 = new IllegalAccessException("Couldn't get field \"" + DynamicUtil.decomposeClass(o.getClass()) + "." + fieldName + "\"" + type); e2.initCause(e); throw e2; } } public static Object getFieldProxy(Object o, String fieldName) throws IllegalAccessException { try { Method proxyGetter = getProxyGetter(o.getClass(), fieldName); if (proxyGetter == null) { proxyGetter = getGetter(o.getClass(), fieldName); } return proxyGetter.invoke(o, new Object[] {}); } catch (Exception e) { String type = null; try { type = getFieldInfo(o.getClass(), fieldName).getGetter().getReturnType().getName(); } catch (Exception e3) { } IllegalAccessException e2 = new IllegalAccessException("Couldn't proxyGet field \"" + o.getClass().getName() + "." + fieldName + "\"" + (type == null ? "" : " (a " + type + ")")); e2.initCause(e); throw e2; } } public static void setFieldValue(Object o, String fieldName, Object fieldValue) throws IllegalAccessException { try { if (fieldValue instanceof ProxyReference) { getProxySetter(o.getClass(), fieldName).invoke(o, new Object[] {fieldValue}); } else { getSetter(o.getClass(), fieldName).invoke(o, new Object[] {fieldValue}); } } catch (Exception e) { String type = null; try { type = getFieldInfo(o.getClass(), fieldName).getGetter().getReturnType().getName(); } catch (Exception e3) { } IllegalArgumentException e2 = new IllegalArgumentException("Couldn't set field \"" + DynamicUtil.decomposeClass(o.getClass()) + "." + fieldName + "\"" + (type == null ? "" : " (a " + type + ")") + " to \"" + fieldValue + "\" (a " + fieldValue.getClass().getName() + ")"); e2.initCause(e); throw e2; } } /** * Returns the Method object that is the getter for the field name * * @param c the Class * @param fieldName the name of the relevant field * @return the Getter, or null if the field is not found */ public static Method getGetter(Class c, String fieldName) { FieldInfo info = getFieldInfo(c, fieldName); if (info != null) { return info.getGetter(); } return null; } /** * Returns the Method object that is the setter for the field name * * @param c the Class * @param fieldName the name of the relevant field * @return the setter, or null if the field is not found */ public static Method getSetter(Class c, String fieldName) { FieldInfo info = getFieldInfo(c, fieldName); if (info != null) { return info.getSetter(); } return null; } /** * Returns the Method object that is the proxySetter for the field name * * @param c the Class * @param fieldName the name of the relevant field * @return the proxySetter, or null if it is not present or the field is not found */ public static Method getProxySetter(Class c, String fieldName) { FieldInfo info = getFieldInfo(c, fieldName); if (info != null) { return info.getProxySetter(); } return null; } /** * Returns the Method object that is the proxyGetter for the field name * * @param c the Class * @param fieldName the name of the relevant field * @return the proxyGetter, or null if it is not present or the field is not found */ public static Method getProxyGetter(Class c, String fieldName) { FieldInfo info = getFieldInfo(c, fieldName); if (info != null) { return info.getProxyGetter(); } return null; } /** * Returns the Map from field name to TypeUtil.FieldInfo objects for all the fields in a * given class. * * @param c the Class * @return a Map from field name to FieldInfo object */ public static Map getFieldInfos(Class c) { Map infos = null; synchronized (classToFieldnameToFieldInfo) { infos = (Map) classToFieldnameToFieldInfo.get(c); if (infos == null) { infos = new HashMap(); Map methods = new HashMap(); Method methodArray[] = c.getMethods(); for (int i = 0; i < methodArray.length; i++) { String methodName = methodArray[i].getName(); methods.put(methodName, methodArray[i]); } Iterator methodIter = methods.keySet().iterator(); while (methodIter.hasNext()) { String getterName = (String) methodIter.next(); if (getterName.startsWith("get")) { String setterName = "set" + getterName.substring(3); String proxySetterName = "proxy" + getterName.substring(3); String proxyGetterName = "proxGet" + getterName.substring(3); if (methods.containsKey(setterName)) { Method getter = (Method) methods.get(getterName); Method setter = (Method) methods.get(setterName); Method proxySetter = (Method) methods.get(proxySetterName); Method proxyGetter = (Method) methods.get(proxyGetterName); String fieldname = (Character.isLowerCase(getterName.charAt(3)) ? getterName.substring(3, 4).toUpperCase() : getterName.substring(3, 4).toLowerCase()) + getterName.substring(4); if (!getter.getName().equals("getClass")) { FieldInfo info = new FieldInfo(fieldname, getter, setter, proxySetter, proxyGetter); infos.put(fieldname, info); } } } } classToFieldnameToFieldInfo.put(c, infos); } } return infos; } /** * Returns a FieldInfo object for the given class and field name. * * @param c the Class * @param fieldname the fieldname * @return a FieldInfo object, or null if the fieldname is not found */ public static FieldInfo getFieldInfo(Class c, String fieldname) { return (FieldInfo) getFieldInfos(c).get(fieldname); } /** * Gets the getter methods for the bean properties of a class * * @param c the Class * @return an array of the getter methods * @throws IntrospectionException if an error occurs */ public static Method[] getGetters(Class c) throws IntrospectionException { PropertyDescriptor[] pd = Introspector.getBeanInfo(c).getPropertyDescriptors(); Collection getters = new HashSet(); for (int i = 0; i < pd.length; i++) { Method getter = pd[i].getReadMethod(); if (!getter.getName().equals("getClass")) { getters.add(getter); } } return (Method[]) getters.toArray(new Method[] {}); } /** * Make all nested objects top-level in returned collection * * @param obj a top-level object or collection of such objects * @return a set of objects * @throws Exception if a problem occurred during flattening */ public static List flatten(Object obj) throws Exception { Collection c; if (obj instanceof Collection) { c = (Collection) obj; } else { c = Arrays.asList(new Object[] {obj}); } try { List toStore = new ArrayList(); Iterator i = c.iterator(); while (i.hasNext()) { flatten(i.next(), toStore); } return toStore; } catch (Exception e) { throw new Exception("Problem occurred flattening object", e); } } private static void flatten(Object o, Collection c) throws Exception { if (o == null || c.contains(o)) { return; } c.add(o); Method[] getters = TypeUtil.getGetters(o.getClass()); for (int i = 0; i < getters.length; i++) { Method getter = getters[i]; Class returnType = getter.getReturnType(); if (Collection.class.isAssignableFrom(returnType)) { Iterator iter = ((Collection) getter.invoke(o, new Object[] {})).iterator(); while (iter.hasNext()) { flatten(iter.next(), c); } } else if (!returnType.isPrimitive() && !returnType.getName().startsWith("java")) { flatten(getter.invoke(o, new Object[] {}), c); } } } /** * Returns the Class for a given name (promoting primitives to their container class) * * @param type a classname * @return the corresponding Class */ public static Class instantiate(String type) { if (type.equals(Integer.TYPE.toString())) { return Integer.class; } if (type.equals(Boolean.TYPE.toString())) { return Boolean.class; } if (type.equals(Double.TYPE.toString())) { return Double.class; } if (type.equals(Float.TYPE.toString())) { return Float.class; } if (type.equals(Long.TYPE.toString())) { return Long.class; } if (type.equals(Short.TYPE.toString())) { return Short.class; } if (type.equals(Byte.TYPE.toString())) { return Byte.class; } if (type.equals(Character.TYPE.toString())) { return Character.class; } Class cls = null; try { cls = Class.forName(type); } catch (Exception e) { } return cls; } /** * Returns an object for a given String * * @param clazz the class to convert to * @param value the value to convert * @return the corresponding Class */ public static Object stringToObject(Class clazz, String value) { if (clazz.equals(Integer.class) || clazz.equals(Integer.TYPE)) { return Integer.valueOf(value); } if (clazz.equals(Boolean.class) || clazz.equals(Boolean.TYPE)) { return Boolean.valueOf(value); } if (clazz.equals(Double.class) || clazz.equals(Double.TYPE)) { return Double.valueOf(value); } if (clazz.equals(Float.class) || clazz.equals(Float.TYPE)) { return Float.valueOf(value); } if (clazz.equals(Long.class) || clazz.equals(Long.TYPE)) { return Long.valueOf(value); } if (clazz.equals(Short.class) || clazz.equals(Short.TYPE)) { return Short.valueOf(value); } if (clazz.equals(Byte.class) || clazz.equals(Byte.TYPE)) { return Byte.valueOf(value); } if (clazz.equals(Character.class) || clazz.equals(Character.TYPE)) { return new Character(value.charAt(0)); } if (clazz.equals(Date.class)) { return new Date(Long.parseLong(value)); } if (clazz.equals(BigDecimal.class)) { return new BigDecimal(value); } if (clazz.equals(String.class)) { return new String(value); } if (clazz.equals(URL.class)) { try { return new URL(value); } catch (MalformedURLException e) { throw new RuntimeException(e); } } return value; } /** * Returns a String for a given object * * @param value the value to convert * @return the string representation */ public static String objectToString(Object value) { if (value instanceof Date) { return "" + ((Date) value).getTime(); } else { return value.toString(); } } /** * Inner class to hold info on a field. * * @author Matthew Wakeling * @author Andrew Varley */ public static class FieldInfo { private String name; private Method getter; private Method setter; private Method proxySetter; private Method proxyGetter; /** * Construct a new FieldInfo object. * * @param name the field name * @param getter the getter Method to retrieve the value * @param setter the setter Method to alter the value * @param proxySetter the setter Method to set the value to a ProxyReference * @param proxyGetter the getter Method to get the value without dereferencing * ProxyReferences */ public FieldInfo(String name, Method getter, Method setter, Method proxySetter, Method proxyGetter) { this.name = name; this.getter = getter; this.setter = setter; this.proxySetter = proxySetter; this.proxyGetter = proxyGetter; } /** * Returns the field name * * @return a String */ public String getName() { return name; } /** * Returns the getter Method. * * @return a getter Method */ public Method getGetter() { return getter; } /** * Returns the setter Method. * * @return a setter Method */ public Method getSetter() { return setter; } /** * Returns the proxySetter Method. * * @return a proxySetter Method */ public Method getProxySetter() { return proxySetter; } /** * Returns the proxyGetter Method. * * @return a proxyGetter Method */ public Method getProxyGetter() { return proxyGetter; } /** * Returns the type of the field. * * @return a Class object */ public Class getType() { return getter.getReturnType(); } } }
package handler; import lombok.Getter; import lombok.Setter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.stream.Collectors; public class ConfigHandler { /** The name of the configuration handler. */ private static final String FILENAME_CONFIG = "config.json"; /** The logging levels supported by FFMPEG as of 2015/Nov/1. */ public static final String[] FFMPEG_LOG_LEVELS = {"quiet", "panic", "fatal", "error", "warning", "info", "verbose", "debug", "trace"}; /** The absolute path to ffmpeg/ffmpeg.exe. */ @Getter @Setter private String ffmpegPath = ""; /** The absolute path to 7zip/7zip.exe or whichever compression program is specified. */ @Getter @Setter private String compressionProgramPath = ""; /** The format to encode to. */ @Getter @Setter private String encodeFormat = "mkv"; /** The format to decode to. */ @Getter @Setter private String decodeFormat = "7z"; /** The width, in pixels, of the encoded video. */ @Getter private int encodedVideoWidth; /** The height, in pixels, of the encoded video. */ @Getter private int encodedVideoHeight; /** The framerate of the video. Ex ~ 30fps, 60fps, etc... */ @Getter private int encodedFramerate; /** The size of each frame of video in bytes. */ @Getter private int frameSize; /** The width/height of each encoded macroblock. */ @Getter private int macroBlockDimensions; /** The codec to encode/decode the video with. */ @Getter @Setter private String encodingLibrary = "libvpx"; /** The level of information that should be given by ffmpeg while ffmpeg is running. */ @Getter @Setter private String ffmpegLogLevel = "info"; /** Whether or not to ignore all other ffmpeg options and to use the fullyCustomFfmpegEncodingOptions and fullyCustomFfmpegDecodingOptions instead. */ @Getter @Setter private boolean useFullyCustomFfmpegOptions; /** The user-entered command line arguments to use when encoding with ffmpeg. */ @Getter @Setter private String fullyCustomFfmpegEncodingOptions; /** The user-entered command line arguments to use when encoding with ffmpeg. */ @Getter @Setter private String fullyCustomFfmpegDecodingOptions; /** The base commands to use when compressing a handler before encoding. */ @Getter @Setter private String compressionCommands; /** The extension to use when outputting an archive. */ @Getter @Setter private String compressionOutputExtension; /** Whether or not to warn the user if their settings may not work with YouTube. */ @Getter @Setter private boolean warnUserIfSettingsMayNotWorkForYouTube = true; /** * Reads in each line from the configuration handler and attempts to parse * the specified parameters of the program. * * If a line cannot be parsed, then a warning is logged. */ public void loadConfigSettings() { try ( final InputStream inputStream = new FileInputStream("config.json"); final InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); final BufferedReader bufferedReader = new BufferedReader(streamReader); ) { final List<String> inputLines = bufferedReader.lines().collect(Collectors.toList()); final String jsonData = String.join("\n", inputLines); final JSONParser jsonParser = new JSONParser(); final JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonData); ffmpegPath = (String) jsonObject.get("FFMPEG Path"); compressionProgramPath = (String) jsonObject.get("Compression Program Path"); encodeFormat = (String) jsonObject.get("Enc Format"); decodeFormat = (String) jsonObject.get("Dec Format"); encodedVideoWidth = (int) (long) jsonObject.get("Enc Vid Width"); encodedVideoHeight = (int) (long) jsonObject.get("Enc Vid Height"); encodedFramerate = (int) (long) jsonObject.get("Enc Vid Framerate"); macroBlockDimensions = (int) (long) jsonObject.get("Enc Vid Macro Block Dimensions"); encodingLibrary = (String) jsonObject.get("Enc Library"); ffmpegLogLevel = (String) jsonObject.get("FFMPEG Log Level"); useFullyCustomFfmpegOptions = (Boolean) jsonObject.get("Use Custom FFMPEG Options"); fullyCustomFfmpegEncodingOptions = (String) jsonObject.get("Custom FFMPEG Enc Options"); fullyCustomFfmpegDecodingOptions = (String) jsonObject.get("Custom FFMPEG Dec Options"); compressionCommands = (String) jsonObject.get("Compression Commands"); compressionOutputExtension = (String) jsonObject.get("Compression Output Extension"); warnUserIfSettingsMayNotWorkForYouTube = (Boolean) jsonObject.get("Warn If Settings Possibly Incompatible With YouTube"); } catch(final IOException e) { final Logger logger = LogManager.getLogger(); logger.error(e); createNewConfigFile(); loadConfigSettings(); } catch(final ClassCastException | NullPointerException | ParseException e) { final Logger logger = LogManager.getLogger(); logger.error(e); e.printStackTrace(); setDefaultSettings(); } // Check if all options have been loaded correctly: final Logger logger = LogManager.getLogger(); if(encodedVideoWidth < 1) { logger.warn("Encoded Video Width option is less than 1. Ensure the value is 1 or greater. " + "Defaulting to 1280."); encodedVideoWidth = 1280; } if(encodedVideoHeight < 1) { logger.warn("Encoded Video Height option is less than 1. Ensure the value is 1 or greater. " + "Defaulting to 720."); encodedVideoWidth = 720; } if(encodedFramerate < 1) { logger.warn("Encoded Video Framerate option is less than 1. Ensure the value is 1 or greater. " + "Defaulting to 30."); encodedFramerate = 30; } if(macroBlockDimensions < 1) { logger.warn("Encoded Video Macro Block Dimensions is less than 1. Ensure the value is 1 or greater. " + "Defaulting to 8."); macroBlockDimensions = 8; } // Calculate Frame Size: frameSize = calculateFrameSize(); } /** * Creates a new configuration file, or overwrites the existing file, * using the existing values for each option. */ public void createConfigFile() { final JSONObject configFile = new JSONObject(); configFile.put("FFMPEG Path", ffmpegPath); configFile.put("Compression Program Path", compressionProgramPath); configFile.put("Enc Format", encodeFormat); configFile.put("Dec Format", decodeFormat); configFile.put("Enc Vid Width", encodedVideoWidth); configFile.put("Enc Vid Height", encodedVideoHeight); configFile.put("Enc Vid Framerate", encodedFramerate); configFile.put("Enc Vid Macro Block Dimensions", macroBlockDimensions); configFile.put("Enc Library", encodingLibrary); configFile.put("FFMPEG Log Level", ffmpegLogLevel); configFile.put("Use Custom FFMPEG Options", useFullyCustomFfmpegOptions); configFile.put("Custom FFMPEG Enc Options", fullyCustomFfmpegEncodingOptions); configFile.put("Custom FFMPEG Dec Options", fullyCustomFfmpegDecodingOptions); configFile.put("Compression Commands", compressionCommands); configFile.put("Compression Output Extension", compressionOutputExtension); configFile.put("Warn If Settings Possibly Incompatible With YouTube", warnUserIfSettingsMayNotWorkForYouTube); try ( final FileWriter fileWriter = new FileWriter(FILENAME_CONFIG); ) { fileWriter.write(configFile.toJSONString()); fileWriter.flush(); } catch(final IOException e) { final Logger logger = LogManager.getLogger(); logger.error(e); setDefaultSettings(); } } /** * Creates a new configuration file, or overwrites the existing file, * using the default values for each option. */ public void createNewConfigFile() { final JSONObject configFile = new JSONObject(); configFile.put("FFMPEG Path", ""); configFile.put("Compression Program Path", ""); configFile.put("Enc Format", "mkv"); configFile.put("Dec Format", "jpg"); configFile.put("Enc Vid Width", 1280); configFile.put("Enc Vid Height", 720); configFile.put("Enc Vid Framerate", 30); configFile.put("Enc Vid Macro Block Dimensions", 8); configFile.put("Enc Library", "libvpx"); configFile.put("FFMPEG Log Level", "info"); configFile.put("Use Custom FFMPEG Options", false); configFile.put("Custom FFMPEG Enc Options", ""); configFile.put("Custom FFMPEG Dec Options", ""); configFile.put("Delete Source File When Enc", false); configFile.put("Delete Source File When Dec", false); configFile.put("Compression Commands", "a -m0=lzma -mx=9 -mfb=64 -md=32m -ms=on"); configFile.put("Compression Output Extension", "7z"); configFile.put("Check For Updates", true); configFile.put("Warn If Settings Possibly Incompatible With YouTube", true); try ( final FileWriter fileWriter = new FileWriter(FILENAME_CONFIG); ) { fileWriter.write(configFile.toJSONString()); fileWriter.flush(); } catch(final IOException e) { final Logger logger = LogManager.getLogger(); logger.error(e); setDefaultSettings(); } } /** * Sets all program settings to their default state. * * This should only be called if the configuration file cannot * be created or properly parsed. */ private void setDefaultSettings() { ffmpegPath = ""; compressionProgramPath = ""; encodeFormat = "mkv"; decodeFormat = "7z"; encodedVideoWidth = 1280; encodedVideoHeight = 720; encodedFramerate = 30; macroBlockDimensions = 8; encodingLibrary = "libvpx"; ffmpegLogLevel = "info"; useFullyCustomFfmpegOptions = false; fullyCustomFfmpegEncodingOptions = ""; fullyCustomFfmpegDecodingOptions = ""; compressionCommands = "a -m0=lzma -mx=9 -mfb=64 -md=32m -ms=on"; compressionOutputExtension = "7z"; warnUserIfSettingsMayNotWorkForYouTube = true; } /** * Calculates and returns the Frame Size for the current Encoded * Video Width & Height. * * @return * The Frame Size for the current Encoded Video Width & * Height. */ private int calculateFrameSize() { /* * We want to calculate the frame size in bytes given a resolution (width x height). * * width * height = Total pixels in frame. * * Each pixel is scaled up by a factor of (8 * 8) to ensure * the video uses 8x8 blocks for each pixel, or 64 pixels * per bit. * * Each input byte is a set of 8 1-bit pixels. * Therefore 1 byte = 8 pixels. * This is where the "/ 8" comes from in the last step. */ int frameSize = (encodedVideoWidth * encodedVideoHeight); frameSize /= (macroBlockDimensions * macroBlockDimensions); // (8 *8) frameSize /= Byte.SIZE; return frameSize; } /** * Sets the new Encoded Video Width, then recalculates the Frame Size. * * @param encodedVideoWidth * The width, in pixels, to use when encoding a video. */ public void setEncodedVideoWidth(final int encodedVideoWidth) { if (encodedVideoWidth > 1) { this.encodedVideoWidth = encodedVideoWidth; } else { final Logger logger = LogManager.getLogger(); logger.warn("Encoded Video Width cannot be set to less than 1. Ensure the value is 1 or greater. " + "Defaulting to 1280."); this.encodedVideoWidth = 1280; } calculateFrameSize(); } /** * Sets the new Encoded Video Height, then recalculates the Frame Size. * * @param encodedVideoHeight * The height, in pixels, to use when encoding a video. */ public void setEncodedVideoHeight(final int encodedVideoHeight) { if(encodedVideoHeight >= 1) { this.encodedVideoHeight = encodedVideoHeight; } else { final Logger logger = LogManager.getLogger(); logger.warn("Encoded Video Height cannot be set to less than 1. Ensure the value is 1 or greater. " + "Defaulting to 720."); this.encodedVideoHeight = 720; } calculateFrameSize(); } /** * Sets the new Encoded Video Framerate. * * @param encodedFramerate * The framerate to use when encoding a video. */ public void setEncodedFramerate(final int encodedFramerate) { if(encodedFramerate >= 1) { this.encodedFramerate = encodedFramerate; } else { final Logger logger = LogManager.getLogger(); logger.warn("Encoded Video Framerate cannot be set to less than 1. Ensure the value is 1 or greater. " + "Defaulting to 30."); this.encodedFramerate = 30; } } /** * Sets the new Encoded Video Macro Block Dimensions. * * @param macroBlockDimensions * The new Macro Block width/height to use when encoding a video. */ public void setMacroBlockDimensions(final int macroBlockDimensions) { if(macroBlockDimensions >= 1) { this.macroBlockDimensions = macroBlockDimensions; } else { final Logger logger = LogManager.getLogger(); logger.warn("Encoded Video Framerate cannot be set to less than 1. Ensure the value is 1 or greater. " + "Defaulting to 8."); this.macroBlockDimensions = 8; } } }
package ibis.satin.impl; import ibis.util.Timer; public abstract class Stats extends TupleSpace { void initTimers() { if (totalTimer == null) totalTimer = new Timer(); if (stealTimer == null) stealTimer = new Timer(); if (handleStealTimer == null) handleStealTimer = new Timer(); if (abortTimer == null) abortTimer = new Timer(); if (idleTimer == null) idleTimer = new Timer(); if (pollTimer == null) pollTimer = new Timer(); if (tupleTimer == null) tupleTimer = new Timer(); if (invocationRecordWriteTimer == null) invocationRecordWriteTimer = new Timer(); if (invocationRecordReadTimer == null) invocationRecordReadTimer = new Timer(); if (tupleOrderingWaitTimer == null) tupleOrderingWaitTimer = new Timer(); if (lookupTimer == null) lookupTimer = new Timer(); if (updateTimer == null) updateTimer = new Timer(); if (handleUpdateTimer == null) handleUpdateTimer = new Timer(); if (handleLookupTimer == null) handleLookupTimer = new Timer(); if (tableSerializationTimer == null) tableSerializationTimer = new Timer(); if (tableDeserializationTimer == null) tableDeserializationTimer = new Timer(); if (crashTimer == null) crashTimer = new Timer(); if (redoTimer == null) redoTimer = new Timer(); if (addReplicaTimer == null) addReplicaTimer = new Timer(); } protected StatsMessage createStats() { StatsMessage s = new StatsMessage(); s.spawns = spawns; s.jobsExecuted = jobsExecuted; s.syncs = syncs; s.aborts = aborts; s.abortMessages = abortMessages; s.abortedJobs = abortedJobs; s.stealAttempts = stealAttempts; s.stealSuccess = stealSuccess; s.tupleMsgs = tupleMsgs; s.tupleBytes = tupleBytes; s.stolenJobs = stolenJobs; s.stealRequests = stealRequests; s.interClusterMessages = interClusterMessages; s.intraClusterMessages = intraClusterMessages; s.interClusterBytes = interClusterBytes; s.intraClusterBytes = intraClusterBytes; s.stealTime = stealTimer.totalTimeVal(); s.handleStealTime = handleStealTimer.totalTimeVal(); s.abortTime = abortTimer.totalTimeVal(); s.idleTime = idleTimer.totalTimeVal(); s.idleCount = idleTimer.nrTimes(); s.pollTime = pollTimer.totalTimeVal(); s.pollCount = pollTimer.nrTimes(); s.tupleTime = tupleTimer.totalTimeVal(); s.tupleWaitTime = tupleOrderingWaitTimer.totalTimeVal(); s.tupleWaitCount = tupleOrderingWaitTimer.nrTimes(); s.invocationRecordWriteTime = invocationRecordWriteTimer.totalTimeVal(); s.invocationRecordWriteCount = invocationRecordWriteTimer.nrTimes(); s.invocationRecordReadTime = invocationRecordReadTimer.totalTimeVal(); s.invocationRecordReadCount = invocationRecordReadTimer.nrTimes(); //fault tolerance if (FAULT_TOLERANCE) { s.tableResultUpdates = globalResultTable.numResultUpdates; s.tableLockUpdates = globalResultTable.numLockUpdates; s.tableUpdateMessages = globalResultTable.numUpdateMessages; s.tableLookups = globalResultTable.numLookups; s.tableSuccessfulLookups = globalResultTable.numLookupsSucceded; s.tableRemoteLookups = globalResultTable.numRemoteLookups; s.killedOrphans = killedOrphans; s.restartedJobs = restartedJobs; s.tableLookupTime = lookupTimer.totalTimeVal(); s.tableUpdateTime = updateTimer.totalTimeVal(); s.tableHandleUpdateTime = handleUpdateTimer.totalTimeVal(); s.tableHandleLookupTime = handleLookupTimer.totalTimeVal(); s.tableSerializationTime = tableSerializationTimer.totalTimeVal(); s.tableDeserializationTime = tableDeserializationTimer.totalTimeVal(); s.tableCheckTime = redoTimer.totalTimeVal(); s.crashHandlingTime = crashTimer.totalTimeVal(); s.addReplicaTime = addReplicaTimer.totalTimeVal(); } return s; } protected void printStats() { int size; synchronized (this) { // size = victims.size(); // No, this is one too few. (Ceriel) size = victims.size() + 1; } // add my own stats StatsMessage me = createStats(); totalStats.add(me); java.text.NumberFormat nf = java.text.NumberFormat.getInstance(); // pf.setMaximumIntegerDigits(3); // pf.setMinimumIntegerDigits(3); // for percentages java.text.NumberFormat pf = java.text.NumberFormat.getInstance(); pf.setMaximumFractionDigits(3); pf.setMinimumFractionDigits(3); pf.setGroupingUsed(false); out .println(" if (SPAWN_STATS) { out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns) + " spawns, " + nf.format(totalStats.jobsExecuted) + " executed, " + nf.format(totalStats.syncs) + " syncs"); if (ABORTS) { out.println("SATIN: ABORT: " + nf.format(totalStats.aborts) + " aborts, " + nf.format(totalStats.abortMessages) + " abort msgs, " + nf.format(totalStats.abortedJobs) + " aborted jobs"); } } if (TUPLE_STATS) { out.println("SATIN: TUPLE_SPACE: " + nf.format(totalStats.tupleMsgs) + " bcasts, " + nf.format(totalStats.tupleBytes) + " bytes"); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL: poll count = " + nf.format(totalStats.pollCount)); } if (IDLE_TIMING) { out.println("SATIN: IDLE: idle count = " + nf.format(totalStats.idleCount)); } if (STEAL_STATS) { out .println("SATIN: STEAL: " + nf.format(totalStats.stealAttempts) + " attempts, " + nf.format(totalStats.stealSuccess) + " successes (" + pf .format(((double) totalStats.stealSuccess / totalStats.stealAttempts) * 100.0) + " %)"); out.println("SATIN: MESSAGES: intra " + nf.format(totalStats.intraClusterMessages) + " msgs, " + nf.format(totalStats.intraClusterBytes) + " bytes; inter " + nf.format(totalStats.interClusterMessages) + " msgs, " + nf.format(totalStats.interClusterBytes) + " bytes"); } if (FAULT_TOLERANCE && GRT_STATS) { out.println("SATIN: GLOBAL_RESULT_TABLE: result updates " + nf.format(totalStats.tableResultUpdates) + ",update messages " + nf.format(totalStats.tableUpdateMessages) + ", lock updates " + nf.format(totalStats.tableLockUpdates) + ",lookups " + nf.format(totalStats.tableLookups) + ",successful " + nf.format(totalStats.tableSuccessfulLookups) + ",remote " + nf.format(totalStats.tableRemoteLookups)); } if (FAULT_TOLERANCE && FT_STATS) { out.println("SATIN: FAULT_TOLERANCE: killed orphans " + nf.format(totalStats.killedOrphans)); out.println("SATIN: FAULT_TOLERANCE: restarted jobs " + nf.format(totalStats.restartedJobs)); } out .println(" if (STEAL_TIMING) { out.println("SATIN: STEAL_TIME: total " + Timer.format(totalStats.stealTime) + " time/req " + Timer.format(totalStats.stealTime / totalStats.stealAttempts)); out.println("SATIN: HANDLE_STEAL_TIME: total " + Timer.format(totalStats.handleStealTime) + " time/handle " + Timer.format((totalStats.handleStealTime) / totalStats.stealAttempts)); out.println("SATIN: SERIALIZATION_TIME: total " + Timer.format(totalStats.invocationRecordWriteTime) + " time/write " + Timer.format(totalStats.invocationRecordWriteTime / totalStats.stealSuccess)); out.println("SATIN: DESERIALIZATION_TIME: total " + Timer.format(totalStats.invocationRecordReadTime) + " time/read " + Timer.format(totalStats.invocationRecordReadTime / totalStats.stealSuccess)); } if (ABORT_TIMING) { out.println("SATIN: ABORT_TIME: total " + Timer.format(totalStats.abortTime) + " time/abort " + Timer.format(totalStats.abortTime / totalStats.aborts)); } if (TUPLE_TIMING) { out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total " + Timer.format(totalStats.tupleTime) + " time/bcast " + Timer.format(totalStats.tupleTime / totalStats.tupleMsgs)); out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total " + Timer.format(totalStats.tupleWaitTime) + " time/bcast " + Timer.format(totalStats.tupleWaitTime / totalStats.tupleWaitCount)); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL_TIME: total " + Timer.format(totalStats.pollTime) + " time/poll " + Timer.format(totalStats.pollTime / totalStats.pollCount)); } if (IDLE_TIMING) { out.println("SATIN: IDLE_TIME: total " + Timer.format(totalStats.idleTime) + " time/idle " + Timer.format(totalStats.idleTime / totalStats.idleCount)); } if (FAULT_TOLERANCE && GRT_TIMING) { out.println("SATIN: GRT_UPDATE_TIME: total " + Timer.format(totalStats.tableUpdateTime) + " time/update " + Timer.format(totalStats.tableUpdateTime / (totalStats.tableResultUpdates + totalStats.tableLockUpdates))); out.println("SATIN: GRT_LOOKUP_TIME: total " + Timer.format(totalStats.tableLookupTime) + " time/lookup " + Timer.format(totalStats.tableLookupTime / totalStats.tableLookups)); out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total " + Timer.format(totalStats.tableHandleUpdateTime) + " time/handle " + Timer.format(totalStats.tableHandleUpdateTime / totalStats.tableResultUpdates * (size - 1))); out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total " + Timer.format(totalStats.tableHandleLookupTime) + " time/handle " + Timer.format(totalStats.tableHandleLookupTime / totalStats.tableRemoteLookups)); out.println("SATIN: GRT_SERIALIZATION_TIME: total " + Timer.format(totalStats.tableSerializationTime)); out.println("SATIN: GRT_DESERIALIZATION_TIME: total " + Timer.format(totalStats.tableDeserializationTime)); out.println("SATIN: GRT_CHECK_TIME: total " + Timer.format(totalStats.tableCheckTime) + " time/check " + Timer.format(totalStats.tableCheckTime / totalStats.tableLookups)); } if (FAULT_TOLERANCE && CRASH_TIMING) { out.println("SATIN: CRASH_HANDLING_TIME: total " + Timer.format(totalStats.crashHandlingTime)); } if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) { out.println("SATIN: ADD_REPLICA_TIME: total " + Timer.format(totalStats.addReplicaTime)); } out .println(" out.println("SATIN: TOTAL_RUN_TIME: " + Timer.format(totalTimer.totalTimeVal())); double lbTime = (totalStats.stealTime + totalStats.handleStealTime - totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime) / size; if (lbTime < 0.0) lbTime = 0.0; double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0; double serTime = (totalStats.invocationRecordWriteTime + totalStats.invocationRecordReadTime) / size; double serPerc = serTime / totalTimer.totalTimeVal() * 100.0; double abortTime = totalStats.abortTime / size; double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0; double tupleTime = totalStats.tupleTime / size; double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0; double tupleWaitTime = totalStats.tupleWaitTime / size; double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal() * 100.0; double pollTime = totalStats.pollTime / size; double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0; double tableUpdateTime = totalStats.tableUpdateTime / size; double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal() * 100.0; double tableLookupTime = totalStats.tableLookupTime / size; double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal() * 100.0; double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size; double tableHandleUpdatePerc = tableHandleUpdateTime / totalTimer.totalTimeVal() * 100.0; double tableHandleLookupTime = totalStats.tableHandleLookupTime / size; double tableHandleLookupPerc = tableHandleLookupTime / totalTimer.totalTimeVal() * 100.0; double tableSerializationTime = totalStats.tableSerializationTime / size; double tableSerializationPerc = tableSerializationTime / totalTimer.totalTimeVal() * 100; double tableDeserializationTime = totalStats.tableDeserializationTime / size; double tableDeserializationPerc = tableDeserializationTime / totalTimer.totalTimeVal() * 100; double crashHandlingTime = totalStats.crashHandlingTime / size; double crashHandlingPerc = crashHandlingTime / totalTimer.totalTimeVal() * 100.0; double addReplicaTime = totalStats.addReplicaTime / size; double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal() * 100.0; double totalOverhead = (totalStats.stealTime / size) + abortTime + tupleTime + tupleWaitTime + pollTime + tableUpdateTime + tableLookupTime + tableHandleUpdateTime + tableHandleLookupTime; double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0; double appTime = totalTimer.totalTimeVal() - totalOverhead; if (appTime < 0.0) appTime = 0.0; double appPerc = appTime / totalTimer.totalTimeVal() * 100.0; if (STEAL_TIMING) { out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine " + Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "") + pf.format(lbPerc) + " %)"); out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine " + Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "") + pf.format(serPerc) + " %)"); } if (ABORT_TIMING) { out.println("SATIN: ABORT_TIME: avg. per machine " + Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "") + pf.format(abortPerc) + " %)"); } if (TUPLE_TIMING) { out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine " + Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "") + pf.format(tuplePerc) + " %)"); out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine " + Timer.format(tupleWaitTime) + " (" + (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc) + " %)"); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL_TIME: avg. per machine " + Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "") + pf.format(pollPerc) + " %)"); } if (FAULT_TOLERANCE && GRT_TIMING) { out .println("SATIN: GRT_UPDATE_TIME: avg. per machine " + Timer.format(tableUpdateTime) + " (" + pf.format(tableUpdatePerc) + " %)"); out .println("SATIN: GRT_LOOKUP_TIME: avg. per machine " + Timer.format(tableLookupTime) + " (" + pf.format(tableLookupPerc) + " %)"); out .println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine " + Timer.format(tableHandleUpdateTime) + " (" + pf.format(tableHandleUpdatePerc) + " %)"); out .println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine " + Timer.format(tableHandleLookupTime) + " (" + pf.format(tableHandleLookupPerc) + " %)"); out .println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine " + Timer.format(tableSerializationTime) + " (" + pf.format(tableSerializationPerc) + " %)"); out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine " + Timer.format(tableDeserializationTime) + " (" + pf.format(tableDeserializationPerc) + " %)"); } if (FAULT_TOLERANCE && CRASH_TIMING) { out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine " + Timer.format(crashHandlingTime) + " (" + pf.format(crashHandlingPerc) + " %)"); } if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) { out.println("SATIN: ADD_REPLICA_TIME: avg. per machine " + Timer.format(addReplicaTime) + " (" + pf.format(addReplicaPerc) + " %)"); } out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine " + Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "") + pf.format(totalPerc) + " %)"); out.println("SATIN: USEFUL_APP_TIME: avg. per machine " + Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "") + pf.format(appPerc) + " %)"); } protected void printDetailedStats() { java.text.NumberFormat nf = java.text.NumberFormat.getInstance(); if (SPAWN_STATS) { out.println("SATIN '" + ident.name() + "': SPAWN_STATS: spawns = " + spawns + " executed = " + jobsExecuted + " syncs = " + syncs); if (ABORTS) { out.println("SATIN '" + ident.name() + "': ABORT_STATS 1: aborts = " + aborts + " abort msgs = " + abortMessages + " aborted jobs = " + abortedJobs); } } if (TUPLE_STATS) { out.println("SATIN '" + ident.name() + "': TUPLE_STATS 1: tuple bcast msgs: " + tupleMsgs + ", bytes = " + nf.format(tupleBytes)); } if (STEAL_STATS) { out.println("SATIN '" + ident.name() + "': INTRA_STATS: messages = " + intraClusterMessages + ", bytes = " + nf.format(intraClusterBytes)); out.println("SATIN '" + ident.name() + "': INTER_STATS: messages = " + interClusterMessages + ", bytes = " + nf.format(interClusterBytes)); out .println("SATIN '" + ident.name() + "': STEAL_STATS 1: attempts = " + stealAttempts + " success = " + stealSuccess + " (" + (((double) stealSuccess / stealAttempts) * 100.0) + " %)"); out.println("SATIN '" + ident.name() + "': STEAL_STATS 2: requests = " + stealRequests + " jobs stolen = " + stolenJobs); if (STEAL_TIMING) { out.println("SATIN '" + ident.name() + "': STEAL_STATS 3: attempts = " + stealTimer.nrTimes() + " total time = " + stealTimer.totalTime() + " avg time = " + stealTimer.averageTime()); out.println("SATIN '" + ident.name() + "': STEAL_STATS 4: handleSteals = " + handleStealTimer.nrTimes() + " total time = " + handleStealTimer.totalTime() + " avg time = " + handleStealTimer.averageTime()); out.println("SATIN '" + ident.name() + "': STEAL_STATS 5: invocationRecordWrites = " + invocationRecordWriteTimer.nrTimes() + " total time = " + invocationRecordWriteTimer.totalTime() + " avg time = " + invocationRecordWriteTimer.averageTime()); out.println("SATIN '" + ident.name() + "': STEAL_STATS 6: invocationRecordReads = " + invocationRecordReadTimer.nrTimes() + " total time = " + invocationRecordReadTimer.totalTime() + " avg time = " + invocationRecordReadTimer.averageTime()); } if (ABORTS && ABORT_TIMING) { out.println("SATIN '" + ident.name() + "': ABORT_STATS 2: aborts = " + abortTimer.nrTimes() + " total time = " + abortTimer.totalTime() + " avg time = " + abortTimer.averageTime()); } if (IDLE_TIMING) { out.println("SATIN '" + ident.name() + "': IDLE_STATS: idle count = " + idleTimer.nrTimes() + " total time = " + idleTimer.totalTime() + " avg time = " + idleTimer.averageTime()); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN '" + ident.name() + "': POLL_STATS: poll count = " + pollTimer.nrTimes() + " total time = " + pollTimer.totalTime() + " avg time = " + pollTimer.averageTime()); } if (STEAL_TIMING && IDLE_TIMING) { out.println("SATIN '" + ident.name() + "': COMM_STATS: software comm time = " + Timer.format(stealTimer.totalTimeVal() + handleStealTimer.totalTimeVal() - idleTimer.totalTimeVal())); } if (TUPLE_TIMING) { out.println("SATIN '" + ident.name() + "': TUPLE_STATS 2: bcasts = " + tupleTimer.nrTimes() + " total time = " + tupleTimer.totalTime() + " avg time = " + tupleTimer.averageTime()); out.println("SATIN '" + ident.name() + "': TUPLE_STATS 3: waits = " + tupleOrderingWaitTimer.nrTimes() + " total time = " + tupleOrderingWaitTimer.totalTime() + " avg time = " + tupleOrderingWaitTimer.averageTime()); } algorithm.printStats(out); } if (FAULT_TOLERANCE) { if (GRT_STATS) { out.println("SATIN '" + ident.name() + "': " + globalResultTable.numResultUpdates + " result updates of the table."); out.println("SATIN '" + ident.name() + "': " + globalResultTable.numLockUpdates + " lock updates of the table."); out.println("SATIN '" + ident.name() + "': " + globalResultTable.numUpdateMessages + " update messages."); out.println("SATIN '" + ident.name() + "': " + globalResultTable.numLookupsSucceded + " lookups succeded, of which:"); out.println("SATIN '" + ident.name() + "': " + globalResultTable.numRemoteLookups + " remote lookups."); out.println("SATIN '" + ident.name() + "': " + globalResultTable.maxNumEntries + " entries maximally."); } if (GRT_TIMING) { out.println("SATIN '" + ident.name() + "': " + lookupTimer.totalTime() + " spent in lookups"); out.println("SATIN '" + ident.name() + "': " + lookupTimer.averageTime() + " per lookup"); out.println("SATIN '" + ident.name() + "': " + updateTimer.totalTime() + " spent in updates"); out.println("SATIN '" + ident.name() + "': " + updateTimer.averageTime() + " per update"); out.println("SATIN '" + ident.name() + "': " + handleUpdateTimer.totalTime() + " spent in handling updates"); out.println("SATIN '" + ident.name() + "': " + handleUpdateTimer.averageTime() + " per update handle"); out.println("SATIN '" + ident.name() + "': " + handleLookupTimer.totalTime() + " spent in handling lookups"); out.println("SATIN '" + ident.name() + "': " + handleLookupTimer.averageTime() + " per lookup handle"); } if (CRASH_TIMING) { out .println("SATIN '" + ident.name() + "': " + crashTimer.totalTime() + " spent in handling crashes"); } if (TABLE_CHECK_TIMING) { out.println("SATIN '" + ident.name() + "': " + redoTimer.totalTime() + " spent in redoing"); } if (FT_STATS) { out.println("SATIN '" + ident.name() + "': " + killedOrphans + " orphans killed"); out.println("SATIN '" + ident.name() + "': " + restartedJobs + " jobs restarted"); } } } }
package controllers; import models.Module; import models.ModuleVersion; import models.User; import org.apache.commons.lang.StringUtils; import play.Logger; import play.data.validation.Required; import play.data.validation.Validation; import play.libs.MimeTypes; import play.mvc.Before; import util.JavaExtensions; import util.Util; import java.io.File; import java.io.IOException; import java.util.List; public class Repo extends MyController { // we set it if it's there, otherwise we don't require it @Before static void setConnectedUser() { if(Security.isConnected()) { User user = User.find("byUserName", Security.connected()).first(); renderArgs.put("user", user); } } public static void index(){ List<models.Module> modules = models.Module.find("ORDER BY name").fetch(); render(modules); } public static void versions(@Required String moduleName){ if(validationFailed()){ index(); } models.Module module = models.Module.findByName(moduleName); if(module == null){ Validation.addError(null, "Unknown module"); prepareForErrorRedirect(); index(); } List<models.ModuleVersion> versions = models.ModuleVersion.findByModule(module); render(module, versions); } public static void search(String q){ if(StringUtils.isEmpty(q)) index(); List<models.Module> modules = models.Module.searchByName(q); render(modules, q); } public static void view(@Required String moduleName, @Required String version){ models.ModuleVersion moduleVersion = getModuleVersion(moduleName, version); models.Module module = moduleVersion.module; render(module, moduleVersion); } public static void viewDoc(@Required String moduleName, @Required String version){ models.ModuleVersion moduleVersion = getModuleVersion(moduleName, version); models.Module module = moduleVersion.module; render(module, moduleVersion); } private static ModuleVersion getModuleVersion(String moduleName, String version) { if(validationFailed()) index(); models.ModuleVersion moduleVersion = models.ModuleVersion.findByVersion(moduleName, version); if(moduleVersion == null){ Validation.addError(null, "Unknown module"); prepareForErrorRedirect(); index(); } return moduleVersion; } public static void viewFile(String path) throws IOException{ File repoDir = Util.getRepoDir(); File file = new File(repoDir, path); checkPath(file, repoDir); if(!file.exists()) notFound(path); if(file.isDirectory()){ // try a module version ModuleVersion moduleVersion = findModuleVersion(file); Module module = null; if(moduleVersion == null){ // try a module module= findModule(file); } render("Repo/viewFile.html", file, moduleVersion, module); }else{ response.contentType = MimeTypes.getContentType(file.getName()); increaseStats(file); renderBinary(file); } } private static Module findModule(File file) { for(File f : file.listFiles()){ if(!f.isDirectory()){ // fail fast: if we have a file we're not in a module dir return null; } // look for a ModuleVersion in the first folder we find ModuleVersion v = findModuleVersion(f); // fail fast if there's no ModuleVersion there, it means we're not in a module dir return v != null ? v.module : null; } return null; } private static ModuleVersion findModuleVersion(File file) { for(File f : file.listFiles()){ if(f.isDirectory()){ // fail fast: if we have a directory and it's not "module-doc" we're not in a module version dir if(!f.getName().equals("module-doc")) return null; continue; } ModuleVersion v = findModuleVersion(f.getName(), f, ".car"); if(v != null) return v; } return null; } private static void increaseStats(File file) { String name = file.getName(); ModuleVersion mv = findModuleVersion(name, file, ".car"); if(mv != null){ ModuleVersion.incrementDownloads(mv); return; } mv = findModuleVersion(name, file, ".jar"); if(mv != null){ ModuleVersion.incrementDownloads(mv); return; } mv = findModuleVersion(name, file, ".js"); if(mv != null){ ModuleVersion.incrementJSDownloads(mv); return; } mv = findModuleVersion(name, file, ".src"); if(mv != null){ ModuleVersion.incrementSourceDownloads(mv); return; } } private static ModuleVersion findModuleVersion(String name, File file, String extension){ if(!name.endsWith(extension)){ return null; } String path = JavaExtensions.relative(file); Logger.debug("Path: %s", path); int lastFileSep = path.lastIndexOf(File.separatorChar); if(lastFileSep == -1){ Logger.info("Got a %s without a module? %s", extension, path); return null; } String moduleAndVersion = path.substring(0, lastFileSep); int versionSep = moduleAndVersion.lastIndexOf(File.separatorChar); if(versionSep == -1){ Logger.info("Got a %s without a version? %s", extension, path); return null; } String moduleName = moduleAndVersion.substring(0, versionSep).replace(File.separatorChar, '.'); String version = moduleAndVersion.substring(versionSep+1); if(moduleName.isEmpty() || version.isEmpty()){ Logger.info("Got a %s with empty name or version? %s", extension, path); return null; } String expectedName = moduleName+"-"+version+extension; if(!name.equals(expectedName)){ Logger.info("%s name %s doesn't match expected name %s", extension, name, expectedName); return null; } Logger.debug("We got a %s", extension); ModuleVersion moduleVersion = ModuleVersion.findByVersion(moduleName, version); if(moduleVersion == null){ Logger.info("Failed to find a ModuleVersion for %s/%s", moduleName, version); return null; } return moduleVersion; } public static void noFile() throws IOException{ render(); } private static void checkPath(File file, File repoDir) throws IOException{ String repoPath = repoDir.getCanonicalPath(); String filePath = file.getCanonicalPath(); if(!filePath.startsWith(repoPath)) forbidden("Path is not valid"); } }
package ibis.satin.impl; import ibis.util.Timer; public abstract class Stats extends SharedObjects { protected StatsMessage createStats() { StatsMessage s = new StatsMessage(); s.spawns = spawns; s.jobsExecuted = jobsExecuted; s.syncs = syncs; s.aborts = aborts; s.abortMessages = abortMessages; s.abortedJobs = abortedJobs; s.stealAttempts = stealAttempts; s.stealSuccess = stealSuccess; s.tupleMsgs = tupleMsgs; s.tupleBytes = tupleBytes; s.stolenJobs = stolenJobs; s.stealRequests = stealRequests; s.interClusterMessages = interClusterMessages; s.intraClusterMessages = intraClusterMessages; s.interClusterBytes = interClusterBytes; s.intraClusterBytes = intraClusterBytes; s.stealTime = stealTimer.totalTimeVal(); s.handleStealTime = handleStealTimer.totalTimeVal(); s.abortTime = abortTimer.totalTimeVal(); s.idleTime = idleTimer.totalTimeVal(); s.idleCount = idleTimer.nrTimes(); s.pollTime = pollTimer.totalTimeVal(); s.pollCount = pollTimer.nrTimes(); s.tupleTime = tupleTimer.totalTimeVal(); s.handleTupleTime = handleTupleTimer.totalTimeVal(); s.tupleWaitTime = tupleOrderingWaitTimer.totalTimeVal(); s.tupleWaitCount = tupleOrderingWaitTimer.nrTimes(); s.invocationRecordWriteTime = invocationRecordWriteTimer.totalTimeVal(); s.invocationRecordWriteCount = invocationRecordWriteTimer.nrTimes(); s.invocationRecordReadTime = invocationRecordReadTimer.totalTimeVal(); s.invocationRecordReadCount = invocationRecordReadTimer.nrTimes(); s.returnRecordWriteTime = returnRecordWriteTimer.totalTimeVal(); s.returnRecordWriteCount = returnRecordWriteTimer.nrTimes(); s.returnRecordReadTime = returnRecordReadTimer.totalTimeVal(); s.returnRecordReadCount = returnRecordReadTimer.nrTimes(); s.returnRecordBytes = returnRecordBytes; //fault tolerance if (FAULT_TOLERANCE) { s.tableResultUpdates = globalResultTable.numResultUpdates; s.tableLockUpdates = globalResultTable.numLockUpdates; s.tableUpdateMessages = globalResultTable.numUpdateMessages; s.tableLookups = globalResultTable.numLookups; s.tableSuccessfulLookups = globalResultTable.numLookupsSucceded; s.tableRemoteLookups = globalResultTable.numRemoteLookups; s.killedOrphans = killedOrphans; s.restartedJobs = restartedJobs; s.tableLookupTime = lookupTimer.totalTimeVal(); s.tableUpdateTime = updateTimer.totalTimeVal(); s.tableHandleUpdateTime = handleUpdateTimer.totalTimeVal(); s.tableHandleLookupTime = handleLookupTimer.totalTimeVal(); s.tableSerializationTime = tableSerializationTimer.totalTimeVal(); s.tableDeserializationTime = tableDeserializationTimer .totalTimeVal(); s.tableCheckTime = redoTimer.totalTimeVal(); s.crashHandlingTime = crashTimer.totalTimeVal(); s.addReplicaTime = addReplicaTimer.totalTimeVal(); } if (SHARED_OBJECTS) { s.soInvocations = soInvocations; s.soInvocationsBytes = soInvocationsBytes; s.soTransfers = soTransfers; s.soTransfersBytes = soTransfersBytes; s.handleSOInvocationsTime = handleSOInvocationsTimer.totalTimeVal(); s.broadcastSOInvocationsTime = broadcastSOInvocationsTimer .totalTimeVal(); s.soTransferTime = soTransferTimer.totalTimeVal(); s.soSerializationTime = soSerializationTimer.totalTimeVal(); s.soDeserializationTime = soDeserializationTimer.totalTimeVal() + soBroadcastDeserializationTimer.totalTimeVal(); s.soRealMessageCount = soRealMessageCount; } return s; } private double perStats(double tm, long cnt) { if (cnt == 0) { return 0.0; } return tm / cnt; } protected void printStats() { int size; synchronized (this) { // size = victims.size(); // No, this is one too few. (Ceriel) size = victims.size() + 1; } // add my own stats StatsMessage me = createStats(); totalStats.add(me); java.text.NumberFormat nf = java.text.NumberFormat.getInstance(); // pf.setMaximumIntegerDigits(3); // pf.setMinimumIntegerDigits(3); // for percentages java.text.NumberFormat pf = java.text.NumberFormat.getInstance(); pf.setMaximumFractionDigits(3); pf.setMinimumFractionDigits(3); pf.setGroupingUsed(false); out.println(" + " if (SPAWN_STATS) { out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns) + " spawns, " + nf.format(totalStats.jobsExecuted) + " executed, " + nf.format(totalStats.syncs) + " syncs"); if (ABORTS) { out.println("SATIN: ABORT: " + nf.format(totalStats.aborts) + " aborts, " + nf.format(totalStats.abortMessages) + " abort msgs, " + nf.format(totalStats.abortedJobs) + " aborted jobs"); } } if (TUPLE_STATS) { out.println("SATIN: TUPLE_SPACE: " + nf.format(totalStats.tupleMsgs) + " bcasts, " + nf.format(totalStats.tupleBytes) + " bytes"); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL: poll count = " + nf.format(totalStats.pollCount)); } if (IDLE_TIMING) { out.println("SATIN: IDLE: idle count = " + nf.format(totalStats.idleCount)); } if (STEAL_STATS) { out.println("SATIN: STEAL: " + nf.format(totalStats.stealAttempts) + " attempts, " + nf.format(totalStats.stealSuccess) + " successes (" + pf.format(perStats((double) totalStats.stealSuccess, totalStats.stealAttempts) * 100.0) + " %)"); if (totalStats.asyncStealAttempts != 0) { out.println("SATIN: ASYNCSTEAL: " + nf.format(totalStats.asyncStealAttempts) + " attempts, " + nf.format(totalStats.asyncStealSuccess) + " successes (" + pf.format(perStats((double) totalStats.asyncStealSuccess, totalStats.asyncStealAttempts) * 100.0) + " %)"); } out.println("SATIN: MESSAGES: intra " + nf.format(totalStats.intraClusterMessages) + " msgs, " + nf.format(totalStats.intraClusterBytes) + " bytes; inter " + nf.format(totalStats.interClusterMessages) + " msgs, " + nf.format(totalStats.interClusterBytes) + " bytes"); } if (FAULT_TOLERANCE && GRT_STATS) { out.println("SATIN: GLOBAL_RESULT_TABLE: result updates " + nf.format(totalStats.tableResultUpdates) + ",update messages " + nf.format(totalStats.tableUpdateMessages) + ", lock updates " + nf.format(totalStats.tableLockUpdates) + ",lookups " + nf.format(totalStats.tableLookups) + ",successful " + nf.format(totalStats.tableSuccessfulLookups) + ",remote " + nf.format(totalStats.tableRemoteLookups)); } if (FAULT_TOLERANCE && FT_STATS) { out.println("SATIN: FAULT_TOLERANCE: killed orphans " + nf.format(totalStats.killedOrphans)); out.println("SATIN: FAULT_TOLERANCE: restarted jobs " + nf.format(totalStats.restartedJobs)); } if (SHARED_OBJECTS && SO_STATS) { out.println("SATIN: SO_CALLS: " + nf.format(totalStats.soInvocations) + " invocations " + nf.format(totalStats.soInvocationsBytes) + " bytes, " + nf.format(totalStats.soRealMessageCount) + " messages"); out.println("SATIN: SO_TRANSFER: " + nf.format(totalStats.soTransfers) + " transfers " + nf.format(totalStats.soTransfersBytes) + " bytes "); } out.println(" + " if (STEAL_TIMING) { out.println("SATIN: STEAL_TIME: total " + Timer.format(totalStats.stealTime) + " time/req " + Timer.format(perStats(totalStats.stealTime, totalStats.stealAttempts))); out.println("SATIN: HANDLE_STEAL_TIME: total " + Timer.format(totalStats.handleStealTime) + " time/handle " + Timer.format(perStats(totalStats.handleStealTime, totalStats.stealAttempts))); out.println("SATIN: INV SERIALIZATION_TIME: total " + Timer.format(totalStats.invocationRecordWriteTime) + " time/write " + Timer.format(perStats(totalStats.invocationRecordWriteTime, totalStats.stealSuccess))); out.println("SATIN: INV DESERIALIZATION_TIME: total " + Timer.format(totalStats.invocationRecordReadTime) + " time/read " + Timer.format(perStats(totalStats.invocationRecordReadTime, totalStats.stealSuccess))); out.println("SATIN: RET SERIALIZATION_TIME: total " + Timer.format(totalStats.returnRecordWriteTime) + " time/write " + Timer.format(perStats(totalStats.returnRecordWriteTime, totalStats.returnRecordWriteCount))); out.println("SATIN: RET DESERIALIZATION_TIME: total " + Timer.format(totalStats.returnRecordReadTime) + " time/read " + Timer.format(perStats(totalStats.returnRecordReadTime, totalStats.returnRecordReadCount))); } if (ABORT_TIMING) { out.println("SATIN: ABORT_TIME: total " + Timer.format(totalStats.abortTime) + " time/abort " + Timer .format(perStats(totalStats.abortTime, totalStats.aborts))); } if (TUPLE_TIMING) { out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total " + Timer.format(totalStats.tupleTime) + " time/bcast " + Timer.format(perStats(totalStats.tupleTime, totalStats.tupleMsgs))); out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total " + Timer.format(totalStats.tupleWaitTime) + " time/bcast " + Timer.format(perStats(totalStats.tupleWaitTime, totalStats.tupleWaitCount))); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL_TIME: total " + Timer.format(totalStats.pollTime) + " time/poll " + Timer.format(perStats(totalStats.pollTime, totalStats.pollCount))); } if (IDLE_TIMING) { out.println("SATIN: IDLE_TIME: total " + Timer.format(totalStats.idleTime) + " time/idle " + Timer.format(perStats(totalStats.idleTime, totalStats.idleCount))); } if (FAULT_TOLERANCE && GRT_TIMING) { out .println("SATIN: GRT_UPDATE_TIME: total " + Timer.format(totalStats.tableUpdateTime) + " time/update " + Timer .format(perStats( totalStats.tableUpdateTime, (totalStats.tableResultUpdates + totalStats.tableLockUpdates)))); out.println("SATIN: GRT_LOOKUP_TIME: total " + Timer.format(totalStats.tableLookupTime) + " time/lookup " + Timer.format(perStats(totalStats.tableLookupTime, totalStats.tableLookups))); out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total " + Timer.format(totalStats.tableHandleUpdateTime) + " time/handle " + Timer.format(perStats(totalStats.tableHandleUpdateTime, totalStats.tableResultUpdates * (size - 1)))); out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total " + Timer.format(totalStats.tableHandleLookupTime) + " time/handle " + Timer.format(perStats(totalStats.tableHandleLookupTime, totalStats.tableRemoteLookups))); out.println("SATIN: GRT_SERIALIZATION_TIME: total " + Timer.format(totalStats.tableSerializationTime)); out.println("SATIN: GRT_DESERIALIZATION_TIME: total " + Timer.format(totalStats.tableDeserializationTime)); out.println("SATIN: GRT_CHECK_TIME: total " + Timer.format(totalStats.tableCheckTime) + " time/check " + Timer.format(perStats(totalStats.tableCheckTime, totalStats.tableLookups))); } if (FAULT_TOLERANCE && CRASH_TIMING) { out.println("SATIN: CRASH_HANDLING_TIME: total " + Timer.format(totalStats.crashHandlingTime)); } if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) { out.println("SATIN: ADD_REPLICA_TIME: total " + Timer.format(totalStats.addReplicaTime)); } if (SHARED_OBJECTS && SO_TIMING) { out.println("SATIN: BROADCAST_SO_INVOCATIONS: total " + Timer.format(totalStats.broadcastSOInvocationsTime) + " time/inv " + Timer.format(perStats(totalStats.broadcastSOInvocationsTime, totalStats.soInvocations))); out.println("SATIN: HANDLE_SO_INVOCATIONS: total " + Timer.format(totalStats.handleSOInvocationsTime) + " time/inv " + Timer.format(perStats(totalStats.handleSOInvocationsTime, totalStats.soInvocations * (size - 1)))); out.println("SATIN: SO_TRANSFERS: total " + Timer.format(totalStats.soTransferTime) + " time/transf " + Timer.format(perStats(totalStats.soTransferTime, totalStats.soTransfers))); out.println("SATIN: SO_SERIALIZATION: total " + Timer.format(totalStats.soSerializationTime) + " time/transf " + Timer.format(perStats(totalStats.soSerializationTime, totalStats.soTransfers))); out.println("SATIN: SO_DESERIALIZATION: total " + Timer.format(totalStats.soDeserializationTime) + " time/transf " + Timer.format(perStats(totalStats.soDeserializationTime, totalStats.soTransfers))); } out.println(" + "BREAKDOWN out.println("SATIN: TOTAL_RUN_TIME: " + Timer.format(totalTimer.totalTimeVal())); double lbTime = (totalStats.stealTime + totalStats.handleStealTime - totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime) / size; if (lbTime < 0.0) { lbTime = 0.0; } double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0; double serTime = (totalStats.invocationRecordWriteTime + totalStats.invocationRecordReadTime + totalStats.returnRecordWriteTime + totalStats.returnRecordReadTime) / size; double serPerc = serTime / totalTimer.totalTimeVal() * 100.0; double abortTime = totalStats.abortTime / size; double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0; double tupleTime = totalStats.tupleTime / size; double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0; double handleTupleTime = totalStats.handleTupleTime / size; double handleTuplePerc = handleTupleTime / totalTimer.totalTimeVal() * 100.0; double tupleWaitTime = totalStats.tupleWaitTime / size; double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal() * 100.0; double pollTime = totalStats.pollTime / size; double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0; double tableUpdateTime = totalStats.tableUpdateTime / size; double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal() * 100.0; double tableLookupTime = totalStats.tableLookupTime / size; double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal() * 100.0; double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size; double tableHandleUpdatePerc = tableHandleUpdateTime / totalTimer.totalTimeVal() * 100.0; double tableHandleLookupTime = totalStats.tableHandleLookupTime / size; double tableHandleLookupPerc = tableHandleLookupTime / totalTimer.totalTimeVal() * 100.0; double tableSerializationTime = totalStats.tableSerializationTime / size; double tableSerializationPerc = tableSerializationTime / totalTimer.totalTimeVal() * 100; double tableDeserializationTime = totalStats.tableDeserializationTime / size; double tableDeserializationPerc = tableDeserializationTime / totalTimer.totalTimeVal() * 100; double crashHandlingTime = totalStats.crashHandlingTime / size; double crashHandlingPerc = crashHandlingTime / totalTimer.totalTimeVal() * 100.0; double addReplicaTime = totalStats.addReplicaTime / size; double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal() * 100.0; double broadcastSOInvocationsTime = totalStats.broadcastSOInvocationsTime / size; double broadcastSOInvocationsPerc = broadcastSOInvocationsTime / totalTimer.totalTimeVal() * 100; double handleSOInvocationsTime = totalStats.handleSOInvocationsTime / size; double handleSOInvocationsPerc = handleSOInvocationsTime / totalTimer.totalTimeVal() * 100; double soTransferTime = totalStats.soTransferTime / size; double soTransferPerc = soTransferTime / totalTimer.totalTimeVal() * 100; double soSerializationTime = totalStats.soSerializationTime / size; double soSerializationPerc = soSerializationTime / totalTimer.totalTimeVal() * 100; double soDeserializationTime = totalStats.soDeserializationTime / size; double soDeserializationPerc = soDeserializationTime / totalTimer.totalTimeVal() * 100; double totalOverhead = abortTime + tupleTime + handleTupleTime + tupleWaitTime + pollTime + tableUpdateTime + tableLookupTime + tableHandleUpdateTime + tableHandleLookupTime + handleSOInvocationsTime + broadcastSOInvocationsTime + soTransferTime + (totalStats.stealTime + totalStats.handleStealTime + totalStats.returnRecordReadTime + totalStats.returnRecordWriteTime) / size; double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0; double appTime = totalTimer.totalTimeVal() - totalOverhead; if (appTime < 0.0) { appTime = 0.0; } double appPerc = appTime / totalTimer.totalTimeVal() * 100.0; if (STEAL_TIMING) { out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine " + Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "") + pf.format(lbPerc) + " %)"); out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine " + Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "") + pf.format(serPerc) + " %)"); } if (ABORT_TIMING) { out.println("SATIN: ABORT_TIME: avg. per machine " + Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "") + pf.format(abortPerc) + " %)"); } if (TUPLE_TIMING) { out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine " + Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "") + pf.format(tuplePerc) + " %)"); out.println("SATIN: TUPLE_SPACE_HANDLE_TIME: avg. per machine " + Timer.format(handleTupleTime) + " (" + (handleTuplePerc < 10 ? " " : "") + pf.format(handleTuplePerc) + " %)"); out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine " + Timer.format(tupleWaitTime) + " (" + (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc) + " %)"); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN: POLL_TIME: avg. per machine " + Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "") + pf.format(pollPerc) + " %)"); } if (FAULT_TOLERANCE && GRT_TIMING) { out.println("SATIN: GRT_UPDATE_TIME: avg. per machine " + Timer.format(tableUpdateTime) + " (" + pf.format(tableUpdatePerc) + " %)"); out.println("SATIN: GRT_LOOKUP_TIME: avg. per machine " + Timer.format(tableLookupTime) + " (" + pf.format(tableLookupPerc) + " %)"); out.println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine " + Timer.format(tableHandleUpdateTime) + " (" + pf.format(tableHandleUpdatePerc) + " %)"); out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine " + Timer.format(tableHandleLookupTime) + " (" + pf.format(tableHandleLookupPerc) + " %)"); out.println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine " + Timer.format(tableSerializationTime) + " (" + pf.format(tableSerializationPerc) + " %)"); out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine " + Timer.format(tableDeserializationTime) + " (" + pf.format(tableDeserializationPerc) + " %)"); } if (FAULT_TOLERANCE && CRASH_TIMING) { out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine " + Timer.format(crashHandlingTime) + " (" + pf.format(crashHandlingPerc) + " %)"); } if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) { out.println("SATIN: ADD_REPLICA_TIME: avg. per machine " + Timer.format(addReplicaTime) + " (" + pf.format(addReplicaPerc) + " %)"); } if (SHARED_OBJECTS && SO_TIMING) { out.println("SATIN: BROADCAST_SO_INVOCATIONS: avg. per machine " + Timer.format(broadcastSOInvocationsTime) + " ( " + pf.format(broadcastSOInvocationsPerc) + " %)"); out.println("SATIN: HANDLE_SO_INVOCATIONS: avg. per machine " + Timer.format(handleSOInvocationsTime) + " ( " + pf.format(handleSOInvocationsPerc) + " %)"); out.println("SATIN: SO_TRANSFERS: avg. per machine " + Timer.format(soTransferTime) + " ( " + pf.format(soTransferPerc) + " %)"); out.println("SATIN: SO_SERIALIZATION: avg. per machine " + Timer.format(soSerializationTime) + " ( " + pf.format(soSerializationPerc) + " %)"); out.println("SATIN: SO_DESERIALIZATION: avg. per machine " + Timer.format(soDeserializationTime) + " ( " + pf.format(soDeserializationPerc) + " %)"); } out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine " + Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "") + pf.format(totalPerc) + " %)"); out.println("SATIN: USEFUL_APP_TIME: avg. per machine " + Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "") + pf.format(appPerc) + " %)"); } protected void printDetailedStats() { java.text.NumberFormat nf = java.text.NumberFormat.getInstance(); if (SPAWN_STATS) { out.println("SATIN '" + ident + "': SPAWN_STATS: spawns = " + spawns + " executed = " + jobsExecuted + " syncs = " + syncs); if (ABORTS) { out.println("SATIN '" + ident + "': ABORT_STATS 1: aborts = " + aborts + " abort msgs = " + abortMessages + " aborted jobs = " + abortedJobs); } } if (TUPLE_STATS) { out.println("SATIN '" + ident + "': TUPLE_STATS 1: tuple bcast msgs: " + tupleMsgs + ", bytes = " + nf.format(tupleBytes)); } if (STEAL_STATS) { out.println("SATIN '" + ident + "': INTRA_STATS: messages = " + intraClusterMessages + ", bytes = " + nf.format(intraClusterBytes)); out.println("SATIN '" + ident + "': INTER_STATS: messages = " + interClusterMessages + ", bytes = " + nf.format(interClusterBytes)); out.println("SATIN '" + ident + "': STEAL_STATS 1: attempts = " + stealAttempts + " success = " + stealSuccess + " (" + (perStats((double) stealSuccess, stealAttempts) * 100.0) + " %)"); out.println("SATIN '" + ident + "': STEAL_STATS 2: requests = " + stealRequests + " jobs stolen = " + stolenJobs); if (STEAL_TIMING) { out.println("SATIN '" + ident + "': STEAL_STATS 3: attempts = " + stealTimer.nrTimes() + " total time = " + stealTimer.totalTime() + " avg time = " + stealTimer.averageTime()); out.println("SATIN '" + ident + "': STEAL_STATS 4: handleSteals = " + handleStealTimer.nrTimes() + " total time = " + handleStealTimer.totalTime() + " avg time = " + handleStealTimer.averageTime()); out.println("SATIN '" + ident + "': STEAL_STATS 5: invocationRecordWrites = " + invocationRecordWriteTimer.nrTimes() + " total time = " + invocationRecordWriteTimer.totalTime() + " avg time = " + invocationRecordWriteTimer.averageTime()); out.println("SATIN '" + ident + "': STEAL_STATS 6: invocationRecordReads = " + invocationRecordReadTimer.nrTimes() + " total time = " + invocationRecordReadTimer.totalTime() + " avg time = " + invocationRecordReadTimer.averageTime()); out.println("SATIN '" + ident + "': STEAL_STATS 7: returnRecordWrites = " + returnRecordWriteTimer.nrTimes() + " total time = " + returnRecordWriteTimer.totalTime() + " avg time = " + returnRecordWriteTimer.averageTime()); out.println("SATIN '" + ident + "': STEAL_STATS 8: returnRecordReads = " + returnRecordReadTimer.nrTimes() + " total time = " + returnRecordReadTimer.totalTime() + " avg time = " + returnRecordReadTimer.averageTime()); } if (ABORTS && ABORT_TIMING) { out.println("SATIN '" + ident + "': ABORT_STATS 2: aborts = " + abortTimer.nrTimes() + " total time = " + abortTimer.totalTime() + " avg time = " + abortTimer.averageTime()); } if (IDLE_TIMING) { out.println("SATIN '" + ident + "': IDLE_STATS: idle count = " + idleTimer.nrTimes() + " total time = " + idleTimer.totalTime() + " avg time = " + idleTimer.averageTime()); } if (POLL_FREQ != 0 && POLL_TIMING) { out.println("SATIN '" + ident + "': POLL_STATS: poll count = " + pollTimer.nrTimes() + " total time = " + pollTimer.totalTime() + " avg time = " + pollTimer.averageTime()); } if (STEAL_TIMING && IDLE_TIMING) { out.println("SATIN '" + ident + "': COMM_STATS: software comm time = " + Timer.format(stealTimer.totalTimeVal() + handleStealTimer.totalTimeVal() - idleTimer.totalTimeVal())); } if (TUPLE_TIMING) { out.println("SATIN '" + ident + "': TUPLE_STATS 2: bcasts = " + tupleTimer.nrTimes() + " total time = " + tupleTimer.totalTime() + " avg time = " + tupleTimer.averageTime()); out.println("SATIN '" + ident + "': TUPLE_STATS 3: waits = " + tupleOrderingWaitTimer.nrTimes() + " total time = " + tupleOrderingWaitTimer.totalTime() + " avg time = " + tupleOrderingWaitTimer.averageTime()); } algorithm.printStats(out); } if (FAULT_TOLERANCE) { if (GRT_STATS) { out.println("SATIN '" + ident + "': " + globalResultTable.numResultUpdates + " result updates of the table."); out.println("SATIN '" + ident + "': " + globalResultTable.numLockUpdates + " lock updates of the table."); out .println("SATIN '" + ident + "': " + globalResultTable.numUpdateMessages + " update messages."); out.println("SATIN '" + ident + "': " + globalResultTable.numLookupsSucceded + " lookups succeded, of which:"); out.println("SATIN '" + ident + "': " + globalResultTable.numRemoteLookups + " remote lookups."); out.println("SATIN '" + ident + "': " + globalResultTable.maxNumEntries + " entries maximally."); } if (GRT_TIMING) { out.println("SATIN '" + ident + "': " + lookupTimer.totalTime() + " spent in lookups"); out.println("SATIN '" + ident + "': " + lookupTimer.averageTime() + " per lookup"); out.println("SATIN '" + ident + "': " + updateTimer.totalTime() + " spent in updates"); out.println("SATIN '" + ident + "': " + updateTimer.averageTime() + " per update"); out.println("SATIN '" + ident + "': " + handleUpdateTimer.totalTime() + " spent in handling updates"); out.println("SATIN '" + ident + "': " + handleUpdateTimer.averageTime() + " per update handle"); out.println("SATIN '" + ident + "': " + handleLookupTimer.totalTime() + " spent in handling lookups"); out.println("SATIN '" + ident + "': " + handleLookupTimer.averageTime() + " per lookup handle"); } if (CRASH_TIMING) { out.println("SATIN '" + ident + "': " + crashTimer.totalTime() + " spent in handling crashes"); } if (TABLE_CHECK_TIMING) { out.println("SATIN '" + ident + "': " + redoTimer.totalTime() + " spent in redoing"); } if (FT_STATS) { out.println("SATIN '" + ident + "': " + killedOrphans + " orphans killed"); out.println("SATIN '" + ident + "': " + restartedJobs + " jobs restarted"); } } if (SHARED_OBJECTS && SO_STATS) { out.println("SATIN '" + ident.name() + "': " + soInvocations + " shared object invocations sent."); out.println("SATIN '" + ident.name() + "': " + soTransfers + " shared objects transfered."); } } }
package aQute.bnd.build; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.Formatter; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.StringTokenizer; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.naming.TimeLimitExceededException; import aQute.bnd.annotation.plugin.BndPlugin; import aQute.bnd.connection.settings.ConnectionSettings; import aQute.bnd.exporter.subsystem.SubsystemExporter; import aQute.bnd.header.Attrs; import aQute.bnd.header.OSGiHeader; import aQute.bnd.header.Parameters; import aQute.bnd.http.HttpClient; import aQute.bnd.maven.support.Maven; import aQute.bnd.osgi.About; import aQute.bnd.osgi.Constants; import aQute.bnd.osgi.Macro; import aQute.bnd.osgi.Processor; import aQute.bnd.osgi.Verifier; import aQute.bnd.resource.repository.ResourceRepositoryImpl; import aQute.bnd.service.BndListener; import aQute.bnd.service.RepositoryPlugin; import aQute.bnd.service.action.Action; import aQute.bnd.service.extension.ExtensionActivator; import aQute.bnd.service.lifecycle.LifeCyclePlugin; import aQute.bnd.service.repository.Prepare; import aQute.bnd.service.repository.RepositoryDigest; import aQute.bnd.service.repository.SearchableRepository.ResourceDescriptor; import aQute.bnd.url.MultiURLConnectionHandler; import aQute.bnd.version.Version; import aQute.bnd.version.VersionRange; import aQute.lib.deployer.FileRepo; import aQute.lib.hex.Hex; import aQute.lib.io.IO; import aQute.lib.io.IOConstants; import aQute.lib.settings.Settings; import aQute.lib.strings.Strings; import aQute.lib.utf8properties.UTF8Properties; import aQute.lib.zip.ZipUtil; import aQute.libg.uri.URIUtil; import aQute.service.reporter.Reporter; public class Workspace extends Processor { public static final File BND_DEFAULT_WS = IO.getFile("~/.bnd/default-ws"); public static final String BND_CACHE_REPONAME = "bnd-cache"; public static final String EXT = "ext"; public static final String BUILDFILE = "build.bnd"; public static final String CNFDIR = "cnf"; public static final String BNDDIR = "bnd"; public static final String CACHEDIR = "cache/" + About.CURRENT; public static final String STANDALONE_REPO_CLASS = "aQute.bnd.deployer.repository.FixedIndexedRepo"; static final int BUFFER_SIZE = IOConstants.PAGE_SIZE * 16; private static final String PLUGIN_STANDALONE = "-plugin.standalone_"; private final Pattern EMBEDDED_REPO_TESTING_PATTERN = Pattern .compile(".*biz\\.aQute\\.bnd\\.embedded-repo(-.*)?\\.jar"); static class WorkspaceData { List<RepositoryPlugin> repositories; } private final static Map<File,WeakReference<Workspace>> cache = newHashMap(); static Processor defaults = null; final Map<String,Project> models = newHashMap(); private final Set<String> modelsUnderConstruction = newSet(); final Map<String,Action> commands = newMap(); final Maven maven = new Maven(Processor.getExecutor()); private boolean offline = true; Settings settings = new Settings(); WorkspaceRepository workspaceRepo = new WorkspaceRepository(this); static String overallDriver = "unset"; static Parameters overallGestalt = new Parameters(); /** * Signal a BndListener plugin. We ran an infinite bug loop :-( */ final ThreadLocal<Reporter> signalBusy = new ThreadLocal<Reporter>(); ResourceRepositoryImpl resourceRepositoryImpl; private Parameters gestalt; private String driver; private final WorkspaceLayout layout; final Set<Project> trail = Collections .newSetFromMap(new ConcurrentHashMap<Project,Boolean>()); private WorkspaceData data = new WorkspaceData(); private File buildDir; /** * This static method finds the workspace and creates a project (or returns * an existing project) * * @param projectDir */ public static Project getProject(File projectDir) throws Exception { projectDir = projectDir.getAbsoluteFile(); assert projectDir.isDirectory(); Workspace ws = getWorkspace(projectDir.getParentFile()); return ws.getProject(projectDir.getName()); } static synchronized public Processor getDefaults() { if (defaults != null) return defaults; UTF8Properties props = new UTF8Properties(); InputStream propStream = Workspace.class.getResourceAsStream("defaults.bnd"); if (propStream != null) { try { props.load(propStream); } catch (IOException e) { throw new IllegalArgumentException("Unable to load bnd defaults.", e); } finally { IO.close(propStream); } } else System.err.println("Cannot load defaults"); defaults = new Processor(props, false); return defaults; } public static Workspace createDefaultWorkspace() throws Exception { Workspace ws = new Workspace(BND_DEFAULT_WS, CNFDIR); return ws; } public static Workspace getWorkspace(File workspaceDir) throws Exception { return getWorkspace(workspaceDir, CNFDIR); } public static Workspace getWorkspaceWithoutException(File workspaceDir) throws Exception { try { return getWorkspace(workspaceDir); } catch (IllegalArgumentException e) { return null; } } * /* Return the nearest workspace */ public static Workspace findWorkspace(File base) throws Exception { File rover = base; while (rover != null) { File file = IO.getFile(rover, "cnf/build.bnd"); if (file.isFile()) return getWorkspace(rover); rover = rover.getParentFile(); } return null; } public static Workspace getWorkspace(File workspaceDir, String bndDir) throws Exception { workspaceDir = workspaceDir.getAbsoluteFile(); // the cnf directory can actually be a // file that redirects while (workspaceDir.isDirectory()) { File test = new File(workspaceDir, CNFDIR); if (!test.exists()) test = new File(workspaceDir, bndDir); if (test.isDirectory()) break; if (test.isFile()) { String redirect = IO.collect(test).trim(); test = getFile(test.getParentFile(), redirect).getAbsoluteFile(); workspaceDir = test; } if (!test.exists()) throw new IllegalArgumentException("No Workspace found from: " + workspaceDir); } synchronized (cache) { WeakReference<Workspace> wsr = cache.get(workspaceDir); Workspace ws; if (wsr == null || (ws = wsr.get()) == null) { ws = new Workspace(workspaceDir, bndDir); cache.put(workspaceDir, new WeakReference<Workspace>(ws)); } return ws; } } public Workspace(File workspaceDir) throws Exception { this(workspaceDir, CNFDIR); } public Workspace(File workspaceDir, String bndDir) throws Exception { super(getDefaults()); workspaceDir = workspaceDir.getAbsoluteFile(); setBase(workspaceDir); // setBase before call to setFileSystem this.layout = WorkspaceLayout.BND; addBasicPlugin(new LoggingProgressPlugin()); setFileSystem(workspaceDir, bndDir); } public void setFileSystem(File workspaceDir, String bndDir) throws Exception { workspaceDir = workspaceDir.getAbsoluteFile(); if (!workspaceDir.exists() && !workspaceDir.mkdirs()) { throw new IOException("Could not create directory " + workspaceDir); } assert workspaceDir.isDirectory(); synchronized (cache) { WeakReference<Workspace> wsr = cache.get(getBase()); if ((wsr != null) && (wsr.get() == this)) { cache.remove(getBase()); cache.put(workspaceDir, wsr); } } File buildDir = new File(workspaceDir, bndDir).getAbsoluteFile(); if (!buildDir.isDirectory()) buildDir = new File(workspaceDir, CNFDIR).getAbsoluteFile(); setBuildDir(buildDir); File buildFile = new File(buildDir, BUILDFILE).getAbsoluteFile(); if (!buildFile.isFile()) warning("No Build File in %s", workspaceDir); setProperties(buildFile, workspaceDir); propertiesChanged(); // There is a nasty bug/feature in Java that gives errors on our // SSL use of github. The flag jsse.enableSNIExtension should be set // to false. So here we provide a way to set system properties // as early as possible Attrs sysProps = OSGiHeader.parseProperties(mergeProperties(SYSTEMPROPERTIES)); for (Entry<String,String> e : sysProps.entrySet()) { System.setProperty(e.getKey(), e.getValue()); } } private Workspace(WorkspaceLayout layout) throws Exception { super(getDefaults()); this.layout = layout; setBuildDir(IO.getFile(BND_DEFAULT_WS, CNFDIR)); } public Project getProjectFromFile(File projectDir) throws Exception { projectDir = projectDir.getAbsoluteFile(); assert projectDir.isDirectory(); if (getBase().equals(projectDir.getParentFile())) { return getProject(projectDir.getName()); } return null; } public Project getProject(String bsn) throws Exception { synchronized (models) { Project project = models.get(bsn); if (project != null) return project; if (modelsUnderConstruction.add(bsn)) { try { File projectDir = getFile(bsn); project = new Project(this, projectDir); if (!project.isValid()) return null; models.put(bsn, project); } finally { modelsUnderConstruction.remove(bsn); } } return project; } } void removeProject(Project p) throws Exception { if (p.isCnf()) return; synchronized (models) { models.remove(p.getName()); } for (LifeCyclePlugin lp : getPlugins(LifeCyclePlugin.class)) { lp.delete(p); } } public boolean isPresent(String name) { return models.containsKey(name); } public Collection<Project> getCurrentProjects() { return models.values(); } @Override public boolean refresh() { data = new WorkspaceData(); if (super.refresh()) { for (Project project : getCurrentProjects()) { project.propertiesChanged(); } return true; } return false; } @Override public void propertiesChanged() { data = new WorkspaceData(); File extDir = new File(getBuildDir(), EXT); File[] extensions = extDir.listFiles(); if (extensions != null) { for (File extension : extensions) { String extensionName = extension.getName(); if (extensionName.endsWith(".bnd")) { extensionName = extensionName.substring(0, extensionName.length() - ".bnd".length()); try { doIncludeFile(extension, false, getProperties(), "ext." + extensionName); } catch (Exception e) { exception(e, "PropertiesChanged: %s", e); } } } } super.propertiesChanged(); } public String _workspace(@SuppressWarnings("unused") String args[]) { return getBase().getAbsolutePath(); } public void addCommand(String menu, Action action) { commands.put(menu, action); } public void removeCommand(String menu) { commands.remove(menu); } public void fillActions(Map<String,Action> all) { all.putAll(commands); } public Collection<Project> getAllProjects() throws Exception { List<Project> projects = new ArrayList<Project>(); for (File file : getBase().listFiles()) { if (new File(file, Project.BNDFILE).isFile()) { Project p = getProject(file.getAbsoluteFile().getName()); if (p != null) { projects.add(p); } } } return projects; } /** * Inform any listeners that we changed a file (created/deleted/changed). * * @param f The changed file */ public void changedFile(File f) { List<BndListener> listeners = getPlugins(BndListener.class); for (BndListener l : listeners) try { offline = false; l.changed(f); } catch (Exception e) { e.printStackTrace(); } } public void bracket(boolean begin) { List<BndListener> listeners = getPlugins(BndListener.class); for (BndListener l : listeners) try { if (begin) l.begin(); else l.end(); } catch (Exception e) { // who cares? } } public void signal(Reporter reporter) { if (signalBusy.get() != null) return; signalBusy.set(reporter); try { List<BndListener> listeners = getPlugins(BndListener.class); for (BndListener l : listeners) try { l.signal(this); } catch (Exception e) { // who cares? } } catch (Exception e) { // Ignore } finally { signalBusy.set(null); } } @Override public void signal() { signal(this); } class CachedFileRepo extends FileRepo { final Lock lock = new ReentrantLock(); boolean inited; CachedFileRepo() { super(BND_CACHE_REPONAME, getCache(BND_CACHE_REPONAME), false); } @Override public String toString() { return BND_CACHE_REPONAME; } @Override protected boolean init() throws Exception { if (lock.tryLock(50, TimeUnit.SECONDS) == false) throw new TimeLimitExceededException("Cached File Repo is locked and can't acquire it"); try { if (super.init()) { inited = true; if (!root.exists() && !root.mkdirs()) { throw new IOException("Could not create cache directory " + root); } if (!root.isDirectory()) throw new IllegalArgumentException("Cache directory " + root + " not a directory"); InputStream in = getClass().getResourceAsStream(EMBEDDED_REPO); if (in != null) unzip(in, root); else { // We may be in unit test, look for // biz.aQute.bnd.embedded-repo.jar on the // classpath StringTokenizer classPathTokenizer = new StringTokenizer( System.getProperty("java.class.path", ""), File.pathSeparator); while (classPathTokenizer.hasMoreTokens()) { String classPathEntry = classPathTokenizer.nextToken().trim(); if (EMBEDDED_REPO_TESTING_PATTERN.matcher(classPathEntry).matches()) { in = new FileInputStream(classPathEntry); unzip(in, root); return true; } } error("Couldn't find biz.aQute.bnd.embedded-repo on the classpath"); return false; } return true; } else return false; } finally { lock.unlock(); } } private void unzip(InputStream in, File dir) throws Exception { try (JarInputStream jin = new JarInputStream(in)) { byte[] data = new byte[BUFFER_SIZE]; for (JarEntry jentry = jin.getNextJarEntry(); jentry != null; jentry = jin.getNextJarEntry()) { if (jentry.isDirectory()) { continue; } String jentryName = jentry.getName(); if (jentryName.startsWith("META-INF/")) { continue; } File dest = getFile(dir, jentryName); long modifiedTime = ZipUtil.getModifiedTime(jentry); if (!dest.isFile() || dest.lastModified() < modifiedTime || modifiedTime <= 0) { File dp = dest.getParentFile(); if (!dp.exists() && !dp.mkdirs()) { throw new IOException("Could not create directory " + dp); } try (FileOutputStream out = new FileOutputStream(dest)) { for (int size = jin.read(data); size > 0; size = jin.read(data)) { out.write(data, 0, size); } } } } } finally { in.close(); } } } public void syncCache() throws Exception { CachedFileRepo cf = new CachedFileRepo(); cf.init(); cf.close(); } public List<RepositoryPlugin> getRepositories() throws Exception { if (data.repositories == null) { data.repositories = getPlugins(RepositoryPlugin.class); for (RepositoryPlugin repo : data.repositories) { if (repo instanceof Prepare) { ((Prepare) repo).prepare(); } } } return data.repositories; } public Collection<Project> getBuildOrder() throws Exception { List<Project> result = new ArrayList<Project>(); for (Project project : getAllProjects()) { Collection<Project> dependsOn = project.getDependson(); getBuildOrder(dependsOn, result); if (!result.contains(project)) { result.add(project); } } return result; } private void getBuildOrder(Collection<Project> dependsOn, List<Project> result) throws Exception { for (Project project : dependsOn) { Collection<Project> subProjects = project.getDependson(); for (Project subProject : subProjects) { if (!result.contains(subProject)) { result.add(subProject); } } if (!result.contains(project)) { result.add(project); } } } public static Workspace getWorkspace(String path) throws Exception { File file = IO.getFile(new File(""), path); return getWorkspace(file); } public Maven getMaven() { return maven; } @Override protected void setTypeSpecificPlugins(Set<Object> list) { try { super.setTypeSpecificPlugins(list); list.add(this); list.add(maven); list.add(settings); if (!isTrue(getProperty(NOBUILDINCACHE))) { list.add(new CachedFileRepo()); } resourceRepositoryImpl = new ResourceRepositoryImpl(); resourceRepositoryImpl.setCache(IO.getFile(getProperty(CACHEDIR, "~/.bnd/caches/shas"))); resourceRepositoryImpl.setExecutor(getExecutor()); resourceRepositoryImpl.setIndexFile(getFile(getBuildDir(), "repo.json")); resourceRepositoryImpl.setURLConnector(new MultiURLConnectionHandler(this)); customize(resourceRepositoryImpl, null); list.add(resourceRepositoryImpl); // Exporters list.add(new SubsystemExporter()); try { HttpClient client = new HttpClient(); client.setRegistry(this); try (ConnectionSettings cs = new ConnectionSettings(this, client);) { cs.readSettings(); } list.add(client); } catch (Exception e) { exception(e, "Failed to load the communication settings"); } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } /** * Add any extensions listed * * @param list */ @Override protected void addExtensions(Set<Object> list) { // <bsn>; version=<range> Parameters extensions = getMergedParameters(EXTENSION); Map<DownloadBlocker,Attrs> blockers = new HashMap<DownloadBlocker,Attrs>(); for (Entry<String,Attrs> i : extensions.entrySet()) { String bsn = removeDuplicateMarker(i.getKey()); String stringRange = i.getValue().get(VERSION_ATTRIBUTE); trace("Adding extension %s-%s", bsn, stringRange); if (stringRange == null) stringRange = Version.LOWEST.toString(); else if (!VersionRange.isVersionRange(stringRange)) { error("Invalid version range %s on extension %s", stringRange, bsn); continue; } try { SortedSet<ResourceDescriptor> matches = resourceRepositoryImpl.find(null, bsn, new VersionRange(stringRange)); if (matches.isEmpty()) { error("Extension %s;version=%s not found in base repo", bsn, stringRange); continue; } DownloadBlocker blocker = new DownloadBlocker(this); blockers.put(blocker, i.getValue()); resourceRepositoryImpl.getResource(matches.last().id, blocker); } catch (Exception e) { error("Failed to load extension %s-%s, %s", bsn, stringRange, e); } } trace("Found extensions %s", blockers); for (Entry<DownloadBlocker,Attrs> blocker : blockers.entrySet()) { try { String reason = blocker.getKey().getReason(); if (reason != null) { error("Extension load failed: %s", reason); continue; } @SuppressWarnings("resource") URLClassLoader cl = new URLClassLoader(new URL[] { blocker.getKey().getFile().toURI().toURL() }, getClass().getClassLoader()); Enumeration<URL> manifests = cl.getResources("META-INF/MANIFEST.MF"); while (manifests.hasMoreElements()) { Manifest m = new Manifest(manifests.nextElement().openStream()); Parameters activators = new Parameters(m.getMainAttributes().getValue("Extension-Activator")); for (Entry<String,Attrs> e : activators.entrySet()) { try { Class< ? > c = cl.loadClass(e.getKey()); ExtensionActivator extensionActivator = (ExtensionActivator) c.getConstructor() .newInstance(); customize(extensionActivator, blocker.getValue()); List< ? > plugins = extensionActivator.activate(this, blocker.getValue()); list.add(extensionActivator); if (plugins != null) for (Object plugin : plugins) { list.add(plugin); } } catch (ClassNotFoundException cnfe) { error("Loading extension %s, extension activator missing: %s (ignored)", blocker, e.getKey()); } } } } catch (Exception e) { error("failed to install extension %s due to %s", blocker, e); } } } /** * Return if we're in offline mode. Offline mode is defined as an * environment where nobody tells us the resources are out of date (refresh * or changed). This is currently defined as having bndlisteners. */ public boolean isOffline() { return offline; } public Workspace setOffline(boolean on) { this.offline = on; return this; } /** * Provide access to the global settings of this machine. * * @throws Exception */ public String _global(String[] args) throws Exception { Macro.verifyCommand(args, "${global;<name>[;<default>]}, get a global setting from ~/.bnd/settings.json", null, 2, 3); String key = args[1]; if (key.equals("key.public")) return Hex.toHexString(settings.getPublicKey()); if (key.equals("key.private")) return Hex.toHexString(settings.getPrivateKey()); String s = settings.get(key); if (s != null) return s; if (args.length == 3) return args[2]; return null; } public String _user(String[] args) throws Exception { return _global(args); } /** * Return the repository signature digests. These digests are a unique id * for the contents of the repository */ public Object _repodigests(String[] args) throws Exception { Macro.verifyCommand(args, "${repodigests;[;<repo names>]...}, get the repository digests", null, 1, 10000); List<RepositoryPlugin> repos = getRepositories(); if (args.length > 1) { repos: for (Iterator<RepositoryPlugin> it = repos.iterator(); it.hasNext();) { String name = it.next().getName(); for (int i = 1; i < args.length; i++) { if (name.equals(args[i])) { continue repos; } } it.remove(); } } List<String> digests = new ArrayList<String>(); for (RepositoryPlugin repo : repos) { try { if (repo instanceof RepositoryDigest) { byte[] digest = ((RepositoryDigest) repo).getDigest(); digests.add(Hex.toHexString(digest)); } else { if (args.length != 1) error("Specified repo %s for ${repodigests} was named but it is not found", repo.getName()); } } catch (Exception e) { if (args.length != 1) error("Specified repo %s for digests is not found", repo.getName()); // else Ignore } } return join(digests, ","); } public static Run getRun(File file) throws Exception { if (!file.isFile()) { return null; } File projectDir = file.getParentFile(); File workspaceDir = projectDir.getParentFile(); if (!workspaceDir.isDirectory()) { return null; } Workspace ws = getWorkspaceWithoutException(workspaceDir); if (ws == null) { return null; } return new Run(ws, projectDir, file); } /** * Report details of this workspace */ public void report(Map<String,Object> table) throws Exception { super.report(table); table.put("Workspace", toString()); table.put("Plugins", getPlugins(Object.class)); table.put("Repos", getRepositories()); table.put("Projects in build order", getBuildOrder()); } public File getCache(String name) { return getFile(buildDir, CACHEDIR + "/" + name); } /** * Return the workspace repo */ public WorkspaceRepository getWorkspaceRepository() { return workspaceRepo; } public void checkStructure() { if (!getBuildDir().isDirectory()) error("No directory for cnf %s", getBuildDir()); else { File build = IO.getFile(getBuildDir(), BUILDFILE); if (build.isFile()) { error("No %s file in %s", BUILDFILE, getBuildDir()); } } } public File getBuildDir() { return buildDir; } public void setBuildDir(File buildDir) { this.buildDir = buildDir; } public boolean isValid() { return IO.getFile(getBuildDir(), BUILDFILE).isFile(); } public RepositoryPlugin getRepository(String repo) throws Exception { for (RepositoryPlugin r : getRepositories()) { if (repo.equals(r.getName())) { return r; } } return null; } public void close() { synchronized (cache) { WeakReference<Workspace> wsr = cache.get(getBase()); if ((wsr != null) && (wsr.get() == this)) { cache.remove(getBase()); } } try { super.close(); } catch (IOException e) { /* For backwards compatibility, we ignore the exception */ } } /** * Get the bnddriver, can be null if not set. The overallDriver is the * environment that runs this bnd. */ public String getDriver() { if (driver == null) { driver = getProperty(Constants.BNDDRIVER, null); if (driver != null) driver = driver.trim(); } if (driver != null) return driver; return overallDriver; } /** * Set the driver of this environment */ public static void setDriver(String driver) { overallDriver = driver; } /** * Macro to return the driver. Without any arguments, we return the name of * the driver. If there are arguments, we check each of the arguments * against the name of the driver. If it matches, we return the driver name. * If none of the args match the driver name we return an empty string * (which is false). */ public String _driver(String args[]) { if (args.length == 1) { return getDriver(); } String driver = getDriver(); if (driver == null) driver = getProperty(Constants.BNDDRIVER); if (driver != null) { for (int i = 1; i < args.length; i++) { if (args[i].equalsIgnoreCase(driver)) return driver; } } return ""; } /** * Add a gestalt to all workspaces. The gestalt is a set of parts describing * the environment. Each part has a name and optionally attributes. This * method adds a gestalt to the VM. Per workspace it is possible to augment * this. */ public static void addGestalt(String part, Attrs attrs) { Attrs already = overallGestalt.get(part); if (attrs == null) attrs = new Attrs(); if (already != null) { already.putAll(attrs); } else already = attrs; overallGestalt.put(part, already); } /** * Get the attrs for a gestalt part */ public Attrs getGestalt(String part) { return getGestalt().get(part); } /** * Get the attrs for a gestalt part */ public Parameters getGestalt() { if (gestalt == null) { gestalt = getMergedParameters(Constants.GESTALT); gestalt.mergeWith(overallGestalt, false); } return gestalt; } /** * Get the layout style of the workspace. */ public WorkspaceLayout getLayout() { return layout; } /** * The macro to access the gestalt * <p> * {@code $ gestalt;part[;key[;value]]} */ public String _gestalt(String args[]) { if (args.length >= 2) { Attrs attrs = getGestalt(args[1]); if (attrs == null) return ""; if (args.length == 2) return args[1]; String s = attrs.get(args[2]); if (args.length == 3) { if (s == null) s = ""; return s; } if (args.length == 4) { if (args[3].equals(s)) return s; else return ""; } } throw new IllegalArgumentException("${gestalt;<part>[;key[;<value>]]} has too many arguments"); } @Override public String toString() { return "Workspace [" + getBase().getName() + "]"; } /** * Create a project in this workspace */ public Project createProject(String name) throws Exception { if (!Verifier.SYMBOLICNAME.matcher(name).matches()) { error("A project name is a Bundle Symbolic Name, this must therefore consist of only letters, digits and dots"); return null; } File pdir = getFile(name); pdir.mkdirs(); IO.store("#\n# " + name.toUpperCase().replace('.', ' ') + "\n#\n", getFile(pdir, Project.BNDFILE)); Project p = new Project(this, pdir); p.getTarget().mkdirs(); p.getOutput().mkdirs(); p.getTestOutput().mkdirs(); for (File dir : p.getSourcePath()) { dir.mkdirs(); } p.getTestSrc().mkdirs(); for (LifeCyclePlugin l : getPlugins(LifeCyclePlugin.class)) l.created(p); if (!p.isValid()) { error("project %s is not valid", p); } return p; } /** * Create a new Workspace * * @param wsdir * @throws Exception */ public static Workspace createWorkspace(File wsdir) throws Exception { if (wsdir.exists()) return null; wsdir.mkdirs(); File cnf = IO.getFile(wsdir, CNFDIR); cnf.mkdir(); IO.store("", new File(cnf, BUILDFILE)); IO.store("-nobundles: true\n", new File(cnf, Project.BNDFILE)); File ext = new File(cnf, EXT); ext.mkdir(); Workspace ws = getWorkspace(wsdir); return ws; } /** * Add a plugin * * @param plugin * @throws Exception */ public boolean addPlugin(Class< ? > plugin, String alias, Map<String,String> parameters, boolean force) throws Exception { BndPlugin ann = plugin.getAnnotation(BndPlugin.class); if (alias == null) { if (ann != null) alias = ann.name(); else { alias = Strings.getLastSegment(plugin.getName()).toLowerCase(); if (alias.endsWith("plugin")) { alias = alias.substring(0, alias.length() - "plugin".length()); } } } if (!Verifier.isBsn(alias)) { error("Not a valid plugin name %s", alias); } File ext = getFile(Workspace.CNFDIR + "/" + Workspace.EXT); ext.mkdirs(); File f = new File(ext, alias + ".bnd"); if (!force) { if (f.exists()) { error("Plugin %s already exists", alias); return false; } } else { IO.delete(f); } Object l = plugin.getConstructor().newInstance(); Formatter setup = new Formatter(); try { setup.format(" + "# Plugin %s setup\n" // + "#\n", alias); setup.format("-plugin.%s = %s", alias, plugin.getName()); for (Map.Entry<String,String> e : parameters.entrySet()) { setup.format("; \\\n \t%s = '%s'", e.getKey(), escaped(e.getValue())); } setup.format("\n\n"); String out = setup.toString(); if (l instanceof LifeCyclePlugin) { out = ((LifeCyclePlugin) l).augmentSetup(out, alias, parameters); ((LifeCyclePlugin) l).init(this); } trace("setup %s", out); IO.store(out, f); } finally { setup.close(); } refresh(); for (LifeCyclePlugin lp : getPlugins(LifeCyclePlugin.class)) { lp.addedPlugin(this, plugin.getName(), alias, parameters); } return true; } static Pattern ESCAPE_P = Pattern.compile("(\"|')(.*)\1"); private Object escaped(String value) { Matcher matcher = ESCAPE_P.matcher(value); if (matcher.matches()) value = matcher.group(2); return value.replaceAll("'", "\\'"); } public boolean removePlugin(String alias) { File ext = getFile(Workspace.CNFDIR + "/" + Workspace.EXT); File f = new File(ext, alias + ".bnd"); if (!f.exists()) { error("No such plugin %s", alias); return false; } IO.delete(f); refresh(); return true; } /** * Create a workspace that does not inherit from a cnf directory etc. * * @param run */ public static Workspace createStandaloneWorkspace(Processor run, URI base) throws Exception { String property = run.getProperty(Constants.STANDALONE, ""); Workspace ws = new Workspace(WorkspaceLayout.STANDALONE); // Copy all properties except the type we will add for (Iterator<Map.Entry<Object,Object>> it = run.getProperties().entrySet().iterator(); it.hasNext();) { Entry<Object,Object> entry = it.next(); String key = (String) entry.getKey(); if (key.startsWith(PLUGIN_STANDALONE)) it.remove(); else ws.getProperties().put(key, entry.getValue()); } Parameters standalone = new Parameters(property); int counter = 1; for (Map.Entry<String,Attrs> e : standalone.entrySet()) { String locationStr = e.getKey(); if ("true".equalsIgnoreCase(locationStr)) break; URI resolvedLocation = URIUtil.resolve(base, locationStr); try (Formatter f = new Formatter();) { String name = e.getValue().get("name"); if (name == null) name = locationStr; f.format("%s; name=%s; locations='%s'", STANDALONE_REPO_CLASS, name, resolvedLocation); for (Map.Entry<String,String> attribEntry : e.getValue().entrySet()) { if (!"name".equals(attribEntry.getKey())) f.format(";%s='%s'", attribEntry.getKey(), attribEntry.getValue()); } f.format("\n"); ws.setProperty(PLUGIN_STANDALONE + counter, f.toString()); } counter++; } return ws; } public boolean isDefaultWorkspace() { return BND_DEFAULT_WS.equals(getBase()); } }
package net.izenith.Commands; import java.text.DecimalFormat; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permission; import net.izenith.Main.Util; import net.md_5.bungee.api.ChatColor; public class PlayTime implements HubCommand{ @Override public String getName() { return "playtime"; } @Override public String[] getAliases() { return new String[]{"play","givemearimjobandbitemyear"}; } @Override public void onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Long time = Util.getOnlineTime(Bukkit.getPlayer(args[0])); Double timeHours = new Double(time)/(1000*60*60); DecimalFormat df = new DecimalFormat(" String shortTime = df.format(timeHours); sender.sendMessage(ChatColor.BLUE + args[0] + " has played for " + ChatColor.GREEN + shortTime + " hours"); } @Override public boolean onlyPlayers() { return false; } @Override public boolean hasPermission() { return false; } @Override public Permission getPermission() { return null; } }
package nl.igorski.lib.audio; import android.content.Context; import android.os.Build; import android.os.Handler; import android.util.Log; import nl.igorski.lib.audio.nativeaudio.*; public final class MWEngine extends Thread { /** * interface to receive state change messages from the engine * these messages are constants defined inside Notifications.ids.values() */ public interface IObserver { /** * invoked whenever the engine broadcasts a notification * @param aNotificationId {int} unique identifier for the notification * * supported notification identifiers : * * ERROR_HARDWARE_UNAVAILABLE fired when MWEngine cannot connect to audio hardware (fatal) * ERROR_THREAD_START fired when MWEngine cannot start the rendering thread (fatal) * STATUS_BRIDGE_CONNECTED fired when MWEngine connects to the native layer code through JNI * MARKER_POSITION_REACHED fired when request Sequencer marker position has been reached */ void handleNotification( int aNotificationId ); /** * invoked whenever the engine broadcasts a notification * * @param aNotificationId {int} unique identifier for the notification * @param aNotificationValue {int} payload for the notification * * supported notiifcations identifiers : * * SEQUENCER_POSITION_UPDATED fired when Sequencer has advanced a step, payload describes * the precise buffer offset of the Sequencer when the notification fired * (as a value in the range of 0 - BUFFER_SIZE) * RECORDING_STATE_UPDATED fired when a recording snippet of request size has been written * to the output folder, payload contains snippet number * BOUNCE_COMPLETE fired when the offline bouncing of the Sequencer range has completed */ void handleNotification( int aNotificationId, int aNotificationValue ); } private static MWEngine INSTANCE; private IObserver _observer; private Context _context; private SequencerController _sequencerController; /* audio generation related, should be overridden to match device-specific values */ public static int SAMPLE_RATE = 44100; public static int BUFFER_SIZE = 2048; // we CAN multiply the output the volume to decrease it, preventing rapidly distorting audio ( especially on filters ) private static final float VOLUME_MULTIPLIER = .85f; private static float _volume = .85f /* assumed default level */ * VOLUME_MULTIPLIER; /* recording buffer specific */ private boolean _recordOutput = false; /* engine / thread states */ private boolean _openSLrunning = false; private int _openSLRetry = 0; private boolean _initialCreation = true; private boolean _disposed = false; private boolean _threadStarted = false; private boolean _isRunning = false; private boolean _paused = false; private final Object _pauseLock; /** * The Java-side bridge to manage all native layer components * of the MWEngine audio engine * * @param aContext {Context} current application context * @param aObserver {MWEngine.IObserver} observer that will monitor engine states */ public MWEngine( Context aContext, IObserver aObserver ) { INSTANCE = this; _context = aContext; _observer = aObserver; _pauseLock = new Object(); initJNI(); //setPriority( MAX_PRIORITY ); // no need, all in native layer } /* public methods */ // (re-)registers interface to match current/updated JNI environment public void initJNI() { MWEngineCore.init(); } public void createOutput( int aSampleRate, int aBufferSize ) { SAMPLE_RATE = aSampleRate; BUFFER_SIZE = aBufferSize; // Android emulators can only work at 8 kHz or crash... if ( Build.FINGERPRINT.startsWith( "generic" )) SAMPLE_RATE = 8000; // start w/ default of 120 BPM in 4/4 time _sequencerController = new SequencerController(); _sequencerController.prepare( BUFFER_SIZE, SAMPLE_RATE, 120.0f, 4, 4 ); _disposed = false; } public float getVolume() { return _volume / VOLUME_MULTIPLIER; } public void setVolume( float aValue ) { _volume = aValue * VOLUME_MULTIPLIER; _sequencerController.setVolume(_volume); } public SequencerController getSequencerController() { return _sequencerController; } public ProcessingChain getMasterBusProcessors() { return MWEngineCore.getMasterBusProcessors(); } public void setBouncing( boolean value, String outputDirectory ) { _sequencerController.setBounceState(value, calculateMaxBuffers(), outputDirectory); } /** * records the live output of the engine * * this keeps recording until setRecordingState is invoked with value false * given outputDirectory will contain several .WAV files each at the buffer * length returned by the "calculateMaxBuffers"-method */ public void setRecordingState( boolean value, String outputDirectory ) { int maxRecordBuffers = 0; // create / reset the recorded buffer when // hitting the record button if ( value ) maxRecordBuffers = calculateMaxBuffers(); _recordOutput = value; _sequencerController.setRecordingState(_recordOutput, maxRecordBuffers, outputDirectory); } /** * records the input channel of the Android device, note this can be done * while the engine is running a sequence / synthesizing audio * * given outputDirectory will contain a .WAV file at the buffer length * representing given maxDurationInMilliSeconds */ public void setRecordFromDeviceInputState( boolean value, String outputDirectory, int maxDurationInMilliSeconds ) { int maxRecordBuffers = 0; // create / reset the recorded buffer when // hitting the record button if ( value ) maxRecordBuffers = BufferUtility.millisecondsToBuffer( maxDurationInMilliSeconds, SAMPLE_RATE ); _recordOutput = value; _sequencerController.setRecordingFromDeviceState(_recordOutput, maxRecordBuffers, outputDirectory); } public boolean getRecordingState() { return _recordOutput; } public void reset() { MWEngineCore.reset(); _openSLRetry = 0; } /** * queries whether we can try to restart the engine * in case an error has occurred, note this will also * increment the amount of retries * * @return {boolean} */ public boolean canRestartEngine() { return ++_openSLRetry < 5; } // due to Object pooling we keep the thread alive by just pausing its execution, NOT actual cleanup // exiting the application will kill the native library anyways public void dispose() { pause(); _disposed = true; _openSLrunning = false; MWEngineCore.stop(); // halt the Native audio thread //_isRunning = false; // nope, we won't halt this thread (pooled) } /* threading */ @Override public void start() { if ( !_isRunning ) { if ( !_threadStarted ) super.start(); _threadStarted = true; _isRunning = true; } else { initJNI(); // update reference to this Java object in JNI unpause(); } } /** * invoke when the application suspends, this should * halt the execution of the run method and cause the * thread to clean up to free CPU resources */ public void pause() { synchronized ( _pauseLock ) { _paused = true; } } /** * invoke when the application regains focus */ public void unpause() { initJNI(); synchronized ( _pauseLock ) { _paused = false; _pauseLock.notifyAll(); } } public boolean isPaused() { return _paused; } public void run() { //DebugTool.log( "MWEngine STARTING NATIVE AUDIO RENDER THREAD" ); handleThreadStartTimeout(); while ( _isRunning ) { // start the Native audio thread if ( !_openSLrunning ) { Log.d( "MWENGINE", "STARTING NATIVE THREAD @ " + SAMPLE_RATE + " Hz using " + BUFFER_SIZE + " samples per buffer" ); _openSLrunning = true; MWEngineCore.start(); } // the remainder of this function body is actually blocked // as long as the native thread is running Log.d( "MWENGINE", "MWEngine THREAD STOPPED"); _openSLrunning = false; synchronized ( _pauseLock ) { while ( _paused ) { try { _pauseLock.wait(); } catch ( InterruptedException e ) {} } } } } /* helper functions */ private int calculateMaxBuffers() { // we record a maximum of 30 seconds before invoking the "handleRecordingUpdate"-method on the sequencer final double amountOfMinutes = .5; // convert milliseconds to sample buffer size return ( int ) (( amountOfMinutes * 60000 ) * ( SAMPLE_RATE / 1000 )); } /** * rare bug : occasionally the audio engine won't start, closing / reopening * the application tends to work.... * * this poor man's check checks whether the bridge has submitted its connection * message from the native layer after a short timeout */ private void handleThreadStartTimeout() { if ( !_openSLrunning ) { final Handler handler = new Handler( _context.getMainLooper() ); handler.postDelayed( new Runnable() { public void run() { if ( !_disposed && !_openSLrunning ) _observer.handleNotification( Notifications.ids.ERROR_THREAD_START.ordinal() ); } }, 2000 ); } } /* native bridge methods */ /** * all these methods are static and provide a bridge from C++ back into Java * these methods are used by the native audio engine for updating states and * requesting data * * Java method IDs need to be supplied to C++ in order te make the callbacks, you * can discover the IDs by building the Java project and running the following * command in the output /bin folder: * * javap -s -private -classpath classes nl.igorski.lib.audio.MWEngine */ public static void handleBridgeConnected( int aSomething ) { if ( INSTANCE._observer != null ) INSTANCE._observer.handleNotification( Notifications.ids.STATUS_BRIDGE_CONNECTED.ordinal() ); } public static void handleNotification( int aNotificationId ) { if ( INSTANCE._observer != null ) INSTANCE._observer.handleNotification( aNotificationId ); } public static void handleNotificationWithData( int aNotificationId, int aNotificationData ) { if ( INSTANCE._observer != null ) INSTANCE._observer.handleNotification( aNotificationId, aNotificationData ); } public static void handleTempoUpdated( float aNewTempo ) { // weird bug where on initial start the sequencer would not know the step range... if ( INSTANCE._initialCreation ) { INSTANCE._initialCreation = false; INSTANCE.getSequencerController().setLoopRange( 0, INSTANCE.getSequencerController().getSamplesPerBar() ); } } }
package no.group09.database; import no.group09.database.entity.App; import no.group09.database.entity.BinaryFile; import no.group09.database.entity.Developer; import no.group09.database.entity.Requirements; /** * Constants for use in the database. * Strings which contain the extended SQL queries */ public class Constants { /** Select an app from the database */ protected final static String SELECT_APP = "select * from app where appid=?"; protected final static String SELECT_DEVELOPER = "select * from developer where developerid=?"; protected final static String SELECT_REQUIREMENTS = "select * from requirements where requirementid=?"; protected final static String SELECT_PICTURES = "select * from pictures where pictureid=?"; protected final static String SELECT_BINARYFILES = "select * from binaryfiles where appid=?"; //FIXME:working? /** Insert an app to the database */ protected final static String INSERT_APP = "insert or replace into app (name, rating, developerid, category, description, requirementid) values (?, ?, ?, ?, ?, ?)"; protected final static String INSERT_DEVELOPER = "insert or replace into developer (name, website) values (?, ?)"; protected final static String INSERT_REQUIREMENTS = "insert or replace into requirements (name, description, compatible) values (?, ?, ?)"; protected final static String INSERT_PICTURES = "insert or replace into pictures (appid, fileURL) values (?, ?)"; protected final static String INSERT_BINARYFILES = "insert or replace into binaryfiles (appid, file) values (?, ?)"; //FIXME:working? /** Delete an app from the database */ protected final static String DELETE_APP = "delete from app where appid=?"; protected final static String DELETE_DEVELOPER = "delete from developer where developerid=?"; protected final static String DELETE_REQUIREMENTS = "delete from requirements where requirementid=?"; protected final static String DELETE_PICTURES = "delete from pictures where pictureid=?"; protected final static String DELETE_BINARYFILES = "delete from binaryfiles where appid=?"; //FIXME:working? /** app(appid, name, description, developerid, icon) */ protected final static String APP_TABLE="app"; protected final static String APP_ID="appid"; protected final static String APP_NAME="name"; protected final static String APP_RATING="rating"; protected final static String APP_DEVELOPERID="developerid"; protected final static String APP_CATEGORY="category"; protected final static String APP_DESCRIPTION="description"; protected final static String APP_REQUIREMENTID="requirementid"; /** binaryfile(appid, file) */ protected final static String BINARYFILES_TABLE = "binaryfiles"; protected final static String BINARYFILES_ID = "binaryfileid"; protected final static String BINARYFILES_APPID = "appid"; protected final static String BINARYFILES_FILE = "file"; /** developer(developerid, name, website) */ protected final static String DEVELOPER_TABLE="developer"; protected final static String DEVELOPER_ID="developerid"; protected final static String DEVELOPER_NAME="name"; protected final static String DEVELOPER_WEBSITE="website"; /** pictures(pictureid, appid, fileURL) */ protected final static String PICTURES_TABLE="pictures"; protected final static String PICTURES_ID="pictureid"; protected final static String PICTURES_APPID="appid"; protected final static String PICTURES_FILEURL="fileURL"; /** requirement(requirement, name, description) */ protected final static String REQUIREMENTS_TABLE="requirements"; protected final static String REQUIREMENTS_ID="requirementid"; protected final static String REQUIREMENTS_NAME="name"; protected final static String REQUIREMENTS_DESCRIPTION="description"; protected final static String REQUIREMENTS_COMPATIBLE="compatible"; /** appusespins(appid, requirementid) */ protected final static String APPUSESPINS_TABLE="appusespins"; protected final static String APPUSESPINS_APPID="appid"; protected final static String APPUSESPINS_REQUIREMENTID="requirementid"; /** Database app creation sql statement */ protected static final String DATABASE_CREATE_APP = "CREATE TABLE IF NOT EXISTS app (" + "appid integer primary key autoincrement, " + "name varchar(160), " + "rating int(10), " + "developerid int(10)," + "category varchar(200)," + "description varchar(200)," + "requirementid int(10))"; /** Database binaryfiles creation sql statement */ protected final static String DATABASE_CREATE_BINARYFILES = "CREATE TABLE binaryfiles (" + "binaryfileid integer primary key autoincrement, " + "appid int(10), " + "file BLOB(1000000) )"; //FIXME:working? /** Database developer creation sql statement */ protected static final String DATABASE_CREATE_DEVELOPER = "CREATE TABLE developer (" + "developerid integer primary key autoincrement, " + "name varchar(160), " + "website varchar(200))"; /** Database pictures creation sql statement */ protected static final String DATABASE_CREATE_PICTURES = "CREATE TABLE pictures (" + "pictureid integer primary key autoincrement, " + "appid int(10), " + "fileURL varchar(200))"; /** Database requirement creation sql statement */ protected static final String DATABASE_CREATE_REQUIREMENTS = "CREATE TABLE requirements (" + "requirementid integer primary key autoincrement, " + "name varchar(160), " + "description varchar(200)," + "compatible varchar(10))"; /** Database appUsesPins creation sql statement */ protected static final String DATABASE_CREATE_APPUSESPINS = "CREATE TABLE appUsesPins (" + "appid int(10) , " + "requirementid int(10)" + "FOREIGN KEY (appid) REFERENCES app(appid)," + "FOREIGN KEY (requirementid) REFERENCES requirements(requirementid))"; /** * Populates the database with some hardcoded examples * @param save - the current save class * @param useContentProvider - if you want to use content provider or not */ public static void populateDatabase(Save save) { //App(name, rating, developerid, category, description, requirementid) save.insertApp(new App("FunGame", 3, 1, "Games", "This describes this amazing, life changing app. yey!", 1)); save.insertApp(new App("Game", 4, 2, "Games", "This describes this amazing, life changing app. yey!", 2)); save.insertApp(new App("PlayTime", 2, 5, "Games", "This describes this amazing, life changing app. yey!", 2)); save.insertApp(new App("FunTime", 4, 4, "Games", "This describes this amazing, life changing app. yey!", 3)); save.insertApp(new App("PlayWithPlayers", 1, 2, "Games", "This describes this amazing, life changing app. yey!", 3)); save.insertApp(new App("Medic", 1, 1, "Medical", "This describes this amazing, life changing app. yey!", 2)); save.insertApp(new App("Medical", 6, 3, "Medical", "This describes this amazing, life changing app. yey!", 3)); save.insertApp(new App("Helper", 4, 5, "Medical", "This describes this amazing, life changing app. yey!", 1)); save.insertApp(new App("Tool", 5, 5, "Tools", "This describes this amazing, life changing app. yey!", 2)); save.insertApp(new App("ToolBox", 5, 3, "Tools", "This describes this amazing, life changing app. yey!", 3)); save.insertApp(new App("BoxTooler", 2, 1, "Tools", "This describes this amazing, life changing app. yey!", 3)); save.insertApp(new App("ToolTooler", 3, 1, "Tools", "This describes this amazing, life changing app. yey!", 1)); save.insertApp(new App("ScrewDriver", 4, 1, "Tools", "This describes this amazing, life changing app. yey!", 2)); // save.insertApp(new App("Player", 4, 5, "Media", "This describes this amazing, life changing app. yey!", 1)); // save.insertApp(new App("MusicP", 2, 2, "Media", "This describes this amazing, life changing app. yey!", 3)); save.insertDeveloper(new Developer("Wilhelm", "www.lol.com")); //developer 1 save.insertDeveloper(new Developer("Robin", "www.haha.com")); save.insertDeveloper(new Developer("Jeppe", "www.hehe.com")); save.insertDeveloper(new Developer("Bjrn", "www.hoho.com")); save.insertDeveloper(new Developer("Stle", "www.rofl.com")); save.insertDeveloper(new Developer("Nina", "www.kake.com")); save.insertRequirements(new Requirements("name", "description", true)); //compatible save.insertRequirements(new Requirements("name", "desc..", true)); //compatible save.insertRequirements(new Requirements("name", "desc..", false)); //not compatible //games: LED save.insertBinaryFile(new BinaryFile(1, Constants.getByteExample(1))); save.insertBinaryFile(new BinaryFile(2, Constants.getByteExample(1))); save.insertBinaryFile(new BinaryFile(3, Constants.getByteExample(1))); save.insertBinaryFile(new BinaryFile(4, Constants.getByteExample(1))); save.insertBinaryFile(new BinaryFile(5, Constants.getByteExample(1))); //medical: mario save.insertBinaryFile(new BinaryFile(6, Constants.getByteExample(2))); save.insertBinaryFile(new BinaryFile(7, Constants.getByteExample(2))); save.insertBinaryFile(new BinaryFile(8, Constants.getByteExample(2))); //tool: alternative LED save.insertBinaryFile(new BinaryFile(9, Constants.getByteExample(3))); save.insertBinaryFile(new BinaryFile(10, Constants.getByteExample(3))); save.insertBinaryFile(new BinaryFile(11, Constants.getByteExample(3))); save.insertBinaryFile(new BinaryFile(12, Constants.getByteExample(3))); save.insertBinaryFile(new BinaryFile(13, Constants.getByteExample(3))); // save.insertBinaryFile(new BinaryFile(14, Constants.getByteExample())); // save.insertBinaryFile(new BinaryFile(15, Constants.getByteExample())); } /** returns a example binary file */ public static byte[] getByteExample(int type){ String s = ""; //If it is a game if(type == 1){ //LEDS s = "3A100000000C9464000C948C000C948C000C948C0068" + "3A100010000C948C000C948C000C948C000C948C0030" + "3A100020000C948C000C948C000C948C000C948C0020" + "3A100030000C948C000C948C000C948C000C948C0010" + "3A100040000C9464070C948C000C94DB080C94290924" + "3A100050000C948C000C948C000C948C000C948C00F0" + "3A100060000C948C000C948C000000000024002700ED" + "3A100070002A0000000000250028002B0000000000DE" + "3A1000800023002600290004040404040404040202DA" + "3A100090000202020203030303030301020408102007" + "3A1000A0004080010204081020010204081020000012" + "3A1000B0000007000201000003040600000000000029" + "3A1000C0000000A102950A9A0211241FBECFEFD8E0CA" + "3A1000D000DEBFCDBF11E0A0E0B1E0E4E1F9E102C094" + "3A1000E00005900D92AC3DB107D9F712E0ACEDB1E04F" + "3A1000F00001C01D92A33DB107E1F710E0C6ECD0E0CE" + "3A1001000004C02297FE010E94420CC23CD107C9F7ED" + "3A100110000E94EB0A0C947D0C0C940000CF93DF93AB" + "3A10012000BC018230910510F462E070E0A091D10230" + "3A10013000B091D202ED01E0E0F0E040E050E021C0FB" + "3A10014000888199818617970769F48A819B81309706" + "3A1001500019F09383828304C09093D2028093D102DA" + "3A10016000FE0134C06817790738F44115510519F0BC" + "3A100170008417950708F4AC01FE018A819B819C01DC" + "3A10018000E9012097E9F641155105A9F1CA01861B3D" + "3A10019000970B049708F4BA01E0E0F0E02AC08D91D3" + "3A1001A0009C91119784179507F9F46417750781F4EA" + "3A1001B00012968D919C911397309719F093838283B7" + "3A1001C00004C09093D2028093D102FD0132964CC0BC" + "3A1001D000CA01861B970BFD01E80FF91F619371930C" + "3A1001E00002978D939C9340C0FD01828193819C0175" + "3A1001F000D9011097A1F68091CF029091D002892B5E" + "3A1002000041F48091C6019091C7019093D0028093F0" + "3A10021000CF024091C8015091C9014115510541F4E7" + "3A100220004DB75EB78091C4019091C501481B590B31" + "3A100230002091CF023091D002CA01821B930B861706" + "3A10024000970780F0AB014E5F5F4F8417950750F022" + "3A10025000420F531F5093D0024093CF02F901619394" + "3A10026000719302C0E0E0F0E0CF01DF91CF910895FB" + "3A10027000CF93DF93009709F450C0EC0122971B82C3" + "3A100280001A82A091D102B091D202109709F140E0F8" + "3A1002900050E0AC17BD0708F1BB83AA83FE01219192" + "3A1002A0003191E20FF31FAE17BF0779F48D919C9146" + "3A1002B0001197280F391F2E5F3F4F398328831296DD" + "3A1002C0008D919C9113979B838A834115510571F4FD" + "3A1002D000D093D202C093D10220C012968D919C91EE" + "3A1002E0001397AD01009711F0DC01D3CFFA01D3834E" + "3A1002F000C28321913191E20FF31FCE17DF0769F41A" + "3A1003000088819981280F391F2E5F3F4FFA01318371" + "3A1003100020838A819B8193838283DF91CF9108958B" + "3A10032000A0E0B0E0E6E9F1E00C94480C6C01009725" + "3A1003300029F4CB010E948E006C01C1C08EEF882E83" + "3A100340008FEF982E8C0C9D1C8601060F171F081529" + "3A10035000190508F4B2C0F401A081B181A617B7074E" + "3A10036000B8F0A530B10508F4AAC0CD0104978617EE" + "3A10037000970708F4A4C01297A61BB70BF801A19326" + "3A10038000B193D4016D937C93CF010E94380197C043" + "3A100390007B01EA1AFB0AEEEFFFEFEE0EFF1E3601BD" + "3A1003A0006A0E7B1EC091D102D091D2024424552402" + "3A1003B000AA24BB244AC0C615D705E1F54881598156" + "3A1003C0004E155F05B8F1CA0104978E159F05B0F46C" + "3A1003D0001296A40FB51FF401B183A0832A813B813B" + "3A1003E0004114510431F0D20113963C932E9312978D" + "3A1003F00066C03093D2022093D10261C08A819B8172" + "3A10040000F80193838283425050404E195F09518313" + "3A1004100040834114510431F0D20113961C930E9382" + "3A10042000129704C01093D2020093D102F401718399" + "3A10043000608345C088819981A816B90608F45C01DB" + "3A100440002E018A819B819C01E901209709F0B3CF9D" + "3A100450008091CF029091D00286159705E9F4A616F7" + "3A10046000B706D0F42091C8013091C901211531059A" + "3A1004700041F42DB73EB78091C4019091C501281B6E" + "3A10048000390B02171307C8F41093D0020093CF0260" + "3A10049000D4016D937C9313C0CB010E948E00EC01BC" + "3A1004A000009759F0F40140815181B6010E94650224" + "3A1004B000C6010E9438016E0102C0CC24DD24C601B1" + "3A1004C000CDB7DEB7E0E10C94640CFB01DC0102C0A7" + "3A1004D00001900D9241505040D8F70895FB01DC0186" + "3A1004E00001900D920020E1F708958130910561F4AB" + "3A1004F0006F5F7F4FF1F480EE91E040E050E060E00C" + "3A1005000070E00E9433070895892B99F46F5F7F4F45" + "3A1005100081F487E092E00E94180C80E092E00E9453" + "3A10052000180C89EF91E00E94180C82EF91E00E9474" + "3A10053000180C089580E090E06FEF7FEF0E94750245" + "3A10054000089581E090E06FEF7FEF0E9475020895BB" + "3A1005500080EE91E00E94A20508958091CA0188234F" + "3A1005600009F450C00E94AC072091DC013091DD01FC" + "3A100570004091DE015091DF012854344F4F4F5F4FBF" + "3A10058000621773078407950788F08AE061E00E948C" + "3A1005900034080E94AC076093DC017093DD01809306" + "3A1005A000DE019093DF011092CA0108950E94AC070A" + "3A1005B0002091DC013091DD014091DE015091DF019D" + "3A1005C0002053384F4F4F5F4F6217730784079507CB" + "3A1005D00010F08BE015C00E94AC072091DC01309137" + "3A1005E000DD014091DE015091DF0128513C4F4F4F1A" + "3A1005F0005F4F621773078407950708F457C08CE0B4" + "3A1006000061E03AC00E94AC072091DC013091DD012D" + "3A100610004091DE015091DF012854344F4F4F5F4F1E" + "3A10062000621773078407950790F08AE060E00E94E4" + "3A1006300034080E94AC076093DC017093DD01809365" + "3A10064000DE019093DF0181E08093CA0108950E944A" + "3A10065000AC072091DC013091DD014091DE01509129" + "3A10066000DF012053384F4F4F5F4F621773078407E6" + "3A10067000950728F08BE060E00E94340808950E94FE" + "3A10068000AC072091DC013091DD014091DE015091F9" + "3A10069000DF0128513C4F4F4F5F4F621773078407AC" + "3A1006A000950720F08CE060E00E9434080895EF92F6" + "3A1006B000FF920F931F93DF93CF93CDB7DEB72E97A3" + "3A1006C0000FB6F894DEBF0FBECDBF80EEE82E81E0FE" + "3A1006D000F82EC70140E052EC61E070E00E9419077B" + "3A1006E00084E061E00E94F50784E061E00E94340844" + "3A1006F0008E010F5F1F4FC80160E071E00E94E70BA1" + "3A10070000C701B8010E941507C8010E94180C8E018C" + "3A10071000085F1F4FC80165E071E00E94E70BC70149" + "3A10072000B8010E941107C8010E94180CC7016BE0B4" + "3A1007300071E044E151E00E94D90682E061E00E944C" + "3A10074000F5078DE061E00E94F507C70169E171E0FE" + "3A100750004BE451E00E94A1068AE061E00E94F507A7" + "3A100760008BE061E00E94F5078CE061E00E94F507F4" + "3A100770000E94AC076093DC017093DD018093DE0181" + "3A100780009093DF012E960FB6F894DEBF0FBECDBF5B" + "3A10079000CF91DF911F910F91FF90EF90089580E02E" + "3A1007A00090E0089584E060E00E9434080895CF92BC" + "3A1007B000DF92EF92FF921F93CF93DF93162F6A0180" + "3A1007C00079018CEA92E06FEF0E94550A8CEA92E080" + "3A1007D0006F2D0E94550A8CEA92E06E2D0E94550AF8" + "3A1007E0008CEA92E06EEF0E94550A8CEA92E0612F4B" + "3A1007F0000E94550AC0E0D0E009C0F601EC0FFD1FD1" + "3A100800008CEA92E060810E94550A2196CE15DF05A0" + "3A10081000A0F3DF91CF911F91FF90EF90DF90CF90E9" + "3A1008200008950F931F93CF93DF93EC01062F142F9E" + "3A10083000862F61E00E94F50760E0111161E0802FD2" + "3A100840000E943408CE0165E040E050E020E030E056" + "3A100850000E94D703DF91CF911F910F910895EF92DE" + "3A10086000FF921F93DF93CF930F92CDB7DEB77C013A" + "3A10087000162F862F60E00E94F507812F0E948808BE" + "3A1008800019821816190614F481E08983C70164E0FF" + "3A10089000AE014F5F5F4F21E030E00E94D7030F9021" + "3A1008A000CF91DF911F91FF90EF9008950F931F93C9" + "3A1008B000CF93DF938C01DB01842FE801E885F98574" + "3A1008C000B901AD010995C80163E040E050E020E0C6" + "3A1008D00030E00E94D703DF91CF911F910F910895CF" + "3A1008E000CF92DF92EF92FF920F931F93DF93CF93FC" + "3A1008F00000D0CDB7DEB76C01862FD6011696ED91EC" + "3A10090000FC9117977E010894E11CF11CB70140E0AF" + "3A1009100050E009958C01FC019081818189839A8343" + "3A10092000C60162E0A70122E030E00E94D703C801BF" + "3A100930000E9438010F900F90CF91DF911F910F917E" + "3A10094000FF90EF90DF90CF9008950F931F93CF9378" + "3A10095000DF938C01DB01842FE801EC81FD81B9017B" + "3A10096000AD010995C80161E040E050E020E030E0D1" + "3A100970000E94D703DF91CF911F910F91089560E0FE" + "3A1009800040E050E020E030E00E94D7030895CF928D" + "3A10099000DF92EF92FF920F931F93DF93CF93CDB728" + "3A1009A000DEB727970FB6F894DEBF0FBECDBF7C0130" + "3A1009B0008E010F5F1F4FC80162E671E00E94E70BD6" + "3A1009C000C80163E671E00E949C0B82E190E0E80EB2" + "3A1009D000F91EC801B7010E94AC0BC8016DE671E0B9" + "3A1009E0000E949C0BC80160E771E00E949C0B87E0AD" + "3A1009F00090E0E80EF91EC801B7010E94AC0BC801D7" + "3A100A00006DE671E00E949C0BC8016CE771E00E94EA" + "3A100A10009C0B87E090E0E80EF91EC801B7010E9428" + "3A100A2000AC0BC8016AE871E00E949C0BC8016DE83C" + "3A100A300071E00E949C0B87E090E0E80EF91EC8016F" + "3A100A4000B7010E94AC0BC80168E971E00E949C0BE1" + "3A100A5000CD80DE808CEA92E06FEF0E94550A8CEA2E" + "3A100A600092E06D2D0E94550A8CEA92E06C2D0E9456" + "3A100A7000550A8CEA92E06EEF0E94550A8CEA92E0E9" + "3A100A800066E00E94550AEE24FF2410C0C801B70199" + "3A100A90000E94240BFC016081772767FD70958CEA2A" + "3A100AA00092E00E94550A0894E11CF11CEC14FD042C" + "3A100AB00068F3C8010E94180C27960FB6F894DEBFA1" + "3A100AC0000FBECDBFCF91DF911F910F91FF90EF909F" + "3A100AD000DF90CF9008950F931F93F8014330E1F01A" + "3A100AE000443028F4413079F0423090F409C0453068" + "3A100AF000E1F04530B0F04630E9F04F3F01F51DC060" + "3A100B00000E94BF041CC0422F98010E94A50417C078" + "3A100B1000622F0E94700413C0422F98010E94560455" + "3A100B20000EC0622F0E942F040AC0622F40810E94D3" + "3A100B3000110405C00E94C70402C00E94D2031F9185" + "3A100B40000F9108956F927F928F929F92AF92BF9272" + "3A100B5000CF92DF92EF92FF920F931F93CF93DF9389" + "3A100B6000EC010E94AC0720911502309116024091D1" + "3A100B7000170250911802261737074807590750F4F3" + "3A100B80008091190290911A02892B21F010921A0279" + "3A100B9000109219020E94AC076053784F8F4F9F4FFD" + "3A100BA00060931502709316028093170290931802B7" + "3A100BB00073E0672E712C65E0862E912C54E0A52EF3" + "3A100BC000B12C41E0C42ED12C32E0E32EF12CA3C095" + "3A100BD0008091190290911A0282309105C1F18330FF" + "3A100BE000910534F4009781F0019709F08FC022C07D" + "3A100BF0008430910509F453C0843091050CF444C04D" + "3A100C0000059709F083C056C08CEA92E00E941C0A46" + "3A100C10008F3F910509F07AC0D0921A02C092190252" + "3A100C200080910F0290911002009709F46FC00E940A" + "3A100C300038016CC08CEA92E00E941C0A10921302E8" + "3A100C400080931402F0921A02E09219025FC00091A0" + "3A100C50001302109114028CEA92E00E941C0A90E0A8" + "3A100C6000802B912B909314028093130270921A029E" + "3A100C7000609219020E948E009093100280930F02DE" + "3A100C8000009709F043C03EC08CEA92E00E941C0A23" + "3A100C900080931202B0921A02A092190237C08CEA15" + "3A100CA00092E00E941C0A8093110290921A02809294" + "3A100CB00019022CC080910E0200910F0210911002B7" + "3A100CC000080F111D8CEA92E00E941C0AF801808333" + "3A100CD00080910E028F5F80930E02609113027091DB" + "3A100CE000140290E08617970788F000910F02109188" + "3A100CF0001002CE0140911202209111020E946B0558" + "3A100D000010920E0210921A02109219028881998193" + "3A100D10000196998388838CEA92E00E94EB09892BE3" + "3A100D200009F056CFDF91CF911F910F91FF90EF9077" + "3A100D3000DF90CF90BF90AF909F908F907F906F90FB" + "3A100D40000895CF92DF92EF92FF920F931F93CF936C" + "3A100D5000DF93EC016B017A018BA59CA5892B31F007" + "3A100D6000CE0187966BE971E00E949C0B8E01095DB4" + "3A100D70001F4FC80163E671E00E949C0BC801B701D8" + "3A100D80000E949C0BC8016EE971E00E949C0BC80197" + "3A100D9000B6010E949C0BC8016AEA71E00E949C0B9C" + "3A100DA000DF91CF911F910F91FF90EF90DF90CF9047" + "3A100DB0000895CF92DF92EF92FF920F931F93CF93FC" + "3A100DC000DF93EC017B016A018CA19DA1892B31F09D" + "3A100DD000CE0180966BE971E00E949C0B8E01005E53" + "3A100DE0001F4FC8016DEA71E00E949C0BC801B7015A" + "3A100DF0000E949C0BC80167EB71E00E949C0BC8012C" + "3A100E0000B6010E949C0BC8016AEA71E00E949C0B2B" + "3A100E1000DF91CF911F910F91FF90EF90DF90CF90D6" + "3A100E2000089549960E94010C089542960E94010C73" + "3A100E300008950F931F93182F092F8CEA92E00E94B8" + "3A100E40006409212F302FC901FC0180E090E02FECD4" + "3A100E500033E0338322830196329688309105C9F7B7" + "3A100E60001F910F910895EF92FF920F931F93CF93CD" + "3A100E7000DF93EC017A018B01429662E671E00E94F9" + "3A100E8000E70BCE01499662E671E00E94E70BCE01C6" + "3A100E9000809662E671E00E94E70BCE01879662E6DB" + "3A100EA00071E00E94E70BE114F1040105110529F03E" + "3A100EB000CE01B801A7010E941907DF91CF911F91C0" + "3A100EC0000F91FF90EF9008951F920F920FB60F921F" + "3A100ED00011242F933F938F939F93AF93BF93809150" + "3A100EE0001F0290912002A0912102B0912202309124" + "3A100EF00023020196A11DB11D232F2D5F2D3720F058" + "3A100F00002D570196A11DB11D2093230280931F022E" + "3A100F100090932002A0932102B093220280911B02A1" + "3A100F200090911C02A0911D02B0911E020196A11D7C" + "3A100F3000B11D80931B0290931C02A0931D02B093DD" + "3A100F40001E02BF91AF919F918F913F912F910F9072" + "3A100F50000FBE0F901F9018958FB7F89420911F0225" + "3A100F60003091200240912102509122028FBFB9019D" + "3A100F7000CA010895789484B5826084BD84B5816087" + "3A100F800084BD85B5826085BD85B5816085BDEEE691" + "3A100F9000F0E0808181608083E1E8F0E01082808170" + "3A100FA00082608083808181608083E0E8F0E08081DE" + "3A100FB00081608083E1EBF0E0808184608083E0EBFE" + "3A100FC000F0E0808181608083EAE7F0E080818460E6" + "3A100FD0008083808182608083808181608083808142" + "3A100FE000806880831092C1000895CF93DF93482FCB" + "3A100FF00050E0CA0186569F4FFC0134914A575F4F1B" + "3A10100000FA018491882369F190E0880F991FFC010F" + "3A10101000E859FF4FA591B491FC01EE58FF4FC591DF" + "3A10102000D491662351F42FB7F8948C91932F909517" + "3A1010300089238C93888189230BC0623061F42FB798" + "3A10104000F8948C91932F909589238C938881832B8E" + "3A1010500088832FBF06C09FB7F8948C91832B8C9305" + "3A101060009FBFDF91CF910895482F50E0CA0182556C" + "3A101070009F4FFC012491CA0186569F4FFC01949119" + "3A101080004A575F4FFA013491332309F440C02223B9" + "3A1010900051F1233071F0243028F42130A1F02230B6" + "3A1010A00011F514C02630B1F02730C1F02430D9F446" + "3A1010B00004C0809180008F7703C0809180008F7D75" + "3A1010C0008093800010C084B58F7702C084B58F7D77" + "3A1010D00084BD09C08091B0008F7703C08091B000BB" + "3A1010E0008F7D8093B000E32FF0E0EE0FFF1FEE58EE" + "3A1010F000FF4FA591B4912FB7F894662321F48C91FA" + "3A101100009095892302C08C91892B8C932FBF0895D1" + "3A10111000682F70E0CB0182559F4FFC012491CB01D9" + "3A1011200086569F4FFC0144916A577F4FFB01949173" + "3A10113000992319F420E030E03CC0222351F1233000" + "3A1011400071F0243028F42130A1F0223011F514C0C0" + "3A101150002630B1F02730C1F02430D9F404C080919A" + "3A1011600080008F7703C0809180008F7D8093800006" + "3A1011700010C084B58F7702C084B58F7D84BD09C04F" + "3A101180008091B0008F7703C08091B0008F7D8093F5" + "3A10119000B000892F90E0880F991F84589F4FFC0161" + "3A1011A000A591B4918C9120E030E0842311F021E0EE" + "3A1011B00030E0C90108951F920F920FB60F921124CB" + "3A1011C0002F933F934F938F939F93EF93FF93809130" + "3A1011D000C00082FD1DC04091C60020916402309184" + "3A1011E00065022F5F3F4F2F733070809166029091A0" + "3A1011F00067022817390771F0E0916402F0916502E7" + "3A10120000EC5DFD4F4083309365022093640202C081" + "3A101210008091C600FF91EF919F918F914F913F91E7" + "3A101220002F910F900FBE0F901F901895E091B8026C" + "3A10123000F091B902E05CFF4F819191912081318161" + "3A10124000821B930B8F739070892B11F00E94A80260" + "3A1012500008951F920F920FB60F9211242F933F9370" + "3A101260008F939F93EF93FF932091A8023091A9024F" + "3A101270008091AA029091AB022817390731F480912E" + "3A10128000C1008F7D8093C10014C0E091AA02F0914B" + "3A10129000AB02E859FD4F20818091AA029091AB02E8" + "3A1012A00001968F7390709093AB028093AA02209363" + "3A1012B000C600FF91EF919F918F913F912F910F90D9" + "3A1012C0000FBE0F901F901895AF92BF92DF92EF92D2" + "3A1012D000FF920F931F93CF93DF93EC017A018B0161" + "3A1012E000DD24403081EE580780E0680780E0780711" + "3A1012F00011F0DD24D39491E0A92EB12CEC89FD8965" + "3A10130000DD2069F0C50108A002C0880F991F0A946A" + "3A10131000E2F7808360E079E08DE390E005C0108221" + "3A1013200060E874E88EE190E0A80197010E941E0C2D" + "3A10133000215030404040504056954795379527956D" + "3A1013400080E12030380720F0DD2011F0DD24D6CFF9" + "3A10135000E889F9893083EA89FB89208319A2EE891B" + "3A10136000FF89408121E030E0C9010C8C02C0880F68" + "3A10137000991F0A94E2F7482B4083EE89FF89408148" + "3A10138000C9010D8C02C0880F991F0A94E2F7482BFF" + "3A101390004083EE89FF894081C9010E8C02C0880F0D" + "3A1013A000991F0A94E2F7482B4083EE89FF898081D8" + "3A1013B0000F8C02C0220F331F0A94E2F720952823D6" + "3A1013C0002083DF91CF911F910F91FF90EF90DF90DD" + "3A1013D000BF90AF900895DC011C96ED91FC911D9794" + "3A1013E000E05CFF4F2191319180819181281B390B65" + "3A1013F0002F733070C9010895DC011C96ED91FC91AA" + "3A101400001D97E05CFF4F20813181E054F040DF0107" + "3A10141000AE5BBF4F8D919C9111972817390719F436" + "3A101420002FEF3FEF07C08D919C91E80FF91F80814E" + "3A10143000282F30E0C9010895DC011C96ED91FC9144" + "3A101440001D97E05CFF4F20813181E054F040DF01C7" + "3A10145000AE5BBF4F8D919C9111972817390719F4F6" + "3A101460002FEF3FEF10C08D919C911197E80FF91F5E" + "3A1014700020818D919C91119701968F739070119698" + "3A101480009C938E9330E0C9010895DC0191968C9174" + "3A101490009197882339F05496ED91FC91559780816E" + "3A1014A00086FFF9CF91961C920895CF93DF93EC01BC" + "3A1014B000EE85FF85E05CFF4F20813181E054F040F4" + "3A1014C0002F5F3F4F2F733070DF01AE5BBF4F8D91A9" + "3A1014D0009C91119728173907D1F3E05CFF4F808169" + "3A1014E0009181E054F040E80FF91F6083EE85FF859D" + "3A1014F000E05CFF4F31832083EE89FF89208181E00A" + "3A1015000090E00F8C02C0880F991F0A94E2F7282BF5" + "3A10151000208381E089A3EC89FD89808180648083B8" + "3A1015200081E090E0DF91CF9108951092AF02109288" + "3A10153000AE0288EE93E0A0E0B0E08093B00290931A" + "3A10154000B102A093B202B093B3028FEC91E09093FA" + "3A10155000AD028093AC0284E292E09093B902809352" + "3A10156000B80288E692E09093BB028093BA0285ECC1" + "3A1015700090E09093BD028093BC0284EC90E0909345" + "3A10158000BF028093BE0280EC90E09093C1028093F2" + "3A10159000C00281EC90E09093C3028093C20282EC7F" + "3A1015A00090E09093C5028093C40286EC90E0909303" + "3A1015B000C7028093C60284E08093C80283E08093D0" + "3A1015C000C90287E08093CA0285E08093CB0281E064" + "3A1015D0008093CC020895CF93DF930E94BA070E94B4" + "3A1015E0005703C6E1D9E00E94AD022097E1F30E94C3" + "3A1015F0001609F9CFCF92DF92EF92FF920F931F93CC" + "3A10160000CF93DF937C016B018A01C0E0D0E00FC073" + "3A10161000D6016D916D01D701ED91FC910190F081A2" + "3A10162000E02DC7010995C80FD91F015010400115C1" + "3A10163000110571F7CE01DF91CF911F910F91FF90AE" + "3A10164000EF90DF90CF900895FC019B0184819581FC" + "3A101650006817790728F4608171816115710529F493" + "3A101660001092CE026EEC72E002C0620F731FCB01CB" + "3A1016700008950F931F93CF93DF93EC018B016F5F5E" + "3A101680007F4F888199810E949001009711F480E03A" + "3A1016900005C0998388831B830A8381E0DF91CF9102" + "3A1016A0001F910F910895CF93DF93EC018881998169" + "3A1016B000892B29F08A819B818617970760F4CE01D8" + "3A1016C0000E94390B882341F08C819D81892B19F46C" + "3A1016D000E881F981108281E0DF91CF910895EF9246" + "3A1016E000FF920F931F93CF93DF93EC017B016C81EB" + "3A1016F0007D81E114F104C1F04115510599F08A0191" + "3A10170000060F171FB8010E94530B882369F08881C8" + "3A1017100099812C813D81820F931FB7010E946E0237" + "3A101720001D830C8381E001C080E0DF91CF911F9188" + "3A101730000F91FF90EF9008956115710511F480E00D" + "3A101740000895DB010D900020E9F71197A61BB70B58" + "3A10175000AD010E946F0B0895FB016081718144818E" + "3A1017600055810E946F0B0895CF93DF93EC01888120" + "3A101770009981009711F00E943801198218821D8208" + "3A101780001C821B821A82DF91CF910895EF92FF9203" + "3A101790000F931F93CF93DF93EC017B018A01BA0172" + "3A1017A0000E94530B882321F4CE010E94B40B07C082" + "3A1017B0001D830C8388819981B7010E946E02CE013E" + "3A1017C000DF91CF911F910F91FF90EF900895CF93EC" + "3A1017D000DF93EC01198218821B821A821D821C82FF" + "3A1017E0001E826115710551F0DB010D900020E9F7B3" + "3A1017F0001197A61BB70BAD010E94C60BDF91CF91CD" + "3A101800000895CF93DF93EC01FB018617970761F0F2" + "3A10181000608171816115710529F0448155810E94B3" + "3A10182000C60B02C00E94B40BCE01DF91CF91089588" + "3A10183000FC01808191810E9438010895A1E21A2E55" + "3A10184000AA1BBB1BFD010DC0AA1FBB1FEE1FFF1F64" + "3A10185000A217B307E407F50720F0A21BB30BE40BB4" + "3A10186000F50B661F771F881F991F1A9469F76095FB" + "3A101870007095809590959B01AC01BD01CF010895B5" + "3A10188000EE0FFF1F0590F491E02D09942F923F92E7" + "3A101890004F925F926F927F928F929F92AF92BF9280" + "3A1018A000CF92DF92EF92FF920F931F93CF93DF932C" + "3A1018B000CDB7DEB7CA1BDB0B0FB6F894DEBF0FBE89" + "3A1018C000CDBF09942A88398848885F846E847D84D6" + "3A1018D0008C849B84AA84B984C884DF80EE80FD80D8" + "3A1018E0000C811B81AA81B981CE0FD11D0FB6F8944E" + "3A1018F000DEBF0FBECDBFED01089510E0C6ECD0E015" + "3A1019000004C0FE010E94420C2296C83CD107C9F7D0" + "3A04191000F894FFCF79" + "3A10191400754353530076302E3161004C45445F4C7F" + "3A10192400414D5000322C313300687474703A2F2FBB" + "3A10193400666F6C6B2E6E746E752E6E6F2F73766180" + "3A10194400727661612F7574696C732F70726F327760" + "3A1019540077772F23617070496431004F534E4150A3" + "3A10196400204A61636B65740024242400552C002CE8" + "3A101974004E00007B226E616D65223A2200222C000B" + "3A101984002276657273696F6E223A22002273657241" + "3A101994007669636573223A205B005D2C00226C69D2" + "3A1019A4006E6B73223A205B005D7D002C2000222C9C" + "3A1019B40020226C696E6B223A2200227D007B202259" + "3A1019C4006964223A202200222C202270696E73223C" + "3A1019D400203A22002000D30200000100000000553C" + "3A0C19E4000AFA0AEB091C0AFC09450A007B" + "3A00000001FF"; } //If it is a tool else if (type == 2) { //Mario s = "3A100000000C94EF000C9417010C9417010C94170139" + "3A100010000C9417010C9417010C9417010C94B8114F" + "3A100020000C9417010C9417010C9417010C94611196" + "3A100030000C9417010C9417010C940A110C941701DD" + "3A100040000C94A6130C9417010C9476150C94C415FB" + "3A100050000C9417010C9417010C9417010C941701C0" + "3A100060000C9417010C9417014E0360037203840370" + "3A100070009603A803BA03CC03DE03F00302041404BE" + "3A10008000260438044A045C046E047F049004A1042E" + "3A10009000B204C304D404E504F604070518052905D1" + "3A1000A0003A054B055C056D057E058F05A005B1057C" + "3A1000B000C205D305E405F505060617062806390628" + "3A1000C0004A065B066C067D068E069F06B006C106D4" + "3A1000D000D206E306F406050716072707380749077F" + "3A1000E0005A076B077C078D079E07AF07C007D1072C" + "3A1000F000E207F307040815082608370848085908D6" + "3A100100006A087B088C089D08AE08BF08D008E10883" + "3A10011000F20803091409250936094709580969092C" + "3A100120007A098B099C09AD09BE09CF09E009F109DB" + "3A10013000020A130A240A350A460A570A680A790A83" + "3A100140008A0A9B0AAC0ABD0ACE0ADF0AF00A010B32" + "3A10015000120B230B340B450B560B670B780B890BDB" + "3A100160009A0BAB0BBC0BCD0BDE0BEF0B000C110C89" + "3A10017000220C330C440C550C660C020100000000EC" + "3A1001800000240027002A0000000000250028002B82" + "3A1001900000000000002300260029000404040404D9" + "3A1001A0000404040202020202020303030303030124" + "3A1001B00002040810204080010204081020010204FB" + "3A1001C00008102000000007000201000003040600E0" + "3A1001D00000000000000000002C033017250311244C" + "3A1001E0001FBECFEFD8E0DEBFCDBF11E0A0E0B1E091" + "3A1001F000EEEBF2E302C005900D92AA3DB107D9F7EC" + "3A1002000012E0AAEDB1E001C01D92A73EB107E1F7EF" + "3A1002100011E0CCEDD1E004C02297FE010E94171935" + "3A10022000C83DD107C9F70E9486170C9452190C9447" + "3A100230000000CF93DF93BC018230910510F462E09F" + "3A1002400070E0A091E502B091E602ED01E0E0F0E09F" + "3A1002500040E050E021C0888199818617970769F4B2" + "3A100260008A819B81309719F09383828304C0909395" + "3A10027000E6028093E502FE0134C06817790738F47E" + "3A100280004115510519F08417950708F4AC01FE01DA" + "3A100290008A819B819C01E9012097E9F6411551056E" + "3A1002A000A9F1CA01861B970B049708F4BA01E0E094" + "3A1002B000F0E02AC08D919C91119784179507F9F46D" + "3A1002C0006417750781F412968D919C91139730975E" + "3A1002D00019F09383828304C09093E6028093E50231" + "3A1002E000FD0132964CC0CA01861B970BFD01E80F39" + "3A1002F000F91F6193719302978D939C9340C0FD0108" + "3A10030000828193819C01D9011097A1F68091E3022B" + "3A100310009091E402892B41F48091C6019091C7012C" + "3A100320009093E4028093E3024091C8015091C90187" + "3A100330004115510541F44DB75EB78091C4019091CC" + "3A10034000C501481B590B2091E3023091E402CA0118" + "3A10035000821B930B8617970780F0AB014E5F5F4FB0" + "3A100360008417950750F0420F531F5093E4024093B7" + "3A10037000E302F9016193719302C0E0E0F0E0CF0184" + "3A10038000DF91CF910895CF93DF93009709F450C088" + "3A10039000EC0122971B821A82A091E502B091E6023D" + "3A1003A000109709F140E050E0AC17BD0708F1BB839E" + "3A1003B000AA83FE0121913191E20FF31FAE17BF070F" + "3A1003C00079F48D919C911197280F391F2E5F3F4F23" + "3A1003D0003983288312968D919C9113979B838A83EE" + "3A1003E0004115510571F4D093E602C093E50220C097" + "3A1003F00012968D919C911397AD01009711F0DC013D" + "3A10040000D3CFFA01D383C28321913191E20FF31F3D" + "3A10041000CE17DF0769F488819981280F391F2E5F75" + "3A100420003F4FFA01318320838A819B8193838283AA" + "3A10043000DF91CF910895A0E0B0E0E1E2F2E00C940A" + "3A100440001D196C01009729F4CB010E9419016C0160" + "3A10045000C1C08EEF882E8FEF982E8C0C9D1C8601CC" + "3A10046000060F171F0815190508F4B2C0F401A08182" + "3A10047000B181A617B707B8F0A530B10508F4AAC036" + "3A10048000CD0104978617970708F4A4C01297A61BFE" + "3A10049000B70BF801A193B193D4016D937C93CF0175" + "3A1004A0000E94C30197C07B01EA1AFB0AEEEFFFEF3F" + "3A1004B000EE0EFF1E36016A0E7B1EC091E502D09142" + "3A1004C000E60244245524AA24BB244AC0C615D705F5" + "3A1004D000E1F5488159814E155F05B8F1CA010497CD" + "3A1004E0008E159F05B0F41296A40FB51FF401B183C9" + "3A1004F000A0832A813B814114510431F0D20113962B" + "3A100500003C932E93129766C03093E6022093E50247" + "3A1005100061C08A819B81F80193838283425050405D" + "3A100520004E195F09518340834114510431F0D201C7" + "3A1005300013961C930E93129704C01093E602009337" + "3A10054000E502F4017183608345C088819981A81612" + "3A10055000B90608F45C012E018A819B819C01E901A6" + "3A10056000209709F0B3CF8091E3029091E4028615C1" + "3A100570009705E9F4A616B706D0F42091C80130918A" + "3A10058000C9012115310541F42DB73EB78091C40151" + "3A100590009091C501281B390B02171307C8F410935B" + "3A1005A000E4020093E302D4016D937C9313C0CB016A" + "3A1005B0000E941901EC01009759F0F401408151812A" + "3A1005C000B6010E94F002C6010E94C3016E0102C082" + "3A1005D000CC24DD24C601CDB7DEB7E0E10C94391997" + "3A1005E000FB01DC0102C001900D9241505040D8F750" + "3A1005F0000895FB01DC0101900D920020E1F70895C0" + "3A100600008130910561F46F5F7F4FF1F48EED91E0E1" + "3A1006100040E050E060E070E00E944C100895892BAB" + "3A1006200099F46F5F7F4F81F485E092E00E94B318E8" + "3A100630008EEF91E00E94B31887EF91E00E94B3180B" + "3A1006400080EF91E00E94B318089580E090E06FEF92" + "3A100650007FEF0E940003089581E090E06FEF7FEF4D" + "3A100660000E94000308958EED91E00E94BB0E089554" + "3A10067000E091DC01F091DD01EC38F10514F00C940F" + "3A100680007F0CE938F10510F00C94760CEC5CFF4F10" + "3A10069000EE0FFF1F0590F491E02D099464EF71E0D7" + "3A1006A00080E090E00E94FC138AED91E064E972E042" + "3A1006B00024E630E040E050E00E9405120C94760CF5" + "3A1006C0006BE470E080E090E00E94FC138AED91E022" + "3A1006D00064E972E024E630E040E050E00E94051258" + "3A1006E0000C94760C66E970E080E090E00E94FC13C8" + "3A1006F0008AED91E064E972E024E630E040E050E009" + "3A100700000E9405120C94760C66E970E080E090E09F" + "3A100710000E94FC138AED91E06EEF71E024E630E078" + "3A1007200040E050E00E9405120C94760C62E370E009" + "3A1007300080E090E00E94FC138AED91E064E972E0B1" + "3A1007400024E630E040E050E00E9405120C94760C64" + "3A1007500066E970E080E090E00E94FC138AED91E091" + "3A1007600062E073E024E630E040E050E00E940512D1" + "3A100770000C94760C63E171E080E090E00E94FC1341" + "3A100780008AED91E06CE771E024E630E040E050E073" + "3A100790000E9405120C94760C6FE171E080E090E00D" + "3A1007A0000E94FC138AED91E06EEF71E024E630E0E8" + "3A1007B00040E050E00E9405120C94760C61EE70E06F" + "3A1007C00080E090E00E94FC138AED91E06CE771E01C" + "3A1007D00024E630E040E050E00E9405120C94760CD4" + "3A1007E00068EC70E080E090E00E94FC138AED91E0FC" + "3A1007F00060E471E024E630E040E050E00E94051241" + "3A100800000C94760C6AEF70E080E090E00E94FC139C" + "3A100810008AED91E068EB71E024E630E040E050E0E2" + "3A100820000E9405120C94760C66E970E080E090E07E" + "3A100830000E94FC138AED91E060EE71E020E530E06B" + "3A1008400040E050E00E9405120C94760C65EA70E0DE" + "3A1008500080E090E00E94FC138AED91E062EC71E090" + "3A1008600024E630E040E050E00E9405120C94760C43" + "3A100870006BE470E080E090E00E94FC138AED91E070" + "3A100880006EEA71E024E630E040E050E00E9405129C" + "3A100890000C94760C66E970E080E090E00E94FC1316" + "3A1008A0008AED91E06CE771E024E630E040E050E052" + "3A1008B0000E9405120C94760C64E670E080E090E0F3" + "3A1008C0000E94FC138AED91E064E972E020E530E0DB" + "3A1008D00040E050E00E9405120C94760C64E670E053" + "3A1008E00080E090E00E94FC138AED91E068EF72E0F6" + "3A1008F00022E330E040E050E00E940512F7C76BE4CD" + "3A1009000070E080E090E00E94FC138AED91E06CE5DD" + "3A1009100073E024E630E040E050E00E940512E6C7B4" + "3A1009200066E970E080E090E00E94FC138AED91E0BF" + "3A100930006CEB72E020E530E040E050E00E940512F0" + "3A10094000D5C76BE470E080E090E00E94FC138AED74" + "3A1009500091E068EF72E022E330E040E050E00E9476" + "3A100960000512C4C76FEA70E080E090E00E94FC13BB" + "3A100970008AED91E064E972E020E530E040E050E08B" + "3A100980000E940512B3C766E970E080E090E00E9423" + "3A10099000FC138AED91E068E072E020E530E040E091" + "3A1009A00050E00E940512A2C76BE470E080E090E086" + "3A1009B0000E94FC138AED91E064E472E020E530E0EF" + "3A1009C00040E050E00E94051291C76BE470E080E0C7" + "3A1009D00090E00E94FC138AED91E060EE71E020E56A" + "3A1009E00030E040E050E00E94051280C76FEA70E0FE" + "3A1009F00080E090E00E94FC138AED91E06EEF71E0E0" + "3A100A000024E630E040E050E00E9405126FC763E149" + "3A100A100071E080E090E00E94FC138AED91E06CE7C9" + "3A100A200071E024E630E040E050E00E9405125EC72D" + "3A100A300068EC70E080E090E00E94FC138AED91E0A9" + "3A100A400060E471E024E630E040E050E00E940512EE" + "3A100A50004DC76AEF70E080E090E00E94FC138AEDE1" + "3A100A600091E068EB71E024E630E040E050E00E9465" + "3A100A700005123CC766E970E080E090E00E94FC133C" + "3A100A80008AED91E060EE71E020E530E040E050E07A" + "3A100A90000E9405122BC765EA70E080E090E00E949A" + "3A100AA000FC138AED91E062EC71E024E630E040E076" + "3A100AB00050E00E9405121AC76BE470E080E090E0FD" + "3A100AC0000E94FC138AED91E06EEA71E024E630E0CA" + "3A100AD00040E050E00E94051209C766E970E080E03E" + "3A100AE00090E00E94FC138AED91E06CE771E024E64F" + "3A100AF00030E040E050E00E940512F8C664E670E085" + "3A100B000080E090E00E94FC138AED91E064E972E0DD" + "3A100B100020E530E040E050E00E940512E7C664E6C0" + "3A100B200070E080E090E00E94FC138AED91E068EFB5" + "3A100B300072E022E330E040E050E00E940512D6C6A9" + "3A100B40006BE470E080E090E00E94FC138AED91E09D" + "3A100B50006CE573E024E630E040E050E00E940512CE" + "3A100B6000C5C666E970E080E090E00E94FC138AED63" + "3A100B700091E06CEB72E020E530E040E050E00E9454" + "3A100B80000512B4C66BE470E080E090E00E94FC13B4" + "3A100B90008AED91E068EF72E022E330E040E050E05F" + "3A100BA0000E940512A3C66FEA70E080E090E00E9408" + "3A100BB000FC138AED91E064E972E020E530E040E06A" + "3A100BC00050E00E94051292C666E970E080E090E075" + "3A100BD0000E94FC138AED91E068E072E020E530E0CD" + "3A100BE00040E050E00E94051281C66BE470E080E0B6" + "3A100BF00090E00E94FC138AED91E064E472E020E54D" + "3A100C000030E040E050E00E94051270C66BE470E0F6" + "3A100C100080E090E00E94FC138AED91E060EE71E0CC" + "3A100C200020E530E040E050E00E9405125FC66AEF28" + "3A100C300070E080E090E00E94FC138AED91E064EFA8" + "3A100C400071E024E630E040E050E00E9405124EC61C" + "3A100C500066E970E080E090E00E94FC138AED91E08C" + "3A100C600068EF72E024E630E040E050E00E940512B8" + "3A100C70003DC662E370E080E090E00E94FC138AEDE4" + "3A100C800091E060ED72E024E630E040E050E00E9448" + "3A100C900005122CC66BE470E080E090E00E94FC132B" + "3A100CA0008AED91E068EA72E024E630E040E050E04E" + "3A100CB0000E9405121BC66BE470E080E090E00E9489" + "3A100CC000FC138AED91E06CE672E026E930E040E04A" + "3A100CD00050E00E9405120AC666E970E080E090E0EC" + "3A100CE0000E94FC138AED91E06AE872E026E930E0A8" + "3A100CF00040E050E00E940512F9C566E970E080E02E" + "3A100D000090E00E94FC138AED91E06CE771E024E62C" + "3A100D100030E040E050E00E940512E8C56BE470E06E" + "3A100D200080E090E00E94FC138AED91E06EEA71E0B1" + "3A100D300024E630E040E050E00E940512D7C56BE4A5" + "3A100D400070E080E090E00E94FC138AED91E064EF97" + "3A100D500071E024E630E040E050E00E940512C6C594" + "3A100D600066E970E080E090E00E94FC138AED91E07B" + "3A100D70006EEA71E024E630E040E050E00E940512A7" + "3A100D8000B5C56BE470E080E090E00E94FC138AED52" + "3A100D900091E064EF71E024E630E040E050E00E9432" + "3A100DA0000512A4C562E370E080E090E00E94FC13AD" + "3A100DB0008AED91E06AE372E024E630E040E050E042" + "3A100DC0000E94051293C56EE670E080E090E00E94FC" + "3A100DD000FC138AED91E064EF71E024E630E040E03E" + "3A100DE00050E00E94051282C566E970E080E090E064" + "3A100DF0000E94FC138AED91E068EF72E024E630E097" + "3A100E000040E050E00E94051271C562E370E080E0AE" + "3A100E100090E00E94FC138AED91E060ED72E024E620" + "3A100E200030E040E050E00E94051260C56BE470E0E5" + "3A100E300080E090E00E94FC138AED91E068EA72E0A5" + "3A100E400024E630E040E050E00E9405124FC56BE41C" + "3A100E500070E080E090E00E94FC138AED91E06CE687" + "3A100E600072E026E930E040E050E00E9405123EC505" + "3A100E700066E970E080E090E00E94FC138AED91E06A" + "3A100E80006AE872E028EC30E040E050E00E94051291" + "3A100E90002DC566E970E080E090E00E94FC138AEDC9" + "3A100EA00091E06CEF73E020E530E040E050E00E941C" + "3A100EB00005121CC566E970E080E090E00E94FC131A" + "3A100EC0008AED91E06CEF73E020E530E040E050E027" + "3A100ED0000E9405120BC56BE470E080E090E00E9478" + "3A100EE000FC138AED91E06CEF73E020E530E040E028" + "3A100EF00050E00E940512FAC466E970E080E090E0DC" + "3A100F00000E94FC138AED91E06CE771E024E630E08A" + "3A100F100040E050E00E940512E9C466E970E080E01C" + "3A100F200090E00E94FC138AED91E064EF71E024E60A" + "3A100F300030E040E050E00E940512D8C466E970E05D" + "3A100F400080E090E00E94FC138AED91E068EF72E08F" + "3A100F500024E630E040E050E00E940512C7C462E39E" + "3A100F600070E080E090E00E94FC138AED91E060ED7B" + "3A100F700072E024E630E040E050E00E940512B6C482" + "3A100F80006BE470E080E090E00E94FC138AED91E059" + "3A100F900068EA72E024E630E040E050E00E9405128A" + "3A100FA000A5C46BE470E080E090E00E94FC138AED41" + "3A100FB00091E06CE672E026E930E040E050E00E940B" + "3A100FC000051294C466E970E080E090E00E94FC1392" + "3A100FD0008AED91E06AE872E026E930E040E050E016" + "3A100FE0000E94051283C466E970E080E090E00E94F0" + "3A100FF000FC138AED91E06CE771E024E630E040E01C" + "3A1010000050E00E94051272C46BE470E080E090E052" + "3A101010000E94FC138AED91E06EEA71E024E630E074" + "3A1010200040E050E00E94051261C46BE470E080E093" + "3A1010300090E00E94FC138AED91E064EF71E024E6F9" + "3A1010400030E040E050E00E94051250C466E970E0D4" + "3A1010500080E090E00E94FC138AED91E06EEA71E07E" + "3A1010600024E630E040E050E00E9405123FC46BE40B" + "3A1010700070E080E090E00E94FC138AED91E064EF64" + "3A1010800071E024E630E040E050E00E9405122EC4FA" + "3A1010900062E370E080E090E00E94FC138AED91E052" + "3A1010A0006AE372E024E630E040E050E00E9405127E" + "3A1010B0001DC46EE670E080E090E00E94FC138AEDB3" + "3A1010C00091E064EF71E024E630E040E050E00E94FF" + "3A1010D00005120CC466E970E080E090E00E94FC1309" + "3A1010E0008AED91E068EF72E024E630E040E050E005" + "3A1010F0000E940512FBC362E370E080E090E00E9472" + "3A10110000FC138AED91E060ED72E024E630E040E00F" + "3A1011100050E00E940512EAC36BE470E080E090E0CA" + "3A101120000E94FC138AED91E068EA72E024E630E068" + "3A1011300040E050E00E940512D9C36BE470E080E00B" + "3A1011400090E00E94FC138AED91E06CE672E026E9E3" + "3A1011500030E040E050E00E940512C8C366E970E04C" + "3A1011600080E090E00E94FC138AED91E06AE872E072" + "3A1011700028EC30E040E050E00E940512B7C366E979" + "3A1011800070E080E090E00E94FC138AED91E06CEF4B" + "3A1011900073E020E530E040E050E00E940512A6C375" + "3A1011A00066E970E080E090E00E94FC138AED91E037" + "3A1011B0006CEF73E020E530E040E050E00E94051263" + "3A1011C00095C36BE470E080E090E00E94FC138AED30" + "3A1011D00091E06CEF73E020E530E040E050E00E94E9" + "3A1011E000051284C366E970E080E090E00E94FC1381" + "3A1011F0008AED91E06CE771E024E630E040E050E0F9" + "3A101200000E94051273C366E970E080E090E00E94DE" + "3A10121000FC138AED91E064EF71E024E630E040E0F9" + "3A1012200050E00E94051262C366E970E080E090E041" + "3A101230000E94FC138AED91E068EF72E024E630E052" + "3A1012400040E050E00E94051251C362E370E080E08C" + "3A1012500090E00E94FC138AED91E060ED72E024E6DC" + "3A1012600030E040E050E00E94051240C36BE470E0C3" + "3A1012700080E090E00E94FC138AED91E068EA72E061" + "3A1012800024E630E040E050E00E9405122FC36BE4FA" + "3A1012900070E080E090E00E94FC138AED91E06CE643" + "3A1012A00072E026E930E040E050E00E9405121EC3E3" + "3A1012B00066E970E080E090E00E94FC138AED91E026" + "3A1012C0006AE872E026E930E040E050E00E94051252" + "3A1012D0000DC366E970E080E090E00E94FC138AEDA7" + "3A1012E00091E06CE771E024E630E040E050E00E94DD" + "3A1012F0000512FCC26BE470E080E090E00E94FC13F9" + "3A101300008AED91E06EEA71E024E630E040E050E0E2" + "3A101310000E940512EBC26BE470E080E090E00E9456" + "3A10132000FC138AED91E064EF71E024E630E040E0E8" + "3A1013300050E00E940512DAC266E970E080E090E0B9" + "3A101340000E94FC138AED91E06EEA71E024E630E041" + "3A1013500040E050E00E940512C9C26BE470E080E0FA" + "3A1013600090E00E94FC138AED91E064EF71E024E6C6" + "3A1013700030E040E050E00E940512B8C262E370E045" + "3A1013800080E090E00E94FC138AED91E06AE372E055" + "3A1013900024E630E040E050E00E940512A7C262ED72" + "3A1013A00070E080E090E00E94FC138AED91E069E437" + "3A1013B00072E024E630E040E050E00E94051296C260" + "3A1013C00063E171E080E090E00E94FC138AED91E01F" + "3A1013D00066E272E024E630E040E050E00E94051250" + "3A1013E00085C262ED70E080E090E00E94FC138AED1F" + "3A1013F00091E064EF71E024E630E040E050E00E94CC" + "3A10140000051274C264EB70E080E090E00E94FC136F" + "3A101410008AED91E06CE771E024E630E040E050E0D6" + "3A101420000E94051263C266E970E080E090E00E94CD" + "3A10143000FC138AED91E064EF71E024E630E040E0D7" + "3A1014400050E00E94051252C266E970E080E090E030" + "3A101450000E94FC138AED91E064EF71E024E630E035" + "3A1014600040E050E00E94051241C26BE470E080E071" + "3A1014700090E00E94FC138AED91E064EF71E024E6B5" + "3A1014800030E040E050E00E94051230C266E970E0B2" + "3A1014900080E090E00E94FC138AED91E064EF71E03F" + "3A1014A0002CE330E040E050E00E9405121FC26BE4E4" + "3A1014B00070E080E090E00E94FC138AED91E064EF20" + "3A1014C00071E020E530E040E050E00E9405120EC2DD" + "3A1014D00066E970E080E090E00E94FC138AED91E004" + "3A1014E00064EF71E02CE330E040E050E00E94051230" + "3A1014F000FDC16FEA70E080E090E00E94FC138AED8D" + "3A1015000091E064EF71E020E530E040E050E00E94BF" + "3A101510000512ECC16BE470E080E090E00E94FC13E7" + "3A101520008AED91E064E472E020E530E040E050E0D4" + "3A101530000E940512DBC16FEA70E080E090E00E943B" + "3A10154000FC138AED91E064E972E020E530E040E0D0" + "3A1015500050E00E940512CAC16BE470E080E090E0A8" + "3A101560000E94FC138AED91E064EF71E020E530E029" + "3A1015700040E050E00E940512B9C166E970E080E0E9" + "3A1015800090E00E94FC138AED91E06EEA71E020E5A4" + "3A1015900030E040E050E00E940512A8C16BE470E02A" + "3A1015A00080E090E00E94FC138AED91E06CE771E02E" + "3A1015B00020E530E040E050E00E94051297C16CE267" + "3A1015C00071E080E090E00E94FC138AED91E064EF0E" + "3A1015D00071E02CE330E040E050E00E94051286C14B" + "3A1015E0006BE470E080E090E00E94FC138AED91E0F3" + "3A1015F00064EF71E020E530E040E050E00E94051229" + "3A1016000075C166E970E080E090E00E94FC138AED0D" + "3A1016100091E064EF71E02CE330E040E050E00E94A4" + "3A10162000051264C16FEA70E080E090E00E94FC1354" + "3A101630008AED91E064EF71E020E530E040E050E0B9" + "3A101640000E94051253C16BE470E080E090E00E94BC" + "3A10165000FC138AED91E064E472E020E530E040E0C4" + "3A1016600050E00E94051242C16BE470E080E090E01F" + "3A101670000E94FC138AED91E064E972E020E530E01D" + "3A1016800040E050E00E94051231C161EE70E080E060" + "3A1016900090E00E94FC138AED91E066E673E020E59D" + "3A1016A00030E040E050E00E94051220C162EA70E0A4" + "3A1016B00080E090E00E94FC138AED91E068EF72E018" + "3A1016C00020E530E040E050E00E9405120FC16CE2DE" + "3A1016D00071E080E090E00E94FC138AED91E064EFFD" + "3A1016E00071E02CE330E040E050E00E940512FEC0C3" + "3A1016F0006BE470E080E090E00E94FC138AED91E0E2" + "3A1017000064EF71E020E530E040E050E00E94051217" + "3A10171000EDC066E970E080E090E00E94FC138AED85" + "3A1017200091E064EF71E02CE330E040E050E00E9493" + "3A101730000512DCC06FEA70E080E090E00E94FC13CC" + "3A101740008AED91E064EF71E020E530E040E050E0A8" + "3A101750000E940512CBC06BE470E080E090E00E9434" + "3A10176000FC138AED91E064E472E020E530E040E0B3" + "3A1017700050E00E940512BAC06FEA70E080E090E08D" + "3A101780000E94FC138AED91E064E972E020E530E00C" + "3A1017900040E050E00E940512A9C06BE470E080E0D8" + "3A1017A00090E00E94FC138AED91E064EF71E020E587" + "3A1017B00030E040E050E00E94051298C066E970E019" + "3A1017C00080E090E00E94FC138AED91E06EEA71E007" + "3A1017D00020E530E040E050E00E94051287C06BE455" + "3A1017E00070E080E090E00E94FC138AED91E06CE7ED" + "3A1017F00071E020E530E040E050E00E94051276C044" + "3A101800006CE271E080E090E00E94FC138AED91E0D0" + "3A1018100064E972E024E630E040E050E00E94051206" + "3A1018200065C06BE470E080E090E00E94FC138AEDFC" + "3A1018300091E064E972E024E630E040E050E00E948C" + "3A10184000051254C066E970E080E090E00E94FC134D" + "3A101850008AED91E064E972E024E630E040E050E097" + "3A101860000E94051243C066E970E080E090E00E94AB" + "3A10187000FC138AED91E06EEF71E024E630E040E089" + "3A1018800050E00E94051232C062E370E080E090E018" + "3A101890000E94FC138AED91E064E972E024E630E0F6" + "3A1018A00040E050E00E94051221C066E970E080E04F" + "3A1018B00090E00E94FC138AED91E062E073E024E680" + "3A1018C00030E040E050E00E94051210C061EE70E090" + "3A1018D00080E090E00E94FC138AED91E06CE771E0FB" + "3A1018E00024E630E040E050E00E9405128091DC01E7" + "3A1018F0009091DD0101969093DD018093DC010895C4" + "3A10190000EF92FF920F931F93DF93CF93CDB7DEB784" + "3A101910002E970FB6F894DEBF0FBECDBF0EED11E0CF" + "3A10192000C80140E052EC61E070E00E94321084E0B7" + "3A1019300061E00E94901484E061E00E94CF147E0177" + "3A101940000894E11CF11CC70160E071E00E9482185C" + "3A10195000C801B7010E942E10C7010E94B31888E089" + "3A10196000E82EF12CEC0EFD1EC70165E071E00E942F" + "3A101970008218C801B7010E942A10C7010E94B3183B" + "3A10198000C8016BE071E044E151E00E94F20F82E097" + "3A1019900061E00E9490148DE061E00E949014C80103" + "3A1019A00069E171E04BE451E00E94BA0F8AED91E0E9" + "3A1019B00063E00E947D102E960FB6F894DEBF0FBE36" + "3A1019C000CDBFCF91DF911F910F91FF90EF900895C0" + "3A1019D00080E090E0089584E060E00E94CF140895D4" + "3A1019E000CF92DF92EF92FF921F93CF93DF93162F48" + "3A1019F0006A01790180EC92E06FEF0E94F01680ECB2" + "3A101A000092E06F2D0E94F01680EC92E06E2D0E9405" + "3A101A1000F01680EC92E06EEF0E94F01680EC92E0FF" + "3A101A2000612F0E94F016C0E0D0E009C0F601EC0F73" + "3A101A3000FD1F80EC92E060810E94F0162196CE1589" + "3A101A4000DF05A0F3DF91CF911F91FF90EF90DF9022" + "3A101A5000CF9008950F931F93CF93DF93EC01062F40" + "3A101A6000142F862F61E00E94901460E0111161E054" + "3A101A7000802F0E94CF14CE0165E040E050E020E0CE" + "3A101A800030E00E94F00CDF91CF911F910F910895EB" + "3A101A9000EF92FF921F93DF93CF930F92CDB7DEB7F4" + "3A101AA0007C01162F862F60E00E949014812F0E94E7" + "3A101AB000231519821816190614F481E08983C701C9" + "3A101AC00064E0AE014F5F5F4F21E030E00E94F00C18" + "3A101AD0000F90CF91DF911F91FF90EF9008950F939A" + "3A101AE0001F93CF93DF938C01DB01842FE801E885FE" + "3A101AF000F985B901AD010995C80163E040E050E006" + "3A101B000020E030E00E94F00CDF91CF911F910F9107" + "3A101B10000895CF92DF92EF92FF920F931F93DF937E" + "3A101B2000CF9300D0CDB7DEB76C01862FD6011696C5" + "3A101B3000ED91FC9117977E010894E11CF11CB7010F" + "3A101B400040E050E009958C01FC01908181818983FE" + "3A101B50009A83C60162E0A70122E030E00E94F00C07" + "3A101B6000C8010E94C3010F900F90CF91DF911F9188" + "3A101B70000F91FF90EF90DF90CF9008950F931F93F8" + "3A101B8000CF93DF938C01DB01842FE801EC81FD8191" + "3A101B9000B901AD010995C80161E040E050E020E0E5" + "3A101BA00030E00E94F00CDF91CF911F910F910895CA" + "3A101BB00060E040E050E020E030E00E94F00C08954A" + "3A101BC000CF92DF92EF92FF920F931F93DF93CF9309" + "3A101BD000CDB7DEB727970FB6F894DEBF0FBECDBFE7" + "3A101BE0007C018E010F5F1F4FC80162E671E00E9409" + "3A101BF0008218C80163E671E00E94371882E190E024" + "3A101C0000E80EF91EC801B7010E944718C8016DE629" + "3A101C100071E00E943718C80160E771E00E94371830" + "3A101C200087E090E0E80EF91EC801B7010E9447184E" + "3A101C3000C8016DE671E00E943718C8016CE771E0D9" + "3A101C40000E94371887E090E0E80EF91EC801B7013E" + "3A101C50000E944718C8016AE871E00E943718C8015D" + "3A101C60006DE871E00E94371887E090E0E80EF91EF9" + "3A101C7000C801B7010E944718C80168E971E00E94D5" + "3A101C80003718CD80DE8080EC92E06FEF0E94F01676" + "3A101C900080EC92E06D2D0E94F01680EC92E06C2DAD" + "3A101CA0000E94F01680EC92E06EEF0E94F01680EC3D" + "3A101CB00092E066E00E94F016EE24FF2410C0C801F6" + "3A101CC000B7010E94BF17FC016081772767FD7095FF" + "3A101CD00080EC92E00E94F0160894E11CF11CEC14D8" + "3A101CE000FD0468F3C8010E94B31827960FB6F89454" + "3A101CF000DEBF0FBECDBFCF91DF911F910F91FF903F" + "3A101D0000EF90DF90CF9008950F931F93F801433029" + "3A101D1000E1F0443028F4413079F0423090F409C0C9" + "3A101D20004530E1F04530B0F04630E9F04F3F01F585" + "3A101D30001DC00E94D80D1CC0422F98010E94BE0DEC" + "3A101D400017C0622F0E94890D13C0422F98010E9474" + "3A101D50006F0D0EC0622F0E94480D0AC0622F408195" + "3A101D60000E942A0D05C00E94E00D02C00E94EB0CEB" + "3A101D70001F910F9108956F927F928F929F92AF92D1" + "3A101D8000BF92CF92DF92EF92FF920F931F93CF9368" + "3A101D9000DF93EC010E94EE132091130230911402A4" + "3A101DA0004091150250911602261737074807590728" + "3A101DB00050F48091170290911802892B21F0109213" + "3A101DC0001802109217020E94EE136053784F8F4F43" + "3A101DD0009F4F6093130270931402809315029093A7" + "3A101DE000160273E0672E712C65E0862E912C54E06C" + "3A101DF000A52EB12C41E0C42ED12C32E0E32EF12CE3" + "3A101E0000A3C0809117029091180282309105C1F110" + "3A101E10008330910534F4009781F0019709F08FC069" + "3A101E200022C08430910509F453C0843091050CF42C" + "3A101E300044C0059709F083C056C080EC92E00E9430" + "3A101E4000B7168F3F910509F07AC0D0921802C09260" + "3A101E5000170280910D0290910E02009709F46FC055" + "3A101E60000E94C3016CC080EC92E00E94B7161092F1" + "3A101E7000110280931202F0921802E09217025FC0E2" + "3A101E8000009111021091120280EC92E00E94B716AC" + "3A101E900090E0802B912B909312028093110270920C" + "3A101EA0001802609217020E94190190930E0280930B" + "3A101EB0000D02009709F043C03EC080EC92E00E9402" + "3A101EC000B71680931002B0921802A092170237C082" + "3A101ED00080EC92E00E94B71680930F029092180255" + "3A101EE000809217022CC080910C0200910D0210917B" + "3A101EF0000E02080F111D80EC92E00E94B716F80147" + "3A101F0000808380910C028F5F80930C02609111029C" + "3A101F10007091120290E08617970788F000910D02E9" + "3A101F200010910E02CE014091100220910F020E94EA" + "3A101F3000840E10920C0210921802109217028881DF" + "3A101F4000998101969983888380EC92E00E9486169D" + "3A101F5000892B09F056CFDF91CF911F910F91FF9000" + "3A101F6000EF90DF90CF90BF90AF909F908F907F9039" + "3A101F70006F900895CF92DF92EF92FF920F931F938D" + "3A101F8000CF93DF93EC016B017A018BA59CA5892B84" + "3A101F900031F0CE0187966BE971E00E9437188E010F" + "3A101FA000095D1F4FC80163E671E00E943718C80140" + "3A101FB000B7010E943718C8016EE971E00E94371816" + "3A101FC000C801B6010E943718C8016AEA71E00E9490" + "3A101FD0003718DF91CF911F910F91FF90EF90DF9015" + "3A101FE000CF900895CF92DF92EF92FF920F931F93BD" + "3A101FF000CF93DF93EC017B016A018CA19DA1892B1A" + "3A1020000031F0CE0180966BE971E00E9437188E01A5" + "3A10201000005E1F4FC8016DEA71E00E943718C801C9" + "3A10202000B7010E943718C80167EB71E00E943718AA" + "3A10203000C801B6010E943718C8016AEA71E00E941F" + "3A102040003718DF91CF911F910F91FF90EF90DF90A4" + "3A10205000CF90089549960E949C18089542960E9438" + "3A102060009C1808950F931F93182F092F80EC92E06E" + "3A102070000E94FF15212F302FC901FC0180E090E064" + "3A1020800028EE3CE033832283019632968830910516" + "3A10209000C9F71F910F910895EF92FF920F931F932D" + "3A1020A000CF93DF93EC017A018B01429662E671E0F7" + "3A1020B0000E948218CE01499662E671E00E94821861" + "3A1020C000CE01809662E671E00E948218CE0187966A" + "3A1020D00062E671E00E948218E114F1040105110525" + "3A1020E00029F0CE01B801A7010E943210DF91CF91F3" + "3A1020F0001F910F91FF90EF900895DC0190912E02B7" + "3A10210000933008F083C06C93E92FF0E0E658FE4F5F" + "3A10211000849111968C9311979F5F90932E0281303A" + "3A1021200039F1823009F44BC0882309F072C014BC25" + "3A1021300015BC84B5826084BD85B5816085BD8C91F8" + "3A10214000282F30E0F901E556FE4FE491F0E0EE0F64" + "3A10215000FF1FE957FE4F8591949190931E02809343" + "3A102160001D0221553E4FF901849180931F0208956D" + "3A10217000109280001092810080918100886080938D" + "3A102180008100809181008160809381008C91282F53" + "3A1021900030E0F901E556FE4FE491F0E0EE0FFF1F4D" + "3A1021A000E957FE4F859194919093250280932402E4" + "3A1021B00021553E4FF9018491809326020895109293" + "3A1021C000B0001092B1008091B00082608093B000A6" + "3A1021D0008091B10081608093B1008C91282F30E014" + "3A1021E000F901E556FE4FE491F0E0EE0FFF1FE957CD" + "3A1021F000FE4F8591949190932C0280932B02215550" + "3A102200003E4FF901849180932D0208958FEF11962E" + "3A102210008C9308951F920F920FB60F9211248F93F3" + "3A102220009F93AF93BF93EF93FF9380911902909187" + "3A102230001A02A0911B02B0911C02E0911D02F091C4" + "3A102240001E020097A105B10531F1808190911F0216" + "3A10225000892780838091190290911A02A0911B0214" + "3A10226000B0911C02181619061A061B06FCF4809180" + "3A10227000190290911A02A0911B02B0911C020197C1" + "3A10228000A109B1098093190290931A02A0931B022D" + "3A10229000B0931C020BC080916E008D7F80936E0006" + "3A1022A000908180911F02809589238083FF91EF9117" + "3A1022B000BF91AF919F918F910F900FBE0F901F9084" + "3A1022C00018951F920F920FB60F9211248F939F9320" + "3A1022D000AF93BF93EF93FF938091200290912102DF" + "3A1022E000A0912202B0912302E0912402F0912502F4" + "3A1022F0000097A105B10531F18081909126028927CF" + "3A1023000080838091200290912102A0912202B091BD" + "3A102310002302181619061A061B06FCF480912002E7" + "3A1023200090912102A0912202B09123020197A1096C" + "3A10233000B1098093200290932102A0932202B093CE" + "3A1023400023020BC080916F008D7F80936F0090817E" + "3A1023500080912602809589238083FF91EF91BF9120" + "3A10236000AF919F918F910F900FBE0F901F90189576" + "3A102370001F920F920FB60F9211242F933F934F93FA" + "3A102380005F938F939F93EF93FF9320912702309158" + "3A1023900028024091290250912A02E0912B02F091EB" + "3A1023A0002C02211531054105510579F0808190916C" + "3A1023B0002D0289278083121613061406150684F44D" + "3A1023C00021503040404050400BC0809170008D7FC4" + "3A1023D00080937000908180912D0280958923808365" + "3A1023E00020932702309328024093290250932A0217" + "3A1023F000FF91EF919F918F915F914F913F912F911D" + "3A102400000F900FBE0F901F9018952F923F925F92E2" + "3A102410006F927F928F929F92AF92BF92CF92DF92F4" + "3A10242000EF92FF920F931F93DF93CF9300D000D0D2" + "3A10243000CDB7DEB78C011B0129833A834B835C83C4" + "3A10244000DC0111968C91119787FD6AC18C9161E036" + "3A102450000E949014F8015180552021F0F2E05F169F" + "3A1024600009F0C7C031018824992460E072E18AE74D" + "3A1024700090E0A40193010E94FA1859016A018601B3" + "3A1024800075010894E108F108010911092FEFE2161E" + "3A10249000F1040105110509F008F49BC060E472E441" + "3A1024A0008FE090E0A40193010E94FA1879018A015B" + "3A1024B0000894E108F1080109110982E0581611F0A9" + "3A1024C00092E019C09FEFE916F1040105110509F02A" + "3A1024D00010F492E087C060E970ED83E090E0A40121" + "3A1024E00093010E94FA1879018A010894E108F10821" + "3A1024F0000109110993E0AFEFEA16F1040105110596" + "3A1025000009F008F467C068E478EE81E090E0A40187" + "3A1025100093010E94FA1879018A010894E108F108F0" + "3A1025200001091109552011F493E01EC0B2E05B16B9" + "3A1025300011F094E019C0EFEFEE16F104010511055A" + "3A1025400009F010F494E04EC064E274EF80E090E093" + "3A10255000A40193010E94FA1879018A010894E10804" + "3A10256000F1080109110995E0FFEFEF16F1040105EB" + "3A10257000110581F178F162E17AE780E090E0A40151" + "3A1025800093010E94FA1879018A010894E108F10880" + "3A1025900001091109552011F096E001C094E02FEFD8" + "3A1025A000E216F10401051105A9F0A0F0C601B5017C" + "3A1025B00020E034E040E050E00E94FA1879018A01FE" + "3A1025C0000894E108F10801091109552051F495E03A" + "3A1025D00003C091E0552031F485B5887F982B95BDD7" + "3A1025E0003EC097E08091B100887F982B9093B10016" + "3A1025F00036C05101CC24DD2460E072E18AE790E02E" + "3A10260000A60195010E94FA1879018A010894E1084F" + "3A10261000F1080109110980E0E81680E0F80681E080" + "3A10262000080780E0180710F491E010C068E478EE25" + "3A1026300081E090E0A60195010E94FA1879018A01D3" + "3A102640000894E108F1080109110993E0A1E05A1684" + "3A1026500031F480918100887F982B909381002981AB" + "3A102660003A814B815C81220F331F441F551F8981A2" + "3A102670009A81AB81BC81280F391F4A1F5B1F21152E" + "3A1026800031054105510529F48FEF9FEFAFEFBFEF03" + "3A102690000FC0220C331CB10180E090E00E94B918F9" + "3A1026A00028EE33E040E050E00E94D818C901DA017A" + "3A1026B000E1E05E16A1F0F2E05F1619F1552081F518" + "3A1026C000E7BC8093190290931A02A0931B02B09367" + "3A1026D0001C0280916E00826080936E0021C0F09297" + "3A1026E0008900E09288008093200290932102A093B9" + "3A1026F0002202B093230280916F00826080936F006A" + "3A102700000FC0E092B3008093270290932802A09319" + "3A102710002902B0932A028091700082608093700039" + "3A102720000F900F900F900F90CF91DF911F910F910D" + "3A10273000FF90EF90DF90CF90BF90AF909F908F90E1" + "3A102740007F906F905F903F902F9008951F920F920F" + "3A102750000FB60F9211242F933F938F939F93AF93B4" + "3A10276000BF938091330290913402A0913502B091D1" + "3A102770003602309137020196A11DB11D232F2D5F26" + "3A102780002D3720F02D570196A11DB11D2093370242" + "3A102790008093330290933402A0933502B0933602B3" + "3A1027A00080912F0290913002A0913102B0913202BB" + "3A1027B0000196A11DB11D80932F0290933002A0932A" + "3A1027C0003102B0933202BF91AF919F918F913F91AF" + "3A1027D0002F910F900FBE0F901F9018958FB7F89400" + "3A1027E00020913302309134024091350250913602EB" + "3A1027F0008FBFB901CA0108959B01AC017FB7F8945E" + "3A1028000080912F0290913002A0913102B09132025A" + "3A1028100066B5A89B05C06F3F19F00196A11DB11DBB" + "3A102820007FBFBA2FA92F982F8827860F911DA11D32" + "3A10283000B11D62E0880F991FAA1FBB1F6A95D1F7CF" + "3A10284000BC012DC0FFB7F89480912F029091300207" + "3A10285000A0913102B0913202E6B5A89B05C0EF3FCE" + "3A1028600019F00196A11DB11DFFBFBA2FA92F982FF6" + "3A1028700088278E0F911DA11DB11DE2E0880F991FC1" + "3A10288000AA1FBB1FEA95D1F7861B970B885E934062" + "3A10289000C8F2215030404040504068517C4F2115D3" + "3A1028A00031054105510571F60895789484B582602B" + "3A1028B00084BD84B5816084BD85B5826085BD85B5E4" + "3A1028C000816085BDEEE6F0E0808181608083E1E893" + "3A1028D000F0E01082808182608083808181608083CB" + "3A1028E000E0E8F0E0808181608083E1EBF0E08081CE" + "3A1028F00084608083E0EBF0E0808181608083EAE7A0" + "3A10290000F0E0808184608083808182608083808128" + "3A10291000816080838081806880831092C1000895E7" + "3A10292000CF93DF93482F50E0CA0181559E4FFC01A1" + "3A10293000349145565E4FFA018491882369F190E005" + "3A10294000880F991FFC01E358FE4FA591B491FC013B" + "3A10295000E957FE4FC591D491662351F42FB7F894EF" + "3A102960008C91932F909589238C93888189230BC018" + "3A10297000623061F42FB7F8948C91932F909589234E" + "3A102980008C938881832B88832FBF06C09FB7F894D0" + "3A102990008C91832B8C939FBFDF91CF910895482F0B" + "3A1029A00050E0CA018D539E4FFC012491CA0181550C" + "3A1029B0009E4FFC01949145565E4FFA0134913323AA" + "3A1029C00009F440C0222351F1233071F0243028F45F" + "3A1029D0002130A1F0223011F514C02630B1F027309B" + "3A1029E000C1F02430D9F404C0809180008F7703C0F7" + "3A1029F000809180008F7D8093800010C084B58F7798" + "3A102A000002C084B58F7D84BD09C08091B0008F77EE" + "3A102A100003C08091B0008F7D8093B000E32FF0E081" + "3A102A2000EE0FFF1FE957FE4FA591B4912FB7F89411" + "3A102A3000662321F48C919095892302C08C91892B77" + "3A102A40008C932FBF0895682F70E0CB018D539E4F5C" + "3A102A5000FC012491CB0181559E4FFC0144916556A8" + "3A102A60007E4FFB019491992319F420E030E03CC0A3" + "3A102A7000222351F1233071F0243028F42130A1F0C9" + "3A102A8000223011F514C02630B1F02730C1F02430C7" + "3A102A9000D9F404C0809180008F7703C080918000BA" + "3A102AA0008F7D8093800010C084B58F7702C084B57D" + "3A102AB0008F7D84BD09C08091B0008F7703C0809165" + "3A102AC000B0008F7D8093B000892F90E0880F991F10" + "3A102AD0008F569E4FFC01A591B4918C9120E030E07F" + "3A102AE000842311F021E030E0C90108951F920F9274" + "3A102AF0000FB60F9211242F933F934F938F939F9371" + "3A102B0000EF93FF938091C00082FD1DC04091C600ED" + "3A102B100020917802309179022F5F3F4F2F733070F0" + "3A102B200080917A0290917B022817390771F0E09129" + "3A102B30007802F0917902E85CFD4F4083309379028E" + "3A102B40002093780202C08091C600FF91EF919F917F" + "3A102B50008F914F913F912F910F900FBE0F901F902B" + "3A102B60001895E091CC02F091CD02E05CFF4F81918D" + "3A102B7000919120813181821B930B8F739070892BEF" + "3A102B800011F00E94330308951F920F920FB60F9217" + "3A102B900011242F933F938F939F93EF93FF93209153" + "3A102BA000BC023091BD028091BE029091BF022817F5" + "3A102BB000390731F48091C1008F7D8093C10014C02A" + "3A102BC000E091BE02F091BF02E458FD4F2081809158" + "3A102BD000BE029091BF0201968F7390709093BF02D6" + "3A102BE0008093BE022093C600FF91EF919F918F9139" + "3A102BF0003F912F910F900FBE0F901F901895AF929D" + "3A102C0000BF92DF92EF92FF920F931F93CF93DF93C8" + "3A102C1000EC017A018B01DD24403081EE580780E021" + "3A102C2000680780E0780711F0DD24D39491E0A92EA5" + "3A102C3000B12CEC89FD89DD2069F0C50108A002C036" + "3A102C4000880F991F0A94E2F7808360E079E08DE3B2" + "3A102C500090E005C0108260E874E88EE190E0A80181" + "3A102C600097010E94D818215030404040504056955E" + "3A102C700047953795279580E12030380720F0DD20F3" + "3A102C800011F0DD24D6CFE889F9893083EA89FB8900" + "3A102C9000208319A2EE89FF89408121E030E0C9013B" + "3A102CA0000C8C02C0880F991F0A94E2F7482B4083CE" + "3A102CB000EE89FF894081C9010D8C02C0880F991FE0" + "3A102CC0000A94E2F7482B4083EE89FF894081C901CD" + "3A102CD0000E8C02C0880F991F0A94E2F7482B40839C" + "3A102CE000EE89FF8980810F8C02C0220F331F0A9466" + "3A102CF000E2F7209528232083DF91CF911F910F9138" + "3A102D0000FF90EF90DF90BF90AF900895DC011C968C" + "3A102D1000ED91FC911D97E05CFF4F219131918081F5" + "3A102D20009181281B390B2F733070C9010895DC0184" + "3A102D30001C96ED91FC911D97E05CFF4F2081318145" + "3A102D4000E054F040DF01AE5BBF4F8D919C91119735" + "3A102D50002817390719F42FEF3FEF07C08D919C9189" + "3A102D6000E80FF91F8081282F30E0C9010895DC01A8" + "3A102D70001C96ED91FC911D97E05CFF4F2081318105" + "3A102D8000E054F040DF01AE5BBF4F8D919C911197F5" + "3A102D90002817390719F42FEF3FEF10C08D919C9140" + "3A102DA0001197E80FF91F20818D919C911197019641" + "3A102DB0008F73907011969C938E9330E0C9010895A3" + "3A102DC000DC0191968C919197882339F05496ED917E" + "3A102DD000FC915597808186FFF9CF91961C920895BA" + "3A102DE000CF93DF93EC01EE85FF85E05CFF4F208100" + "3A102DF0003181E054F0402F5F3F4F2F733070DF017F" + "3A102E0000AE5BBF4F8D919C91119728173907D1F375" + "3A102E1000E05CFF4F80819181E054F040E80FF91FA2" + "3A102E20006083EE85FF85E05CFF4F31832083EE8970" + "3A102E3000FF89208181E090E00F8C02C0880F991FEC" + "3A102E40000A94E2F7282B208381E089A3EC89FD898D" + "3A102E500080818064808381E090E0DF91CF9108954C" + "3A102E60001092C3021092C20288EE93E0A0E0B0E09C" + "3A102E70008093C4029093C502A093C602B093C70288" + "3A102E80008EEC91E09093C1028093C00288E392E0BF" + "3A102E90009093CD028093CC028CE792E09093CF0286" + "3A102EA0008093CE0285EC90E09093D1028093D00283" + "3A102EB00084EC90E09093D3028093D20280EC90E077" + "3A102EC0009093D5028093D40281EC90E09093D70246" + "3A102ED0008093D60282EC90E09093D9028093D8023E" + "3A102EE00086EC90E09093DB028093DA0284E080939A" + "3A102EF000DC0283E08093DD0287E08093DE0285E0E0" + "3A102F00008093DF0281E08093E0020895CF93DF9306" + "3A102F10000E9455140E94800CC1EBD5E10E94380339" + "3A102F20002097E1F30E94B115F9CFCF92DF92EF9293" + "3A102F3000FF920F931F93CF93DF937C016B018A0164" + "3A102F4000C0E0D0E00FC0D6016D916D01D701ED91C9" + "3A102F5000FC910190F081E02DC7010995C80FD91FA0" + "3A102F6000015010400115110571F7CE01DF91CF918D" + "3A102F70001F910F91FF90EF90DF90CF900895FC018B" + "3A102F80009B01848195816817790728F4608171819C" + "3A102F90006115710529F41092E20262EE72E002C03E" + "3A102FA000620F731FCB0108950F931F93CF93DF938D" + "3A102FB000EC018B016F5F7F4F888199810E941B021A" + "3A102FC000009711F480E005C0998388831B830A83EE" + "3A102FD00081E0DF91CF911F910F910895CF93DF93FF" + "3A102FE000EC0188819981892B29F08A819B81861740" + "3A102FF000970760F4CE010E94D417882341F08C819A" + "3A103000009D81892B19F4E881F981108281E0DF919B" + "3A10301000CF910895EF92FF920F931F93CF93DF9379" + "3A10302000EC017B016C817D81E114F104C1F041155B" + "3A10303000510599F08A01060F171FB8010E94EE177B" + "3A10304000882369F0888199812C813D81820F931FAB" + "3A10305000B7010E94F9021D830C8381E001C080E06A" + "3A10306000DF91CF911F910F91FF90EF90089561151F" + "3A10307000710511F480E00895DB010D900020E9F75F" + "3A103080001197A61BB70BAD010E940A180895FB010A" + "3A1030900060817181448155810E940A180895CF93FF" + "3A1030A000DF93EC0188819981009711F00E94C301A0" + "3A1030B000198218821D821C821B821A82DF91CF9195" + "3A1030C0000895EF92FF920F931F93CF93DF93EC013C" + "3A1030D0007B018A01BA010E94EE17882321F4CE01F8" + "3A1030E0000E944F1807C01D830C8388819981B70106" + "3A1030F0000E94F902CE01DF91CF911F910F91FF90B5" + "3A10310000EF900895CF93DF93EC01198218821B8210" + "3A103110001A821D821C821E826115710551F0DB012D" + "3A103120000D900020E9F71197A61BB70BAD010E9487" + "3A103130006118DF91CF910895CF93DF93EC01FB01EC" + "3A103140008617970761F0608171816115710529F01B" + "3A10315000448155810E94611802C00E944F18CE011F" + "3A10316000DF91CF910895FC01808191810E94C3017C" + "3A103170000895629FD001739FF001829FE00DF11DC1" + "3A10318000649FE00DF11D929FF00D839FF00D749FE1" + "3A10319000F00D659FF00D9927729FB00DE11DF91F8D" + "3A1031A000639FB00DE11DF91FBD01CF0111240895EA" + "3A1031B000A1E21A2EAA1BBB1BFD010DC0AA1FBB1F3B" + "3A1031C000EE1FFF1FA217B307E407F50720F0A21BAD" + "3A1031D000B30BE40BF50B661F771F881F991F1A941A" + "3A1031E00069F760957095809590959B01AC01BD0144" + "3A1031F000CF01089597FB092E05260ED057FD04D068" + "3A10320000D7DF0AD0001C38F45095409530952195B1" + "3A103210003F4F4F4F5F4F0895F6F79095809570950B" + "3A1032200061957F4F8F4F9F4F0895EE0FFF1F0590C1" + "3A10323000F491E02D09942F923F924F925F926F92FA" + "3A103240007F928F929F92AF92BF92CF92DF92EF9236" + "3A10325000FF920F931F93CF93DF93CDB7DEB7CA1BB7" + "3A10326000DB0B0FB6F894DEBF0FBECDBF09942A88E2" + "3A10327000398848885F846E847D848C849B84AA848A" + "3A10328000B984C884DF80EE80FD800C811B81AA8117" + "3A10329000B981CE0FD11D0FB6F894DEBF0FBECDBFE2" + "3A1032A000ED01089511E0CCEDD1E004C0FE010E94D3" + "3A0E32B00017192296CE3DD107C9F7F894FFCF2B" + "3A1032BE00754353530076302E3161004C45445F4CBC" + "3A1032CE00414D5000322C313300687474703A2F2FF8" + "3A1032DE00666F6C6B2E6E746E752E6E6F2F737661BD" + "3A1032EE00727661612F7574696C732F70726F32779D" + "3A1032FE0077772F23617070496431004F534E4150E0" + "3A10330E00204A61636B65740024242400552C002C24" + "3A10331E004E00007B226E616D65223A2200222C0047" + "3A10332E002276657273696F6E223A2200227365727D" + "3A10333E007669636573223A205B005D2C00226C690E" + "3A10334E006E6B73223A205B005D7D002C2000222CD8" + "3A10335E0020226C696E6B223A2200227D007B202295" + "3A10336E006964223A202200222C202270696E732278" + "3A10337E00203A22002000E702000000000000F016B4" + "3A0A338E0095178616B7169716E0167D" + "3A00000001FF"; } else { //AlternateLeds s = "3A100000000C9464000C948C000C948C000C948C0068" + "3A100010000C948C000C948C000C948C000C948C0030" + "3A100020000C948C000C948C000C948C000C948C0020" + "3A100030000C948C000C948C000C948C000C948C0010" + "3A100040000C9418070C948C000C948F080C94DD0809" + "3A100050000C948C000C948C000C948C000C948C00F0" + "3A100060000C948C000C948C000000000024002700ED" + "3A100070002A0000000000250028002B0000000000DE" + "3A1000800023002600290004040404040404040202DA" + "3A100090000202020203030303030301020408102007" + "3A1000A0004080010204081020010204081020000012" + "3A1000B0000007000201000003040600000000000029" + "3A1000C0000000A102490A9A0211241FBECFEFD8E016" + "3A1000D000DEBFCDBF11E0A0E0B1E0ECE7F8E102C087" + "3A1000E00005900D92AC3DB107D9F712E0ACEDB1E04F" + "3A1000F00001C01D92A33DB107E1F710E0C6ECD0E0CE" + "3A1001000004C02297FE010E94F60BC23CD107C9F73A" + "3A100110000E949F0A0C94310C0C940000CF93DF9343" + "3A10012000BC018230910510F462E070E0A091D10230" + "3A10013000B091D202ED01E0E0F0E040E050E021C0FB" + "3A10014000888199818617970769F48A819B81309706" + "3A1001500019F09383828304C09093D2028093D102DA" + "3A10016000FE0134C06817790738F44115510519F0BC" + "3A100170008417950708F4AC01FE018A819B819C01DC" + "3A10018000E9012097E9F641155105A9F1CA01861B3D" + "3A10019000970B049708F4BA01E0E0F0E02AC08D91D3" + "3A1001A0009C91119784179507F9F46417750781F4EA" + "3A1001B00012968D919C911397309719F093838283B7" + "3A1001C00004C09093D2028093D102FD0132964CC0BC" + "3A1001D000CA01861B970BFD01E80FF91F619371930C" + "3A1001E00002978D939C9340C0FD01828193819C0175" + "3A1001F000D9011097A1F68091CF029091D002892B5E" + "3A1002000041F48091C6019091C7019093D0028093F0" + "3A10021000CF024091C8015091C9014115510541F4E7" + "3A100220004DB75EB78091C4019091C501481B590B31" + "3A100230002091CF023091D002CA01821B930B861706" + "3A10024000970780F0AB014E5F5F4F8417950750F022" + "3A10025000420F531F5093D0024093CF02F901619394" + "3A10026000719302C0E0E0F0E0CF01DF91CF910895FB" + "3A10027000CF93DF93009709F450C0EC0122971B82C3" + "3A100280001A82A091D102B091D202109709F140E0F8" + "3A1002900050E0AC17BD0708F1BB83AA83FE01219192" + "3A1002A0003191E20FF31FAE17BF0779F48D919C9146" + "3A1002B0001197280F391F2E5F3F4F398328831296DD" + "3A1002C0008D919C9113979B838A834115510571F4FD" + "3A1002D000D093D202C093D10220C012968D919C91EE" + "3A1002E0001397AD01009711F0DC01D3CFFA01D3834E" + "3A1002F000C28321913191E20FF31FCE17DF0769F41A" + "3A1003000088819981280F391F2E5F3F4FFA01318371" + "3A1003100020838A819B8193838283DF91CF9108958B" + "3A10032000A0E0B0E0E6E9F1E00C94FC0B6C01009772" + "3A1003300029F4CB010E948E006C01C1C08EEF882E83" + "3A100340008FEF982E8C0C9D1C8601060F171F081529" + "3A10035000190508F4B2C0F401A081B181A617B7074E" + "3A10036000B8F0A530B10508F4AAC0CD0104978617EE" + "3A10037000970708F4A4C01297A61BB70BF801A19326" + "3A10038000B193D4016D937C93CF010E94380197C043" + "3A100390007B01EA1AFB0AEEEFFFEFEE0EFF1E3601BD" + "3A1003A0006A0E7B1EC091D102D091D2024424552402" + "3A1003B000AA24BB244AC0C615D705E1F54881598156" + "3A1003C0004E155F05B8F1CA0104978E159F05B0F46C" + "3A1003D0001296A40FB51FF401B183A0832A813B813B" + "3A1003E0004114510431F0D20113963C932E9312978D" + "3A1003F00066C03093D2022093D10261C08A819B8172" + "3A10040000F80193838283425050404E195F09518313" + "3A1004100040834114510431F0D20113961C930E9382" + "3A10042000129704C01093D2020093D102F401718399" + "3A10043000608345C088819981A816B90608F45C01DB" + "3A100440002E018A819B819C01E901209709F0B3CF9D" + "3A100450008091CF029091D00286159705E9F4A616F7" + "3A10046000B706D0F42091C8013091C901211531059A" + "3A1004700041F42DB73EB78091C4019091C501281B6E" + "3A10048000390B02171307C8F41093D0020093CF0260" + "3A10049000D4016D937C9313C0CB010E948E00EC01BC" + "3A1004A000009759F0F40140815181B6010E94650224" + "3A1004B000C6010E9438016E0102C0CC24DD24C601B1" + "3A1004C000CDB7DEB7E0E10C94180CFB01DC0102C0F3" + "3A1004D00001900D9241505040D8F70895FB01DC0186" + "3A1004E00001900D920020E1F708958130910561F4AB" + "3A1004F0006F5F7F4FF1F480EE91E040E050E060E00C" + "3A1005000070E00E94E7060895892B99F46F5F7F4F92" + "3A1005100081F487E092E00E94CC0B80E092E00E94A0" + "3A10052000CC0B89EF91E00E94CC0B82EF91E00E940E" + "3A10053000CC0B089580E090E06FEF7FEF0E94750292" + "3A10054000089581E090E06FEF7FEF0E9475020895BB" + "3A1005500080EE91E00E94560508958091CA0188239B" + "3A1005600069F10E9460072091DC013091DD0140912A" + "3A10057000DE015091DF0124543D4F4F4F5F4F621712" + "3A1005800073078407950708F445C08AE061E00E947C" + "3A10059000E8078BE060E00E94E8078CE061E00E94E1" + "3A1005A000E8070E9460076093DC017093DD0180938F" + "3A1005B000DE019093DF011092CA0108950E94600746" + "3A1005C0002091DC013091DD014091DE015091DF018D" + "3A1005D00024543D4F4F4F5F4F6217730784079507B1" + "3A1005E000C8F08AE060E00E94E8078BE061E00E94CA" + "3A1005F000E8078CE060E00E94E8070E9460076093D3" + "3A10060000DC017093DD018093DE019093DF0181E0D6" + "3A100610008093CA010895EF92FF920F931F93DF9387" + "3A10062000CF93CDB7DEB72E970FB6F894DEBF0FBECF" + "3A10063000CDBF80EEE82E81E0F82EC70140E052ECFD" + "3A1006400061E070E00E94CD0684E061E00E94A907AD" + "3A1006500084E061E00E94E8078E010F5F1F4FC80130" + "3A1006600060E071E00E949B0BC701B8010E94C906BF" + "3A10067000C8010E94CC0B8E01085F1F4FC80165E0C6" + "3A1006800071E00E949B0BC701B8010E94C506C8011A" + "3A100690000E94CC0BC7016BE071E044E151E00E9485" + "3A1006A0008D0682E061E00E94A9078DE061E00E9472" + "3A1006B000A907C70169E171E04BE451E00E945506CA" + "3A1006C0008AE061E00E94A9078BE061E00E94A9072F" + "3A1006D0008CE061E00E94A9070E9460076093DC0142" + "3A1006E0007093DD018093DE019093DF012E960FB6AB" + "3A1006F000F894DEBF0FBECDBFCF91DF911F910F9158" + "3A10070000FF90EF90089580E090E0089584E060E02D" + "3A100710000E94E8070895CF92DF92EF92FF921F9315" + "3A10072000CF93DF93162F6A0179018CEA92E06FEF85" + "3A100730000E94090A8CEA92E06F2D0E94090A8CEA55" + "3A1007400092E06E2D0E94090A8CEA92E06EEF0E9400" + "3A10075000090A8CEA92E0612F0E94090AC0E0D0E009" + "3A1007600009C0F601EC0FFD1F8CEA92E060810E9447" + "3A10077000090A2196CE15DF05A0F3DF91CF911F91D5" + "3A10078000FF90EF90DF90CF9008950F931F93CF933A" + "3A10079000DF93EC01062F142F862F61E00E94A9073A" + "3A1007A00060E0111161E0802F0E94E807CE0165E052" + "3A1007B00040E050E020E030E00E948B03DF91CF91D9" + "3A1007C0001F910F910895EF92FF921F93DF93CF93A4" + "3A1007D0000F92CDB7DEB77C01162F862F60E00E9406" + "3A1007E000A907812F0E943C0819821816190614F4D3" + "3A1007F00081E08983C70164E0AE014F5F5F4F21E074" + "3A1008000030E00E948B030F90CF91DF911F91FF90FA" + "3A10081000EF9008950F931F93CF93DF938C01DB012B" + "3A10082000842FE801E885F985B901AD010995C80172" + "3A1008300063E040E050E020E030E00E948B03DF9175" + "3A10084000CF911F910F910895CF92DF92EF92FF9277" + "3A100850000F931F93DF93CF9300D0CDB7DEB76C011A" + "3A10086000862FD6011696ED91FC9117977E0108947C" + "3A10087000E11CF11CB70140E050E009958C01FC013E" + "3A100880009081818189839A83C60162E0A70122E079" + "3A1008900030E00E948B03C8010E9438010F900F9036" + "3A1008A000CF91DF911F910F91FF90EF90DF90CF904C" + "3A1008B00008950F931F93CF93DF938C01DB01842F57" + "3A1008C000E801EC81FD81B901AD010995C80161E044" + "3A1008D00040E050E020E030E00E948B03DF91CF91B8" + "3A1008E0001F910F91089560E040E050E020E030E07B" + "3A1008F0000E948B030895CF92DF92EF92FF920F93A5" + "3A100900001F93DF93CF93CDB7DEB727970FB6F89439" + "3A10091000DEBF0FBECDBF7C018E010F5F1F4FC80130" + "3A1009200062E671E00E949B0BC80163E671E00E94E1" + "3A10093000500B82E190E0E80EF91EC801B7010E9459" + "3A10094000600BC8016DE671E00E94500BC80160E7C2" + "3A1009500071E00E94500B87E090E0E80EF91EC8019C" + "3A10096000B7010E94600BC8016DE671E00E94500B58" + "3A10097000C8016CE771E00E94500B87E090E0E80E40" + "3A10098000F91EC801B7010E94600BC8016AE871E056" + "3A100990000E94500BC8016DE871E00E94500B87E087" + "3A1009A00090E0E80EF91EC801B7010E94600BC80173" + "3A1009B00068E971E00E94500BCD80DE808CEA92E005" + "3A1009C0006FEF0E94090A8CEA92E06D2D0E94090ADD" + "3A1009D0008CEA92E06C2D0E94090A8CEA92E06EEF9C" + "3A1009E0000E94090A8CEA92E066E00E94090AEE245D" + "3A1009F000FF2410C0C801B7010E94D80AFC01608121" + "3A100A0000772767FD70958CEA92E00E94090A0894A6" + "3A100A1000E11CF11CEC14FD0468F3C8010E94CC0B2E" + "3A100A200027960FB6F894DEBF0FBECDBFCF91DF91F2" + "3A100A30001F910F91FF90EF90DF90CF9008950F934B" + "3A100A40001F93F8014330E1F0443028F4413079F04D" + "3A100A5000423090F409C04530E1F04530B0F0463006" + "3A100A6000E9F04F3F01F51DC00E9473041CC0422FE6" + "3A100A700098010E94590417C0622F0E94240413C0D9" + "3A100A8000422F98010E940A040EC0622F0E94E303C5" + "3A100A90000AC0622F40810E94C50305C00E947B04EA" + "3A100AA00002C00E9486031F910F9108956F927F925A" + "3A100AB0008F929F92AF92BF92CF92DF92EF92FF926E" + "3A100AC0000F931F93CF93DF93EC010E946007209157" + "3A100AD0001502309116024091170250911802261704" + "3A100AE00037074807590750F48091190290911A026C" + "3A100AF000892B21F010921A02109219020E946007AD" + "3A100B00006053784F8F4F9F4F60931502709316027A" + "3A100B1000809317029093180273E0672E712C65E0A2" + "3A100B2000862E912C54E0A52EB12C41E0C42ED12C60" + "3A100B300032E0E32EF12CA3C08091190290911A02A9" + "3A100B400082309105C1F18330910534F4009781F032" + "3A100B5000019709F08FC022C08430910509F453C079" + "3A100B6000843091050CF444C0059709F083C056C049" + "3A100B70008CEA92E00E94D0098F3F910509F07AC07B" + "3A100B8000D0921A02C092190280910F029091100225" + "3A100B9000009709F46FC00E9438016CC08CEA92E0A3" + "3A100BA0000E94D0091092130280931402F0921A024C" + "3A100BB000E09219025FC000911302109114028CEAB6" + "3A100BC00092E00E94D00990E0802B912B9093140228" + "3A100BD0008093130270921A02609219020E948E0092" + "3A100BE0009093100280930F02009709F043C03EC01B" + "3A100BF0008CEA92E00E94D00980931202B0921A020D" + "3A100C0000A092190237C08CEA92E00E94D00980932A" + "3A100C1000110290921A02809219022CC080910E0249" + "3A100C200000910F0210911002080F111D8CEA92E042" + "3A100C30000E94D009F801808380910E028F5F80931B" + "3A100C40000E02609113027091140290E086179707CC" + "3A100C500088F000910F0210911002CE014091120213" + "3A100C6000209111020E941F0510920E0210921A028A" + "3A100C700010921902888199810196998388838CEA60" + "3A100C800092E00E949F09892B09F056CFDF91CF9106" + "3A100C90001F910F91FF90EF90DF90CF90BF90AF909A" + "3A100CA0009F908F907F906F900895CF92DF92EF92F8" + "3A100CB000FF920F931F93CF93DF93EC016B017A01A7" + "3A100CC0008BA59CA5892B31F0CE0187966BE971E04D" + "3A100CD0000E94500B8E01095D1F4FC80163E671E051" + "3A100CE0000E94500BC801B7010E94500BC8016EE969" + "3A100CF00071E00E94500BC801B6010E94500BC80160" + "3A100D00006AEA71E00E94500BDF91CF911F910F9121" + "3A100D1000FF90EF90DF90CF900895CF92DF92EF9207" + "3A100D2000FF920F931F93CF93DF93EC017B016A0136" + "3A100D30008CA19DA1892B31F0CE0180966BE971E0E9" + "3A100D40000E94500B8E01005E1F4FC8016DEA71E0DA" + "3A100D50000E94500BC801B7010E94500BC80167EBFD" + "3A100D600071E00E94500BC801B6010E94500BC801EF" + "3A100D70006AEA71E00E94500BDF91CF911F910F91B1" + "3A100D8000FF90EF90DF90CF90089549960E94B50BA9" + "3A100D9000089542960E94B50B08950F931F93182F44" + "3A100DA000092F8CEA92E00E941809212F302FC901E7" + "3A100DB000FC0180E090E023E833E033832283019656" + "3A100DC000329688309105C9F71F910F910895EF92DF" + "3A100DD000FF920F931F93CF93DF93EC017A018B0166" + "3A100DE000429662E671E00E949B0BCE01499662E654" + "3A100DF00071E00E949B0BCE01809662E671E00E943A" + "3A100E00009B0BCE01879662E671E00E949B0BE1147A" + "3A100E1000F1040105110529F0CE01B801A7010E94D6" + "3A100E2000CD06DF91CF911F910F91FF90EF90089524" + "3A100E30001F920F920FB60F9211242F933F938F930F" + "3A100E40009F93AF93BF9380911F0290912002A09136" + "3A100E50002102B0912202309123020196A11DB11D01" + "3A100E6000232F2D5F2D3720F02D570196A11DB11D89" + "3A100E70002093230280931F0290932002A0932102CB" + "3A100E8000B093220280911B0290911C02A0911D023E" + "3A100E9000B0911E020196A11DB11D80931B0290937B" + "3A100EA0001C02A0931D02B0931E02BF91AF919F91AF" + "3A100EB0008F913F912F910F900FBE0F901F9018951B" + "3A100EC0008FB7F89420911F023091200240912102A7" + "3A100ED000509122028FBFB901CA010895789484B558" + "3A100EE000826084BD84B5816084BD85B5826085BD26" + "3A100EF00085B5816085BDEEE6F0E08081816080830C" + "3A100F0000E1E8F0E0108280818260808380818160EE" + "3A100F10008083E0E8F0E0808181608083E1EBF0E0B5" + "3A100F2000808184608083E0EBF0E080818160808359" + "3A100F3000EAE7F0E080818460808380818260808342" + "3A100F40008081816080838081806880831092C1006D" + "3A100F50000895CF93DF93482F50E0CA0186569F4FE4" + "3A100F6000FC0134914A575F4FFA018491882369F15B" + "3A100F700090E0880F991FFC01E859FF4FA591B491AB" + "3A100F8000FC01EE58FF4FC591D491662351F42FB761" + "3A100F9000F8948C91932F909589238C938881892341" + "3A100FA0000BC0623061F42FB7F8948C91932F909519" + "3A100FB00089238C938881832B88832FBF06C09FB79A" + "3A100FC000F8948C91832B8C939FBFDF91CF910895E0" + "3A100FD000482F50E0CA0182559F4FFC012491CA015D" + "3A100FE00086569F4FFC0194914A575F4FFA01349106" + "3A100FF000332309F440C0222351F1233071F024300F" + "3A1010000028F42130A1F0223011F514C02630B1F0BF" + "3A101010002730C1F02430D9F404C0809180008F774C" + "3A1010200003C0809180008F7D8093800010C084B5C4" + "3A101030008F7702C084B58F7D84BD09C08091B000D8" + "3A101040008F7703C08091B0008F7D8093B000E32F35" + "3A10105000F0E0EE0FFF1FEE58FF4FA591B4912FB7B0" + "3A10106000F894662321F48C919095892302C08C9189" + "3A10107000892B8C932FBF0895682F70E0CB01825588" + "3A101080009F4FFC012491CB0186569F4FFC01449158" + "3A101090006A577F4FFB019491992319F420E030E0C7" + "3A1010A0003CC0222351F1233071F0243028F4213048" + "3A1010B000A1F0223011F514C02630B1F02730C1F074" + "3A1010C0002430D9F404C0809180008F7703C08091D0" + "3A1010D00080008F7D8093800010C084B58F7702C020" + "3A1010E00084B58F7D84BD09C08091B0008F7703C027" + "3A1010F0008091B0008F7D8093B000892F90E0880FA1" + "3A10110000991F84589F4FFC01A591B4918C9120E0C8" + "3A1011100030E0842311F021E030E0C90108951F92EE" + "3A101120000F920FB60F9211242F933F934F938F93EB" + "3A101130009F93EF93FF938091C00082FD1DC040916B" + "3A10114000C60020916402309165022F5F3F4F2F73DC" + "3A10115000307080916602909167022817390771F00C" + "3A10116000E0916402F0916502EC5DFD4F40833093A5" + "3A1011700065022093640202C08091C600FF91EF9146" + "3A101180009F918F914F913F912F910F900FBE0F9094" + "3A101190001F901895E091B802F091B902E05CFF4F02" + "3A1011A0008191919120813181821B930B8F7390707B" + "3A1011B000892B11F00E94A80208951F920F920FB67A" + "3A1011C0000F9211242F933F938F939F93EF93FF934D" + "3A1011D0002091A8023091A9028091AA029091AB02BD" + "3A1011E0002817390731F48091C1008F7D8093C100A9" + "3A1011F00014C0E091AA02F091AB02E859FD4F2081A2" + "3A101200008091AA029091AB0201968F739070909397" + "3A10121000AB028093AA022093C600FF91EF919F91A9" + "3A101220008F913F912F910F900FBE0F901F901895A7" + "3A10123000AF92BF92DF92EF92FF920F931F93CF93E3" + "3A10124000DF93EC017A018B01DD24403081EE5807F9" + "3A1012500080E0680780E0780711F0DD24D39491E006" + "3A10126000A92EB12CEC89FD89DD2069F0C50108A00B" + "3A1012700002C0880F991F0A94E2F7808360E079E04A" + "3A101280008DE390E005C0108260E874E88EE190E0A4" + "3A10129000A80197010E94D20B21503040404050409D" + "3A1012A000569547953795279580E12030380720F0EF" + "3A1012B000DD2011F0DD24D6CFE889F9893083EA8971" + "3A1012C000FB89208319A2EE89FF89408121E030E06B" + "3A1012D000C9010C8C02C0880F991F0A94E2F7482BB1" + "3A1012E0004083EE89FF894081C9010D8C02C0880FBF" + "3A1012F000991F0A94E2F7482B4083EE89FF894081C9" + "3A10130000C9010E8C02C0880F991F0A94E2F7482B7E" + "3A101310004083EE89FF8980810F8C02C0220F331F2A" + "3A101320000A94E2F7209528232083DF91CF911F9123" + "3A101330000F91FF90EF90DF90BF90AF900895DC0188" + "3A101340001C96ED91FC911D97E05CFF4F219131912E" + "3A1013500080819181281B390B2F733070C90108954A" + "3A10136000DC011C96ED91FC911D97E05CFF4F208104" + "3A101370003181E054F040DF01AE5BBF4F8D919C9115" + "3A1013800011972817390719F42FEF3FEF07C08D91F8" + "3A101390009C91E80FF91F8081282F30E0C901089542" + "3A1013A000DC011C96ED91FC911D97E05CFF4F2081C4" + "3A1013B0003181E054F040DF01AE5BBF4F8D919C91D5" + "3A1013C00011972817390719F42FEF3FEF10C08D91AF" + "3A1013D0009C911197E80FF91F20818D919C91119795" + "3A1013E00001968F73907011969C938E9330E0C90193" + "3A1013F0000895DC0191968C919197882339F0549649" + "3A10140000ED91FC915597808186FFF9CF91961C92C2" + "3A101410000895CF93DF93EC01EE85FF85E05CFF4FED" + "3A1014200020813181E054F0402F5F3F4F2F733070A7" + "3A10143000DF01AE5BBF4F8D919C9111972817390743" + "3A10144000D1F3E05CFF4F80819181E054F040E80FE0" + "3A10145000F91F6083EE85FF85E05CFF4F31832083B9" + "3A10146000EE89FF89208181E090E00F8C02C0880F17" + "3A10147000991F0A94E2F7282B208381E089A3EC8945" + "3A10148000FD8980818064808381E090E0DF91CF914D" + "3A1014900008951092AF021092AE0288EE93E0A0E0A1" + "3A1014A000B0E08093B0029093B102A093B202B093E7" + "3A1014B000B3028FEC91E09093AD028093AC0284E292" + "3A1014C00092E09093B9028093B80288E692E09093FC" + "3A1014D000BB028093BA0285EC90E09093BD028093AA" + "3A1014E000BC0284EC90E09093BF028093BE0280EC3B" + "3A1014F00090E09093C1028093C00281EC90E09093C1" + "3A10150000C3028093C20282EC90E09093C502809364" + "3A10151000C40286EC90E09093C7028093C60284E0F8" + "3A101520008093C80283E08093C90287E08093CA0257" + "3A1015300085E08093CB0281E08093CC020895CF9325" + "3A10154000DF930E946E070E940B03CAECD8E00E9452" + "3A10155000AD022097E1F30E94CA08F9CFCF92DF9243" + "3A10156000EF92FF920F931F93CF93DF937C016B0158" + "3A101570008A01C0E0D0E00FC0D6016D916D01D701A6" + "3A10158000ED91FC910190F081E02DC7010995C80F04" + "3A10159000D91F015010400115110571F7CE01DF91DF" + "3A1015A000CF911F910F91FF90EF90DF90CF90089512" + "3A1015B000FC019B01848195816817790728F460817B" + "3A1015C00071816115710529F41092CE026EEC72E002" + "3A1015D00002C0620F731FCB0108950F931F93CF9327" + "3A1015E000DF93EC018B016F5F7F4F888199810E94AF" + "3A1015F0009001009711F480E005C0998388831B83D4" + "3A101600000A8381E0DF91CF911F910F910895CF93CD" + "3A10161000DF93EC0188819981892B29F08A819B8154" + "3A101620008617970760F4CE010E94ED0A882341F0E7" + "3A101630008C819D81892B19F4E881F981108281E0E8" + "3A10164000DF91CF910895EF92FF920F931F93CF9365" + "3A10165000DF93EC017B016C817D81E114F104C1F029" + "3A101660004115510599F08A01060F171FB8010E9414" + "3A10167000070B882369F0888199812C813D81820F35" + "3A10168000931FB7010E946E021D830C8381E001C08D" + "3A1016900080E0DF91CF911F910F91FF90EF9008951F" + "3A1016A0006115710511F480E00895DB010D900020B3" + "3A1016B000E9F71197A61BB70BAD010E94230B089504" + "3A1016C000FB0160817181448155810E94230B089543" + "3A1016D000CF93DF93EC0188819981009711F00E94EC" + "3A1016E0003801198218821D821C821B821A82DF91A6" + "3A1016F000CF910895EF92FF920F931F93CF93DF93B3" + "3A10170000EC017B018A01BA010E94070B882321F4B6" + "3A10171000CE010E94680B07C01D830C8388819981CC" + "3A10172000B7010E946E02CE01DF91CF911F910F9100" + "3A10173000FF90EF900895CF93DF93EC011982188208" + "3A101740001B821A821D821C821E826115710551F056" + "3A10175000DB010D900020E9F71197A61BB70BAD0137" + "3A101760000E947A0BDF91CF910895CF93DF93EC0124" + "3A10177000FB018617970761F0608171816115710522" + "3A1017800029F0448155810E947A0B02C00E94680BA7" + "3A10179000CE01DF91CF910895FC01808191810E945B" + "3A1017A00038010895A1E21A2EAA1BBB1BFD010DC032" + "3A1017B000AA1FBB1FEE1FFF1FA217B307E407F50701" + "3A1017C00020F0A21BB30BE40BF50B661F771F881FDD" + "3A1017D000991F1A9469F760957095809590959B0173" + "3A1017E000AC01BD01CF010895EE0FFF1F0590F491EC" + "3A1017F000E02D09942F923F924F925F926F927F92C9" + "3A101800008F929F92AF92BF92CF92DF92EF92FF9210" + "3A101810000F931F93CF93DF93CDB7DEB7CA1BDB0BBC" + "3A101820000FB6F894DEBF0FBECDBF09942A88398861" + "3A1018300048885F846E847D848C849B84AA84B98468" + "3A10184000C884DF80EE80FD800C811B81AA81B98174" + "3A10185000CE0FD11D0FB6F894DEBF0FBECDBFED0188" + "3A10186000089510E0C6ECD0E004C0FE010E94F60B23" + "3A0C1870002296C83CD107C9F7F894FFCFBE" + "3A10187C00754353530076302E3161004C45445F4C18" + "3A10188C00414D5000322C313300687474703A2F2F54" + "3A10189C00666F6C6B2E6E746E752E6E6F2F73766119" + "3A1018AC00727661612F7574696C732F70726F3277F9" + "3A1018BC0077772F23617070496431004F534E41503C" + "3A1018CC00204A61636B65740024242400552C002C81" + "3A1018DC004E00007B226E616D65223A2200222C00A4" + "3A1018EC002276657273696F6E223A220022736572DA" + "3A1018FC007669636573223A205B005D2C00226C696B" + "3A10190C006E6B73223A205B005D7D002C2000222C34" + "3A10191C0020226C696E6B223A2200227D007B2022F1" + "3A10192C006964223A202200222C202270696E7322D4" + "3A10193C00203A22002000D302000001000000000920" + "3A0C194C000AAE0A9F09D009B009F9090091" + "3A00000001FF"; } byte[] bytes = s.getBytes(); return bytes; } }
// This file is part of the "OPeNDAP 4 Data Server (aka Hyrax)" project. // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. package opendap.async; import opendap.bes.BES; import opendap.bes.BESConfig; import opendap.bes.BESManager; import opendap.bes.dapResponders.BesApi; import opendap.bes.dapResponders.DapDispatcher; import opendap.coreServlet.ReqInfo; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.RequestDispatcher; import javax.servlet.ServletInputStream; import javax.servlet.http.*; import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.Principal; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * IsoDispatchHandler for ISO responses from Hyrax */ public class AsyncDispatcher extends DapDispatcher { private Logger log; private boolean initialized; private boolean usePendingAndGoneResponses; private ReentrantLock cacheLock; private ConcurrentHashMap<String,Date> asyncCache; private String _prefix = "async/"; private int cachePersistTime; // In milliseconds private int responseDelay; // In milliseconds //private String dapMetadataRegex = ".*\\.xml|.*\\.iso|.*\\.rubric|.*\\.ver|.*\\.ddx|.*\\.dds|.*\\.das|.*\\.info|.*\\.html?"; //private Pattern dapMetadataPattern = Pattern.compile(dapMetadataRegex, Pattern.CASE_INSENSITIVE); private String dap4DataRegex; private Pattern dap4DataPattern; private String dap2DataRegex; private Pattern dap2DataPattern; public AsyncDispatcher(){ log = LoggerFactory.getLogger(getClass()); asyncCache = new ConcurrentHashMap<String, Date>(); cacheLock = new ReentrantLock(); cachePersistTime = 3600000; // In milliseconds responseDelay = 60000; // In milliseconds usePendingAndGoneResponses = true; dap4DataRegex = "(.*\\.dap((\\.xml)|(\\.csv)|(\\.nc))?$)"; dap4DataPattern = Pattern.compile(dap4DataRegex, Pattern.CASE_INSENSITIVE); dap2DataRegex = ".*\\.dods|.*\\.asc(ii)?"; dap2DataPattern = Pattern.compile(dap2DataRegex, Pattern.CASE_INSENSITIVE); initialized = false; } @Override public void init(HttpServlet servlet,Element config) throws Exception { if(initialized) return; BesApi besApi = new BesApi(); init(servlet, config ,besApi); ingestPrefix(config); ingestCachePersistTime(config); ingestResponseDelay(config); ingestUsePendingGone(config); // What follows is a hack to get a particular BES, the BES with prefix, to service these requests. // We know the that BESManager.getConfig() returns a clone of the config so that we can abuse // it as we see fit. Element besManagerConfig = BESManager.getConfig(); List besList = besManagerConfig.getChildren("BES"); BES bes; BESConfig besConfig; Element besConfigElement; for (Object o : besList) { besConfigElement = (Element) o; Element prefixElement = besConfigElement.getChild("prefix"); String prefix = null; if(prefixElement!=null) prefix = prefixElement.getTextTrim(); // Find the BESs whose prefix is "/" note that there may be more than one // And that's fine. This will just cause the BESManager to form another BESGroup with // the new prefix. if(prefix!=null && prefix.equals("/")){ // Change the prefix to be the prefix for our async responder. prefixElement.setText(_prefix); besConfig = new BESConfig(besConfigElement); // Add the new BES to the BESManager bes = new BES(besConfig); BESManager.addBes(bes); log.info("Added BES to service asynchronous responses. BES prefix: '"+_prefix+"'"); initialized = true; } } } private void ingestPrefix(Element config) throws Exception{ String msg; Element e = config.getChild("prefix"); if(e!=null) _prefix = e.getTextTrim(); if(_prefix.equals("/")){ msg = "Bad Configuration. The <Handler> " + "element that declares " + this.getClass().getName() + " MUST provide 1 <prefix> " + "child element whose value may not be equal to \"/\""; log.error(msg); throw new Exception(msg); } if(_prefix.endsWith("/")) _prefix = _prefix.substring(0,_prefix.length()-1); if(!_prefix.startsWith("/")) _prefix = "/" + _prefix; log.info("prefix="+ _prefix); } private void ingestCachePersistTime(Element config) throws Exception{ String msg; Element e = config.getChild("cachePersistTime"); if(e!=null) cachePersistTime = Integer.parseInt(e.getTextTrim()) * 1000; // Make it into milliseconds if(cachePersistTime < 0){ msg = "Bad Configuration. The <Handler> " + "element that declares " + this.getClass().getName() + " MUST provide a <cachePersistTime> " + "child element whose value may not be less than 0"; log.error(msg); throw new Exception(msg); } log.info("cachePersistTime="+ cachePersistTime); } private void ingestUsePendingGone(Element config) throws Exception{ String msg; Element e = config.getChild("usePendingAndGoneResponses"); if(e!=null) usePendingAndGoneResponses = e.getTextTrim().equalsIgnoreCase("true"); log.info("usePendingAndGoneResponses="+ usePendingAndGoneResponses); } private void ingestResponseDelay(Element config) throws Exception{ String msg; Element e = config.getChild("responseDelay"); if(e!=null) responseDelay = Integer.parseInt(e.getTextTrim()) * 1000; // Make it into milliseconds if(responseDelay < 0){ msg = "Bad Configuration. The <Handler> " + "element that declares " + this.getClass().getName() + " MUST provide a <responseDelay> " + "child element whose value may not be less than 0"; log.error(msg); throw new Exception(msg); } log.info("responseDelay="+ responseDelay); } @Override public boolean requestDispatch(HttpServletRequest request, HttpServletResponse response, boolean sendResponse) throws Exception { String serviceContext = ReqInfo.getFullServiceContext(request); String relativeURL = ReqInfo.getLocalUrl(request); log.debug("The client requested this resource: " + relativeURL); log.debug("serviceContext: "+serviceContext); log.debug("relativeURL: "+relativeURL); if(!relativeURL.startsWith("/")) relativeURL = "/" + relativeURL; boolean isMyRequest = relativeURL.startsWith(_prefix); if (isMyRequest) { if(sendResponse){ return(sendAsyncResponse(request, response)); } else { return(super.requestDispatch(request, response, false)); } } return isMyRequest; } public boolean sendAsyncResponse(HttpServletRequest request, HttpServletResponse response) throws Exception { log.info("Sending Asynchronous Response"); // If it's a DAP4 Data request then do the asynchronous dance. if(isDap4DataRequest(request)) return(asyncDap4DataResponse(request, response)); // If it's a DAP2 Data request then do the asynchronous dance. else if(isDap2DataRequest(request)) return(asyncDap2DataResponse(request, response)); return(super.requestDispatch(request,response,true)); } public boolean isDap4DataRequest(HttpServletRequest req){ String relativeURL = ReqInfo.getLocalUrl(req); Matcher m = dap4DataPattern.matcher(relativeURL); return m.matches(); } public boolean isDap2DataRequest(HttpServletRequest req){ String relativeURL = ReqInfo.getLocalUrl(req); Matcher m = dap2DataPattern.matcher(relativeURL); return m.matches(); } /** * * @param request The request to evaluate for the client headers and CE syntax * @return Returns -1 if the client has not indicated that -1 if it can accept an asynchronous response. * Returns 0 if the client has indicated that it will accept any length delay. A return value greater than * 0 indicates the time, in milliseconds, that client is willing to wait for a response. */ public long getClientAsyncAcceptVal_ms(HttpServletRequest request){ // Get the values of the "async" parameter in the query string. String[] ceAsyncAccept = request.getParameterValues("async"); // Get the values of the (possibly repeated) DAP Async Accept header Enumeration enm = request.getHeaders(HttpHeaders.ASYNC_ACCEPT); Vector<String> v = new Vector<String>(); while(enm.hasMoreElements()) v.add((String)enm.nextElement()); long acceptableDelay; long headerAcceptDelay = -1; long ceAcceptDelay = -1; // Check the constraint expression for the async control parameter if(ceAsyncAccept!=null && ceAsyncAccept.length>0){ try { // Only look at the first value. ceAcceptDelay = Long.parseLong(ceAsyncAccept[0])*1000; // Value comes as seconds, make it milliseconds } catch(NumberFormatException e){ log.error("Unable to ingest the value of the "+ HttpHeaders.ASYNC_ACCEPT+ " header. msg: "+e.getMessage()); ceAcceptDelay = -1; } } // Check HTTP headers for Async Control if(v.size()>0){ try { // Only look at the first value. headerAcceptDelay = Long.parseLong(v.get(0))*1000; // Value comes as seconds, make it milliseconds } catch(NumberFormatException e){ log.error("Unable to ingest the value of the "+ HttpHeaders.ASYNC_ACCEPT+ " header. msg: "+e.getMessage()); headerAcceptDelay = -1; } } // The constraint expression parameter "asnyc=seconds" takes precedence. acceptableDelay = headerAcceptDelay; if(ceAcceptDelay>=0){ acceptableDelay = ceAcceptDelay; } return acceptableDelay; } /** * * @param request The client request to evaluate to see if the target URL needs to have the async parameter added * the query string * @return Returns -1 if the client has not indicated that -1 if it can accept an asynchronous response. * Returns 0 if the client has indicated that it will accept any length delay. A return value greater than * 0 indicates the time, in milliseconds, that client is willing to wait for a response. */ public boolean addAsyncParameterToCE(HttpServletRequest request){ // Get the values of the async parameter in the query string. String[] ceAsyncAccept = request.getParameterValues("async"); // Get the values of the (possibly repeated) DAP Async Accept header Enumeration enm = request.getHeaders(HttpHeaders.ASYNC_ACCEPT); Vector<String> acceptAsyncHeaderValues = new Vector<String>(); while(enm.hasMoreElements()) acceptAsyncHeaderValues.add((String)enm.nextElement()); return ceAsyncAccept==null && acceptAsyncHeaderValues.size()>0; } public boolean asyncDap2DataResponse(HttpServletRequest request, HttpServletResponse response) throws Exception { Date now = new Date(); Date timeAvailable; String xmlBase = DocFactory.getXmlBase(request); timeAvailable = addResourceToCacheAsNeeded(xmlBase); long timeTillReady = timeAvailable.getTime() - now.getTime(); if(timeTillReady>0){ log.info("Delaying DAP2 data request for "+timeTillReady+"ms"); try { Thread.sleep(timeTillReady);} catch(InterruptedException e){ log.error("Thread Interrupted. msg: "+e.getMessage());} } return(super.requestDispatch(request,response,true)); } /** * * @param id The resource ID * @return The time at which the resource will be available. */ private Date addResourceToCacheAsNeeded(String id){ Date now = new Date(); Date timeAvailable; timeAvailable = new Date(now.getTime()+ getResponseDelay_ms()); Date resourceAvailabilityTime = asyncCache.putIfAbsent(id,timeAvailable); if(resourceAvailabilityTime != null) return resourceAvailabilityTime; return timeAvailable; } public boolean asyncDap4DataResponse(HttpServletRequest request, HttpServletResponse response) throws Exception { Date now = new Date(); Date startTime; String xmlBase = DocFactory.getXmlBase(request); long clientAcceptableDelay_ms = getClientAsyncAcceptVal_ms(request); if(clientAcceptableDelay_ms<0){ // There was no indication that the client can accept an asynchronous response, so tell that // it's required that they indicate their willingness to accept async in order to get the resource. Document asyncResponse = DocFactory.getAsynchronousResponseRequired(request, getResponseDelay_s(), getCachePersistTime_s()); response.setHeader(HttpHeaders.ASYNC_REQUIRED, ""); sendDocument(response, asyncResponse, HttpServletResponse.SC_BAD_REQUEST); return true; } else if(clientAcceptableDelay_ms>0 && clientAcceptableDelay_ms < getResponseDelay_ms()){ // The client indicated that amount of time that they are willing to wait for the // asynchronous response is less than the expected delay. // So - tell them that the request is REJECTED! Document asyncResponse = DocFactory.getAsynchronousResponseRejected(request, DocFactory.reasonCode.TIME, "Acceptable access delay was less than estimated delay."); sendDocument(response, asyncResponse, HttpServletResponse.SC_PRECONDITION_FAILED); return true; } else { // Looks like the client wants an async response! // First, let's figure out if the request is for a pending, or expired resource. startTime = asyncCache.get(xmlBase); if(startTime!=null) { Date endTime = new Date(startTime.getTime()+cachePersistTime); if(now.after(startTime)){ if(now.before(endTime) ){ // The request if for an available resource. I.e. The requested resource is in the cache, // it's start has past and it's end time has not yet arrived. So - send the data. // And because this is hack to add DAP4 functionality to a DAP2 server, make the request // palatable to the underlying DAP2 service. Dap4RequestToDap2Request dap2Request = new Dap4RequestToDap2Request(request); return(super.requestDispatch(dap2Request,response,true)); } else if(now.after(endTime)){ if(usePendingAndGoneResponses){ // Async Response is expired. Return GONE! Document asyncResponse = DocFactory.getAsynchronousResponseGone(request); sendDocument(response, asyncResponse, HttpServletResponse.SC_GONE); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } asyncCache.remove(xmlBase, startTime); return true; } } else { if(usePendingAndGoneResponses){ // Async Response is PENDING! Document asyncResponse = DocFactory.getAsynchronousResponsePending(request); sendDocument(response, asyncResponse, HttpServletResponse.SC_CONFLICT); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } return true; } } // The resource is not in the cache, so add the resource to the cache. and then // tell the client that the request is accepted. addResourceToCacheAsNeeded(xmlBase); sendAsyncRequestAccepted(request,response); return true; } } public void sendAsyncRequestAccepted(HttpServletRequest request, HttpServletResponse response) throws IOException { // Async Request is accepted. response.setHeader(HttpHeaders.ASYNC_ACCEPTED, getResponseDelay_s()+""); String requestUrl = request.getRequestURL().toString(); String ce = request.getQueryString(); if(addAsyncParameterToCE(request)) ce="async="+ getClientAsyncAcceptVal_ms(request) + "&" + ce; String resultLinkUrl = requestUrl + "?" + ce; Document asyncResponse = DocFactory.getAsynchronousResponseAccepted( request, resultLinkUrl, getResponseDelay_s(), getCachePersistTime_s()); sendDocument(response, asyncResponse, HttpServletResponse.SC_ACCEPTED); } public static void sendDocument(HttpServletResponse response, Document doc, int httpStatus) throws IOException { XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); response.setStatus(httpStatus); response.setContentType("text/xml"); response.getOutputStream().print(xmlo.outputString(doc)); } private int getResponseDelay_s(){ return responseDelay/1000; } private int getCachePersistTime_s(){ return cachePersistTime/1000; } private int getResponseDelay_ms(){ return responseDelay; } private int getCachePersistTime_ms(){ return cachePersistTime; } class Dap4RequestToDap2Request implements HttpServletRequest { HttpServletRequest r; public Dap4RequestToDap2Request(HttpServletRequest request) { r = request; } public String getAuthType() { return r.getAuthType(); } public Cookie[] getCookies() { return r.getCookies(); } public long getDateHeader(String s) { return r.getDateHeader(s); } public String getHeader(String s) { return r.getHeader(s); } public Enumeration getHeaders(String s) { return r.getHeaders(s); } public Enumeration getHeaderNames() { return r.getHeaderNames(); } public int getIntHeader(String s) { return r.getIntHeader(s); } public String getMethod() { return r.getMethod(); } public String getPathInfo() { return r.getPathInfo(); } public String getPathTranslated() { return r.getPathTranslated(); } public String getContextPath() { return r.getContextPath(); } public String getQueryString() { String query = r.getQueryString(); log.debug("dap4 query: "+query); String dap2Query = convertDap4ceToDap2ce(r); log.debug("dap2 query: "+dap2Query); return dap2Query; } /** * This prunes the async control by simply ignoring it. * Since the DAP4 query string utilizes a regular KVP structure with the DAP4 projection held * in a parameter/key named "proj" and the DAP4 selection held in a series of zero or more * instances of the parameter/key named "sel". <br/> * This gives us the ability to: * <ul> * <li>Quickly extract the projection and selection.</li> * <li>utilize other key/parameter names for other purposes.</li> * </ul> * The async parameter is an example of one of these other keys. * @param req The request to use as the source of the DAP4 constraint expression * @return A DAP2 constraint expression */ public String convertDap4ceToDap2ce(HttpServletRequest req){ StringBuilder dap2Query = new StringBuilder(); String projection = req.getParameter("proj"); String[] selectionClauses = req.getParameterValues("sel"); if(projection!=null) dap2Query.append(projection); if(selectionClauses!=null){ for(String selClause:selectionClauses){ if(dap2Query.length()>0) dap2Query.append("&"); dap2Query.append(selClause); } } return dap2Query.toString(); } public String getRemoteUser() { return r.getRemoteUser(); } public boolean isUserInRole(String s) { return r.isUserInRole(s); } public Principal getUserPrincipal() { return r.getUserPrincipal(); } public String getRequestedSessionId() { return r.getRequestedSessionId(); } public String getRequestURI() { return r.getRequestURI(); } public StringBuffer getRequestURL() { return r.getRequestURL(); } public String getServletPath() { return r.getServletPath(); } public HttpSession getSession(boolean b) { return r.getSession(b); } public HttpSession getSession() { return r.getSession(); } public boolean isRequestedSessionIdValid() { return r.isRequestedSessionIdValid(); } public boolean isRequestedSessionIdFromCookie() { return r.isRequestedSessionIdFromCookie(); } public boolean isRequestedSessionIdFromURL() { return r.isRequestedSessionIdFromURL(); } @Deprecated public boolean isRequestedSessionIdFromUrl() { return r.isRequestedSessionIdFromUrl(); } public Object getAttribute(String s) { return r.getAttribute(s); } public Enumeration getAttributeNames() { return r.getAttributeNames(); } public String getCharacterEncoding() { return r.getCharacterEncoding(); } public void setCharacterEncoding(String s) throws UnsupportedEncodingException { r.setCharacterEncoding(s); } public int getContentLength() { return r.getContentLength(); } public String getContentType() { return r.getContentType(); } public ServletInputStream getInputStream() throws IOException { return r.getInputStream(); } public String getParameter(String s) { return r.getParameter(s); } public Enumeration getParameterNames() { return r.getParameterNames(); } public String[] getParameterValues(String s) { return r.getParameterValues(s); } public Map getParameterMap() { return r.getParameterMap(); } public String getProtocol() { return r.getProtocol(); } public String getScheme() { return r.getScheme(); } public String getServerName() { return r.getServerName(); } public int getServerPort() { return r.getServerPort(); } public BufferedReader getReader() throws IOException { return r.getReader(); } public String getRemoteAddr() { return r.getRemoteAddr(); } public String getRemoteHost() { return r.getRemoteHost(); } public void setAttribute(String s, Object o) { r.setAttribute(s, o); } public void removeAttribute(String s) { r.removeAttribute(s); } public Locale getLocale() { return r.getLocale(); } public Enumeration getLocales() { return r.getLocales(); } public boolean isSecure() { return r.isSecure(); } public RequestDispatcher getRequestDispatcher(String s) { return r.getRequestDispatcher(s); } @Deprecated public String getRealPath(String s) { return r.getRealPath(s); } public int getRemotePort() { return r.getRemotePort(); } public String getLocalName() { return r.getLocalName(); } public String getLocalAddr() { return r.getLocalAddr(); } public int getLocalPort() { return r.getLocalPort(); } } }
package org.appwork.utils.swing; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Polygon; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.Timer; import org.appwork.swing.components.tooltips.ExtTooltip; import org.appwork.swing.components.tooltips.ToolTipController; import org.appwork.swing.components.tooltips.ToolTipHandler; import org.appwork.swing.components.tooltips.TooltipTextDelegateFactory; import org.appwork.utils.NullsafeAtomicReference; import org.appwork.utils.formatter.SizeFormatter; import org.appwork.utils.locale._AWU; import org.appwork.utils.swing.graph.Limiter; /** * @author thomas * */ abstract public class Graph extends JPanel implements ToolTipHandler { private static final long serialVersionUID = 6943108941655020136L; private int i; private int[] cache; private transient NullsafeAtomicReference<Thread> fetcherThread = new NullsafeAtomicReference<Thread>(null); private int interval = 1000; private final Object LOCK = new Object(); private Color currentColorTop; private Color currentColorBottom; public long average; private int[] averageCache; private Color averageColor = new Color(0x333333); private Color averageTextColor = new Color(0); private int capacity = 0; private Color textColor = new Color(0); protected int value; private Font textFont; private int all; private Limiter[] limiter; private TooltipTextDelegateFactory tooltipFactory; private boolean antiAliasing = false; public Graph() { this(60, 1000); } public Graph(final int capacity, final int interval) { this.tooltipFactory = new TooltipTextDelegateFactory(this); // ToolTipController.getInstance(). this.currentColorTop = new Color(100, 100, 100, 40); this.currentColorBottom = new Color(100, 100, 100, 80); this.average = 0; this.setInterval(interval); this.setCapacity(capacity); this.setOpaque(false); } public ExtTooltip createExtTooltip(final Point mousePosition) { return this.getTooltipFactory().createTooltip(); } /** * @return */ protected String createTooltipText() { return this.getAverageSpeedString() + " " + this.getSpeedString(); } /** * @return the averageColor */ public Color getAverageColor() { return this.averageColor; } public long getAverageSpeed() { if (this.all == 0) { return 0; } return this.average / this.all; } /** * @return */ public String getAverageSpeedString() { // TODO Auto-generated method stub if (this.all <= 0) { return null; } return _AWU.T.AppWorkUtils_Graph_getAverageSpeedString(SizeFormatter.formatBytes(this.average / this.all)); } /** * @return the averageTextColor */ public Color getAverageTextColor() { return this.averageTextColor; } /** * @return the colorB */ public Color getCurrentColorBottom() { return this.currentColorBottom; } /** * @return the colorA */ public Color getCurrentColorTop() { return this.currentColorTop; } public int getInterval() { return this.interval; } /** * @return */ public Limiter[] getLimiter() { return this.limiter; } /** * @return */ protected int getPaintHeight() { return this.getHeight(); } /** * @return */ public String getSpeedString() { // TODO Auto-generated method stub if (this.all <= 0) { return null; } return _AWU.T.AppWorkUtils_Graph_getSpeedString(SizeFormatter.formatBytes(this.value)); } /** * @return the textColor */ public Color getTextColor() { return this.textColor; } /** * @return the textFont */ public Font getTextFont() { return this.textFont; } public int getTooltipDelay(final Point mousePositionOnScreen) { return 0; } public TooltipTextDelegateFactory getTooltipFactory() { return this.tooltipFactory; } /** * @return */ abstract public int getValue(); /** * @return the antiAliasing */ public boolean isAntiAliasing() { return this.antiAliasing; } public boolean isTooltipDisabledUntilNextRefocus() { return false; } @Override public boolean isTooltipWithoutFocusEnabled() { // TODO Auto-generated method stub return true; } @Override public void paintComponent(final Graphics g) { super.paintComponent(g); this.paintComponent(g, true); } /** * @param g * @param b */ public void paintComponent(final Graphics g, final boolean paintText) { final Thread thread = this.fetcherThread.get(); if (thread != null) { final Graphics2D g2 = (Graphics2D) g; if (!this.antiAliasing) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } else { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } g2.setStroke(new BasicStroke(1)); int id = this.i; int max = 10; for (final int element : this.cache) { max = Math.max(element, max); } for (final int element : this.averageCache) { max = Math.max(element, max); } Limiter[] limitertmp = null; if ((limitertmp = this.getLimiter()) != null) { for (final Limiter l : limitertmp) { max = Math.max(l.getValue(), max); } } final int height = this.getPaintHeight(); final Polygon poly = new Polygon(); poly.addPoint(0, this.getHeight()); final Polygon apoly = new Polygon(); apoly.addPoint(0, this.getHeight()); final int[] lCache = this.cache; final int[] laverageCache = this.averageCache; for (int x = 0; x < lCache.length; x++) { poly.addPoint(x * this.getWidth() / (lCache.length - 1), this.getHeight() - (int) (height * lCache[id] * 0.9) / max); if (this.averageColor != null) { apoly.addPoint(x * this.getWidth() / (lCache.length - 1), this.getHeight() - (int) (height * laverageCache[id] * 0.9) / max); } id++; id = id % lCache.length; } poly.addPoint(this.getWidth(), this.getHeight()); apoly.addPoint(this.getWidth(), this.getHeight()); g2.setPaint(new GradientPaint(this.getWidth() / 2, this.getHeight() - this.getPaintHeight(), this.currentColorTop, this.getWidth() / 2, this.getHeight(), this.currentColorBottom)); g2.fill(poly); g2.setColor(this.currentColorBottom); g2.draw(poly); if (this.averageColor != null) { ((Graphics2D) g).setColor(this.averageColor); final AlphaComposite ac5 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f); g2.setComposite(ac5); g2.fill(apoly); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); g2.draw(apoly); } if (limitertmp != null) { int h; for (final Limiter l : limitertmp) { if (l.getValue() > 0) { h = this.getHeight() - (int) (height * l.getValue() * 0.9) / max; g2.setPaint(new GradientPaint(this.getWidth() / 2, h, l.getColorA(), this.getWidth() / 2, h + height / 10, l.getColorB())); g2.fillRect(0, h, this.getWidth(), height / 10); // g2.drawRect(0, h, this.getWidth(), height / 5); } } } // Draw speed string if (paintText) { int xText = this.getWidth(); if (this.textFont != null) { g2.setFont(this.textFont); } // current speed String speedString = this.getSpeedString(); if (speedString != null && thread != null) { g2.setColor(this.getTextColor()); // align right. move left xText = xText - 3 - g2.getFontMetrics().stringWidth(speedString); g2.drawString(speedString, xText, 12); } // average speed if (this.getAverageTextColor() != null) { speedString = this.getAverageSpeedString(); if (speedString != null && thread != null) { g2.setColor(this.getAverageTextColor()); xText = xText - 3 - g2.getFontMetrics().stringWidth(speedString); g2.drawString(speedString, xText, 12); } } } } } /** * resets the average cache and makes sure, that the average recalculates * within a few cycles */ protected void resetAverage() { final int tmp = this.all; if (tmp == 0) { this.average = 0; } else { this.average /= tmp; } this.average *= 3; this.all = 3; } /** * @param antiAliasing * the antiAliasing to set */ public void setAntiAliasing(final boolean antiAliasing) { this.antiAliasing = antiAliasing; } /** * @param averageColor * the averageColor to set */ public void setAverageColor(final Color averageColor) { this.averageColor = averageColor; if (averageColor.getAlpha() == 0) { this.averageColor = null; } } /** * @param averageTextColor * the averageTextColor to set */ public void setAverageTextColor(final Color averageTextColor) { this.averageTextColor = averageTextColor; if (averageTextColor.getAlpha() == 0) { this.averageTextColor = null; } } /** * @param j */ protected void setCapacity(final int cap) { if (this.fetcherThread.get() != null) { throw new IllegalStateException("Already started"); } final int[] lcache = new int[cap]; for (int x = 0; x < cap; x++) { lcache[x] = 0; } final int[] laverageCache = new int[cap]; for (int x = 0; x < cap; x++) { laverageCache[x] = 0; } this.capacity = cap; this.averageCache = laverageCache; this.cache = lcache; } /** * @param colorB * the colorB to set */ public void setCurrentColorBottom(final Color colorB) { this.currentColorBottom = colorB; } /** * @param colorA * the colorA to set */ public void setCurrentColorTop(final Color colorA) { this.currentColorTop = colorA; } public void setInterval(final int interval) { this.interval = interval; } public void setLimiter(final Limiter[] limiter) { this.limiter = limiter; } /** * @param textColor * the textColor to set */ public void setTextColor(final Color textColor) { this.textColor = textColor; } /** * @param textFont * the textFont to set */ public void setTextFont(final Font textFont) { this.textFont = textFont; } public void setTooltipFactory(final TooltipTextDelegateFactory tooltipFactory) { this.tooltipFactory = tooltipFactory; } @Override public void setToolTipText(final String text) { this.putClientProperty(JComponent.TOOL_TIP_TEXT_KEY, text); if (text == null || text.length() == 0) { ToolTipController.getInstance().unregister(this); } else { ToolTipController.getInstance().register(this); } } public void start() { synchronized (this.LOCK) { Thread thread = this.fetcherThread.get(); if (thread != null && thread.isAlive()) { // already running return; } this.i = 0; thread = new Thread("Speedmeter updater") { @Override public void run() { Timer painter = null; try { painter = new Timer(Graph.this.getInterval(), new ActionListener() { public void actionPerformed(final ActionEvent e) { synchronized (Graph.this.LOCK) { Graph.this.setToolTipText(Graph.this.createTooltipText()); Graph.this.repaint(); } } }); painter.setRepeats(true); painter.setInitialDelay(0); painter.start(); Graph.this.all = 0; Graph.this.average = 0; while (Thread.currentThread() == Graph.this.fetcherThread.get()) { synchronized (Graph.this.LOCK) { Graph.this.value = Graph.this.getValue(); if (Graph.this.all == Graph.this.cache.length) { Graph.this.average = Graph.this.average - Graph.this.cache[Graph.this.i] + Graph.this.value; } else { Graph.this.average = Graph.this.average + Graph.this.value; } Graph.this.all = Math.min(Graph.this.all + 1, Graph.this.cache.length); Graph.this.averageCache[Graph.this.i] = (int) (Graph.this.average / Graph.this.all); Graph.this.cache[Graph.this.i] = Graph.this.value; Graph.this.i++; Graph.this.i = Graph.this.i % Graph.this.cache.length; } if (this.isInterrupted() || Thread.currentThread() != Graph.this.fetcherThread.get()) { return; } try { Thread.sleep(Graph.this.getInterval()); } catch (final InterruptedException e) { return; } } } finally { synchronized (Graph.this.LOCK) { Graph.this.fetcherThread.compareAndSet(Thread.currentThread(), null); if (painter != null) { painter.stop(); } } new EDTRunner() { @Override protected void runInEDT() { Graph.this.repaint(); } }; } } }; thread.setDaemon(true); this.fetcherThread.set(thread); thread.start(); } } public void stop() { synchronized (this.LOCK) { final Thread oldThread = this.fetcherThread.getAndSet(null); if (oldThread != null) { oldThread.interrupt(); } Graph.this.repaint(); this.setCapacity(this.capacity); } } @Override public boolean updateTooltip(final ExtTooltip activeToolTip, final MouseEvent e) { return false; } }
package org.broad.igv.ui; import org.apache.log4j.Logger; import org.broad.igv.track.AttributeManager; import org.broad.igv.ui.color.ColorUtilities; import org.broad.igv.ui.util.LinkCheckBox; import org.broad.igv.util.ResourceLocator; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.swing.*; import javax.swing.tree.*; import java.awt.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.*; import java.util.List; import static org.broad.igv.util.ResourceLocator.AttributeType.*; /** * Parses XML file of IGV resources, and displays them in tree format. * * @author eflakes */ public class ResourceTree { private StringBuffer buffer = new StringBuffer(); private static String FAILED_TO_CREATE_RESOURCE_TREE_DIALOG = "Failure while creating the resource tree dialog"; private static Logger log = Logger.getLogger(ResourceTree.class); private static String XML_ROOT = "Global"; private List<CheckableResource> leafResources = new ArrayList(); private HashMap<String, TreeNode> leafNodeMap = new HashMap(); private JTree tree; private Set<String> selectedLeafNodePaths = new LinkedHashSet(); private static enum TreeExpansionFlag { EXPAND_ALL, EXPAND_ROOT_ONLY, EXPAND_SELECTED_ONLY, } private ResourceTree() { } static class CancelableOptionPane extends JOptionPane { private boolean canceled = false; CancelableOptionPane(Object o, int i, int i1) { super(o, i, i1); } public boolean isCanceled() { return canceled; } public void setCanceled(boolean canceled) { this.canceled = canceled; } } /** * Shows a tree of selectable resources. * * @param document The document that represents an XML resource tree. * @param dialogTitle * @return the resources selected by user. */ public static LinkedHashSet<ResourceLocator> showResourceTreeDialog(Component parent, Document document, String dialogTitle) { JDialog dialog = null; final LinkedHashSet<ResourceLocator> locators = new LinkedHashSet(); try { final ResourceTree resourceTree = new ResourceTree(); final JTree dialogTree = resourceTree.createTreeFromDOM(document); int optionType = JOptionPane.OK_CANCEL_OPTION; int messageType = JOptionPane.PLAIN_MESSAGE; final CancelableOptionPane optionPane = new CancelableOptionPane(new JScrollPane(dialogTree), messageType, optionType); optionPane.setPreferredSize(new Dimension(650, 500)); optionPane.setOpaque(true); optionPane.setBackground(Color.WHITE); optionPane.addPropertyChangeListener(JOptionPane.VALUE_PROPERTY, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { Object value = e.getNewValue(); if (value instanceof Integer) { int option = (Integer) value; if (option == JOptionPane.CANCEL_OPTION) { optionPane.setCanceled(true); } else { LinkedHashSet<ResourceLocator> selectedLocators = resourceTree.getSelectedResourceLocators(); for (ResourceLocator locator : selectedLocators) { locators.add(locator); } } } } }); dialog = optionPane.createDialog(parent, (dialogTitle == null ? "Resource Tree" : dialogTitle)); dialog.setBackground(Color.WHITE); dialog.getContentPane().setBackground(Color.WHITE); Component[] children = optionPane.getComponents(); if (children != null) { for (Component child : children) { child.setBackground(Color.WHITE); } } dialog.setResizable(true); dialog.pack(); dialog.setLocationRelativeTo(parent); dialog.setVisible(true); return optionPane.isCanceled() ? null : locators; } catch (Exception e) { log.error(FAILED_TO_CREATE_RESOURCE_TREE_DIALOG, e); return null; } } private void initTree(DefaultMutableTreeNode rootNode) { tree = new JTree(rootNode); tree.setExpandsSelectedPaths(true); tree.setCellRenderer(new NodeRenderer()); tree.setCellEditor(new ResourceEditor(tree)); tree.setEditable(true); } private JTree createTreeFromDOM(Document document) { Element rootElement = (Element) document.getElementsByTagName(XML_ROOT).item(0); if (rootElement == null) { return new JTree(new DefaultMutableTreeNode("")); } String nodeName = rootElement.getNodeName(); if (!nodeName.equalsIgnoreCase(XML_ROOT)) { throw new RuntimeException(rootElement + " is not the root of the xml document!"); } String rootLabel = getAttribute(rootElement, "name"); DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(rootLabel); initTree(rootNode); Set<ResourceLocator> loadedResources = IGV.hasInstance() ? IGV.getInstance().getDataResourceLocators() : Collections.<ResourceLocator>emptySet(); loadedResources.addAll(AttributeManager.getInstance().getLoadedResources()); // Build and attach descendants of the root node to the tree buildLocatorTree(rootNode, rootElement, loadedResources, this); // Force proper checks on startup recheckTree(); expandTree(TreeExpansionFlag.EXPAND_SELECTED_ONLY, true); tree.updateUI(); // Tree state not always correct without this call return tree; } /** * Build a tree of all resources, placed under {@code treeNode}, starting * from {@code xmlNode}. * * @param treeNode * @param xmlNode * @param alreadyLoaded Resources which have already been loaded. These will be checked * @param resourceTree ResourceTree instance. Can be null if not intending UI interaction */ public static void buildLocatorTree(DefaultMutableTreeNode treeNode, Element xmlNode, Set<ResourceLocator> alreadyLoaded, ResourceTree resourceTree) { String name = getAttribute(xmlNode, NAME.getText()); ResourceLocator locator = new ResourceLocator( getAttribute(xmlNode, SERVER_URL.getText()), getAttribute(xmlNode, PATH.getText()) ); locator.setName(name); String infoLink = getAttribute(xmlNode, HYPERLINK.getText()); if (infoLink == null) { infoLink = getAttribute(xmlNode, INFOLINK.getText()); } locator.setInfolink(infoLink); if (xmlNode.getTagName().equalsIgnoreCase("Resource")) { String resourceType = getAttribute(xmlNode, RESOURCE_TYPE.getText()); locator.setType(resourceType); String sampleId = getAttribute(xmlNode, SAMPLE_ID.getText()); if (sampleId == null) { // legacy option sampleId = getAttribute(xmlNode, ID.getText()); } locator.setSampleId(sampleId); locator.setUrl(getAttribute(xmlNode, URL.getText())); locator.setDescription(getAttribute(xmlNode, DESCRIPTION.getText())); locator.setTrackLine(getAttribute(xmlNode, TRACK_LINE.getText())); locator.setName(name); // Special element for alignment tracks locator.setCoverage(getAttribute(xmlNode, COVERAGE.getText())); String colorString = getAttribute(xmlNode, COLOR.getText()); if (colorString != null) { try { Color c = ColorUtilities.stringToColor(colorString); locator.setColor(c); } catch (Exception e) { log.error("Error setting color: ", e); } } } NodeList nodeList = xmlNode.getChildNodes(); Node xmlChildNode; // If we have children treat it as a category not a leaf for (int i = 0; i < nodeList.getLength(); i++) { xmlChildNode = nodeList.item(i); String nodeName = xmlChildNode.getNodeName(); if (nodeName.equalsIgnoreCase("#text")) { continue; } // Need to check class of child node, its not necessarily an // element (could be a comment for example). if (xmlChildNode instanceof Element) { String categoryLabel = getAttribute((Element) xmlChildNode, NAME.getText()); DefaultMutableTreeNode treeChildNode = new DefaultMutableTreeNode(categoryLabel); treeNode.add(treeChildNode); buildLocatorTree(treeChildNode, (Element) xmlChildNode, alreadyLoaded, resourceTree); } } CheckableResource resource = new CheckableResource(name, false, locator); treeNode.setUserObject(resource); if (resourceTree != null) { resource.setEnabled(resourceTree.tree.isEnabled()); // If it's a leaf set the checkbox to represent the resource if (treeNode.isLeaf()) { resourceTree.expandPath(new TreePath(treeNode.getPath())); treeNode.setAllowsChildren(false); // If data already loaded disable the check box if (alreadyLoaded.contains(locator)) { resource.setEnabled(false); resource.setSelected(true); resourceTree.checkParentNode(treeNode, true); } resourceTree.leafResources.add(resource); } else { treeNode.setAllowsChildren(true); boolean hasSelectedChildren = resourceTree.hasSelectedChildren(treeNode); resource.setSelected(hasSelectedChildren); if (true || hasSelectedChildren) { ResourceEditor.checkOrUncheckParentNodesRecursively(treeNode, true); } } // Store the paths to all the leaf nodes for easy access if (treeNode.isLeaf()) { resourceTree.leafNodeMap.put(resourceTree.getPath(treeNode), treeNode); } } } public TreeNode checkParentNode(TreeNode childNode, boolean isSelected) { TreeNode parentNode = childNode.getParent(); Object parentsUserObject = ((DefaultMutableTreeNode) parentNode).getUserObject(); if (parentsUserObject instanceof CheckableResource) { CheckableResource parentResource = ((CheckableResource) parentsUserObject); if (parentResource.isEnabled()) { parentResource.setSelected(isSelected); } } return parentNode; } public List<CheckableResource> getLeafResources() { return leafResources; } public LinkedHashSet<ResourceLocator> getSelectedResourceLocators() { LinkedHashSet<ResourceLocator> resourceLocators = new LinkedHashSet(); for (CheckableResource resource : leafResources) { if (resource.isSelected()) { resourceLocators.add(resource.getResourceLocator()); } } return resourceLocators; } private static String getAttribute(Element element, String key) { String value = element.getAttribute(key); if (value != null) { if (value.trim().equals("")) { value = null; } } return value; } private LinkedHashSet<DefaultMutableTreeNode> findSelectedLeafNodes( TreeModel model, TreeNode parentNode, LinkedHashSet<DefaultMutableTreeNode> allCheckedLeafNodes) { if (allCheckedLeafNodes == null) { allCheckedLeafNodes = new LinkedHashSet(); } int count = model.getChildCount(parentNode); for (int i = 0; i < count; i++) { TreeNode childNode = (TreeNode) model.getChild(parentNode, i); if (!childNode.isLeaf()) { findSelectedLeafNodes(model, childNode, allCheckedLeafNodes); } else { DefaultMutableTreeNode node = (DefaultMutableTreeNode) childNode; CheckableResource resource = (CheckableResource) node.getUserObject(); if (resource.isSelected()) { allCheckedLeafNodes.add(node); } } } return allCheckedLeafNodes; } /** * Node's Renderer */ static class NodeRenderer implements TreeCellRenderer { private LinkCheckBox renderer = new LinkCheckBox(); private Color selectionForeground; private Color selectionBackground; private Color textForeground; private Color textBackground; public NodeRenderer() { Font fontValue; fontValue = UIManager.getFont("Tree.font"); if (fontValue != null) { renderer.setFont(fontValue); } Boolean booleanValue = (Boolean) UIManager.get("Tree.drawsFocusBorderAroundIcon"); renderer.setFocusPainted( (booleanValue != null) && (booleanValue.booleanValue())); selectionForeground = UIManager.getColor("Tree.selectionForeground"); selectionBackground = UIManager.getColor("Tree.selectionBackground"); textForeground = UIManager.getColor("Tree.textForeground"); textBackground = UIManager.getColor("Tree.textBackground"); renderer.setSelected(false); } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isNodeSelected, boolean isNodeExpanded, boolean isLeaf, int row, boolean hasFocus) { // Convert value into a usable string String stringValue = ""; if (value != null) { String toStringValue = value.toString(); if (toStringValue != null) { stringValue = toStringValue; } } // Initialize checkbox state and selection renderer.setSelected(false); renderer.setText(stringValue); renderer.setEnabled(tree.isEnabled()); // Tell renderer how to highlight nodes on selection if (isNodeSelected) { renderer.setForeground(selectionForeground); renderer.setBackground(selectionBackground); } else { renderer.setForeground(textForeground); renderer.setBackground(textBackground); } if (value != null) { if (value instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; Object userObject = node.getUserObject(); if (userObject instanceof CheckableResource) { CheckableResource resource = (CheckableResource) userObject; renderer.setText(resource.getText()); renderer.setSelected(resource.isSelected()); renderer.setEnabled(resource.isEnabled()); String hyperLink = resource.getResourceLocator().getInfolink(); if (hyperLink == null) { renderer.showHyperLink(false); } else { renderer.setHyperLink(hyperLink); renderer.showHyperLink(true); } } } } return renderer; } protected LinkCheckBox getRendereringComponent() { return renderer; } } /** * Node's Resource Editor */ static class ResourceEditor extends AbstractCellEditor implements TreeCellEditor { NodeRenderer renderer = new NodeRenderer(); JTree tree; public ResourceEditor(JTree tree) { this.tree = tree; } public Object getCellEditorValue() { DataResource resource = null; TreePath treePath = tree.getEditingPath(); if (treePath != null) { Object node = treePath.getLastPathComponent(); if ((node != null) && (node instanceof DefaultMutableTreeNode)) { LinkCheckBox checkbox = renderer.getRendereringComponent(); DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node; Object userObject = treeNode.getUserObject(); resource = (CheckableResource) userObject; // Don't change resource if disabled if (!resource.isEnabled()) { return resource; } boolean isChecked = checkbox.isSelected(); // Check/Uncheck the selected node. This code ONLY handles // the clicked node. Not it's ancestors or decendants. if (isChecked) { ((CheckableResource) resource).setSelected(true); } else { // See if we are allowed to unchecking this specific // node - if not, it won't be done. This does not // prevent it's children from being unchecked. uncheckCurrentNodeIfAllowed((CheckableResource) resource, treeNode); } /* * Now we have to check or uncheck the descendants and * ancestors depending on what we did above. */ boolean checkRelatives = isChecked; // If we found a mix of select leave and selected but // but disabled leave we must be trying to toggle off // the children if (hasSelectedAndLockedDescendants(treeNode)) { checkRelatives = false; } // If we found only locked leave we must be trying to toggle // on the unlocked children else if (hasLockedDescendants(treeNode)) { checkRelatives = true; } // Otherwise, just use the value of the checkbox if (!treeNode.isLeaf()) { //check up and down the tree // If not a leaf check/uncheck children as requested checkOrUncheckChildNodesRecursively(treeNode, checkRelatives); // If not a leaf check/uncheck ancestors checkOrUncheckParentNodesRecursively(treeNode, ((CheckableResource) resource).isSelected()); } else { // it must be a leaf - so check up the tree checkOrUncheckParentNodesRecursively(treeNode, checkRelatives); } } tree.treeDidChange(); } return resource; } /* * Uncheck a node unless rule prevent this behavior. */ private void uncheckCurrentNodeIfAllowed(CheckableResource resource, TreeNode treeNode) { // If we are unchecking a parent make sure there are // no checked children if (!hasSelectedChildren(treeNode)) { ((CheckableResource) resource).setSelected(false); } else { // If node has selected children and has disabled descendants we // must not unselect if (hasLockedDescendants(treeNode)) { ((CheckableResource) resource).setSelected(true); } else { // No disabled descendants so we can uncheck at will ((CheckableResource) resource).setSelected(false); } } } /** * Call to recursively check or uncheck the parent ancestors of the * passed node. */ static public void checkOrUncheckParentNodesRecursively(TreeNode node, boolean checkParentNode) { if (node == null) { return; } TreeNode parentNode = node.getParent(); if (parentNode == null) { return; } Object parentUserObject = ((DefaultMutableTreeNode) parentNode).getUserObject(); CheckableResource parentNodeResource = null; if (parentUserObject instanceof CheckableResource) { parentNodeResource = ((CheckableResource) parentUserObject); } if (parentNodeResource != null) { // If parent's current check state matchs what we want there // is nothing to do so just leave if (parentNodeResource.isSelected() == checkParentNode) { return; } else if (checkParentNode) { parentNodeResource.setSelected(true); } else { // Uncheck Only if their are no selected descendants if (!hasSelectedChildren(parentNode)) { parentNodeResource.setSelected(false); } } } checkOrUncheckParentNodesRecursively(parentNode, checkParentNode); } /** * Can only be called from getCellEditorValue() to recursively check * or uncheck the children of the passed parent node. */ private void checkOrUncheckChildNodesRecursively(TreeNode currentNode, boolean isCheckingNeeded) { Object parentUserObject = ((DefaultMutableTreeNode) currentNode).getUserObject(); CheckableResource currentTreeNodeResource = null; if (parentUserObject instanceof CheckableResource) { currentTreeNodeResource = ((CheckableResource) parentUserObject); } if (currentTreeNodeResource != null) { // Set all enabled children to the checked state of their parent Enumeration children = currentNode.children(); while (children.hasMoreElements()) { TreeNode childNode = (TreeNode) children.nextElement(); Object childsUserObject = ((DefaultMutableTreeNode) childNode).getUserObject(); if (childsUserObject instanceof CheckableResource) { CheckableResource childResource = ((CheckableResource) childsUserObject); if (childResource.isEnabled()) { // Child must be checked if it has selected // selected and disabled descendants if (hasLockedDescendants(childNode)) { childResource.setSelected(true); } else { // else check/uncheck as requested childResource.setSelected(isCheckingNeeded); } } } checkOrUncheckChildNodesRecursively(childNode, isCheckingNeeded); } } } public boolean hasLockedDescendants(TreeNode treeNode) { Enumeration children = treeNode.children(); while (children.hasMoreElements()) { TreeNode childNode = (TreeNode) children.nextElement(); Object childsUserObject = ((DefaultMutableTreeNode) childNode).getUserObject(); if (childsUserObject instanceof CheckableResource) { CheckableResource childResource = ((CheckableResource) childsUserObject); // If disabled say so if (!childResource.isEnabled()) { return true; } } // If a descendant is disabled say so if (hasLockedDescendants(childNode)) { return true; } } return false; } static public boolean hasSelectedDescendants(TreeNode treeNode) { Enumeration children = treeNode.children(); while (children.hasMoreElements()) { TreeNode childNode = (TreeNode) children.nextElement(); Object childsUserObject = ((DefaultMutableTreeNode) childNode).getUserObject(); if (childsUserObject instanceof CheckableResource) { CheckableResource childResource = ((CheckableResource) childsUserObject); // If has selected say so if (childResource.isSelected()) { return true; } } // If has selected descendant say so if (hasSelectedDescendants(childNode)) { return true; } } return false; } static public boolean hasSelectedChildren(TreeNode treeNode) { Enumeration children = treeNode.children(); while (children.hasMoreElements()) { TreeNode childNode = (TreeNode) children.nextElement(); Object childsUserObject = ((DefaultMutableTreeNode) childNode).getUserObject(); if (childsUserObject instanceof CheckableResource) { CheckableResource childResource = ((CheckableResource) childsUserObject); if (childResource.isSelected()) { return true; } } } return false; } /** * Return true if it find nodes that ar both selected and disabled * * @param treeNode * @return true if we are working with preselected nodes */ public boolean hasLockedChildren(TreeNode treeNode) { boolean hasSelectedAndDisabled = false; Enumeration children = treeNode.children(); while (children.hasMoreElements()) { TreeNode childNode = (TreeNode) children.nextElement(); Object childsUserObject = ((DefaultMutableTreeNode) childNode).getUserObject(); if (childsUserObject instanceof CheckableResource) { CheckableResource childResource = ((CheckableResource) childsUserObject); if (!childResource.isEnabled() && childResource.isSelected()) { hasSelectedAndDisabled = true; } if (hasSelectedAndDisabled) { break; } } } return (hasSelectedAndDisabled); } /** * @param treeNode * @return true if we are working with preselected nodes */ public boolean hasSelectedAndLockedChildren(TreeNode treeNode) { boolean hasSelected = false; boolean hasSelectedAndDisabled = false; Enumeration children = treeNode.children(); while (children.hasMoreElements()) { TreeNode childNode = (TreeNode) children.nextElement(); Object childsUserObject = ((DefaultMutableTreeNode) childNode).getUserObject(); if (childsUserObject instanceof CheckableResource) { CheckableResource childResource = ((CheckableResource) childsUserObject); if (childResource.isSelected() && childResource.isEnabled()) { hasSelected = true; } if (!childResource.isEnabled() && childResource.isSelected()) { hasSelectedAndDisabled = true; } if (hasSelected & hasSelectedAndDisabled) { break; } } } // If we have both we can return true return (hasSelected & hasSelectedAndDisabled); } /** * @param treeNode * @return true if we are working with preselected nodes */ public boolean hasSelectedAndLockedDescendants(TreeNode treeNode) { boolean hasSelected = false; boolean hasSelectedAndDisabled = false; Enumeration children = treeNode.children(); while (children.hasMoreElements()) { TreeNode childNode = (TreeNode) children.nextElement(); Object childsUserObject = ((DefaultMutableTreeNode) childNode).getUserObject(); if (childsUserObject instanceof CheckableResource) { CheckableResource childResource = ((CheckableResource) childsUserObject); if (childResource.isSelected() && childResource.isEnabled()) { hasSelected = true; } if (!childResource.isEnabled() && childResource.isSelected()) { hasSelectedAndDisabled = true; } if (hasSelected & hasSelectedAndDisabled) { break; } } // If has a mix of selected and checked but disableddescendant if (hasSelectedAndLockedDescendants(childNode)) { return true; } } // If we have both we can return true return (hasSelected & hasSelectedAndDisabled); } @Override public boolean isCellEditable(EventObject event) { boolean returnValue = false; if (event instanceof MouseEvent) { MouseEvent mouseEvent = (MouseEvent) event; TreePath treePath = tree.getPathForLocation( mouseEvent.getX(), mouseEvent.getY()); if (treePath != null) { Object node = treePath.getLastPathComponent(); if ((node != null) && (node instanceof DefaultMutableTreeNode)) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node; Object userObject = treeNode.getUserObject(); if (userObject instanceof CheckableResource) { returnValue = true; } else if (userObject instanceof CheckableResource) { returnValue = true; } } } } return returnValue; } public Component getTreeCellEditorComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row) { Component rendererComponent = renderer.getTreeCellRendererComponent( tree, value, true, expanded, leaf, row, true); ItemListener itemListener = new ItemListener() { public void itemStateChanged(ItemEvent itemEvent) { if (stopCellEditing()) { fireEditingStopped(); } } }; if (rendererComponent instanceof LinkCheckBox) { ((LinkCheckBox) rendererComponent).addItemListener(itemListener); } return rendererComponent; } } public static class CheckableResource implements SelectableResource { final static protected Color partialSelectionColor = new Color(255, 128, 128); protected boolean isParentOfPartiallySelectedChildren = false; protected String text; protected boolean selected; protected ResourceLocator dataResourceLocator; protected boolean isEnabled = true; public CheckableResource() { } public CheckableResource(String text, boolean selected, ResourceLocator dataResourceLocator) { this.text = text; this.selected = selected; this.dataResourceLocator = dataResourceLocator; } public boolean isSelected() { return selected; } public void setSelected(boolean newValue) { selected = newValue; } public boolean isEnabled() { return isEnabled; } public void setEnabled(boolean value) { isEnabled = value; } public String getText() { return text; } public void setText(String newValue) { text = newValue; } public ResourceLocator getResourceLocator() { return dataResourceLocator; } public void setResourceLocator(ResourceLocator dataResourceLocator) { this.dataResourceLocator = dataResourceLocator; } public boolean isParentOfPartiallySelectedChildren() { return isParentOfPartiallySelectedChildren; } public void setIsParentOfPartiallySelectedChildren(boolean value) { this.isParentOfPartiallySelectedChildren = value; } public Color getBackground() { if (isParentOfPartiallySelectedChildren()) { return partialSelectionColor; } else { return Color.WHITE; } } @Override public String toString() { return text + ":" + selected; } } static interface SelectableResource extends DataResource { public boolean isSelected(); public void setSelected(boolean newValue); } static interface DataResource { public ResourceLocator getResourceLocator(); public void setText(String newValue); public String getText(); public void setEnabled(boolean value); public boolean isEnabled(); } /** * Expands tree. */ private void expandTree(TreeExpansionFlag expansionFlag, boolean skipSelectingEnabledNodes) { TreeNode root = (TreeNode) tree.getModel().getRoot(); if (expansionFlag == TreeExpansionFlag.EXPAND_SELECTED_ONLY) { if (selectedLeafNodePaths.isEmpty()) { TreePath rootPath = new TreePath(root); expandPath(rootPath); } else { boolean[] expansionVetoed = {true}; // Default to not expanded expandSelectedDescendants(new TreePath(root), true, expansionVetoed, skipSelectingEnabledNodes); } } else if (expansionFlag == TreeExpansionFlag.EXPAND_ALL) { expandAllDescendants(new TreePath(root), true, skipSelectingEnabledNodes); } else if (expansionFlag == TreeExpansionFlag.EXPAND_ROOT_ONLY) { TreePath rootPath = new TreePath(root); expandPath(rootPath); checkAllSelectedLeafNodes(rootPath, skipSelectingEnabledNodes); } } /** * Expands all children of a tree node. */ private void expandAllDescendants(TreePath parentPath, boolean isExpanding, boolean skipSelectingEnabledNodes) { // Traverse children TreeNode node = (TreeNode) parentPath.getLastPathComponent(); for (Enumeration e = node.children(); e.hasMoreElements(); ) { TreeNode n = (TreeNode) e.nextElement(); TreePath childPath = parentPath.pathByAddingChild(n); expandAllDescendants(childPath, isExpanding, skipSelectingEnabledNodes); } // Expansion or collapse must be done bottom-up if (isExpanding) { expandPath(parentPath); } else { collapsePath(parentPath); } // Leaf nodes processing if (node.isLeaf()) { String path = getPath((DefaultMutableTreeNode) node); if (selectedLeafNodePaths.contains(path)) { manuallySelectNode((DefaultMutableTreeNode) node, skipSelectingEnabledNodes); } } } /** * Expands all children of a tree node. */ private void expandSelectedDescendants(TreePath parentPath, boolean isExpanding, boolean[] expansionVetoed, boolean skipSelectingEnabledNodes) { boolean[] expansionIsVetoed = {true}; // true: Defaults to not expanded // Traverse children TreeNode node = (TreeNode) parentPath.getLastPathComponent(); for (Enumeration e = node.children(); e.hasMoreElements(); ) { DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) e.nextElement(); // Leaf nodes processing if (childNode.isLeaf()) { String path = getPath(childNode); if (selectedLeafNodePaths.contains(path)) { manuallySelectNode(childNode, skipSelectingEnabledNodes); expansionIsVetoed[0] = false; } } TreePath childPath = parentPath.pathByAddingChild(childNode); expandSelectedDescendants(childPath, isExpanding, expansionVetoed, skipSelectingEnabledNodes); } if (expansionIsVetoed[0]) return; // Expansion or collapse must be done bottom-up if (isExpanding) { expandPath(parentPath); } else { collapsePath(parentPath); } } private String getPath(DefaultMutableTreeNode treeNode) { buffer.delete(0, buffer.length()); TreeNode[] nodesInPath = treeNode.getPath(); for (Object element : nodesInPath) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) element; Object userObject = node.getUserObject(); if (userObject instanceof CheckableResource) { CheckableResource resource = (CheckableResource) userObject; buffer.append(resource.getText()); if (!node.isLeaf()) { buffer.append("/"); } } else if (userObject instanceof CheckableResource) { CheckableResource resource = (CheckableResource) userObject; buffer.append(resource.getText()); if (!node.isLeaf()) { buffer.append("/"); } } else { buffer.append(userObject.toString()); if (!node.isLeaf()) { buffer.append("/"); } } } return buffer.toString(); } private void manuallySelectNode(DefaultMutableTreeNode childNode, boolean skipSelectingEnabledNodes) { Object userObject = childNode.getUserObject(); if (userObject instanceof CheckableResource) { CheckableResource resource = (CheckableResource) userObject; // Leave if node is disable if (skipSelectingEnabledNodes && resource.isEnabled()) { return; } // Don't select the node if already selected if (resource.isSelected()) return; resource.setSelected(true); if (childNode.isLeaf()) { TreeNode parentNode = childNode.getParent(); Object parentsUserObject = ((DefaultMutableTreeNode) parentNode).getUserObject(); if (parentsUserObject instanceof CheckableResource) { CheckableResource parentResource = ((CheckableResource) parentsUserObject); if (!parentResource.isSelected()) { parentResource.setSelected(true); } tree.treeDidChange(); } } } } private void checkAllSelectedLeafNodes(TreePath parentPath, boolean skipSelectingEnabledNodes) { // Traverse children TreeNode node = (TreeNode) parentPath.getLastPathComponent(); for (Enumeration e = node.children(); e.hasMoreElements(); ) { TreeNode n = (TreeNode) e.nextElement(); TreePath childPath = parentPath.pathByAddingChild(n); checkAllSelectedLeafNodes(childPath, skipSelectingEnabledNodes); } // Leaf nodes processing if (node.isLeaf()) { String path = getPath((DefaultMutableTreeNode) node); if (selectedLeafNodePaths.contains(path)) { manuallySelectNode((DefaultMutableTreeNode) node, skipSelectingEnabledNodes); } } } private void collapsePath(TreePath treePath) { if (!tree.isCollapsed(treePath)) { tree.collapsePath(treePath); } } private void expandPath(TreePath treePath) { if (!tree.isExpanded(treePath)) { tree.expandPath(treePath); } } public boolean hasSelectedChildren(TreeNode treeNode) { Enumeration children = treeNode.children(); while (children.hasMoreElements()) { TreeNode childNode = (TreeNode) children.nextElement(); Object childsUserObject = ((DefaultMutableTreeNode) childNode).getUserObject(); if (childsUserObject instanceof CheckableResource) { CheckableResource childResource = ((CheckableResource) childsUserObject); if (childResource.isSelected()) { return true; } tree.treeDidChange(); } } return false; } static private Set<ResourceLocator> getLoadedResources() { Set<ResourceLocator> loadedResources = IGV.getInstance().getDataResourceLocators(); loadedResources.addAll(AttributeManager.getInstance().getLoadedResources()); return loadedResources; } /** * This method will only check tree items. */ private void recheckTree() { if (leafNodeMap != null && !leafNodeMap.isEmpty()) { Collection<TreeNode> leaves = leafNodeMap.values(); for (TreeNode leafNode : leaves) { TreeNode parent = leafNode.getParent(); if (parent != null) { Object userObject = ((DefaultMutableTreeNode) leafNode).getUserObject(); CheckableResource checkableLeafResource = ((CheckableResource) userObject); if (userObject != null) { if (checkableLeafResource.isSelected()) { checkNode(parent, true); while (true) { parent = parent.getParent(); if (parent == null) { break; } checkNode(parent, true); } } } } } } } protected void checkNode(TreeNode node, boolean checked) { // Only allowed to check if (!checked) return; Object userObject = ((DefaultMutableTreeNode) node).getUserObject(); CheckableResource nodeResource = null; if (userObject instanceof CheckableResource) { nodeResource = ((CheckableResource) userObject); nodeResource.setSelected(checked); } } }
package org.exist.config; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.log4j.Logger; import org.exist.EXistException; import org.exist.collections.Collection; import org.exist.collections.IndexInfo; import org.exist.config.annotation.ConfigurationClass; import org.exist.config.annotation.ConfigurationFieldAsAttribute; import org.exist.config.annotation.ConfigurationFieldAsElement; import org.exist.config.annotation.ConfigurationFieldSettings; import org.exist.dom.DocumentAtExist; import org.exist.dom.DocumentImpl; import org.exist.dom.ElementAtExist; import org.exist.memtree.SAXAdapter; import org.exist.security.Subject; import org.exist.storage.BrokerPool; import org.exist.storage.DBBroker; import org.exist.storage.lock.Lock; import org.exist.storage.sync.Sync; import org.exist.storage.txn.TransactionManager; import org.exist.storage.txn.Txn; import org.exist.util.ConfigurationHelper; import org.exist.util.MimeType; import org.exist.xmldb.XmldbURI; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class Configurator { protected final static Logger LOG = Logger.getLogger(Configurator.class); protected static ConcurrentMap<XmldbURI, Configuration> hotConfigs = new ConcurrentHashMap<XmldbURI, Configuration>(); private static Map<Class<Configurable>, Map<String, Field>> map = new HashMap<Class<Configurable>, Map<String, Field>>(); protected static Map<String, Field> getProperyFieldMap(Class<?> clazz) { if (map.containsKey(clazz)) return map.get(clazz); Map<String, Field> link = new HashMap<String, Field>(); for (Field field : clazz.getDeclaredFields()) { if (field.isAnnotationPresent(ConfigurationFieldAsAttribute.class)) { link.put(field.getAnnotation(ConfigurationFieldAsAttribute.class).value(), field); } else if (field.isAnnotationPresent(ConfigurationFieldAsElement.class)) { link.put(field.getAnnotation(ConfigurationFieldAsElement.class).value(), field); } } Class<?> superClass = clazz.getSuperclass(); if (superClass.isAnnotationPresent(ConfigurationClass.class)) { //if (superClass.getAnnotation(ConfigurationClass.class).value().equals( clazz.getAnnotation(ConfigurationClass.class).value() )) link.putAll( getProperyFieldMap(superClass) ); } return link; } public static Method searchForSetMethod(Class<?> clazz, Field field) { try { String methodName = "set"+field.getName(); methodName = methodName.toLowerCase(); for (Method method : clazz.getMethods()) { if (method.getName().toLowerCase().equals(methodName)) return method; } } catch (SecurityException e) { } catch (NoClassDefFoundError e) { } return null; } public static Method searchForAddMethod(Class<?> clazz, Field field) { try { String methodName = "add"+field.getName(); methodName = methodName.toLowerCase(); for (Method method : clazz.getMethods()) { if (method.getName().toLowerCase().equals(methodName) && method.getParameterTypes().length == 1 && method.getParameterTypes()[0].getName().equals("org.exist.config.Configuration")) return method; } } catch (SecurityException e) { } catch (NoClassDefFoundError e) { } return null; } public static Configuration configure(Configurable instance, Configuration configuration) { if (configuration == null) return null; Class<?> clazz = instance.getClass(); instance.getClass().getAnnotations(); if (!clazz.isAnnotationPresent(ConfigurationClass.class)) { //LOG.info("no configuration name at "+instance.getClass()); return null; } String configName = clazz.getAnnotation(ConfigurationClass.class).value(); Configuration config = configuration.getConfiguration(configName); if (config == null) { System.out.println("no configuration ["+configName+"]"); return null; } if (config instanceof ConfigurationImpl) { ConfigurationImpl impl = (ConfigurationImpl) config; //XXX: lock issue here, fix it Configurable configurable = null; if (impl.configuredObjectReferene != null) configurable = impl.configuredObjectReferene.get(); if (configurable != null) { if (configurable != instance) throw new IllegalArgumentException( "Configuration can't be used by "+instance+", " + "because allready in use by "+configurable); } else impl.configuredObjectReferene = new WeakReference<Configurable>(instance); //end (lock issue) } return configureByCurrent(instance, config); } private static Configuration configureByCurrent(Configurable instance, Configuration configuration) { Map<String, Field> properyFieldMap = getProperyFieldMap(instance.getClass()); Set<String> properties = configuration.getProperties(); if (properties.size() == 0) { //LOG.info("no properties for "+instance.getClass()+" @ "+configuration); return configuration; } //process simple types: String, int, long, boolean for (String property : properties) { if (!properyFieldMap.containsKey(property)) { System.out.println("unused property "+property+" @"+configuration.getName()); continue; } Field field = properyFieldMap.get(property); field.setAccessible(true); Object value = null; String typeName = field.getType().getName(); try { if (typeName.equals("java.lang.String")) { value = configuration.getProperty(property); } else if (typeName.equals("int") || typeName.equals("java.lang.Integer")) { if (field.isAnnotationPresent(ConfigurationFieldSettings.class)) { String settings = field.getAnnotation(ConfigurationFieldSettings.class).value(); int radix = 10; if (settings.startsWith("radix=")) { radix = Integer.valueOf(settings.substring(6)); } value = Integer.valueOf( configuration.getProperty(property), radix ); } else { value = configuration.getPropertyInteger(property); } } else if (typeName.equals("long") || typeName.equals("java.lang.Long")) { value = configuration.getPropertyLong(property); } else if (typeName.equals("boolean") || typeName.equals("java.lang.Boolean")) { value = configuration.getPropertyBoolean(property); } else if (typeName.equals("java.util.List")) { //skip, it will be processed as structure } else if (typeName.equals("org.exist.xmldb.XmldbURI")) { value = org.exist.xmldb.XmldbURI.create( configuration.getProperty(property) ); } else { LOG.warn("skip unsupported configuration value type "+field.getType()); } if (value != null && !value.equals( field.get(instance) ) ) { Method method = searchForSetMethod(instance.getClass(), field); if (method != null) { try { method.invoke(instance, value); } catch (InvocationTargetException e) { method = null; } } if (method == null) field.set(instance, value); } } catch (IllegalArgumentException e) { LOG.error("configuration error: \n" + " config: "+configuration.getName()+"\n" + " property: "+property+"\n" + " message: "+e.getMessage()); return null; //XXX: throw configuration error } catch (IllegalAccessException e) { LOG.error("security error: "+e.getMessage()); return null; //XXX: throw configuration error } } //process simple structures: List try { for (Field field : properyFieldMap.values()) { String typeName = field.getType().getName(); if (typeName.equals("java.util.List")) { if (!field.isAnnotationPresent(ConfigurationFieldAsElement.class)) { LOG.warn("Wrong annotation for strucure: "+field.getName()+", list can't be configurated throw attribute."); continue; } String property = field.getAnnotation(ConfigurationFieldAsElement.class).value(); field.setAccessible(true); List<Configurable> list = (List<Configurable>) field.get(instance); List<Configuration> confs = configuration.getConfigurations(property); if (list == null) { list = new ArrayList<Configurable>(confs.size()); field.set(instance, list); } if (confs != null) { //remove & update for (Iterator<Configurable> iterator = list.iterator() ; iterator.hasNext() ; ) { Configurable obj = iterator.next(); Configuration current_conf = obj.getConfiguration(); if (current_conf == null) { //skip internal staff if (obj instanceof org.exist.security.internal.RealmImpl) { //TODO: static list continue; } else { LOG.warn("Unconfigured instance ["+obj+"], remove the object."); iterator.remove(); continue; } } String id = current_conf.getProperty(Configuration.ID); if (id == null) { LOG.warn("Subconfiguration must have id ["+obj+"], remove the object."); iterator.remove(); continue; } for (Iterator<Configuration> i = confs.iterator() ; i.hasNext() ;) { Configuration conf = i.next(); if (id.equals( conf.getProperty(Configuration.ID) )) { current_conf.checkForUpdates(conf.getElement()); i.remove(); break; } } LOG.info("Configuration was removed, remove the object ["+obj+"]."); iterator.remove(); } //create for (Configuration conf : confs) { Method method = searchForAddMethod(instance.getClass(), field); if (method != null) { try { method.invoke(instance, conf); continue; } catch (InvocationTargetException e) { method = null; } } String id = conf.getProperty(Configuration.ID); if (id == null) { LOG.warn("Subconfiguration must have id ["+conf+"], skip instance creation."); continue; } String clazzName = "org.exist.security.realm."+id.toLowerCase()+"."+id+"Realm"; Class<?> clazz; try { clazz = Class.forName(clazzName); Constructor<Configurable> constructor = (Constructor<Configurable>) clazz.getConstructor(instance.getClass(), Configuration.class); list.add( constructor.newInstance(instance, conf) ); } catch (ClassNotFoundException e) { LOG.warn("Class ["+clazzName+"] not found, skip instance creation."); continue; } catch (SecurityException e) { LOG.warn("Security exception on class ["+clazzName+"] creation, skip instance creation."); continue; } catch (NoSuchMethodException e) { LOG.warn("Class ["+clazzName+"] consctuctor not found, skip instance creation."); continue; } catch (InstantiationException e) { LOG.warn("Instantiation exception on class ["+clazzName+"] creation, skip instance creation."); continue; } catch (InvocationTargetException e) { LOG.warn("Invocation target exception on class ["+clazzName+"] creation, skip instance creation."); continue; } } } } } } catch (IllegalArgumentException e) { e.printStackTrace(); return null; } catch (IllegalAccessException e) { e.printStackTrace(); return null; } return configuration; } // public static Configuration parse(InputStream is) throws ExceptionConfiguration { // throw new ExceptionConfiguration("parser was not implemented"); public static Configuration parse(File file) throws ConfigurationException { try { return parse(new FileInputStream(file)); } catch (FileNotFoundException e) { throw new ConfigurationException(e); } } // public static Configuration parseDefault() throws ExceptionConfiguration { // throw new ExceptionConfiguration("default configuration parser was not implemented"); public static Configuration parse(InputStream is) throws ConfigurationException { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); InputSource src = new InputSource(is); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); SAXAdapter adapter = new SAXAdapter(); reader.setContentHandler(adapter); reader.parse(src); return new ConfigurationImpl((ElementAtExist) adapter.getDocument().getDocumentElement()); } catch (ParserConfigurationException e) { throw new ConfigurationException(e); } catch (SAXException e) { throw new ConfigurationException(e); } catch (IOException e) { throw new ConfigurationException(e); } } public static Configuration parseDefault() throws ConfigurationException { try { return parse(new FileInputStream(ConfigurationHelper.lookup("conf.xml"))); } catch (FileNotFoundException e) { throw new ConfigurationException(e); } } protected static void asXMLtoBuffer(Configurable instance, StringBuilder buf) throws ConfigurationException { Class<?> clazz = instance.getClass(); instance.getClass().getAnnotations(); if (!clazz.isAnnotationPresent(ConfigurationClass.class)) { return; //UNDERSTAND: throw exception } String configName = clazz.getAnnotation(ConfigurationClass.class).value(); //open tag buf.append("<"); buf.append(configName); buf.append(" xmlns='"+Configuration.NS+"'"); StringBuilder bufContext = new StringBuilder(); StringBuilder bufferToUse; boolean simple = true; //store filed's values as attributes or elements depends on annotation Map<String, Field> properyFieldMap = getProperyFieldMap(instance.getClass()); for (Entry<String, Field> entry : properyFieldMap.entrySet()) { simple = true; final Field field = entry.getValue(); field.setAccessible(true); try { //skip null values if (field.get(instance) == null) continue; boolean storeAsAttribute = true; if (field.isAnnotationPresent(ConfigurationFieldAsElement.class)) { storeAsAttribute = false; } if (storeAsAttribute) { buf.append(" "); buf.append(entry.getKey()); buf.append("='"); bufferToUse = buf; } else { bufferToUse = new StringBuilder(); } String typeName = field.getType().getName(); if (typeName.equals("java.lang.String")) { bufferToUse.append(field.get(instance)); } else if (typeName.equals("int") || typeName.equals("java.lang.Integer")) { if (field.isAnnotationPresent(ConfigurationFieldSettings.class)) { String settings = field.getAnnotation(ConfigurationFieldSettings.class).value(); int radix = 10; if (settings.startsWith("radix=")) { try { radix = Integer.valueOf(settings.substring(6)); } catch (Exception e) { //UNDERSTAND: ignore, set back to default or throw error? radix = 10; } } bufferToUse.append(Integer.toString((Integer)field.get(instance), radix) ); } else { bufferToUse.append(field.get(instance)); } } else if (typeName.equals("long") || typeName.equals("java.lang.Long")) { bufferToUse.append(field.get(instance)); } else if (typeName.equals("boolean") || typeName.equals("java.lang.Boolean")) { if ((Boolean) field.get(instance)) { bufferToUse.append("true"); } else { bufferToUse.append("false"); } } else if (typeName.equals("java.util.List")) { simple = false; @SuppressWarnings("unchecked") List<Configurable> list = (List<Configurable>) field.get(instance); for (Configurable el : list) { asXMLtoBuffer(el, bufferToUse); } } else { LOG.warn("field '"+field.getName()+"' have unsupported type ["+typeName+"] - skiped"); //unsupported type - skip //buf.append(field.get(instance)); } if (storeAsAttribute) { buf.append("'"); } else if (bufferToUse.length() > 0){ if (simple) { bufContext.append("<"); bufContext.append(entry.getKey()); bufContext.append(">"); } bufContext.append(bufferToUse); if (simple) { bufContext.append("</"); bufContext.append(entry.getKey()); bufContext.append(">"); } } } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new ConfigurationException(e.getMessage(), e); } } buf.append(">"); buf.append(bufContext); //close tag buf.append("</"); buf.append(configName); buf.append(">"); } public static Configuration parse(Configurable instance, DBBroker broker, Collection collection, XmldbURI fileURL) throws ConfigurationException { Configuration conf; synchronized (hotConfigs) { conf = hotConfigs.get(collection.getURI().append(fileURL)); } if (conf != null) return conf; //XXX: locking required DocumentAtExist document = collection.getDocument(broker, fileURL); if (document == null) { if (broker.isReadOnly()) { //database in read-only mode & there no configuration file, //create in memory document & configuration try { StringBuilder buf = new StringBuilder(); asXMLtoBuffer(instance, buf); if (buf.length() == 0) return null; return parse( new ByteArrayInputStream(buf.toString().getBytes("UTF-8")) ); } catch (UnsupportedEncodingException e) { return null; } } else { try { document = save(instance, broker, collection, fileURL); } catch (IOException e) { return null; } } } if (document == null) return null; //possible on corrupted database, find better solution (recovery flag?) //throw new ConfigurationException("The configuration file can't be found, url = "+collection.getURI().append(fileURL)); ElementAtExist confElement = (ElementAtExist) document.getDocumentElement(); if (confElement == null) return null; //possible on corrupted database, find better solution (recovery flag?) //throw new ConfigurationException("The configuration file is empty, url = "+collection.getURI().append(fileURL)); conf = new ConfigurationImpl(confElement); synchronized (hotConfigs) { hotConfigs.put(document.getURI(), conf); } return conf; } public static Configuration parse(DocumentAtExist document) throws ConfigurationException { if (document == null) return null; Configuration conf; synchronized (hotConfigs) { conf = hotConfigs.get(document.getURI()); } if (conf != null) return conf; ElementAtExist confElement = (ElementAtExist) document.getDocumentElement(); if (confElement == null) return null; //possible on corrupted database, find better solution (recovery flag?) //throw new ConfigurationException("The configuration file is empty, url = "+collection.getURI().append(fileURL)); conf = new ConfigurationImpl(confElement); synchronized (hotConfigs) { hotConfigs.put(document.getURI(), conf); } return conf; } public static DocumentAtExist save(Configurable instance, XmldbURI uri) throws IOException, ConfigurationException { BrokerPool database; try { database = BrokerPool.getInstance(); } catch (EXistException e) { throw new IOException(e); } DBBroker broker = null; try { broker = database.get(null); Collection collection = broker.getCollection(uri.removeLastSegment()); if (collection == null) throw new IOException("Collection URI = "+uri.removeLastSegment()+" not found."); return save(instance, broker, collection, uri.lastSegment()); } catch (EXistException e) { throw new IOException(e); } finally { database.release(broker); } } public static DocumentAtExist save(Configurable instance, DBBroker broker, Collection collection, XmldbURI uri) throws IOException, ConfigurationException { StringBuilder buf = new StringBuilder(); asXMLtoBuffer(instance, buf); if (buf.length() == 0) return null; BrokerPool pool = broker.getBrokerPool(); TransactionManager transact = pool.getTransactionManager(); Txn txn = transact.beginTransaction(); LOG.info("STORING CONFIGURATION collection = "+collection.getURI()+" document = "+uri); Subject currentUser = broker.getUser(); try { broker.setUser(pool.getSecurityManager().getSystemSubject()); String data = buf.toString(); txn.acquireLock(collection.getLock(), Lock.WRITE_LOCK); IndexInfo info = collection.validateXMLResource(txn, broker, uri, data); DocumentImpl doc = info.getDocument(); doc.getMetadata().setMimeType(MimeType.XML_TYPE.getName()); doc.setPermissions(0770); collection.store(txn, broker, info, data, false); broker.saveCollection(txn, doc.getCollection()); transact.commit(txn); } catch (Exception e) { transact.abort(txn); e.printStackTrace(); throw new IOException(e); } finally { broker.setUser(currentUser); } broker.flush(); broker.sync(Sync.MAJOR_SYNC); return collection.getDocument(broker, uri.lastSegment()); } public static synchronized void clear() { synchronized (hotConfigs) { for (Configuration conf : hotConfigs.values()) { if (conf instanceof ConfigurationImpl) { ((ConfigurationImpl) conf).configuredObjectReferene = null; } } hotConfigs.clear(); } map.clear(); } public static void unregister(Configuration configuration) { if (configuration == null) return; synchronized (hotConfigs) { if (hotConfigs.containsValue(configuration)) { for (Entry<XmldbURI, Configuration> entry : hotConfigs.entrySet()) { if (entry.getValue() == configuration) { hotConfigs.remove(entry.getKey()); return; } } } } } }
package org.exist.storage.dom; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.Stack; import org.exist.dom.DocumentImpl; import org.exist.dom.NodeProxy; import org.exist.dom.StoredNode; import org.exist.numbering.DLNBase; import org.exist.numbering.NodeId; import org.exist.storage.BrokerPool; import org.exist.storage.BufferStats; import org.exist.storage.NativeBroker; import org.exist.storage.Signatures; import org.exist.storage.StorageAddress; import org.exist.storage.btree.BTree; import org.exist.storage.btree.BTreeCallback; import org.exist.storage.btree.BTreeException; import org.exist.storage.btree.DBException; import org.exist.storage.btree.IndexQuery; import org.exist.storage.btree.Value; import org.exist.storage.cache.Cache; import org.exist.storage.cache.Cacheable; import org.exist.storage.cache.LRUCache; import org.exist.storage.journal.LogEntryTypes; import org.exist.storage.journal.Loggable; import org.exist.storage.journal.Lsn; import org.exist.storage.lock.Lock; import org.exist.storage.lock.ReentrantReadWriteLock; import org.exist.storage.txn.TransactionException; import org.exist.storage.txn.Txn; import org.exist.util.ByteConversion; import org.exist.util.Configuration; import org.exist.util.Lockable; import org.exist.util.ReadOnlyException; import org.exist.util.hashtable.Object2LongIdentityHashMap; import org.exist.util.sanity.SanityCheck; import org.exist.xquery.TerminatedException; import org.w3c.dom.Node; /** * This is the main storage for XML nodes. Nodes are stored in document order. * Every document gets its own sequence of pages, which is bound to the writing * thread to avoid conflicting writes. The page structure is as follows: * | page header | (tid1 node-data, tid2 node-data, ..., tidn node-data) | * * node-data contains the raw binary data of the node. Within a page, a node is * identified by a unique id, called tuple id (tid). Every node can thus be * located by a virtual address pointer, which consists of the page id and the * tid. Both components are encoded in a long value (with additional bits used * for optional flags). The address pointer is used to reference nodes from the * indexes. It should thus remain unchanged during the life-time of a document. * * However, XUpdate requests may insert new nodes in the middle of a page. In * these cases, the page will be split and the upper portion of the page is * copied to a split page. The record in the original page will be replaced by a * forward link, pointing to the new location of the node data in the split * page. * * As a consequence, the class has to distinguish three different types of data * records: * * 1) Ordinary record: * | tid | length | data | * * 3) Relocated record: * | tid | length | address pointer to original location | data | * * 2) Forward link: * | tid | address pointer | * * tid and length each use two bytes (short), address pointers 8 bytes (long). * The upper two bits of the tid are used to indicate the type of the record * (see {@link org.exist.storage.dom.ItemId}). * * @author Wolfgang Meier <wolfgang@exist-db.org> */ public class DOMFile extends BTree implements Lockable { public static final String FILE_NAME = "dom.dbx"; public static final String FILE_KEY_IN_CONFIG = "db-connection.dom"; public static final int LENGTH_TID = 2; //sizeof short public static final int LENGTH_DATA_LENGTH = 2; //sizeof short public static final int LENGTH_ORIGINAL_LOCATION = 8; //sizeof long public static final int LENGTH_FORWARD_LOCATION = 8; //sizeof long public static final int LENGTH_OVERFLOW_LOCATION = 8; //sizeof long /* * Byte ids for the records written to the log file. */ public final static byte LOG_CREATE_PAGE = 0x10; public final static byte LOG_ADD_VALUE = 0x11; public final static byte LOG_REMOVE_VALUE = 0x12; public final static byte LOG_REMOVE_EMPTY_PAGE = 0x13; public final static byte LOG_UPDATE_VALUE = 0x14; public final static byte LOG_REMOVE_PAGE = 0x15; public final static byte LOG_WRITE_OVERFLOW = 0x16; public final static byte LOG_REMOVE_OVERFLOW = 0x17; public final static byte LOG_INSERT_RECORD = 0x18; public final static byte LOG_SPLIT_PAGE = 0x19; public final static byte LOG_ADD_LINK = 0x1A; public final static byte LOG_ADD_MOVED_REC = 0x1B; public final static byte LOG_UPDATE_HEADER = 0x1C; public final static byte LOG_UPDATE_LINK = 0x1D; static { // register log entry types for this db file LogEntryTypes.addEntryType(LOG_CREATE_PAGE, CreatePageLoggable.class); LogEntryTypes.addEntryType(LOG_ADD_VALUE, AddValueLoggable.class); LogEntryTypes.addEntryType(LOG_REMOVE_VALUE, RemoveValueLoggable.class); LogEntryTypes.addEntryType(LOG_REMOVE_EMPTY_PAGE, RemoveEmptyPageLoggable.class); LogEntryTypes.addEntryType(LOG_UPDATE_VALUE, UpdateValueLoggable.class); LogEntryTypes.addEntryType(LOG_REMOVE_PAGE, RemovePageLoggable.class); LogEntryTypes.addEntryType(LOG_WRITE_OVERFLOW, WriteOverflowPageLoggable.class); LogEntryTypes.addEntryType(LOG_REMOVE_OVERFLOW, RemoveOverflowLoggable.class); LogEntryTypes.addEntryType(LOG_INSERT_RECORD, InsertValueLoggable.class); LogEntryTypes.addEntryType(LOG_SPLIT_PAGE, SplitPageLoggable.class); LogEntryTypes.addEntryType(LOG_ADD_LINK, AddLinkLoggable.class); LogEntryTypes.addEntryType(LOG_ADD_MOVED_REC, AddMovedValueLoggable.class); LogEntryTypes.addEntryType(LOG_UPDATE_HEADER, UpdateHeaderLoggable.class); LogEntryTypes.addEntryType(LOG_UPDATE_LINK, UpdateLinkLoggable.class); } public final static short FILE_FORMAT_VERSION_ID = 4; // page types public final static byte LOB = 21; public final static byte RECORD = 20; public final static short OVERFLOW = 0; public final static long DATA_SYNC_PERIOD = 4200; private final Cache dataCache; private BTreeFileHeader fileHeader; private Object owner = null; private Lock lock = null; private final Object2LongIdentityHashMap pages = new Object2LongIdentityHashMap( 64); private DocumentImpl currentDocument = null; private final AddValueLoggable addValueLog = new AddValueLoggable(); public DOMFile(BrokerPool pool, byte id, String dataDir, Configuration config) throws DBException { super(pool, id, true, pool.getCacheManager(), 0.01); lock = new ReentrantReadWriteLock(getFileName()); fileHeader = (BTreeFileHeader) getFileHeader(); fileHeader.setPageCount(0); fileHeader.setTotalCount(0); dataCache = new LRUCache(256, 0.0, 1.0); dataCache.setFileName(getFileName()); cacheManager.registerCache(dataCache); File file = new File(dataDir + File.separatorChar + getFileName()); setFile(file); if (exists()) { open(); } else { if (LOG.isDebugEnabled()) LOG.debug("Creating data file: " + file.getName()); create(); } config.setProperty(getConfigKeyForFile(), this); } public static String getFileName() { return FILE_NAME; } public static String getConfigKeyForFile() { return FILE_KEY_IN_CONFIG; } protected final Cache getPageBuffer() { return dataCache; } /** * @return file version. */ public short getFileVersion() { return FILE_FORMAT_VERSION_ID; } public void setCurrentDocument(DocumentImpl doc) { this.currentDocument = doc; } /** * Append a value to the current page. * * This method is called when storing a new document. Each writing thread * gets its own sequence of pages for writing a document, so all document * nodes are stored in sequential order. A new page will be allocated if the * current page is full. If the value is larger than the page size, it will * be written to an overflow page. * * @param value the value to append * @return the virtual storage address of the value */ public long add(Txn transact, byte[] value) throws ReadOnlyException { if (value == null || value.length == 0) return KEY_NOT_FOUND; // overflow value? if (value.length + 2 + 2 > fileHeader.getWorkSize()) { LOG.debug("Creating overflow page"); OverflowDOMPage overflow = new OverflowDOMPage(transact); overflow.write(transact, value); byte[] pnum = ByteConversion.longToByte(overflow.getPageNum()); return add(transact, pnum, true); } else return add(transact, value, false); } /** * Append a value to the current page. If overflowPage is true, the value * will be saved into its own, reserved chain of pages. The current page * will just contain a link to the first overflow page. * * @param value * @param overflowPage * @return the virtual storage address of the value * @throws ReadOnlyException */ private long add(Txn transaction, byte[] value, boolean overflowPage) throws ReadOnlyException { final int vlen = value.length; // always append data to the end of the file DOMPage page = getCurrentPage(transaction); // does value fit into current data page? if (page == null || page.len + LENGTH_TID + LENGTH_DATA_LENGTH + vlen > page.data.length) { DOMPage newPage = new DOMPage(); if (page != null) { DOMFilePageHeader ph = page.getPageHeader(); if (isTransactional && transaction != null) { UpdateHeaderLoggable loggable = new UpdateHeaderLoggable( transaction, ph.getPrevDataPage(), page.getPageNum(), newPage.getPageNum(), ph.getPrevDataPage(), ph.getNextDataPage() ); writeToLog(loggable, page.page); } ph.setNextDataPage(newPage.getPageNum()); newPage.getPageHeader().setPrevDataPage(page.getPageNum()); page.setDirty(true); dataCache.add(page); } if (isTransactional && transaction != null) { CreatePageLoggable loggable = new CreatePageLoggable( transaction, page == null ? Page.NO_PAGE : page.getPageNum(), newPage.getPageNum(), Page.NO_PAGE); writeToLog(loggable, newPage.page); } page = newPage; setCurrentPage(newPage); } // save tuple identifier final DOMFilePageHeader ph = page.getPageHeader(); final short tid = ph.getNextTID(); // LOG.debug("writing to " + page.getPageNum() + "; " + page.len + "; // tid = " + tid + // "; len = " + valueLen + "; dataLen = " + page.data.length); if (isTransactional && transaction != null) { addValueLog.clear(transaction, page.getPageNum(), tid, value); writeToLog(addValueLog, page.page); } // save TID ByteConversion.shortToByte(tid, page.data, page.len); page.len += LENGTH_TID; // save data length // overflow pages have length 0 ByteConversion.shortToByte(overflowPage ? OVERFLOW : (short) vlen, page.data, page.len); page.len += LENGTH_DATA_LENGTH; // save data System.arraycopy(value, 0, page.data, page.len, vlen); page.len += vlen; ph.incRecordCount(); ph.setDataLength(page.len); page.setDirty(true); dataCache.add(page, 2); // create pointer from pageNum and offset into page final long p = StorageAddress.createPointer((int) page.getPageNum(), tid); return p; } private void writeToLog(Loggable loggable, Page page) { try { logManager.writeToLog(loggable); page.getPageHeader().setLsn(loggable.getLsn()); } catch (TransactionException e) { LOG.warn(e.getMessage(), e); } } /** * Store a raw binary resource into the file. The data will always be * written into an overflow page. * * @param value Binary resource as byte array */ public long addBinary(Txn transaction, DocumentImpl doc, byte[] value) { OverflowDOMPage overflow = new OverflowDOMPage(transaction); int pagesCount = overflow.write(transaction, value); doc.getMetadata().setPageCount(pagesCount); return overflow.getPageNum(); } /** * Store a raw binary resource into the file. The data will always be * written into an overflow page. * * @param is Binary resource as stream. */ public long addBinary(Txn transaction, DocumentImpl doc, InputStream is) { OverflowDOMPage overflow = new OverflowDOMPage(transaction); int pagesCount = overflow.write(transaction, is); doc.getMetadata().setPageCount(pagesCount); return overflow.getPageNum(); } /** * Return binary data stored with {@link #addBinary(Txn, DocumentImpl, byte[])}. * * @param pageNum */ public byte[] getBinary(long pageNum) { return getOverflowValue(pageNum); } public void readBinary(long pageNum, OutputStream os) { try { OverflowDOMPage overflow = new OverflowDOMPage(pageNum); overflow.streamTo(os); } catch (IOException e) { LOG.error("io error while loading overflow value", e); } } /** * Insert a new node after the specified node. * * @param key * @param value */ public long insertAfter(Txn transaction, DocumentImpl doc, Value key, byte[] value) { try { final long p = findValue(key); if (p == KEY_NOT_FOUND) return p; return insertAfter(transaction, doc, p, value); } catch (BTreeException e) { LOG.warn("key not found", e); } catch (IOException e) { LOG.warn("IO error", e); } return KEY_NOT_FOUND; } /** * Insert a new node after the node located at the specified address. * * If the previous node is in the middle of a page, the page is split. If * the node is appended at the end and the page does not have enough room * for the node, a new page is added to the page sequence. * * @param doc * the document to which the new node belongs. * @param address * the storage address of the node after which the new value * should be inserted. * @param value * the value of the new node. */ public long insertAfter(Txn transaction, DocumentImpl doc, long address, byte[] value) { // check if we need an overflow page boolean isOverflow = false; if (value.length + 2 + 2 > fileHeader.getWorkSize()) { OverflowDOMPage overflow = new OverflowDOMPage(transaction); LOG.debug("creating overflow page: " + overflow.getPageNum()); overflow.write(transaction, value); value = ByteConversion.longToByte(overflow.getPageNum()); isOverflow = true; } // locate the node to insert after RecordPos rec = findRecord(address); if (rec == null) { SanityCheck.TRACE("page not found"); return KEY_NOT_FOUND; } short len = ByteConversion.byteToShort(rec.getPage().data, rec.offset); rec.offset += LENGTH_DATA_LENGTH; if (ItemId.isRelocated(rec.getTID())) rec.offset += LENGTH_ORIGINAL_LOCATION; if (len == OVERFLOW) rec.offset += LENGTH_OVERFLOW_LOCATION; else rec.offset += len; int dlen = rec.getPage().getPageHeader().getDataLength(); // insert in the middle of the page? if (rec.offset < dlen) { if (dlen + value.length + 2 + 2 < fileHeader.getWorkSize() && rec.getPage().getPageHeader().hasRoom()) { // LOG.debug("copying data in page " + rec.getPage().getPageNum() // + "; offset = " + rec.offset + "; dataLen = " // + dataLen + "; valueLen = " + value.length); // new value fits into the page int end = rec.offset + value.length + 2 + 2; System.arraycopy(rec.getPage().data, rec.offset, rec.getPage().data, end, dlen - rec.offset); rec.getPage().len = dlen + value.length + 2 + 2; rec.getPage().getPageHeader().setDataLength(rec.getPage().len); } else { // doesn't fit: split the page rec = splitDataPage(transaction, doc, rec); if (rec.offset + value.length + 2 + 2 > fileHeader.getWorkSize() || !rec.getPage().getPageHeader().hasRoom()) { // still not enough free space: create a new page DOMPage newPage = new DOMPage(); LOG.debug("creating additional page: " + newPage.getPageNum() + "; prev = " + rec.getPage().getPageNum() + "; next = " + rec.getPage().ph.getNextDataPage()); if (isTransactional && transaction != null) { CreatePageLoggable loggable = new CreatePageLoggable( transaction, rec.getPage().getPageNum(), newPage.getPageNum(), rec.getPage().ph.getNextDataPage()); writeToLog(loggable, newPage.page); } // adjust page links newPage.getPageHeader().setNextDataPage( rec.getPage().getPageHeader().getNextDataPage()); newPage.getPageHeader().setPrevDataPage( rec.getPage().getPageNum()); if (isTransactional && transaction != null) { UpdateHeaderLoggable loggable = new UpdateHeaderLoggable( transaction, rec.getPage().ph.getPrevDataPage(), rec.getPage().getPageNum(), newPage.getPageNum(), rec.getPage().ph.getPrevDataPage(), rec.getPage().ph.getNextDataPage() ); writeToLog(loggable, rec.getPage().page); } rec.getPage().getPageHeader().setNextDataPage( newPage.getPageNum()); if (newPage.ph.getNextDataPage() != Page.NO_PAGE) { // link the next page in the chain back to the new page inserted DOMPage nextInChain = getCurrentPage(newPage.ph.getNextDataPage()); if (isTransactional && transaction != null) { UpdateHeaderLoggable loggable = new UpdateHeaderLoggable(transaction, newPage.getPageNum(), nextInChain.getPageNum(), nextInChain.ph.getNextDataPage(), nextInChain.ph.getPrevDataPage(), nextInChain.ph.getNextDataPage()); writeToLog(loggable, nextInChain.page); } nextInChain.ph.setPrevDataPage(newPage.getPageNum()); nextInChain.setDirty(true); dataCache.add(nextInChain); } rec.getPage().setDirty(true); dataCache.add(rec.getPage()); rec.setPage(newPage); rec.offset = 0; rec.getPage().len = value.length + 2 + 2; rec.getPage().getPageHeader().setDataLength(rec.getPage().len); rec.getPage().getPageHeader().setRecordCount((short) 1); } else { rec.getPage().len = rec.offset + value.length + 2 + 2; rec.getPage().getPageHeader().setDataLength(rec.getPage().len); dlen = rec.offset; } } } else if (dlen + value.length + 2 + 2 > fileHeader.getWorkSize() || !rec.getPage().getPageHeader().hasRoom()) { // does value fit into page? DOMPage newPage = new DOMPage(); LOG.debug("creating new page: " + newPage.getPageNum()); if (isTransactional && transaction != null) { CreatePageLoggable loggable = new CreatePageLoggable( transaction, rec.getPage().getPageNum(), newPage.getPageNum(), rec.getPage().ph.getNextDataPage()); writeToLog(loggable, newPage.page); } long nextPageNr = rec.getPage().getPageHeader().getNextDataPage(); newPage.getPageHeader().setNextDataPage(nextPageNr); newPage.getPageHeader().setPrevDataPage(rec.getPage().getPageNum()); if (isTransactional && transaction != null) { UpdateHeaderLoggable loggable = new UpdateHeaderLoggable(transaction, rec.getPage().ph.getPrevDataPage(), rec.getPage().getPageNum(), newPage.getPageNum(), rec.getPage().ph.getPrevDataPage(), rec.getPage().ph.getNextDataPage()); writeToLog(loggable, rec.getPage().page); } rec.getPage().getPageHeader().setNextDataPage(newPage.getPageNum()); if (Page.NO_PAGE != nextPageNr) { DOMPage nextPage = getCurrentPage(nextPageNr); if (isTransactional && transaction != null) { UpdateHeaderLoggable loggable = new UpdateHeaderLoggable(transaction, newPage.getPageNum(), nextPage.getPageNum(), nextPage.ph.getNextDataPage(), nextPage.ph.getPrevDataPage(), nextPage.ph.getNextDataPage()); writeToLog(loggable, nextPage.page); } nextPage.getPageHeader().setPrevDataPage(newPage.getPageNum()); nextPage.setDirty(true); dataCache.add(nextPage); } rec.getPage().setDirty(true); dataCache.add(rec.getPage()); rec.setPage(newPage); rec.offset = 0; rec.getPage().len = value.length + 2+ 2; rec.getPage().getPageHeader().setDataLength(rec.getPage().len); } else { rec.getPage().len = dlen + value.length + 2 + 2; rec.getPage().getPageHeader().setDataLength(rec.getPage().len); } // write the data short tid = rec.getPage().getPageHeader().getNextTID(); if (isTransactional && transaction != null) { Loggable loggable = new InsertValueLoggable(transaction, rec.getPage().getPageNum(), isOverflow, tid, value, rec.offset); writeToLog(loggable, rec.getPage().page); } // writing tid ByteConversion.shortToByte((short) tid, rec.getPage().data, rec.offset); rec.offset += LENGTH_TID; // writing value length ByteConversion.shortToByte(isOverflow ? OVERFLOW : (short) value.length, rec.getPage().data, rec.offset); rec.offset += LENGTH_DATA_LENGTH; // writing data System.arraycopy(value, 0, rec.getPage().data, rec.offset, value.length); rec.offset += value.length; rec.getPage().getPageHeader().incRecordCount(); rec.getPage().setDirty(true); if (doc != null && rec.getPage().getPageHeader().getCurrentTID() >= ItemId.DEFRAG_LIMIT) doc.triggerDefrag(); // LOG.debug(debugPageContents(rec.page)); dataCache.add(rec.getPage()); // LOG.debug(debugPages(doc)); return StorageAddress.createPointer((int) rec.getPage().getPageNum(), tid); } /** * Split a data page at the position indicated by the rec parameter. * * The portion of the page starting at rec.offset is moved into a new page. * Every moved record is marked as relocated and a link is stored into the * original page to point to the new record position. * * @param doc * @param rec */ private RecordPos splitDataPage(Txn transaction, DocumentImpl doc, RecordPos rec) { if (currentDocument != null) currentDocument.getMetadata().incSplitCount(); // check if a split is really required. A split is not required if all // records following the split point are already links to other pages. In this // case, the new record is just appended to a new page linked to the old one. boolean requireSplit = false; for (int pos = rec.offset; pos < rec.getPage().len;) { short tid = ByteConversion.byteToShort(rec.getPage().data, pos); pos += LENGTH_TID; if (!ItemId.isLink(tid)) { requireSplit = true; break; } pos += LENGTH_FORWARD_LOCATION; } if (!requireSplit) { LOG.debug("page " + rec.getPage().getPageNum() + ": no split required"); rec.offset = rec.getPage().len; return rec; } // copy the old data up to the split point into a new array int oldDataLen = rec.getPage().getPageHeader().getDataLength(); byte[] oldData = rec.getPage().data; if (isTransactional && transaction != null) { Loggable loggable = new SplitPageLoggable(transaction, rec.getPage().getPageNum(), rec.offset, oldData, oldDataLen); writeToLog(loggable, rec.getPage().page); } rec.getPage().data = new byte[fileHeader.getWorkSize()]; System.arraycopy(oldData, 0, rec.getPage().data, 0, rec.offset); // the old rec.page now contains a copy of the data up to the split // point rec.getPage().len = rec.offset; rec.getPage().setDirty(true); // create a first split page DOMPage firstSplitPage = new DOMPage(); if (isTransactional && transaction != null) { Loggable loggable = new CreatePageLoggable( transaction, rec.getPage().getPageNum(), firstSplitPage.getPageNum(), Page.NO_PAGE, rec.getPage().getPageHeader().getCurrentTID()); writeToLog(loggable, firstSplitPage.page); } DOMPage nextSplitPage = firstSplitPage; nextSplitPage.getPageHeader().setNextTID( (short) (rec.getPage().getPageHeader().getCurrentTID())); long backLink; short splitRecordCount = 0; LOG.debug("splitting " + rec.getPage().getPageNum() + " at " + rec.offset + ": new: " + nextSplitPage.getPageNum() + "; next: " + rec.getPage().getPageHeader().getNextDataPage()); // start copying records from rec.offset to the new split pages for (int pos = rec.offset; pos < oldDataLen; splitRecordCount++) { // read the current id short tid = ByteConversion.byteToShort(oldData, pos); pos += LENGTH_TID; if (ItemId.isLink(tid)) { /* This is already a link, so we just copy it */ if (rec.getPage().len + LENGTH_TID + LENGTH_FORWARD_LOCATION > fileHeader.getWorkSize()) { /* no room in the old page, append a new one */ DOMPage newPage = new DOMPage(); if (isTransactional && transaction != null) { Loggable loggable = new CreatePageLoggable( transaction, rec.getPage().getPageNum(), newPage.getPageNum(), rec.getPage().getPageHeader().getNextDataPage(), rec.getPage().getPageHeader().getCurrentTID()); writeToLog(loggable, firstSplitPage.page); loggable = new UpdateHeaderLoggable(transaction, rec.getPage().ph.getPrevDataPage(), rec.getPage().getPageNum(), newPage.getPageNum(), rec.getPage().ph.getPrevDataPage(), rec.getPage().ph.getNextDataPage()); writeToLog(loggable, nextSplitPage.page); } newPage.getPageHeader().setNextTID((short)(rec.getPage().getPageHeader().getCurrentTID())); newPage.getPageHeader().setPrevDataPage(rec.getPage().getPageNum()); newPage.getPageHeader().setNextDataPage(rec.getPage().getPageHeader().getNextDataPage()); LOG.debug("appending page after split: " + newPage.getPageNum()); rec.getPage().getPageHeader().setNextDataPage(newPage.getPageNum()); rec.getPage().getPageHeader().setDataLength(rec.getPage().len); rec.getPage().getPageHeader().setRecordCount(countRecordsInPage(rec.getPage())); rec.getPage().setDirty(true); dataCache.add(rec.getPage()); dataCache.add(newPage); rec.setPage(newPage); rec.getPage().len = 0; } if (isTransactional && transaction != null) { long oldLink = ByteConversion.byteToLong(oldData, pos); Loggable loggable = new AddLinkLoggable(transaction, rec.getPage().getPageNum(), ItemId.getId(tid), oldLink); writeToLog(loggable, rec.getPage().page); } ByteConversion.shortToByte(tid, rec.getPage().data, rec.getPage().len); rec.getPage().len += LENGTH_TID; System.arraycopy(oldData, pos, rec.getPage().data, rec.getPage().len, LENGTH_FORWARD_LOCATION); rec.getPage().len += LENGTH_FORWARD_LOCATION; pos += LENGTH_FORWARD_LOCATION; continue; } // read data length short storedLen = ByteConversion.byteToShort(oldData, pos); pos += LENGTH_DATA_LENGTH; // if this is an overflow page, the real data length is always 8 // byte for the page number of the overflow page short realLen = (storedLen == OVERFLOW ? LENGTH_OVERFLOW_LOCATION : storedLen); // check if we have room in the current split page if (nextSplitPage.len + LENGTH_TID + LENGTH_DATA_LENGTH + LENGTH_ORIGINAL_LOCATION + realLen > fileHeader.getWorkSize()) { // not enough room in the split page: append a new page DOMPage newPage = new DOMPage(); if (isTransactional && transaction != null) { Loggable loggable = new CreatePageLoggable( transaction, nextSplitPage.getPageNum(), newPage.getPageNum(), Page.NO_PAGE, rec.getPage().getPageHeader().getCurrentTID()); writeToLog(loggable, firstSplitPage.page); loggable = new UpdateHeaderLoggable(transaction, nextSplitPage.ph.getPrevDataPage(), nextSplitPage.getPageNum(), newPage.getPageNum(), nextSplitPage.ph.getPrevDataPage(), nextSplitPage.ph.getNextDataPage()); writeToLog(loggable, nextSplitPage.page); } newPage.getPageHeader().setNextTID(rec.getPage().getPageHeader().getCurrentTID()); newPage.getPageHeader().setPrevDataPage( nextSplitPage.getPageNum()); LOG.debug("creating new split page: " + newPage.getPageNum()); nextSplitPage.getPageHeader().setNextDataPage( newPage.getPageNum()); nextSplitPage.getPageHeader().setDataLength(nextSplitPage.len); nextSplitPage.getPageHeader().setRecordCount(splitRecordCount); nextSplitPage.setDirty(true); dataCache.add(nextSplitPage); dataCache.add(newPage); nextSplitPage = newPage; splitRecordCount = 0; } /* * if the record has already been relocated, read the original * storage address and update the link there. */ if (ItemId.isRelocated(tid)) { backLink = ByteConversion.byteToLong(oldData, pos); pos += LENGTH_ORIGINAL_LOCATION; RecordPos origRec = findRecord(backLink, false); long oldLink = ByteConversion.byteToLong(origRec.getPage().data, origRec.offset); long forwardLink = StorageAddress.createPointer( (int) nextSplitPage.getPageNum(), ItemId.getId(tid)); if (isTransactional && transaction != null) { Loggable loggable = new UpdateLinkLoggable(transaction, origRec.getPage().getPageNum(), origRec.offset, forwardLink, oldLink); writeToLog(loggable, origRec.getPage().page); } ByteConversion.longToByte(forwardLink, origRec.getPage().data, origRec.offset); origRec.getPage().setDirty(true); dataCache.add(origRec.getPage()); } else backLink = StorageAddress.createPointer((int) rec.getPage().getPageNum(), ItemId.getId(tid)); /* * save the record to the split page: */ if (isTransactional && transaction != null) { byte[] logData = new byte[realLen]; System.arraycopy(oldData, pos, logData, 0, realLen); Loggable loggable = new AddMovedValueLoggable(transaction, nextSplitPage.getPageNum(), tid, logData, backLink); writeToLog(loggable, nextSplitPage.page); } // set the relocated flag and save the item id ByteConversion.shortToByte(ItemId.setIsRelocated(tid), nextSplitPage.data, nextSplitPage.len); nextSplitPage.len += LENGTH_TID; // save length field ByteConversion.shortToByte(storedLen, nextSplitPage.data, nextSplitPage.len); nextSplitPage.len += LENGTH_DATA_LENGTH; // save link to the original page ByteConversion.longToByte(backLink, nextSplitPage.data, nextSplitPage.len); nextSplitPage.len += LENGTH_ORIGINAL_LOCATION; // now save the data try { System.arraycopy(oldData, pos, nextSplitPage.data, nextSplitPage.len, realLen); } catch (ArrayIndexOutOfBoundsException e) { SanityCheck.TRACE("pos = " + pos + "; len = " + nextSplitPage.len + "; currentLen = " + realLen + "; tid = " + tid + "; page = " + rec.getPage().getPageNum()); throw e; } nextSplitPage.len += realLen; pos += realLen; // save a link pointer in the original page if the record has not // been relocated before. if (!ItemId.isRelocated(tid)) { if (rec.getPage().len + LENGTH_TID + LENGTH_FORWARD_LOCATION > fileHeader.getWorkSize()) { // the link doesn't fit into the old page. Append a new page DOMPage newPage = new DOMPage(); if (isTransactional && transaction != null) { Loggable loggable = new CreatePageLoggable( transaction, rec.getPage().getPageNum(), newPage.getPageNum(), rec.getPage().getPageHeader().getNextDataPage(), rec.getPage().getPageHeader().getCurrentTID()); writeToLog(loggable, firstSplitPage.page); loggable = new UpdateHeaderLoggable(transaction, rec.getPage().ph.getPrevDataPage(), rec.getPage().getPageNum(), newPage.getPageNum(), rec.getPage().ph.getPrevDataPage(), rec.getPage().ph.getNextDataPage()); writeToLog(loggable, nextSplitPage.page); } newPage.getPageHeader().setNextTID(rec.getPage().ph.getCurrentTID()); newPage.getPageHeader().setPrevDataPage(rec.getPage().getPageNum()); newPage.getPageHeader().setNextDataPage(rec.getPage().getPageHeader().getNextDataPage()); LOG.debug("creating new page after split: " + newPage.getPageNum()); rec.getPage().getPageHeader().setNextDataPage(newPage.getPageNum()); rec.getPage().getPageHeader().setDataLength(rec.getPage().len); rec.getPage().getPageHeader().setRecordCount(countRecordsInPage(rec.getPage())); rec.getPage().setDirty(true); dataCache.add(rec.getPage()); dataCache.add(newPage); rec.setPage(newPage); rec.getPage().len = 0; } long forwardLink = StorageAddress.createPointer( (int) nextSplitPage.getPageNum(), ItemId.getId(tid)); if (isTransactional && transaction != null) { Loggable loggable = new AddLinkLoggable(transaction, rec.getPage().getPageNum(), tid, forwardLink); writeToLog(loggable, rec.getPage().page); } ByteConversion.shortToByte(ItemId.setIsLink(tid), rec.getPage().data, rec.getPage().len); rec.getPage().len += LENGTH_TID; ByteConversion.longToByte(forwardLink, rec.getPage().data, rec.getPage().len); rec.getPage().len += LENGTH_FORWARD_LOCATION; } } // end of for loop: finished copying data // link the split pages to the original page if (nextSplitPage.len == 0) { LOG.warn("page " + nextSplitPage.getPageNum() + " is empty. Remove it"); // if nothing has been copied to the last split page, // remove it dataCache.remove(nextSplitPage); if (nextSplitPage == firstSplitPage) firstSplitPage = null; try { unlinkPages(nextSplitPage.page); } catch (IOException e) { LOG.warn("Failed to remove empty split page: " + e.getMessage(), e); } nextSplitPage = null; } else { if (isTransactional && transaction != null) { Loggable loggable = new UpdateHeaderLoggable(transaction, nextSplitPage.ph.getPrevDataPage(), nextSplitPage.getPageNum(), rec.getPage().ph.getNextDataPage(), nextSplitPage.ph.getPrevDataPage(), nextSplitPage.ph.getNextDataPage()); writeToLog(loggable, nextSplitPage.page); } nextSplitPage.getPageHeader().setDataLength(nextSplitPage.len); nextSplitPage.getPageHeader().setNextDataPage( rec.getPage().getPageHeader().getNextDataPage()); nextSplitPage.getPageHeader().setRecordCount(splitRecordCount); nextSplitPage.setDirty(true); dataCache.add(nextSplitPage); if (isTransactional && transaction != null) { Loggable loggable = new UpdateHeaderLoggable(transaction, rec.getPage().getPageNum(), firstSplitPage.getPageNum(), firstSplitPage.ph.getNextDataPage(), firstSplitPage.ph.getPrevDataPage(), firstSplitPage.ph.getNextDataPage()); writeToLog(loggable, nextSplitPage.page); } firstSplitPage.getPageHeader().setPrevDataPage(rec.getPage().getPageNum()); if (nextSplitPage != firstSplitPage) { firstSplitPage.setDirty(true); dataCache.add(firstSplitPage); } } long nextPageNr = rec.getPage().getPageHeader().getNextDataPage(); if (Page.NO_PAGE != nextPageNr) { DOMPage nextPage = getCurrentPage(nextPageNr); if (isTransactional && transaction != null) { Loggable loggable = new UpdateHeaderLoggable(transaction, nextSplitPage.getPageNum(), nextPage.getPageNum(), Page.NO_PAGE, nextPage.ph.getPrevDataPage(), nextPage.ph.getNextDataPage()); writeToLog(loggable, nextPage.page); } nextPage.getPageHeader().setPrevDataPage(nextSplitPage.getPageNum()); nextPage.setDirty(true); dataCache.add(nextPage); } rec.setPage(getCurrentPage(rec.getPage().getPageNum())); if (firstSplitPage != null) { if (isTransactional && transaction != null) { Loggable loggable = new UpdateHeaderLoggable(transaction, rec.getPage().ph.getPrevDataPage(), rec.getPage().getPageNum(), firstSplitPage.getPageNum(), rec.getPage().ph.getPrevDataPage(), rec.getPage().ph.getNextDataPage()); writeToLog(loggable, rec.getPage().page); } rec.getPage().getPageHeader().setNextDataPage(firstSplitPage.getPageNum()); } rec.getPage().getPageHeader().setDataLength(rec.getPage().len); rec.getPage().getPageHeader().setRecordCount(countRecordsInPage(rec.getPage())); rec.offset = rec.getPage().len; return rec; } /** * Returns the number of records stored in a page. * * @param page * @return The number of records */ private short countRecordsInPage(DOMPage page) { short count = 0; final int dlen = page.getPageHeader().getDataLength(); for (int pos = 0; pos < dlen; count++) { short tid = ByteConversion.byteToShort(page.data, pos); pos += LENGTH_TID; if (ItemId.isLink(tid)) { pos += LENGTH_FORWARD_LOCATION; } else { short vlen = ByteConversion.byteToShort(page.data, pos); pos += LENGTH_DATA_LENGTH; if (ItemId.isRelocated(tid)) { pos += vlen == OVERFLOW ? LENGTH_ORIGINAL_LOCATION + LENGTH_OVERFLOW_LOCATION : LENGTH_ORIGINAL_LOCATION + vlen; } else pos += vlen == OVERFLOW ? LENGTH_OVERFLOW_LOCATION : vlen; } } // LOG.debug("page " + page.getPageNum() + " has " + count + " // records."); return count; } public String debugPageContents(DOMPage page) { StringBuffer buf = new StringBuffer(); buf.append("Page " + page.getPageNum() + ": "); short count = 0; short vlen; int dlen = page.getPageHeader().getDataLength(); for (int pos = 0; pos < dlen; count++) { short tid = ByteConversion.byteToShort(page.data, pos); pos += LENGTH_TID; if (ItemId.isLink(tid)) buf.append('L'); else if (ItemId.isRelocated(tid)) buf.append('R'); buf.append(ItemId.getId(tid) + "[" + pos); if (ItemId.isLink(tid)) { buf.append(':').append(LENGTH_FORWARD_LOCATION).append("] "); pos += LENGTH_FORWARD_LOCATION; } else { vlen = ByteConversion.byteToShort(page.data, pos); pos += LENGTH_DATA_LENGTH; if (vlen < 0) { LOG.warn("Illegal length: " + vlen); return buf.toString(); } buf.append(':').append(vlen).append("]"); if (ItemId.isRelocated(tid)) pos += LENGTH_ORIGINAL_LOCATION; buf.append(':').append(Signatures.getType(page.data[pos])).append(' '); pos += vlen; } } buf.append("; records in page: " + count); buf.append("; nextTID: " + page.getPageHeader().getCurrentTID()); buf.append("; length: " + page.getPageHeader().getDataLength()); return buf.toString(); } public boolean close() throws DBException { if (!isReadOnly()) flush(); super.close(); return true; } public void closeAndRemove() { super.closeAndRemove(); cacheManager.deregisterCache(dataCache); } public boolean create() throws DBException { if (super.create((short) -1)) return true; else return false; } public FileHeader createFileHeader() { return new BTreeFileHeader(1024, PAGE_SIZE); } protected void unlinkPages(Page page) throws IOException { super.unlinkPages(page); } public PageHeader createPageHeader() { return new DOMFilePageHeader(); } public ArrayList findKeys(IndexQuery query) throws IOException, BTreeException { final FindCallback cb = new FindCallback(FindCallback.KEYS); try { query(query, cb); } catch (TerminatedException e) { // Should never happen here LOG.warn("Method terminated"); } return cb.getValues(); } private final static class ChildNode { StoredNode node; int index = 0; public ChildNode(StoredNode node) { this.node = node; } } /* TODO: Non-recursive implementation. Should be faster, but no measurable * difference observed so far. Keep as reference for future uses. */ private long findNode2(StoredNode node, NodeId target, Iterator iter) { Stack stack = new Stack(); stack.push(new ChildNode(node)); while(!stack.isEmpty()) { StoredNode temp = ((ChildNode) stack.peek()).node; int index = ((ChildNode) stack.peek()).index; if (index < temp.getChildCount()) { ((ChildNode) stack.peek()).index++; temp = (StoredNode) iter.next(); if (target.equals(temp.getNodeId())) return ((NodeIterator) iter).currentAddress(); if (temp.hasChildNodes()) { stack.push(new ChildNode(temp)); index = 0; } } while (index == temp.getChildCount()) { stack.pop(); if (!stack.isEmpty()) { index = ((ChildNode) stack.peek()).index; temp = ((ChildNode) stack.peek()).node; } else break; } } return KEY_NOT_FOUND; } private long findNode(StoredNode node, NodeId target, Iterator iter) { if (node.hasChildNodes()) { for (int i = 0; i < node.getChildCount(); i++) { StoredNode child = (StoredNode) iter.next(); SanityCheck.ASSERT(child != null, "Next node missing."); if (target.equals(child.getNodeId())) { return ((NodeIterator) iter).currentAddress(); } long p; if ((p = findNode(child, target, iter)) != KEY_NOT_FOUND) return p; } } return KEY_NOT_FOUND; } /** * Find a node by searching for a known ancestor in the index. If an * ancestor is found, it is traversed to locate the specified descendant * node. * * @param lock * @param node * @return The node's adress or <code>KEY_NOT_FOUND</code> if the node can not be found. * @throws IOException * @throws BTreeException */ protected long findValue(Object lock, NodeProxy node) throws IOException, BTreeException { final DocumentImpl doc = (DocumentImpl) node.getDocument(); final NativeBroker.NodeRef nodeRef = new NativeBroker.NodeRef(doc.getDocId(), node.getNodeId()); // first try to find the node in the index final long p = findValue(nodeRef); if (p == KEY_NOT_FOUND) { // node not found in index: try to find the nearest available // ancestor and traverse it NodeId id = node.getNodeId(); long parentPointer = KEY_NOT_FOUND; do { id = id.getParentId(); if (id == NodeId.DOCUMENT_NODE) { SanityCheck.TRACE("Node " + node.getDocument().getDocId() + ":" + node.getNodeId() + " not found."); throw new BTreeException("node " + node.getNodeId() + " not found."); } NativeBroker.NodeRef parentRef = new NativeBroker.NodeRef(doc.getDocId(), id); try { parentPointer = findValue(parentRef); } catch (BTreeException bte) { } } while (parentPointer == KEY_NOT_FOUND); final Iterator iter = new NodeIterator(lock, this, node.getDocument(), parentPointer); final StoredNode n = (StoredNode) iter.next(); final long address = findNode(n, node.getNodeId(), iter); if (address == KEY_NOT_FOUND) { // if(LOG.isDebugEnabled()) // LOG.debug("Node data location not found for node " + // node.gid); return KEY_NOT_FOUND; } else return address; } else return p; } /** * Find matching nodes for the given query. * * @param query * Description of the Parameter * @return Description of the Return Value * @exception IOException * Description of the Exception * @exception BTreeException * Description of the Exception */ public ArrayList findValues(IndexQuery query) throws IOException, BTreeException { FindCallback cb = new FindCallback(FindCallback.VALUES); try { query(query, cb); } catch (TerminatedException e) { // Should never happen LOG.warn("Method terminated"); } return cb.getValues(); } /** * Flush all buffers to disk. * * @return Description of the Return Value * @exception DBException * Description of the Exception */ public boolean flush() throws DBException { boolean flushed = false; //TODO : record transaction as a valuable flush ? if (isTransactional) logManager.flushToLog(true); if (!BrokerPool.FORCE_CORRUPTION) { flushed = flushed | super.flush(); flushed = flushed | dataCache.flush(); } // closeDocument(); return flushed; } public void printStatistics() { super.printStatistics(); NumberFormat nf = NumberFormat.getPercentInstance(); NumberFormat nf2 = NumberFormat.getInstance(); StringBuffer buf = new StringBuffer(); buf.append(getFile().getName()).append(" DATA "); buf.append("Buffers occupation : "); if (dataCache.getBuffers() == 0 && dataCache.getUsedBuffers() == 0) buf.append("N/A"); else buf.append(nf.format(dataCache.getUsedBuffers()/(float)dataCache.getBuffers())); buf.append(" (" + nf2.format(dataCache.getUsedBuffers()) + " out of " + nf2.format(dataCache.getBuffers()) + ")"); //buf.append(dataCache.getBuffers()).append(" / "); //buf.append(dataCache.getUsedBuffers()).append(" / "); buf.append(" Cache efficiency : "); if (dataCache.getHits() == 0 && dataCache.getFails() == 0) buf.append("N/A"); else buf.append(nf.format(dataCache.getHits()/(float)(dataCache.getFails() + dataCache.getHits()))); //buf.append(dataCache.getHits()).append(" / "); //buf.append(dataCache.getFails()); LOG.info(buf.toString()); } public BufferStats getDataBufferStats() { return new BufferStats(dataCache.getBuffers(), dataCache .getUsedBuffers(), dataCache.getHits(), dataCache.getFails()); } /** * Retrieve a node by key * * @param key * @return Description of the Return Value */ public Value get(Value key) { try { long p = findValue(key); if (p == KEY_NOT_FOUND) return null; return get(p); } catch (BTreeException bte) { return null; // key not found } catch (IOException ioe) { LOG.debug(ioe); return null; } } /** * Retrieve a node described by the given NodeProxy. * * @param node * Description of the Parameter * @return Description of the Return Value */ public Value get(NodeProxy node) { try { long p = findValue(owner, node); if (p == KEY_NOT_FOUND) return null; return get(p); } catch (BTreeException bte) { return null; } catch (IOException ioe) { LOG.debug(ioe); return null; } } /** * Retrieve node at virtual address p. * * @param p * Description of the Parameter * @return Description of the Return Value */ public Value get(long p) { RecordPos rec = findRecord(p); if (rec == null) { // SanityCheck.TRACE("object at " + StorageAddress.toString(p) // + " not found."); return null; } short storedLen = ByteConversion.byteToShort(rec.getPage().data, rec.offset); rec.offset += LENGTH_DATA_LENGTH; if (ItemId.isRelocated(rec.getTID())) rec.offset += LENGTH_ORIGINAL_LOCATION; Value v; if (storedLen == OVERFLOW) { long pnum = ByteConversion.byteToLong(rec.getPage().data, rec.offset); byte[] data = getOverflowValue(pnum); v = new Value(data); } else v = new Value(rec.getPage().data, rec.offset, storedLen); v.setAddress(p); return v; } protected byte[] getOverflowValue(long pnum) { try { OverflowDOMPage overflow = new OverflowDOMPage(pnum); return overflow.read(); } catch (IOException e) { LOG.error("io error while loading overflow value", e); return null; } } public void removeOverflowValue(Txn transaction, long pnum) { try { OverflowDOMPage overflow = new OverflowDOMPage(pnum); overflow.delete(transaction); } catch (IOException e) { LOG.error("io error while removing overflow value", e); } } /** * Retrieve the last page in the current sequence. * * @return The currentPage value */ private final synchronized DOMPage getCurrentPage(Txn transaction) { long pnum = pages.get(owner); if (pnum == Page.NO_PAGE) { final DOMPage page = new DOMPage(); pages.put(owner, page.page.getPageNum()); // LOG.debug("new page created: " + page.getPage().getPageNum() + " by " // + owner + // "; thread: " + Thread.currentThread().getName()); dataCache.add(page); if (isTransactional && transaction != null) { CreatePageLoggable loggable = new CreatePageLoggable( transaction, Page.NO_PAGE, page.getPageNum(), Page.NO_PAGE); writeToLog(loggable, page.page); } return page; } else return getCurrentPage(pnum); } /** * Retrieve the page with page number p * * @param p * Description of the Parameter * @return The currentPage value */ protected final DOMPage getCurrentPage(long p) { DOMPage page = (DOMPage) dataCache.get(p); if (page == null) { // LOG.debug("Loading page " + p + " from file"); page = new DOMPage(p); } return page; } public void closeDocument() { pages.remove(owner); // SanityCheck.TRACE("current doc closed by: " + owner + // "; thread: " + Thread.currentThread().getName()); } /** * Open the file. * * @return Description of the Return Value * @exception DBException * Description of the Exception */ public boolean open() throws DBException { return super.open(FILE_FORMAT_VERSION_ID); } /** * Put a new key/value pair. * * @param key * Description of the Parameter * @param value * Description of the Parameter * @return Description of the Return Value */ public long put(Txn transaction, Value key, byte[] value) throws ReadOnlyException { long p = add(transaction, value); try { addValue(transaction, key, p); } catch (IOException ioe) { LOG.debug(ioe); return KEY_NOT_FOUND; } catch (BTreeException bte) { LOG.debug(bte); return KEY_NOT_FOUND; } return p; } /** * Physically remove a node. The data of the node will be removed from the * page and the occupied space is freed. */ public void remove(Value key) { remove(null, key); } public void remove(Txn transaction, Value key) { try { long p = findValue(key); if (p == KEY_NOT_FOUND) return; remove(transaction, key, p); } catch (BTreeException bte) { LOG.debug(bte); } catch (IOException ioe) { LOG.debug(ioe); } } /** * Remove the link at the specified position from the file. * * @param p */ private void removeLink(Txn transaction, long p) { RecordPos rec = findRecord(p, false); DOMFilePageHeader ph = rec.getPage().getPageHeader(); if (isTransactional && transaction != null) { byte[] data = new byte[8]; System.arraycopy(rec.getPage().data, rec.offset, data, 0, 8); RemoveValueLoggable loggable = new RemoveValueLoggable(transaction, rec.getPage().getPageNum(), rec.getTID(), rec.offset - 2, data, false, 0); writeToLog(loggable, rec.getPage().page); } int end = rec.offset + 8; System.arraycopy(rec.getPage().data, end, rec.getPage().data, rec.offset - 2, rec.getPage().len - end); rec.getPage().len = rec.getPage().len - (2 + 8); ph.setDataLength(rec.getPage().len); rec.getPage().setDirty(true); ph.decRecordCount(); // LOG.debug("size = " + ph.getRecordCount()); if (rec.getPage().len == 0) { if (isTransactional && transaction != null) { RemoveEmptyPageLoggable loggable = new RemoveEmptyPageLoggable( transaction, rec.getPage().getPageNum(), rec.getPage().ph.getPrevDataPage(), rec.getPage().ph.getNextDataPage()); writeToLog(loggable, rec.getPage().page); } removePage(rec.getPage()); rec.setPage(null); } else { dataCache.add(rec.getPage()); // printPageContents(rec.page); } } /** * Physically remove a node. The data of the node will be removed from the * page and the occupied space is freed. * * @param p */ public void removeNode(long p) { removeNode(null, p); } public void removeNode(Txn transaction, long p) { RecordPos rec = findRecord(p); final int startOffset = rec.offset - 2; final DOMFilePageHeader ph = rec.getPage().getPageHeader(); short vlen = ByteConversion.byteToShort(rec.getPage().data, rec.offset); rec.offset += LENGTH_DATA_LENGTH; short l = vlen; if (ItemId.isLink(rec.getTID())) { throw new RuntimeException("Cannot remove link ..."); } boolean isOverflow = false; long backLink = 0; if (ItemId.isRelocated(rec.getTID())) { backLink = ByteConversion.byteToLong(rec.getPage().data, rec.offset); rec.offset += LENGTH_ORIGINAL_LOCATION; l += LENGTH_ORIGINAL_LOCATION; removeLink(transaction, backLink); } if (l == OVERFLOW) { // remove overflow value isOverflow = true; long overflowLink = ByteConversion.byteToLong(rec.getPage().data, rec.offset); rec.offset += LENGTH_OVERFLOW_LOCATION; try { OverflowDOMPage overflow = new OverflowDOMPage(overflowLink); overflow.delete(transaction); } catch (IOException e) { LOG.error("io error while removing overflow page", e); } l += LENGTH_OVERFLOW_LOCATION; vlen = LENGTH_OVERFLOW_LOCATION; } if (isTransactional && transaction != null) { byte[] data = new byte[vlen]; System.arraycopy(rec.getPage().data, rec.offset, data, 0, vlen); RemoveValueLoggable loggable = new RemoveValueLoggable(transaction, rec.getPage().getPageNum(), rec.getTID(), startOffset, data, isOverflow, backLink); writeToLog(loggable, rec.getPage().page); } int end = startOffset + 2 + 2 + l; int len = ph.getDataLength(); // remove old value System.arraycopy(rec.getPage().data, end, rec.getPage().data, startOffset, len - end); rec.getPage().setDirty(true); rec.getPage().len = len - (2 + 2 + l); rec.getPage().setDirty(true); ph.setDataLength(rec.getPage().len); ph.decRecordCount(); if (rec.getPage().len == 0) { LOG.debug("removing page " + rec.getPage().getPageNum()); if (isTransactional && transaction != null) { RemoveEmptyPageLoggable loggable = new RemoveEmptyPageLoggable( transaction, rec.getPage().getPageNum(), rec.getPage().ph .getPrevDataPage(), rec.getPage().ph .getNextDataPage()); writeToLog(loggable, rec.getPage().page); } removePage(rec.getPage()); rec.setPage(null); } else { rec.getPage().cleanUp(); dataCache.add(rec.getPage()); } } /** * Physically remove a node. The data of the node will be removed from the * page and the occupied space is freed. */ public void remove(Value key, long p) { remove(null, key, p); } public void remove(Txn transaction, Value key, long p) { removeNode(transaction, p); try { removeValue(transaction, key); } catch (BTreeException e) { LOG.warn("btree error while removing node", e); } catch (IOException e) { LOG.warn("io error while removing node", e); } } /** * Remove the specified page. The page is added to the list of free pages. * * @param page */ public void removePage(DOMPage page) { dataCache.remove(page); DOMFilePageHeader ph = page.getPageHeader(); if (ph.getNextDataPage() != Page.NO_PAGE) { DOMPage next = getCurrentPage(ph.getNextDataPage()); next.getPageHeader().setPrevDataPage(ph.getPrevDataPage()); // LOG.debug(next.getPageNum() + ".prev = " + ph.getPrevDataPage()); next.setDirty(true); dataCache.add(next); } if (ph.getPrevDataPage() != Page.NO_PAGE) { DOMPage prev = getCurrentPage(ph.getPrevDataPage()); prev.getPageHeader().setNextDataPage(ph.getNextDataPage()); // LOG.debug(prev.getPageNum() + ".next = " + ph.getNextDataPage()); prev.setDirty(true); dataCache.add(prev); } try { ph.setNextDataPage(Page.NO_PAGE); ph.setPrevDataPage(Page.NO_PAGE); ph.setDataLength(0); ph.setNextTID(ItemId.UNKNOWN_ID); ph.setRecordCount((short) 0); unlinkPages(page.page); } catch (IOException ioe) { LOG.warn(ioe); } if (currentDocument != null) currentDocument.getMetadata().decPageCount(); } /** * Remove a sequence of pages, starting with the page denoted by the passed * address pointer p. * * @param transaction * @param p */ public void removeAll(Txn transaction, long p) { // StringBuffer debug = new StringBuffer(); // debug.append("Removed pages: "); long pnum = StorageAddress.pageFromPointer(p); while (Page.NO_PAGE != pnum) { DOMPage page = getCurrentPage(pnum); if (isTransactional && transaction != null) { RemovePageLoggable loggable = new RemovePageLoggable( transaction, pnum, page.ph.getPrevDataPage(), page.ph.getNextDataPage(), page.data, page.len, page.ph.getCurrentTID(), page.ph.getRecordCount()); writeToLog(loggable, page.page); } pnum = page.getPageHeader().getNextDataPage(); dataCache.remove(page); try { DOMFilePageHeader ph = page.getPageHeader(); ph.setNextDataPage(Page.NO_PAGE); ph.setPrevDataPage(Page.NO_PAGE); ph.setDataLength(0); ph.setNextTID(ItemId.UNKNOWN_ID); ph.setRecordCount((short) 0); page.len = 0; unlinkPages(page.page); } catch (IOException e) { LOG.warn("Error while removing page: " + e.getMessage(), e); } } // LOG.debug(debug.toString()); } public String debugPages(DocumentImpl doc, boolean showPageContents) { StringBuffer buf = new StringBuffer(); buf.append("Pages used by ").append(doc.getURI()); buf.append("; docId ").append(doc.getDocId()).append(':'); long pnum = StorageAddress.pageFromPointer(((StoredNode) doc .getFirstChild()).getInternalAddress()); while (Page.NO_PAGE != pnum) { DOMPage page = getCurrentPage(pnum); dataCache.add(page); buf.append(' ').append(pnum); pnum = page.getPageHeader().getNextDataPage(); if (showPageContents) LOG.debug(debugPageContents(page)); } //Commented out since DocmentImpl has no more internal address //buf.append("; Document metadata at " // + StorageAddress.toString(doc.getInternalAddress())); return buf.toString(); } /** * Set the last page in the sequence to which nodes are currently appended. * * @param page * The new currentPage value */ private final void setCurrentPage(DOMPage page) { long pnum = pages.get(owner); if (pnum == page.page.getPageNum()) return; // pages.remove(owner); // LOG.debug("current page set: " + page.getPage().getPageNum() + " by " + // owner.hashCode() + // "; thread: " + Thread.currentThread().getName()); pages.put(owner, page.page.getPageNum()); } /** * Get the active Lock object for this file. * * @see org.exist.util.Lockable#getLock() */ public final Lock getLock() { return lock; } /** * The current object owning this file. * * @param obj * The new ownerObject value */ public final void setOwnerObject(Object obj) { // if(owner != obj && obj != null) // LOG.debug("owner set -> " + obj.hashCode()); owner = obj; } /** * Update the key/value pair. * * @param key * Description of the Parameter * @param value * Description of the Parameter * @return Description of the Return Value */ public boolean update(Txn transaction, Value key, byte[] value) throws ReadOnlyException { try { long p = findValue(key); if (p == KEY_NOT_FOUND) return false; update(transaction, p, value); } catch (BTreeException bte) { LOG.debug(bte); bte.printStackTrace(); return false; } catch (IOException ioe) { LOG.debug(ioe); return false; } return true; } /** * Update the key/value pair where the value is found at address p. * * @param transaction * @param p * @param value * @throws org.exist.util.ReadOnlyException */ public void update(Txn transaction, long p, byte[] value) throws ReadOnlyException { RecordPos rec = findRecord(p); short vlen = ByteConversion.byteToShort(rec.getPage().data, rec.offset); rec.offset += LENGTH_DATA_LENGTH; if (ItemId.isRelocated(rec.getTID())) rec.offset += LENGTH_ORIGINAL_LOCATION; if (value.length < vlen) { // value is smaller than before throw new IllegalStateException("shrinked"); } else if (value.length > vlen) { throw new IllegalStateException("value too long: expected: " + value.length + "; got: " + vlen); } else { if (isTransactional && transaction != null) { Loggable loggable = new UpdateValueLoggable(transaction, rec.getPage().getPageNum(), rec.getTID(), value, rec.getPage().data, rec.offset); writeToLog(loggable, rec.getPage().page); } // value length unchanged System.arraycopy(value, 0, rec.getPage().data, rec.offset, value.length); } rec.getPage().setDirty(true); } /** * Retrieve the string value of the specified node. This is an optimized low-level method * which will directly traverse the stored DOM nodes and collect the string values of * the specified root node and all its descendants. By directly scanning the stored * node data, we do not need to create a potentially large amount of node objects * and thus save memory and time for garbage collection. * * @param node * @return string value of the specified node */ public String getNodeValue(StoredNode node, boolean addWhitespace) { try { long address = node.getInternalAddress(); RecordPos rec = null; // try to directly locate the root node through its storage address if (address != StoredNode.UNKNOWN_NODE_IMPL_ADDRESS) rec = findRecord(address); if (rec == null) { // fallback to a btree lookup if the node could not be found // by its storage address address = findValue(this, new NodeProxy(node)); if (address == BTree.KEY_NOT_FOUND) return null; rec = findRecord(address); SanityCheck.THROW_ASSERT(rec != null, "Node data could not be found!"); } // we collect the string values in binary format and append to a ByteArrayOutputStream final ByteArrayOutputStream os = new ByteArrayOutputStream(); // now traverse the tree getNodeValue((DocumentImpl)node.getOwnerDocument(), os, rec, true, addWhitespace); final byte[] data = os.toByteArray(); String value; try { value = new String(data, "UTF-8"); } catch (UnsupportedEncodingException e) { LOG.warn("UTF-8 error while reading node value", e); //TODO : why not store another string like "OOOPS !" ? //then return null value = new String(data); } return value; } catch (BTreeException e) { LOG.warn("btree error while reading node value", e); } catch (IOException e) { LOG.warn("io error while reading node value", e); } return null; } /** * Recursive method to retrieve the string values of the root node * and all its descendants. */ private void getNodeValue(DocumentImpl doc, ByteArrayOutputStream os, RecordPos rec, boolean firstCall, boolean addWhitespace) { // locate the next real node, skipping relocated nodes boolean foundNext = false; do { if (rec.offset > rec.getPage().getPageHeader().getDataLength()) { // end of page reached, proceed to the next page final long nextPage = rec.getPage().getPageHeader().getNextDataPage(); if (nextPage == Page.NO_PAGE) { SanityCheck.TRACE("bad link to next page! offset: " + rec.offset + "; len: " + rec.getPage().getPageHeader().getDataLength() + ": " + rec.getPage().page.getPageInfo()); return; } rec.setPage(getCurrentPage(nextPage)); dataCache.add(rec.getPage()); rec.offset = 2; } //TODO : understand this ! -pb short tid = ByteConversion.byteToShort(rec.getPage().data, rec.offset - 2); rec.setTID(tid); if (ItemId.isLink(rec.getTID())) { // this is a link: skip it rec.offset += (LENGTH_TID + LENGTH_FORWARD_LOCATION); } else // ok: node found foundNext = true; } while (!foundNext); // read the page len int len = ByteConversion.byteToShort(rec.getPage().data, rec.offset); rec.offset += LENGTH_DATA_LENGTH; // check if the node was relocated if (ItemId.isRelocated(rec.getTID())) rec.offset += LENGTH_ORIGINAL_LOCATION; byte[] data = rec.getPage().data; int readOffset = rec.offset; boolean inOverflow = false; if (len == OVERFLOW) { // if we have an overflow value, load it from the overflow page final long op = ByteConversion.byteToLong(data, rec.offset); data = getOverflowValue(op); rec.offset += 2 + 8; len = data.length; readOffset = 0; inOverflow = true; } // check the type of the node final short type = Signatures.getType(data[readOffset++]); // switch on the node type switch (type) { case Node.ELEMENT_NODE: final int children = ByteConversion.byteToInt(data, readOffset); readOffset += 4; int dlnLen = ByteConversion.byteToShort(data, readOffset); readOffset += 2; readOffset += doc.getBroker().getBrokerPool().getNodeFactory().lengthInBytes(dlnLen, data, readOffset); final short attributes = ByteConversion.byteToShort(data, readOffset); final boolean extraWhitespace = addWhitespace && children - attributes > 1; rec.offset += len + 2; for (int i = 0; i < children; i++) { //recursive call getNodeValue(doc, os, rec, false, addWhitespace); if (extraWhitespace) os.write((byte) ' '); } return; case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: dlnLen = ByteConversion.byteToShort(data, readOffset); readOffset += 2; int nodeIdLen = doc.getBroker().getBrokerPool().getNodeFactory().lengthInBytes(dlnLen, data, readOffset); readOffset += nodeIdLen; os.write(data, readOffset, len - nodeIdLen - (2 + 1)); break; case Node.ATTRIBUTE_NODE: // use attribute value if the context node is an attribute, i.e. // if this is the first call to the method if (firstCall) { int start = readOffset - 1; final byte idSizeType = (byte) (data[start] & 0x3); final boolean hasNamespace = (data[start] & 0x10) == 0x10; dlnLen = ByteConversion.byteToShort(data, readOffset); readOffset += 2; nodeIdLen = doc.getBroker().getBrokerPool().getNodeFactory().lengthInBytes(dlnLen, data, readOffset); readOffset += nodeIdLen + Signatures.getLength(idSizeType); if (hasNamespace) { readOffset += 2; // skip namespace id final short prefixLen = ByteConversion.byteToShort(data, readOffset); readOffset += prefixLen + 2; // skip prefix } os.write(rec.getPage().data, readOffset, len - (readOffset - start)); } break; } if (!inOverflow) // if it isn't an overflow value, add the value length to the current offset rec.offset += len + 2; } protected RecordPos findRecord(long p) { return findRecord(p, true); } /** * Find a record within the page or the pages linked to it. * * @param p * @return The record position in the page */ protected RecordPos findRecord(long p, boolean skipLinks) { long pageNr = StorageAddress.pageFromPointer(p); short tid = StorageAddress.tidFromPointer(p); while (pageNr != Page.NO_PAGE) { DOMPage page = getCurrentPage(pageNr); dataCache.add(page); RecordPos rec = page.findRecord(tid); if (rec == null) { pageNr = page.getPageHeader().getNextDataPage(); if (pageNr == page.getPageNum()) { SanityCheck.TRACE("circular link to next page on " + pageNr); return null; } } else if (rec.isLink()) { if (!skipLinks) return rec; long forwardLink = ByteConversion.byteToLong(page.data, rec.offset); // LOG.debug("following link on " + pageNr + // " to page " // + StorageAddress.pageFromPointer(forwardLink) // + "; tid=" // + StorageAddress.tidFromPointer(forwardLink)); // load the link page pageNr = StorageAddress.pageFromPointer(forwardLink); tid = StorageAddress.tidFromPointer(forwardLink); } else { return rec; } } return null; } private boolean requiresRedo(Loggable loggable, DOMPage page) { return loggable.getLsn() > page.getPageHeader().getLsn(); } protected void redoCreatePage(CreatePageLoggable loggable) { DOMPage newPage = getCurrentPage(loggable.newPage); DOMFilePageHeader ph = newPage.getPageHeader(); if (ph.getLsn() == Lsn.LSN_INVALID || requiresRedo(loggable, newPage)) { try { reuseDeleted(newPage.page); ph.setStatus(RECORD); ph.setDataLength(0); ph.setNextTID(ItemId.UNKNOWN_ID); ph.setRecordCount((short) 0); newPage.len = 0; newPage.data = new byte[fileHeader.getWorkSize()]; ph.setPrevDataPage(Page.NO_PAGE); if (loggable.nextTID != ItemId.UNKNOWN_ID) ph.setNextTID(loggable.nextTID); ph.setLsn(loggable.getLsn()); newPage.setDirty(true); if (loggable.nextPage == Page.NO_PAGE) ph.setNextDataPage(Page.NO_PAGE); else ph.setNextDataPage(loggable.nextPage); if (loggable.prevPage == Page.NO_PAGE) ph.setPrevDataPage(Page.NO_PAGE); else ph.setPrevDataPage(loggable.prevPage); } catch (IOException e) { LOG.warn("Failed to redo " + loggable.dump() + ": " + e.getMessage(), e); } } dataCache.add(newPage); } protected void undoCreatePage(CreatePageLoggable loggable) { DOMPage page = getCurrentPage(loggable.newPage); DOMFilePageHeader ph = page.getPageHeader(); dataCache.remove(page); try { ph.setNextDataPage(Page.NO_PAGE); ph.setPrevDataPage(Page.NO_PAGE); ph.setDataLength(0); ph.setNextTID(ItemId.UNKNOWN_ID); ph.setRecordCount((short) 0); page.len = 0; unlinkPages(page.page); } catch (IOException e) { LOG.warn("Error while removing page: " + e.getMessage(), e); } } protected void redoAddValue(AddValueLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); if (ph.getLsn() != Lsn.LSN_INVALID && requiresRedo(loggable, page)) { try { ByteConversion.shortToByte(loggable.tid, page.data, page.len); page.len += LENGTH_TID; // save data length // overflow pages have length 0 short vlen = (short) loggable.value.length; ByteConversion.shortToByte(vlen, page.data, page.len); page.len += LENGTH_DATA_LENGTH; // save data System.arraycopy(loggable.value, 0, page.data, page.len, vlen); page.len += vlen; ph.incRecordCount(); ph.setDataLength(page.len); page.setDirty(true); ph.setNextTID(loggable.tid); ph.setLsn(loggable.getLsn()); dataCache.add(page, 2); } catch (ArrayIndexOutOfBoundsException e) { LOG.warn("page: " + page.getPageNum() + "; len = " + page.len + "; value = " + loggable.value.length); throw e; } } } protected void undoAddValue(AddValueLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); RecordPos pos = page.findRecord(ItemId.getId(loggable.tid)); SanityCheck.ASSERT(pos != null, "Record not found!"); int startOffset = pos.offset - 2; // get the record length short l = ByteConversion.byteToShort(page.data, pos.offset); // end offset int end = startOffset + LENGTH_TID + LENGTH_DATA_LENGTH + l; int len = ph.getDataLength(); // remove old value System.arraycopy(page.data, end, page.data, startOffset, len - end); page.setDirty(true); page.len = len - (LENGTH_TID + LENGTH_DATA_LENGTH + l); ph.setDataLength(page.len); page.setDirty(true); ph.decRecordCount(); } protected void redoUpdateValue(UpdateValueLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); if (ph.getLsn() != Lsn.LSN_INVALID && requiresRedo(loggable, page)) { RecordPos rec = page.findRecord(ItemId.getId(loggable.tid)); SanityCheck.THROW_ASSERT(rec != null, "tid " + ItemId.getId(loggable.tid) + " not found on page " + page.getPageNum() + "; contents: " + debugPageContents(page)); ByteConversion.byteToShort(rec.getPage().data, rec.offset); rec.offset += LENGTH_DATA_LENGTH; if (ItemId.isRelocated(rec.getTID())) rec.offset += LENGTH_ORIGINAL_LOCATION; System.arraycopy(loggable.value, 0, rec.getPage().data, rec.offset, loggable.value.length); rec.getPage().ph.setLsn(loggable.getLsn()); rec.getPage().setDirty(true); dataCache.add(rec.getPage()); } } protected void undoUpdateValue(UpdateValueLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); RecordPos rec = page.findRecord(ItemId.getId(loggable.tid)); SanityCheck.THROW_ASSERT(rec != null, "tid " + ItemId.getId(loggable.tid) + " not found on page " + page.getPageNum() + "; contents: " + debugPageContents(page)); short len = ByteConversion.byteToShort(rec.getPage().data, rec.offset); SanityCheck.THROW_ASSERT(len == loggable.oldValue.length); rec.offset += LENGTH_DATA_LENGTH; if (ItemId.isRelocated(rec.getTID())) rec.offset += LENGTH_ORIGINAL_LOCATION; System.arraycopy(loggable.oldValue, 0, page.data, rec.offset, loggable.oldValue.length); page.ph.setLsn(loggable.getLsn()); page.setDirty(true); dataCache.add(page); } protected void redoRemoveValue(RemoveValueLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); // LOG.debug(debugPageContents(page)); DOMFilePageHeader ph = page.getPageHeader(); if (ph.getLsn() != Lsn.LSN_INVALID && requiresRedo(loggable, page)) { RecordPos pos = page.findRecord(ItemId.getId(loggable.tid)); SanityCheck.ASSERT(pos != null, "Record not found: " + ItemId.getId(loggable.tid) + ": " + page.page.getPageInfo() + "\n" + debugPageContents(page)); int startOffset = pos.offset - 2; if (ItemId.isLink(loggable.tid)) { int end = pos.offset + LENGTH_FORWARD_LOCATION; System.arraycopy(page.data, end, page.data, pos.offset - 2, page.len - end); page.len = page.len - (LENGTH_DATA_LENGTH + LENGTH_FORWARD_LOCATION); } else { // get the record length short l = ByteConversion.byteToShort(page.data, pos.offset); if (ItemId.isRelocated(loggable.tid)) { pos.offset += LENGTH_ORIGINAL_LOCATION; l += LENGTH_ORIGINAL_LOCATION; } if (l == OVERFLOW) l += LENGTH_OVERFLOW_LOCATION; // end offset int end = startOffset + LENGTH_TID + LENGTH_DATA_LENGTH + l; int len = ph.getDataLength(); // remove old value System.arraycopy(page.data, end, page.data, startOffset, len - end); page.setDirty(true); page.len = len - (LENGTH_TID + LENGTH_DATA_LENGTH + l); } ph.setDataLength(page.len); page.setDirty(true); ph.decRecordCount(); ph.setLsn(loggable.getLsn()); page.cleanUp(); dataCache.add(page); } // LOG.debug(debugPageContents(page)); } protected void undoRemoveValue(RemoveValueLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); // LOG.debug(debugPageContents(page)); DOMFilePageHeader ph = page.getPageHeader(); int offset = loggable.offset; short vlen = (short) loggable.oldData.length; if (offset < page.ph.getDataLength()) { // make room for the removed value int required; if (ItemId.isLink(loggable.tid)) required = LENGTH_TID + LENGTH_FORWARD_LOCATION; else required = LENGTH_TID + LENGTH_DATA_LENGTH + vlen; if (ItemId.isRelocated(loggable.tid)) required += LENGTH_ORIGINAL_LOCATION; int end = offset + required; try { System.arraycopy(page.data, offset, page.data, end, page.ph.getDataLength() - offset); } catch(ArrayIndexOutOfBoundsException e) { SanityCheck.TRACE("Error while copying data on page " + page.getPageNum() + "; tid: " + ItemId.getId(loggable.tid) + "; required: " + required + "; offset: " + offset + "; end: " + end + "; len: " + (page.ph.getDataLength() - offset) + "; avail: " + page.data.length + "; work: " + fileHeader.getWorkSize()); } } //save TID ByteConversion.shortToByte(loggable.tid, page.data, offset); offset += LENGTH_TID; if (ItemId.isLink(loggable.tid)) { System.arraycopy(loggable.oldData, 0, page.data, offset, LENGTH_FORWARD_LOCATION); page.len += (LENGTH_TID + LENGTH_FORWARD_LOCATION); } else { // save data length // overflow pages have length 0 if (loggable.isOverflow) { ByteConversion.shortToByte(OVERFLOW, page.data, offset); } else { ByteConversion.shortToByte(vlen, page.data, offset); } offset += LENGTH_DATA_LENGTH; if (ItemId.isRelocated(loggable.tid)) { ByteConversion.longToByte(loggable.backLink, page.data, offset); offset += LENGTH_ORIGINAL_LOCATION; page.len += LENGTH_ORIGINAL_LOCATION; } // save data System.arraycopy(loggable.oldData, 0, page.data, offset, vlen); page.len += (LENGTH_TID + LENGTH_DATA_LENGTH + vlen); } ph.incRecordCount(); ph.setDataLength(page.len); page.setDirty(true); page.cleanUp(); dataCache.add(page, 2); // LOG.debug(debugPageContents(page)); } protected void redoRemoveEmptyPage(RemoveEmptyPageLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); if (ph.getLsn() != Lsn.LSN_INVALID && requiresRedo(loggable, page)) { removePage(page); } } protected void undoRemoveEmptyPage(RemoveEmptyPageLoggable loggable) { try { DOMPage newPage = getCurrentPage(loggable.pageNum); reuseDeleted(newPage.page); if (loggable.prevPage == Page.NO_PAGE) newPage.getPageHeader().setPrevDataPage(Page.NO_PAGE); else { DOMPage oldPage = getCurrentPage(loggable.prevPage); oldPage.getPageHeader().setNextDataPage(newPage.getPageNum()); oldPage.setDirty(true); dataCache.add(oldPage); newPage.getPageHeader().setPrevDataPage(oldPage.getPageNum()); } if (loggable.nextPage == Page.NO_PAGE) newPage.getPageHeader().setNextDataPage(Page.NO_PAGE); else { DOMPage oldPage = getCurrentPage(loggable.nextPage); oldPage.getPageHeader().setPrevDataPage(newPage.getPageNum()); newPage.getPageHeader().setNextDataPage(loggable.nextPage); oldPage.setDirty(true); dataCache.add(oldPage); } newPage.ph.setNextTID(ItemId.UNKNOWN_ID); newPage.setDirty(true); dataCache.add(newPage); } catch (IOException e) { LOG.warn("Error during undo: " + e.getMessage(), e); } } protected void redoRemovePage(RemovePageLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); if (ph.getLsn() != Lsn.LSN_INVALID && requiresRedo(loggable, page)) { dataCache.remove(page); try { ph.setNextDataPage(Page.NO_PAGE); ph.setPrevDataPage(Page.NO_PAGE); ph.setDataLen(fileHeader.getWorkSize()); ph.setDataLength(0); ph.setNextTID(ItemId.UNKNOWN_ID); ph.setRecordCount((short) 0); page.len = 0; unlinkPages(page.page); } catch (IOException e) { LOG.warn("Error while removing page: " + e.getMessage(), e); } } } protected void undoRemovePage(RemovePageLoggable loggable) { try { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); reuseDeleted(page.page); ph.setStatus(RECORD); ph.setNextDataPage(loggable.nextPage); ph.setPrevDataPage(loggable.prevPage); ph.setNextTID(loggable.oldTid); ph.setRecordCount(loggable.oldRecCnt); ph.setDataLength(loggable.oldLen); System.arraycopy(loggable.oldData, 0, page.data, 0, loggable.oldLen); page.len = loggable.oldLen; page.setDirty(true); dataCache.add(page); } catch (IOException e) { LOG.warn("Failed to undo " + loggable.dump() + ": " + e.getMessage(), e); } } protected void redoWriteOverflow(WriteOverflowPageLoggable loggable) { try { Page page = getPage(loggable.pageNum); page.read(); PageHeader ph = page.getPageHeader(); reuseDeleted(page); ph.setStatus(RECORD); if (ph.getLsn() != Lsn.LSN_INVALID && requiresRedo(loggable, page)) { if (loggable.nextPage == Page.NO_PAGE) { ph.setNextPage(Page.NO_PAGE); } else { ph.setNextPage(loggable.nextPage); } ph.setLsn(loggable.getLsn()); writeValue(page, loggable.value); } } catch (IOException e) { LOG.warn("Failed to redo " + loggable.dump() + ": " + e.getMessage(), e); } } protected void undoWriteOverflow(WriteOverflowPageLoggable loggable) { try { Page page = getPage(loggable.pageNum); page.read(); unlinkPages(page); } catch (IOException e) { LOG.warn("Failed to undo " + loggable.dump() + ": " + e.getMessage(), e); } } protected void redoRemoveOverflow(RemoveOverflowLoggable loggable) { try { Page page = getPage(loggable.pageNum); page.read(); PageHeader ph = page.getPageHeader(); if (ph.getLsn() != Lsn.LSN_INVALID && requiresRedo(loggable, page)) { unlinkPages(page); } } catch (IOException e) { LOG.warn("Failed to undo " + loggable.dump() + ": " + e.getMessage(), e); } } protected void undoRemoveOverflow(RemoveOverflowLoggable loggable) { try { Page page = getPage(loggable.pageNum); page.read(); PageHeader ph = page.getPageHeader(); reuseDeleted(page); ph.setStatus(RECORD); if (loggable.nextPage == Page.NO_PAGE) { ph.setNextPage(Page.NO_PAGE); } else { ph.setNextPage(loggable.nextPage); } writeValue(page, loggable.oldData); } catch (IOException e) { LOG.warn("Failed to redo " + loggable.dump() + ": " + e.getMessage(), e); } } protected void redoInsertValue(InsertValueLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); if (ph.getLsn() != Lsn.LSN_INVALID && requiresRedo(loggable, page)) { int dlen = page.getPageHeader().getDataLength(); int offset = loggable.offset; // insert in the middle of the page? if (offset < dlen) { int end = offset + loggable.value.length + 2 + 2; try { System.arraycopy(page.data, offset, page.data, end, dlen - offset); } catch(ArrayIndexOutOfBoundsException e) { SanityCheck.TRACE("Error while copying data on page " + page.getPageNum() + "; tid: " + loggable.tid + "; offset: " + offset + "; end: " + end + "; len: " + (dlen - offset)); } } // writing tid ByteConversion.shortToByte((short) loggable.tid, page.data, offset); offset += LENGTH_TID; page.len += LENGTH_TID; // writing value length ByteConversion.shortToByte(loggable.isOverflow() ? OVERFLOW : (short) loggable.value.length, page.data, offset); offset += LENGTH_DATA_LENGTH; page.len += LENGTH_DATA_LENGTH; // writing data System.arraycopy(loggable.value, 0, page.data, offset, loggable.value.length); offset += loggable.value.length; page.len += loggable.value.length; page.getPageHeader().incRecordCount(); ph.setDataLength(page.len); ph.setNextTID(loggable.tid); page.setDirty(true); dataCache.add(page); } } protected void undoInsertValue(InsertValueLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); if (ItemId.isLink(loggable.tid)) { int end = loggable.offset + LENGTH_FORWARD_LOCATION; System.arraycopy(page.data, end, page.data, loggable.offset - 2, page.len - end); page.len = page.len - (LENGTH_DATA_LENGTH + LENGTH_FORWARD_LOCATION); } else { // get the record length int offset = loggable.offset + 2; short l = ByteConversion.byteToShort(page.data, offset); if (ItemId.isRelocated(loggable.tid)) { offset += LENGTH_ORIGINAL_LOCATION; l += LENGTH_ORIGINAL_LOCATION; } if (l == OVERFLOW) l += LENGTH_OVERFLOW_LOCATION; // end offset int end = loggable.offset + (2 + LENGTH_DATA_LENGTH + l); int len = ph.getDataLength(); // remove value try { System.arraycopy(page.data, end, page.data, loggable.offset, len - end); } catch (ArrayIndexOutOfBoundsException e) { SanityCheck.TRACE("Error while copying data on page " + page.getPageNum() + "; tid: " + loggable.tid + "; offset: " + loggable.offset + "; end: " + end + "; len: " + (len - end) + "; dataLength: " + len); } page.len = len - (LENGTH_TID + LENGTH_DATA_LENGTH + l); } ph.setDataLength(page.len); page.setDirty(true); ph.decRecordCount(); ph.setLsn(loggable.getLsn()); page.cleanUp(); dataCache.add(page); } protected void redoSplitPage(SplitPageLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); if (ph.getLsn() != Lsn.LSN_INVALID && requiresRedo(loggable, page)) { byte[] oldData = page.data; page.data = new byte[fileHeader.getWorkSize()]; System.arraycopy(oldData, 0, page.data, 0, loggable.splitOffset); page.len = loggable.splitOffset; ph.setDataLength(page.len); ph.setRecordCount(countRecordsInPage(page)); page.setDirty(true); dataCache.add(page); } } protected void undoSplitPage(SplitPageLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); page.data = loggable.oldData; page.len = loggable.oldLen; ph.setDataLength(page.len); page.setDirty(true); ph.setLsn(loggable.getLsn()); page.cleanUp(); dataCache.add(page); } protected void redoAddLink(AddLinkLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); if (ph.getLsn() != Lsn.LSN_INVALID && requiresRedo(loggable, page)) { ByteConversion.shortToByte(ItemId.setIsLink(loggable.tid), page.data, page.len); page.len += LENGTH_TID; ByteConversion.longToByte(loggable.link, page.data, page.len); page.len += LENGTH_FORWARD_LOCATION; page.setDirty(true); ph.setNextTID(ItemId.getId(loggable.tid)); ph.setDataLength(page.len); ph.setLsn(loggable.getLsn()); ph.incRecordCount(); dataCache.add(page); } } protected void undoAddLink(AddLinkLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); RecordPos rec = page.findRecord(loggable.tid); int end = rec.offset + LENGTH_FORWARD_LOCATION; System.arraycopy(page.data, end, page.data, rec.offset - 2, page.len - end); page.len = page.len - (LENGTH_TID + LENGTH_FORWARD_LOCATION); ph.setDataLength(page.len); page.setDirty(true); ph.decRecordCount(); ph.setLsn(loggable.getLsn()); page.cleanUp(); dataCache.add(page); } protected void redoUpdateLink(UpdateLinkLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); if (ph.getLsn() != Lsn.LSN_INVALID && requiresRedo(loggable, page)) { ByteConversion.longToByte(loggable.link, page.data, loggable.offset); page.setDirty(true); ph.setLsn(loggable.getLsn()); dataCache.add(page); } } protected void undoUpdateLink(UpdateLinkLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); ByteConversion.longToByte(loggable.oldLink, page.data, loggable.offset); page.setDirty(true); ph.setLsn(loggable.getLsn()); dataCache.add(page); } protected void redoAddMovedValue(AddMovedValueLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); if (ph.getLsn() != Lsn.LSN_INVALID && requiresRedo(loggable, page)) { try { ByteConversion.shortToByte(ItemId.setIsRelocated(loggable.tid), page.data, page.len); page.len += LENGTH_TID; short vlen = (short) loggable.value.length; // save data length // overflow pages have length 0 ByteConversion.shortToByte(vlen, page.data, page.len); page.len += LENGTH_DATA_LENGTH; ByteConversion.longToByte(loggable.backLink, page.data, page.len); page.len += LENGTH_FORWARD_LOCATION; // save data System.arraycopy(loggable.value, 0, page.data, page.len, vlen); page.len += vlen; ph.incRecordCount(); ph.setDataLength(page.len); page.setDirty(true); ph.setNextTID(ItemId.getId(loggable.tid)); ph.incRecordCount(); ph.setLsn(loggable.getLsn()); dataCache.add(page, 2); } catch (ArrayIndexOutOfBoundsException e) { LOG.warn("page: " + page.getPageNum() + "; len = " + page.len + "; value = " + loggable.value.length); throw e; } } } protected void undoAddMovedValue(AddMovedValueLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); RecordPos rec = page.findRecord(ItemId.getId(loggable.tid)); SanityCheck.ASSERT(rec != null, "Record with tid " + ItemId.getId(loggable.tid) + " not found: " + debugPageContents(page)); // get the record length short l = ByteConversion.byteToShort(page.data, rec.offset); // end offset int end = rec.offset + 2 + 8 + l; int len = ph.getDataLength(); // remove value try { System.arraycopy(page.data, end, page.data, rec.offset - 2, len - end); } catch (ArrayIndexOutOfBoundsException e) { SanityCheck.TRACE("Error while copying data on page " + page.getPageNum() + "; tid: " + loggable.tid + "; offset: " + (rec.offset - 2) + "; end: " + end + "; len: " + (len - end)); } page.setDirty(true); page.len = len - (LENGTH_TID + LENGTH_DATA_LENGTH + 8 + l); ph.setDataLength(page.len); ph.decRecordCount(); ph.setLsn(loggable.getLsn()); page.cleanUp(); dataCache.add(page); } protected void redoUpdateHeader(UpdateHeaderLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); if (ph.getLsn() != Lsn.LSN_INVALID && requiresRedo(loggable, page)) { if (loggable.nextPage != Page.NO_PAGE) ph.setNextDataPage(loggable.nextPage); if (loggable.prevPage != Page.NO_PAGE) ph.setPrevDataPage(loggable.prevPage); page.setDirty(true); ph.setLsn(loggable.getLsn()); dataCache.add(page, 2); } } protected void undoUpdateHeader(UpdateHeaderLoggable loggable) { DOMPage page = getCurrentPage(loggable.pageNum); DOMFilePageHeader ph = page.getPageHeader(); if (loggable.oldPrev != Page.NO_PAGE) ph.setPrevDataPage(loggable.oldPrev); if (loggable.oldNext != Page.NO_PAGE) ph.setNextDataPage(loggable.oldNext); page.setDirty(true); ph.setLsn(loggable.getLsn()); dataCache.add(page, 2); } protected void dumpValue(Writer writer, Value key) throws IOException { writer.write(Integer.toString(ByteConversion.byteToInt(key.data(), key.start()))); writer.write(':'); try { int bytes = key.getLength() - 4; byte[] data = key.data(); for (int i = 0; i < bytes; i++) { writer.write(DLNBase.toBitString(data[key.start() + 4 + i])); } } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage() + ": doc: " + Integer.toString(ByteConversion.byteToInt(key.data(), key.start()))); } } protected final static class DOMFilePageHeader extends BTreePageHeader { protected int dataLen = 0; protected long nextDataPage = Page.NO_PAGE; protected long prevDataPage = Page.NO_PAGE; protected short tid = ItemId.UNKNOWN_ID; protected short records = 0; public DOMFilePageHeader() { super(); } public DOMFilePageHeader(byte[] data, int offset) throws IOException { super(data, offset); } public void decRecordCount() { --records; } public short getCurrentTID() { return tid; } public short getNextTID() { if (++tid == ItemId.ID_MASK) throw new RuntimeException("no spare ids on page"); return tid; } public boolean hasRoom() { return tid < ItemId.MAX_ID; } public void setNextTID(short tid) { if (tid > ItemId.MAX_ID) throw new RuntimeException("TID overflow! TID = " + tid); this.tid = tid; } public int getDataLength() { return dataLen; } public long getNextDataPage() { return nextDataPage; } public long getPrevDataPage() { return prevDataPage; } public short getRecordCount() { return records; } public void incRecordCount() { records++; } public int read(byte[] data, int offset) throws IOException { offset = super.read(data, offset); records = ByteConversion.byteToShort(data, offset); offset += 2; dataLen = ByteConversion.byteToInt(data, offset); offset += 4; nextDataPage = ByteConversion.byteToLong(data, offset); offset += 8; prevDataPage = ByteConversion.byteToLong(data, offset); offset += 8; tid = ByteConversion.byteToShort(data, offset); return offset + 2; } public int write(byte[] data, int offset) throws IOException { offset = super.write(data, offset); ByteConversion.shortToByte(records, data, offset); offset += 2; ByteConversion.intToByte(dataLen, data, offset); offset += 4; ByteConversion.longToByte(nextDataPage, data, offset); offset += 8; ByteConversion.longToByte(prevDataPage, data, offset); offset += 8; ByteConversion.shortToByte(tid, data, offset); return offset + 2; } public void setDataLength(int len) { dataLen = len; } public void setNextDataPage(long page) { nextDataPage = page; } public void setPrevDataPage(long page) { prevDataPage = page; } public void setRecordCount(short recs) { records = recs; } } protected final class DOMPage implements Cacheable { // the raw working data (without page header) of this page byte[] data; // the current size of the used data int len = 0; // the low-level page Page page; DOMFilePageHeader ph; // fields required by Cacheable int refCount = 0; int timestamp = 0; // has the page been saved or is it dirty? boolean saved = true; // set to true if the page has been removed from the cache boolean invalidated = false; public DOMPage() { page = createNewPage(); ph = (DOMFilePageHeader) page.getPageHeader(); // LOG.debug("Created new page: " + page.getPageNum()); data = new byte[fileHeader.getWorkSize()]; len = 0; } public DOMPage(long pos) { try { page = getPage(pos); load(page); } catch (IOException ioe) { LOG.debug(ioe); ioe.printStackTrace(); } } public DOMPage(Page page) { this.page = page; load(page); } protected Page createNewPage() { try { Page page = getFreePage(); DOMFilePageHeader ph = (DOMFilePageHeader) page.getPageHeader(); ph.setStatus(RECORD); ph.setDirty(true); ph.setNextDataPage(Page.NO_PAGE); ph.setPrevDataPage(Page.NO_PAGE); ph.setNextPage(Page.NO_PAGE); ph.setNextTID(ItemId.UNKNOWN_ID); ph.setDataLength(0); ph.setRecordCount((short) 0); if (currentDocument != null) currentDocument.getMetadata().incPageCount(); // LOG.debug("New page: " + page.getPageNum() + "; " + page.getPageInfo()); return page; } catch (IOException ioe) { LOG.warn(ioe); return null; } } public RecordPos findRecord(short targetId) { final int dlen = ph.getDataLength(); RecordPos rec = null; for (int pos = 0; pos < dlen;) { short tid = ByteConversion.byteToShort(data, pos); pos += LENGTH_TID; if (ItemId.matches(tid, targetId)) { if (ItemId.isLink(tid)) { rec = new RecordPos(pos, this, tid, true); } else { rec = new RecordPos(pos, this, tid); } break; } else if (ItemId.isLink(tid)) { pos += LENGTH_FORWARD_LOCATION; } else { short vlen = ByteConversion.byteToShort(data, pos); pos += LENGTH_DATA_LENGTH; if (vlen < 0) { LOG.warn("page = " + page.getPageNum() + "; pos = " + pos + "; vlen = " + vlen + "; tid = " + tid + "; target = " + targetId); } if (ItemId.isRelocated(tid)) { pos += LENGTH_ORIGINAL_LOCATION + vlen; } else { pos += vlen; } if (vlen == OVERFLOW) pos += LENGTH_OVERFLOW_LOCATION; } } return rec; } /* * (non-Javadoc) * * @see org.exist.storage.cache.Cacheable#getKey() */ public long getKey() { return page.getPageNum(); } /* * (non-Javadoc) * * @see org.exist.storage.cache.Cacheable#getReferenceCount() */ public int getReferenceCount() { return refCount; } public int decReferenceCount() { return refCount > 0 ? --refCount : 0; } public int incReferenceCount() { if (refCount < Cacheable.MAX_REF) ++refCount; return refCount; } /* * (non-Javadoc) * * @see org.exist.storage.cache.Cacheable#setReferenceCount(int) */ public void setReferenceCount(int count) { refCount = count; } /* * (non-Javadoc) * * @see org.exist.storage.cache.Cacheable#setTimestamp(int) */ public void setTimestamp(int timestamp) { this.timestamp = timestamp; } /* * (non-Javadoc) * * @see org.exist.storage.cache.Cacheable#getTimestamp() */ public int getTimestamp() { return timestamp; } public DOMFilePageHeader getPageHeader() { return ph; } public long getPageNum() { return page.getPageNum(); } public boolean isDirty() { return !saved; } public void setDirty(boolean dirty) { saved = !dirty; page.getPageHeader().setDirty(dirty); } private void load(Page page) { try { data = page.read(); ph = (DOMFilePageHeader) page.getPageHeader(); len = ph.getDataLength(); if (data.length == 0) { data = new byte[fileHeader.getWorkSize()]; len = 0; return; } } catch (IOException ioe) { LOG.debug(ioe); ioe.printStackTrace(); } saved = true; } public void write() { if (page == null) return; try { if (!ph.isDirty()) return; ph.setDataLength(len); writeValue(page, data); setDirty(false); } catch (IOException ioe) { LOG.error(ioe); } } public String dumpPage() { return "Contents of page " + page.getPageNum() + ": " + hexDump(data); } public boolean sync(boolean syncJournal) { if (isDirty()) { write(); if (isTransactional && syncJournal && logManager.lastWrittenLsn() < ph.getLsn()) logManager.flushToLog(true); return true; } return false; } /* * (non-Javadoc) * * @see org.exist.storage.cache.Cacheable#allowUnload() */ public boolean allowUnload() { return true; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { DOMPage other = (DOMPage) obj; return page.equals(other.page); } public void invalidate() { invalidated = true; } public boolean isInvalidated() { return invalidated; } /** * Walk through the page after records have been removed. Set the tid * counter to the next spare id that can be used for following * insertions. */ public void cleanUp() { final int dlen = ph.getDataLength(); short maxTID = 0; for (int pos = 0; pos < dlen;) { short tid = ByteConversion.byteToShort(data, pos); pos += LENGTH_TID; if (ItemId.getId(tid) > ItemId.MAX_ID) { LOG.debug(debugPageContents(this)); throw new RuntimeException("TID overflow in page " + getPageNum()); } if (ItemId.getId(tid) > maxTID) maxTID = ItemId.getId(tid); if (ItemId.isLink(tid)) { pos += LENGTH_FORWARD_LOCATION; } else { short vlen = ByteConversion.byteToShort(data, pos); pos += LENGTH_DATA_LENGTH; if (ItemId.isRelocated(tid)) { pos += vlen == OVERFLOW ? LENGTH_ORIGINAL_LOCATION + LENGTH_OVERFLOW_LOCATION : LENGTH_ORIGINAL_LOCATION + vlen; } else pos += vlen == OVERFLOW ? LENGTH_OVERFLOW_LOCATION : vlen; } } ph.setNextTID(maxTID); } } /** * This represents an overflow page. Overflow pages are created if the node * data exceeds the size of one page. An overflow page is a sequence of * DOMPages. * * @author wolf * */ protected final class OverflowDOMPage { Page firstPage = null; public OverflowDOMPage(Txn transaction) { firstPage = createNewPage(); LOG.debug("Creating overflow page: " + firstPage.getPageNum()); } public OverflowDOMPage(long first) throws IOException { firstPage = getPage(first); } protected Page createNewPage() { try { Page page = getFreePage(); DOMFilePageHeader ph = (DOMFilePageHeader) page.getPageHeader(); ph.setStatus(RECORD); ph.setDirty(true); ph.setNextDataPage(Page.NO_PAGE); ph.setPrevDataPage(Page.NO_PAGE); ph.setNextPage(Page.NO_PAGE); ph.setNextTID(ItemId.UNKNOWN_ID); ph.setDataLength(0); ph.setRecordCount((short) 0); if (currentDocument != null) currentDocument.getMetadata().incPageCount(); // LOG.debug("New page: " + page.getPageNum() + "; " + page.getPageInfo()); return page; } catch (IOException ioe) { LOG.warn(ioe); return null; } } // Write binary resource from inputstream public int write(Txn transaction, InputStream is) { int pageCount = 0; Page currentPage = firstPage; try { // Transfer bytes from inputstream to db final int chunkSize = fileHeader.getWorkSize(); byte[] buf = new byte[chunkSize]; int len = is.read(buf); // Check if stream does contain any data if (len < 1){ currentPage.setPageNum(Page.NO_PAGE); currentPage.getPageHeader().setNextPage(Page.NO_PAGE); //Shouldn't we return 0 here ? return -1; } // Read remaining stream while ( len > -1 ) { // If there are bytes in stream, read if (len > 0){ Value value = new Value(buf, 0, len); Page nextPage; if (len == chunkSize) { nextPage = createNewPage(); currentPage.getPageHeader().setNextPage(nextPage.getPageNum()); } else { nextPage = null; currentPage.getPageHeader().setNextPage(Page.NO_PAGE); } // If no data is in input stream left, don't write if (isTransactional && transaction != null) { long nextPageNum = (nextPage == null) ? Page.NO_PAGE : nextPage.getPageNum(); Loggable loggable = new WriteOverflowPageLoggable( transaction, currentPage.getPageNum(), nextPageNum , value); writeToLog(loggable, currentPage); } writeValue(currentPage, value); pageCount++; currentPage = nextPage; } len = is.read(buf); } // TODO what if remaining length=0? } catch (IOException ex) { LOG.error("io error while writing overflow page", ex); } return pageCount; } public int write(Txn transaction, byte[] data) { int pageCount = 0; try { int remaining = data.length; Page currentPage = firstPage; int pos = 0; while (remaining > 0) { final int chunkSize = remaining > fileHeader.getWorkSize() ? fileHeader.getWorkSize() : remaining; remaining -= chunkSize; Value value = new Value(data, pos, chunkSize); Page nextPage; if (remaining > 0) { nextPage = createNewPage(); currentPage.getPageHeader().setNextPage(nextPage.getPageNum()); } else { nextPage = null; currentPage.getPageHeader().setNextPage(Page.NO_PAGE); } if (isTransactional && transaction != null) { Loggable loggable = new WriteOverflowPageLoggable( transaction, currentPage.getPageNum(), remaining > 0 ? nextPage.getPageNum() : Page.NO_PAGE, value); writeToLog(loggable, currentPage); } writeValue(currentPage, value); pos += chunkSize; currentPage = nextPage; ++pageCount; } } catch (IOException e) { LOG.error("io error while writing overflow page", e); } return pageCount; } public byte[] read() { ByteArrayOutputStream os = new ByteArrayOutputStream(); streamTo(os); return os.toByteArray(); } public void streamTo(OutputStream os) { Page page = firstPage; int count = 0; while (page != null) { try { byte[] chunk = page.read(); os.write(chunk); long nextPageNumber = page.getPageHeader().getNextPage(); page = (nextPageNumber == Page.NO_PAGE) ? null : getPage(nextPageNumber); } catch (IOException e) { LOG.error("io error while loading overflow page " + firstPage.getPageNum() + "; read: " + count, e); break; } ++count; } } public void delete(Txn transaction) throws IOException { Page page = firstPage; while (page != null) { LOG.debug("removing overflow page " + page.getPageNum()); long nextPageNumber = page.getPageHeader().getNextPage(); if (isTransactional && transaction != null) { byte[] chunk = page.read(); Loggable loggable = new RemoveOverflowLoggable(transaction, page.getPageNum(), nextPageNumber, chunk); writeToLog(loggable, page); } unlinkPages(page); page = (nextPageNumber == Page.NO_PAGE) ? null : getPage(nextPageNumber); } } public long getPageNum() { return firstPage.getPageNum(); } } public final void addToBuffer(DOMPage page) { dataCache.add(page); } private final class FindCallback implements BTreeCallback { public final static int KEYS = 1; public final static int VALUES = 0; int mode; ArrayList values = new ArrayList(); public FindCallback(int mode) { this.mode = mode; } public ArrayList getValues() { return values; } public boolean indexInfo(Value value, long pointer) { switch (mode) { case VALUES: RecordPos rec = findRecord(pointer); short len = ByteConversion.byteToShort(rec.getPage().data, rec.offset); values.add(new Value(rec.getPage().data, rec.offset + LENGTH_DATA_LENGTH, len)); return true; case KEYS: values.add(value); return true; } return false; } } }
package org.exist.xquery; import java.util.Iterator; import org.exist.dom.DocumentImpl; import org.exist.dom.DocumentSet; import org.exist.dom.ExtArrayNodeSet; import org.exist.dom.NodeProxy; import org.exist.dom.NodeSet; import org.exist.dom.NodeVisitor; import org.exist.dom.StoredNode; import org.exist.dom.VirtualNodeSet; import org.exist.numbering.NodeId; import org.exist.storage.ElementIndex; import org.exist.storage.ElementValue; import org.exist.storage.NotificationService; import org.exist.storage.UpdateListener; import org.exist.xquery.value.Item; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.Type; import org.w3c.dom.Node; /** * Processes all location path steps (like descendant::*, ancestor::XXX). * * The results of the first evaluation of the expression are cached for the * lifetime of the object and only reloaded if the context sequence (as passed * to the {@link #eval(Sequence, Item)} method) has changed. * * @author wolf */ public class LocationStep extends Step { private final int ATTR_DIRECT_SELECT_THRESHOLD = 10; protected NodeSet currentSet = null; protected DocumentSet currentDocs = null; protected UpdateListener listener = null; protected Expression parent = null; // Fields for caching the last result protected CachedResult cached = null; protected int parentDeps = Dependency.UNKNOWN_DEPENDENCY; protected boolean preload = false; protected boolean inUpdate = false; // Cache for the current NodeTest type private Integer nodeTestType = null; public LocationStep(XQueryContext context, int axis) { super(context, axis); } public LocationStep(XQueryContext context, int axis, NodeTest test) { super(context, axis, test); } /* * (non-Javadoc) * * @see org.exist.xquery.AbstractExpression#getDependencies() */ public int getDependencies() { int deps = Dependency.CONTEXT_SET; for (Iterator i = predicates.iterator(); i.hasNext();) { deps |= ((Predicate) i.next()).getDependencies(); } return deps; } /** * If the current path expression depends on local variables from a for * expression, we can optimize by preloading entire element or attribute * sets. * * @return */ protected boolean preloadNodeSets() { // TODO : log elsewhere ? if (preload) { context.getProfiler().message(this, Profiler.OPTIMIZATIONS, null, "Preloaded NodeSets"); return true; } if (inUpdate) return false; if ((parentDeps & Dependency.LOCAL_VARS) == Dependency.LOCAL_VARS) { context.getProfiler().message(this, Profiler.OPTIMIZATIONS, null, "Preloaded NodeSets"); return true; } return false; } protected Sequence applyPredicate(Sequence outerSequence, Sequence contextSequence) throws XPathException { if (contextSequence == null) return Sequence.EMPTY_SEQUENCE; if (predicates.size() == 0) // Nothing to apply return contextSequence; Predicate pred; Sequence result = contextSequence; for (Iterator i = predicates.iterator(); i.hasNext();) { // TODO : log and/or profile ? pred = (Predicate) i.next(); pred.setContextDocSet(getContextDocSet()); result = pred.evalPredicate(outerSequence, result, axis); } return result; } /* * (non-Javadoc) * * @see org.exist.xquery.Step#analyze(org.exist.xquery.Expression) */ public void analyze(AnalyzeContextInfo contextInfo) throws XPathException { this.parent = contextInfo.getParent(); parentDeps = parent.getDependencies(); if ((contextInfo.getFlags() & IN_UPDATE) > 0) inUpdate = true; if ((contextInfo.getFlags() & SINGLE_STEP_EXECUTION) > 0) { preload = true; } // Mark ".", which is expanded as self::node() by the parser //even though it may *also* be relevant with atomic sequences if (this.axis == Constants.SELF_AXIS && this.test.getType()== Type.NODE) contextInfo.addFlag(DOT_TEST); // TODO : log somewhere ? super.analyze(contextInfo); } public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException { if (context.getProfiler().isEnabled()) { context.getProfiler().start(this); context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies())); if (contextSequence != null) context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence); if (contextItem != null) context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence()); } Sequence result; if (contextItem != null) contextSequence = contextItem.toSequence(); /* * if(contextSequence == null) //Commented because this the high level * result nodeset is *really* null result = NodeSet.EMPTY_SET; //Try to * return cached results else */if (cached != null && cached.isValid(contextSequence)) { // WARNING : commented since predicates are *also* applied below ! /* * if (predicates.size() > 0) { applyPredicate(contextSequence, * cached.getResult()); } else { */ result = cached.getResult(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "Using cached results", result); } else if (needsComputation()) { if (contextSequence == null) throw new XPathException(getASTNode(), "XPDY0002 : undefined context sequence for '" + this.toString() + "'"); switch (axis) { case Constants.DESCENDANT_AXIS: case Constants.DESCENDANT_SELF_AXIS: result = getDescendants(context, contextSequence .toNodeSet()); break; case Constants.CHILD_AXIS: //VirtualNodeSets may have modified the axis ; checking the type //TODO : futher checks ? if (this.test.getType() == 2) { this.axis = Constants.ATTRIBUTE_AXIS; result = getAttributes(context, contextSequence.toNodeSet()); } else result = getChildren(context, contextSequence.toNodeSet()); break; case Constants.ANCESTOR_SELF_AXIS: case Constants.ANCESTOR_AXIS: result = getAncestors(context, contextSequence.toNodeSet()); break; case Constants.PARENT_AXIS: result = getParents(context, contextSequence.toNodeSet()); break; case Constants.SELF_AXIS: if (!(contextSequence instanceof VirtualNodeSet) && Type.subTypeOf(contextSequence.getItemType(), Type.ATOMIC)) result = getSelfAtomic(contextSequence); else result = getSelf(context, contextSequence.toNodeSet()); break; case Constants.ATTRIBUTE_AXIS: case Constants.DESCENDANT_ATTRIBUTE_AXIS: result = getAttributes(context, contextSequence.toNodeSet()); break; case Constants.PRECEDING_AXIS: result = getPreceding(context, contextSequence.toNodeSet()); break; case Constants.FOLLOWING_AXIS: result = getFollowing(context, contextSequence.toNodeSet()); break; case Constants.PRECEDING_SIBLING_AXIS: case Constants.FOLLOWING_SIBLING_AXIS: result = getSiblings(context, contextSequence.toNodeSet()); break; default: throw new IllegalArgumentException( "Unsupported axis specified"); } } else result = NodeSet.EMPTY_SET; // Caches the result if (contextSequence instanceof NodeSet) { // TODO : cache *after* removing duplicates ? -pb cached = new CachedResult((NodeSet) contextSequence, result); registerUpdateListener(); } // Remove duplicate nodes result.removeDuplicates(); // Apply the predicate result = applyPredicate(contextSequence, result); if (context.getProfiler().isEnabled()) context.getProfiler().end(this, "", result); return result; } // Avoid unnecessary tests (these should be detected by the parser) private boolean needsComputation() { // TODO : log this ? switch (axis) { // Certainly not exhaustive case Constants.ANCESTOR_SELF_AXIS: case Constants.PARENT_AXIS: case Constants.SELF_AXIS: if (nodeTestType == null) nodeTestType = new Integer(test.getType()); if (nodeTestType.intValue() != Type.NODE && nodeTestType.intValue() != Type.ELEMENT) { if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "avoid useless computations"); return false; } } return true; } /** * @param context * @param contextSet * @return */ protected Sequence getSelf(XQueryContext context, NodeSet contextSet) { if (test.isWildcardTest()) { if (nodeTestType == null) nodeTestType = new Integer(test.getType()); if (Type.subTypeOf(nodeTestType.intValue(), Type.NODE)) { if (Expression.NO_CONTEXT_ID != contextId) { if (contextSet instanceof VirtualNodeSet) { ((VirtualNodeSet) contextSet).setInPredicate(true); ((VirtualNodeSet) contextSet).setSelfIsContext(); ((VirtualNodeSet) contextSet).setContextId(contextId); } else if (Type.subTypeOf(contextSet.getItemType(), Type.NODE)) { NodeProxy p; for (Iterator i = contextSet.iterator(); i.hasNext();) { p = (NodeProxy) i.next(); if (test.matches(p)) p.addContextNode(contextId, p); } } } return contextSet; } else { VirtualNodeSet vset = new VirtualNodeSet(axis, test, contextId, contextSet); vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId); return vset; } } else { DocumentSet docs = getDocumentSet(contextSet); NodeSelector selector = new SelfSelector(contextSet, contextId); ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); return index.findElementsByTagName(ElementValue.ELEMENT, docs, test .getName(), selector); } } protected Sequence getSelfAtomic(Sequence contextSequence) throws XPathException { if (!test.isWildcardTest()) throw new XPathException(getASTNode(), test.toString() + " cannot be applied to an atomic value."); return contextSequence; } protected NodeSet getAttributes(XQueryContext context, NodeSet contextSet) { if (test.isWildcardTest()) { NodeSet result = new VirtualNodeSet(axis, test, contextId, contextSet); ((VirtualNodeSet) result) .setInPredicate(Expression.NO_CONTEXT_ID != contextId); return result; // if there's just a single known node in the context, it is faster // do directly search for the attribute in the parent node. } else if (!(contextSet instanceof VirtualNodeSet) && axis == Constants.ATTRIBUTE_AXIS && contextSet.getLength() < ATTR_DIRECT_SELECT_THRESHOLD) { if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "direct attribute selection"); if (contextSet.getLength() == 0) return NodeSet.EMPTY_SET; NodeProxy proxy = contextSet.get(0); if (proxy != null && proxy.getInternalAddress() != StoredNode.UNKNOWN_NODE_IMPL_ADDRESS) return contextSet.directSelectAttribute(test.getName(), contextId); } if (preloadNodeSets()) { DocumentSet docs = getDocumentSet(contextSet); if (currentSet == null || currentDocs == null || !(docs.equals(currentDocs))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); // TODO : why a null selector here ? We have one below ! currentSet = index.findElementsByTagName( ElementValue.ATTRIBUTE, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } switch (axis) { case Constants.ATTRIBUTE_AXIS: return currentSet.selectParentChild(contextSet, NodeSet.DESCENDANT, contextId); case Constants.DESCENDANT_ATTRIBUTE_AXIS: return currentSet.selectAncestorDescendant(contextSet, NodeSet.DESCENDANT, false, contextId); default: throw new IllegalArgumentException( "Unsupported axis specified"); } } else { NodeSelector selector; DocumentSet docs = getDocumentSet(contextSet); // TODO : why a selector here ? We havn't one above ! switch (axis) { case Constants.ATTRIBUTE_AXIS: selector = new ChildSelector(contextSet, contextId); break; case Constants.DESCENDANT_ATTRIBUTE_AXIS: selector = new DescendantSelector(contextSet, contextId); break; default: throw new IllegalArgumentException( "Unsupported axis specified"); } ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); if (contextSet instanceof ExtArrayNodeSet) { return index.findDescendantsByTagName(ElementValue.ATTRIBUTE, test.getName(), axis, docs, (ExtArrayNodeSet) contextSet, contextId); } else { return index.findElementsByTagName(ElementValue.ATTRIBUTE, docs, test.getName(), selector); } } } protected NodeSet getChildren(XQueryContext context, NodeSet contextSet) { if (test.isWildcardTest()) { // test is one out of *, text(), node() VirtualNodeSet vset = new VirtualNodeSet(axis, test, contextId, contextSet); vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId); return vset; } else if (preloadNodeSets()) { DocumentSet docs = getDocumentSet(contextSet); // TODO : understand why this one is different from the other ones if (currentSet == null || currentDocs == null || !(docs == currentDocs || docs.equals(currentDocs))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } return currentSet.selectParentChild(contextSet, NodeSet.DESCENDANT, contextId); } else { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); DocumentSet docs = getDocumentSet(contextSet); if (contextSet instanceof ExtArrayNodeSet) { return index.findDescendantsByTagName(ElementValue.ELEMENT, test.getName(), axis, docs, (ExtArrayNodeSet) contextSet, contextId); } else { // if (contextSet instanceof VirtualNodeSet) // ((VirtualNodeSet)contextSet).realize(); NodeSelector selector = new ChildSelector(contextSet, contextId); return index.findElementsByTagName(ElementValue.ELEMENT, docs, test .getName(), selector); } } } protected NodeSet getDescendants(XQueryContext context, NodeSet contextSet) { if (test.isWildcardTest()) { // test is one out of *, text(), node() VirtualNodeSet vset = new VirtualNodeSet(axis, test, contextId, contextSet); vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId); return vset; } else if (preloadNodeSets()) { DocumentSet docs = getDocumentSet(contextSet); // TODO : understand why this one is different from the other ones if (currentSet == null || currentDocs == null || !(docs == currentDocs || docs.equals(currentDocs))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } switch (axis) { case Constants.DESCENDANT_SELF_AXIS: return currentSet.selectAncestorDescendant(contextSet, NodeSet.DESCENDANT, true, contextId); case Constants.DESCENDANT_AXIS: return currentSet.selectAncestorDescendant(contextSet, NodeSet.DESCENDANT, false, contextId); default: throw new IllegalArgumentException( "Unsupported axis specified"); } } else { NodeSelector selector; DocumentSet docs = contextSet.getDocumentSet(); switch (axis) { case Constants.DESCENDANT_SELF_AXIS: selector = new DescendantOrSelfSelector(contextSet, contextId); break; case Constants.DESCENDANT_AXIS: selector = new DescendantSelector(contextSet, contextId); break; default: throw new IllegalArgumentException( "Unsupported axis specified"); } ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); if (contextSet instanceof ExtArrayNodeSet) { return index.findDescendantsByTagName(ElementValue.ELEMENT, test.getName(), axis, docs, (ExtArrayNodeSet) contextSet, contextId); } else return index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), selector); } } protected NodeSet getSiblings(XQueryContext context, NodeSet contextSet) { if (test.isWildcardTest()) { ExtArrayNodeSet result = new ExtArrayNodeSet(contextSet.getLength()); SiblingVisitor visitor = new SiblingVisitor(result); for (Iterator i = contextSet.iterator(); i.hasNext();) { NodeProxy current = (NodeProxy) i.next(); NodeId parentId = current.getNodeId().getParentId(); if(parentId.getTreeLevel() == 1 && current.getDocument().getCollection().isTempCollection()) continue; StoredNode parentNode = context.getBroker().objectWith(current.getOwnerDocument(), parentId); visitor.setContext(current); parentNode.accept(visitor); } return result; } else { DocumentSet docs = getDocumentSet(contextSet); if (currentSet == null || currentDocs == null || !(docs.equals(currentDocs))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } switch (axis) { case Constants.PRECEDING_SIBLING_AXIS: return currentSet.selectPrecedingSiblings(contextSet, contextId); case Constants.FOLLOWING_SIBLING_AXIS: return currentSet.selectFollowingSiblings(contextSet, contextId); default: throw new IllegalArgumentException( "Unsupported axis specified"); } } } private class SiblingVisitor implements NodeVisitor { private ExtArrayNodeSet resultSet; private NodeProxy contextNode; public SiblingVisitor(ExtArrayNodeSet resultSet) { this.resultSet = resultSet; } public void setContext(NodeProxy contextNode) { this.contextNode = contextNode; } public boolean visit(StoredNode current) { if (contextNode.getNodeId().getTreeLevel() == current.getNodeId().getTreeLevel()) { int cmp = current.getNodeId().compareTo(contextNode.getNodeId()); if (((axis == Constants.FOLLOWING_SIBLING_AXIS && cmp > 0) || (axis == Constants.PRECEDING_SIBLING_AXIS && cmp < 0)) && test.matches(current)) { NodeProxy sibling = resultSet.get((DocumentImpl) current.getOwnerDocument(), current.getNodeId()); if (sibling == null) { sibling = new NodeProxy((DocumentImpl) current.getOwnerDocument(), current.getNodeId(), current.getInternalAddress()); if (Expression.NO_CONTEXT_ID != contextId) { sibling.addContextNode(contextId, contextNode); } else sibling.copyContext(contextNode); resultSet.add(sibling); resultSet.setSorted(sibling.getDocument(), true); } else if (Expression.NO_CONTEXT_ID != contextId) sibling.addContextNode(contextId, contextNode); } } return true; } } protected NodeSet getPreceding(XQueryContext context, NodeSet contextSet) throws XPathException { if (test.isWildcardTest()) { // TODO : throw an exception here ! Don't let this pass through return NodeSet.EMPTY_SET; } else { DocumentSet docs = getDocumentSet(contextSet); if (currentSet == null || currentDocs == null || !(docs.equals(currentDocs))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } return currentSet.selectPreceding(contextSet); } } protected NodeSet getFollowing(XQueryContext context, NodeSet contextSet) throws XPathException { if (test.isWildcardTest()) { // TODO : throw an exception here ! Don't let this pass through return NodeSet.EMPTY_SET; } else { DocumentSet docs = getDocumentSet(contextSet); if (currentSet == null || currentDocs == null || !(docs.equals(currentDocs))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } return currentSet.selectFollowing(contextSet); } } protected NodeSet getAncestors(XQueryContext context, NodeSet contextSet) { if (test.isWildcardTest()) { NodeSet result = new ExtArrayNodeSet(); result.setProcessInReverseOrder(true); for (Iterator i = contextSet.iterator(); i.hasNext();) { NodeProxy current = (NodeProxy) i.next(); NodeProxy ancestor; if (axis == Constants.ANCESTOR_SELF_AXIS && test.matches(current)) { ancestor = new NodeProxy(current.getDocument(), current.getNodeId(), Node.ELEMENT_NODE, current.getInternalAddress()); NodeProxy t = result.get(ancestor); if (t == null) { if (Expression.NO_CONTEXT_ID != contextId) ancestor.addContextNode(contextId, current); else ancestor.copyContext(current); result.add(ancestor); } else t.addContextNode(contextId, current); } NodeId parentID = current.getNodeId().getParentId(); while (parentID != null) { ancestor = new NodeProxy(current.getDocument(), parentID, Node.ELEMENT_NODE); // Filter out the temporary nodes wrapper element if (parentID != NodeId.DOCUMENT_NODE && !(parentID.getTreeLevel() == 1 && current.getDocument().getCollection().isTempCollection())) { if (test.matches(ancestor)) { NodeProxy t = result.get(ancestor); if (t == null) { if (Expression.NO_CONTEXT_ID != contextId) ancestor.addContextNode(contextId, current); else ancestor.copyContext(current); result.add(ancestor); } else t.addContextNode(contextId, current); } } parentID = parentID.getParentId(); } } return result; } else if (preloadNodeSets()) { DocumentSet docs = getDocumentSet(contextSet); if (currentSet == null || currentDocs == null || !(docs.equals(currentDocs))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } switch (axis) { case Constants.ANCESTOR_SELF_AXIS: return currentSet.selectAncestors(contextSet, true, contextId); case Constants.ANCESTOR_AXIS: return currentSet.selectAncestors(contextSet, false, contextId); default: throw new IllegalArgumentException( "Unsupported axis specified"); } } else { NodeSelector selector; DocumentSet docs = getDocumentSet(contextSet); switch (axis) { case Constants.ANCESTOR_SELF_AXIS: selector = new AncestorSelector(contextSet, contextId, true); break; case Constants.ANCESTOR_AXIS: selector = new AncestorSelector(contextSet, contextId, false); break; default: throw new IllegalArgumentException( "Unsupported axis specified"); } ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); return index.findElementsByTagName(ElementValue.ELEMENT, docs, test .getName(), selector); } } protected NodeSet getParents(XQueryContext context, NodeSet contextSet) { if (test.isWildcardTest()) { NodeSet temp = contextSet.getParents(contextId); NodeSet result = new ExtArrayNodeSet(); NodeProxy p; for (Iterator i = temp.iterator(); i.hasNext(); ) { p = (NodeProxy) i.next(); if (test.matches(p)) result.add(p); } return result; } else if (preloadNodeSets()) { DocumentSet docs = getDocumentSet(contextSet); if (currentSet == null || currentDocs == null || !(docs.equals(currentDocs))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } return contextSet.selectParentChild(currentSet, NodeSet.ANCESTOR); } else { DocumentSet docs = getDocumentSet(contextSet); NodeSelector selector = new ParentSelector(contextSet, contextId); ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); return index.findElementsByTagName(ElementValue.ELEMENT, docs, test .getName(), selector); } } protected DocumentSet getDocumentSet(NodeSet contextSet) { DocumentSet ds = getContextDocSet(); if (ds == null) ds = contextSet.getDocumentSet(); return ds; } protected void registerUpdateListener() { if (listener == null) { listener = new UpdateListener() { public void documentUpdated(DocumentImpl document, int event) { if (document == null || event == UpdateListener.ADD || event == UpdateListener.REMOVE) { // clear all currentDocs = null; currentSet = null; cached = null; } else { if (currentDocs != null && currentDocs.contains(document.getDocId())) { currentDocs = null; currentSet = null; } if (cached != null && cached.getResult().getDocumentSet() .contains(document.getDocId())) cached = null; } } public void debug() { LOG.debug("UpdateListener: Line: " + LocationStep.this.toString() + "; id: " + LocationStep.this.getExpressionId()); } }; NotificationService service = context.getBroker().getBrokerPool() .getNotificationService(); service.subscribe(listener); } } protected void deregisterUpdateListener() { if (listener != null) { NotificationService service = context.getBroker().getBrokerPool() .getNotificationService(); service.unsubscribe(listener); } } /* * (non-Javadoc) * * @see org.exist.xquery.Step#resetState() */ public void resetState() { super.resetState(); currentSet = null; currentDocs = null; cached = null; deregisterUpdateListener(); listener = null; } }
package org.exist.xquery; import org.exist.dom.DocumentImpl; import org.exist.dom.DocumentSet; import org.exist.dom.ExtNodeSet; import org.exist.dom.NewArrayNodeSet; import org.exist.dom.NodeProxy; import org.exist.dom.NodeSet; import org.exist.dom.NodeVisitor; import org.exist.dom.StoredNode; import org.exist.dom.VirtualNodeSet; import org.exist.numbering.NodeId; import org.exist.storage.ElementIndex; import org.exist.storage.ElementValue; import org.exist.storage.UpdateListener; import org.exist.xquery.value.*; import org.exist.memtree.NodeImpl; import org.exist.memtree.InMemoryNodeSet; import org.exist.stax.EmbeddedXMLStreamReader; import org.exist.stax.StaXUtil; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.stream.StreamFilter; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamException; import java.util.Iterator; import java.io.IOException; /** * Processes all location path steps (like descendant::*, ancestor::XXX). * * The results of the first evaluation of the expression are cached for the * lifetime of the object and only reloaded if the context sequence (as passed * to the {@link #eval(Sequence, Item)} method) has changed. * * @author wolf */ public class LocationStep extends Step { private final int ATTR_DIRECT_SELECT_THRESHOLD = 10; protected NodeSet currentSet = null; protected DocumentSet currentDocs = null; protected UpdateListener listener = null; protected Expression parent = null; // Fields for caching the last result protected CachedResult cached = null; protected int parentDeps = Dependency.UNKNOWN_DEPENDENCY; protected boolean preloadedData = false; protected boolean optimized = false; protected boolean inUpdate = false; protected boolean useDirectAttrSelect = true; protected boolean useDirectChildSelect = false; protected boolean applyPredicate = true; // Cache for the current NodeTest type private Integer nodeTestType = null; /** * Creates a new <code>LocationStep</code> instance. * * @param context a <code>XQueryContext</code> value * @param axis an <code>int</code> value */ public LocationStep(XQueryContext context, int axis) { super(context, axis); } /** * Creates a new <code>LocationStep</code> instance. * * @param context a <code>XQueryContext</code> value * @param axis an <code>int</code> value * @param test a <code>NodeTest</code> value */ public LocationStep(XQueryContext context, int axis, NodeTest test) { super(context, axis, test); } /* * (non-Javadoc) * * @see org.exist.xquery.AbstractExpression#getDependencies() */ public int getDependencies() { int deps = Dependency.CONTEXT_SET; //self axis has an obvious dependency on the context item //TODO : I guess every other axis too... so we might consider using Constants.UNKNOWN_AXIS here //BUT //in a predicate, the expression can't depend on... itself if (!this.inPredicate && this.axis == Constants.SELF_AXIS) deps = deps | Dependency.CONTEXT_ITEM; //TODO : normally, we should call this one... //int deps = super.getDependencies(); ??? for (Iterator i = predicates.iterator(); i.hasNext();) { deps |= ((Predicate) i.next()).getDependencies(); } //TODO : should we remove the CONTEXT_ITEM dependency returned by the predicates ? See the comment above. //consider nested predicates however... return deps; } /** * If the current path expression depends on local variables from a for * expression, we can optimize by preloading entire element or attribute * sets. * * @return Whether or not we can optimize */ protected boolean hasPreloadedData() { // TODO : log elsewhere ? if (preloadedData) { context.getProfiler().message(this, Profiler.OPTIMIZATIONS, null, "Preloaded NodeSets"); return true; } if (inUpdate) return false; if ((parentDeps & Dependency.LOCAL_VARS) == Dependency.LOCAL_VARS) { context.getProfiler().message(this, Profiler.OPTIMIZATIONS, null, "Preloaded NodeSets"); return true; } return false; } /** * The method <code>setPreloadedData</code> * * @param docs a <code>DocumentSet</code> value * @param nodes a <code>NodeSet</code> value */ public void setPreloadedData(DocumentSet docs, NodeSet nodes) { this.preloadedData = true; this.currentDocs = docs; this.currentSet = nodes; this.optimized = true; } /** * The method <code>applyPredicate</code> * * @param outerSequence a <code>Sequence</code> value * @param contextSequence a <code>Sequence</code> value * @return a <code>Sequence</code> value * @exception XPathException if an error occurs */ protected Sequence applyPredicate(Sequence outerSequence, Sequence contextSequence) throws XPathException { if (contextSequence == null) return Sequence.EMPTY_SEQUENCE; if (predicates.size() == 0 || !applyPredicate) // Nothing to apply return contextSequence; Sequence result; Predicate pred = (Predicate) predicates.get(0); // If the current step is an // abbreviated step, we have to treat the predicate // specially to get the context position right. //a[1] translates to /descendant-or-self::node()/a[1], // so we need to return the 1st a from any parent of a. // If the predicate is known to return a node set, no special treatment is required. if (abbreviatedStep && (pred.getExecutionMode() != Predicate.NODE || !contextSequence.isPersistentSet())) { result = new ValueSequence(); if (contextSequence.isPersistentSet()) { NodeSet contextSet = contextSequence.toNodeSet(); outerSequence = contextSet.getParents(getExpressionId()); for (SequenceIterator i = outerSequence.iterate(); i.hasNext(); ) { NodeValue node = (NodeValue) i.nextItem(); Sequence newContextSeq = contextSet.selectParentChild((NodeSet) node, NodeSet.DESCENDANT, getExpressionId()); Sequence temp = processPredicate(outerSequence, newContextSeq); result.addAll(temp); } } else { MemoryNodeSet nodes = contextSequence.toMemNodeSet(); outerSequence = nodes.getParents(new AnyNodeTest()); for (SequenceIterator i = outerSequence.iterate(); i.hasNext(); ) { NodeValue node = (NodeValue) i.nextItem(); InMemoryNodeSet newSet = new InMemoryNodeSet(); ((NodeImpl)node).selectChildren(test, newSet); Sequence temp = processPredicate(outerSequence, newSet); result.addAll(temp); } } } else result = processPredicate(outerSequence, contextSequence); return result; } private Sequence processPredicate(Sequence outerSequence, Sequence contextSequence) throws XPathException { Predicate pred; Sequence result = contextSequence; for (Iterator i = predicates.iterator(); i.hasNext();) { // TODO : log and/or profile ? pred = (Predicate) i.next(); pred.setContextDocSet(getContextDocSet()); result = pred.evalPredicate(outerSequence, result, axis); //subsequent predicates operate on the result of the previous one outerSequence = null; } return result; } /* * (non-Javadoc) * * @see org.exist.xquery.Step#analyze(org.exist.xquery.Expression) */ public void analyze(AnalyzeContextInfo contextInfo) throws XPathException { this.parent = contextInfo.getParent(); parentDeps = parent.getDependencies(); if ((contextInfo.getFlags() & IN_UPDATE) > 0) inUpdate = true; if ((contextInfo.getFlags() & SINGLE_STEP_EXECUTION) > 0) { preloadedData = true; } if ((contextInfo.getFlags() & NEED_INDEX_INFO) > 0) { useDirectAttrSelect = false; } if ((contextInfo.getFlags() & USE_TREE_TRAVERSAL) > 0) { useDirectChildSelect = true; } // Mark ".", which is expanded as self::node() by the parser //even though it may *also* be relevant with atomic sequences if (this.axis == Constants.SELF_AXIS && this.test.getType()== Type.NODE) contextInfo.addFlag(DOT_TEST); // TODO : log somewhere ? super.analyze(contextInfo); } /** * The method <code>eval</code> * * @param contextSequence a <code>Sequence</code> value * @param contextItem an <code>Item</code> value * @return a <code>Sequence</code> value * @exception XPathException if an error occurs */ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException { if (context.getProfiler().isEnabled()) { context.getProfiler().start(this); context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies())); if (contextSequence != null) context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence); if (contextItem != null) context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence()); } Sequence result; if (contextItem != null) { contextSequence = contextItem.toSequence(); } /* * if(contextSequence == null) //Commented because this the high level * result nodeset is *really* null result = NodeSet.EMPTY_SET; //Try to * return cached results else */ // TODO: disabled cache for now as it may cause concurrency issues // better use compile-time inspection and maybe a pragma to mark those // sections in the query that can be safely cached // if (cached != null && cached.isValid(contextSequence, contextItem)) { // // WARNING : commented since predicates are *also* applied below ! // /* // * if (predicates.size() > 0) { applyPredicate(contextSequence, // * cached.getResult()); } else { // */ // result = cached.getResult(); // if (context.getProfiler().isEnabled()) { // LOG.debug("Using cached results"); // context.getProfiler().message(this, Profiler.OPTIMIZATIONS, // "Using cached results", result); if (needsComputation()) { if (contextSequence == null) throw new XPathException(this, "XPDY0002 : undefined context sequence for '" + this.toString() + "'"); switch (axis) { case Constants.DESCENDANT_AXIS: case Constants.DESCENDANT_SELF_AXIS: result = getDescendants(context, contextSequence); break; case Constants.CHILD_AXIS: //VirtualNodeSets may have modified the axis ; checking the type //TODO : further checks ? if (this.test.getType() == Type.ATTRIBUTE) { this.axis = Constants.ATTRIBUTE_AXIS; result = getAttributes(context, contextSequence); } else { result = getChildren(context, contextSequence); } break; case Constants.ANCESTOR_SELF_AXIS: case Constants.ANCESTOR_AXIS: result = getAncestors(context, contextSequence); break; case Constants.PARENT_AXIS: result = getParents(context, contextSequence); break; case Constants.SELF_AXIS: if (!(contextSequence instanceof VirtualNodeSet) && Type.subTypeOf(contextSequence.getItemType(), Type.ATOMIC)) { //This test is copied from the legacy method getSelfAtomic() if (!test.isWildcardTest()) throw new XPathException(this, test.toString() + " cannot be applied to an atomic value."); result = contextSequence; } else { result = getSelf(context, contextSequence); } break; case Constants.ATTRIBUTE_AXIS: case Constants.DESCENDANT_ATTRIBUTE_AXIS: result = getAttributes(context, contextSequence); break; case Constants.PRECEDING_AXIS: result = getPreceding(context, contextSequence); break; case Constants.FOLLOWING_AXIS: result = getFollowing(context, contextSequence); break; case Constants.PRECEDING_SIBLING_AXIS: case Constants.FOLLOWING_SIBLING_AXIS: result = getSiblings(context, contextSequence); break; default: throw new IllegalArgumentException("Unsupported axis specified"); } } else { result = NodeSet.EMPTY_SET; } // Caches the result if (axis != Constants.SELF_AXIS && contextSequence != null && contextSequence.isCacheable()) { // TODO : cache *after* removing duplicates ? -pb cached = new CachedResult(contextSequence, contextItem, result); registerUpdateListener(); } // Remove duplicate nodes result.removeDuplicates(); // Apply the predicate result = applyPredicate(contextSequence, result); if (context.getProfiler().isEnabled()) context.getProfiler().end(this, "", result); //actualReturnType = result.getItemType(); return result; } // Avoid unnecessary tests (these should be detected by the parser) private boolean needsComputation() { // TODO : log this ? switch (axis) { // Certainly not exhaustive case Constants.ANCESTOR_SELF_AXIS: case Constants.PARENT_AXIS: // case Constants.SELF_AXIS: if (nodeTestType == null) nodeTestType = new Integer(test.getType()); if (nodeTestType.intValue() != Type.NODE && nodeTestType.intValue() != Type.ELEMENT && nodeTestType.intValue() != Type.PROCESSING_INSTRUCTION) { if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "avoid useless computations"); return false; } } return true; } /** * The method <code>getSelf</code> * * @param context a <code>XQueryContext</code> value * @param contextSequence a <code>NodeSet</code> value * @return a <code>Sequence</code> value */ protected Sequence getSelf(XQueryContext context, Sequence contextSequence) throws XPathException { if (!contextSequence.isPersistentSet()) { MemoryNodeSet nodes = contextSequence.toMemNodeSet(); return nodes.getSelf(test); } NodeSet contextSet = contextSequence.toNodeSet(); if (test.getType() == Type.PROCESSING_INSTRUCTION) { VirtualNodeSet vset = new VirtualNodeSet(context.getBroker(), axis, test, contextId, contextSet); vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId); return vset; } if (test.isWildcardTest()) { if (nodeTestType == null) { nodeTestType = new Integer(test.getType()); } if (Type.subTypeOf(nodeTestType.intValue(), Type.NODE)) { if (Expression.NO_CONTEXT_ID != contextId) { if (contextSet instanceof VirtualNodeSet) { ((VirtualNodeSet) contextSet).setInPredicate(true); ((VirtualNodeSet) contextSet).setContextId(contextId); ((VirtualNodeSet) contextSet).setSelfIsContext(); } else if (Type.subTypeOf(contextSet.getItemType(), Type.NODE)) { NodeProxy p; for (Iterator i = contextSet.iterator(); i.hasNext();) { p = (NodeProxy) i.next(); if (test.matches(p)) p.addContextNode(contextId, p); } } } return contextSet; } else { VirtualNodeSet vset = new VirtualNodeSet(context.getBroker(), axis, test, contextId, contextSet); vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId); return vset; } } else { DocumentSet docs = getDocumentSet(contextSet); ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); NodeSelector selector = new SelfSelector(contextSet, contextId); return index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), selector); } } /** * The method <code>getAttributes</code> * * @param context a <code>XQueryContext</code> value * @param contextSequence a <code>NodeSet</code> value * @return a <code>NodeSet</code> value */ protected Sequence getAttributes(XQueryContext context, Sequence contextSequence) throws XPathException { if (!contextSequence.isPersistentSet()) { MemoryNodeSet nodes = contextSequence.toMemNodeSet(); if (axis == Constants.DESCENDANT_ATTRIBUTE_AXIS) return nodes.getDescendantAttributes(test); else return nodes.getAttributes(test); } NodeSet contextSet = contextSequence.toNodeSet(); boolean selectDirect = false; if (useDirectAttrSelect && axis == Constants.ATTRIBUTE_AXIS) { if (contextSet instanceof VirtualNodeSet) selectDirect = ((VirtualNodeSet) contextSet).preferTreeTraversal() && contextSet.getLength() < ATTR_DIRECT_SELECT_THRESHOLD; else selectDirect = contextSet.getLength() < ATTR_DIRECT_SELECT_THRESHOLD; } if (selectDirect) { if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "direct attribute selection"); if (contextSet.isEmpty()) return NodeSet.EMPTY_SET; //TODO : why only the first node ? NodeProxy proxy = contextSet.get(0); if (proxy != null) return contextSet.directSelectAttribute(context.getBroker(), test, contextId); } if (test.isWildcardTest()) { NodeSet result = new VirtualNodeSet(context.getBroker(), axis, test, contextId, contextSet); ((VirtualNodeSet) result).setInPredicate(Expression.NO_CONTEXT_ID != contextId); return result; // if there's just a single known node in the context, it is faster // do directly search for the attribute in the parent node. } if (hasPreloadedData()) { DocumentSet docs = getDocumentSet(contextSet); synchronized (context) { if (currentSet == null || currentDocs == null || (!optimized && !(docs == currentDocs || docs.equalDocs(currentDocs)))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); // TODO : why a null selector here ? We have one below ! currentSet = index.findElementsByTagName( ElementValue.ATTRIBUTE, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } switch (axis) { case Constants.ATTRIBUTE_AXIS: return currentSet.selectParentChild(contextSet, NodeSet.DESCENDANT, contextId); case Constants.DESCENDANT_ATTRIBUTE_AXIS: return currentSet.selectAncestorDescendant(contextSet, NodeSet.DESCENDANT, false, contextId); default: throw new IllegalArgumentException( "Unsupported axis specified"); } } } else { DocumentSet docs = getDocumentSet(contextSet); ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); if (contextSet instanceof ExtNodeSet && !contextSet.getProcessInReverseOrder()) { return index.findDescendantsByTagName(ElementValue.ATTRIBUTE, test.getName(), axis, docs, (ExtNodeSet) contextSet, contextId); } else { NodeSelector selector; switch (axis) { case Constants.ATTRIBUTE_AXIS: selector = new ChildSelector(contextSet, contextId); break; case Constants.DESCENDANT_ATTRIBUTE_AXIS: selector = new DescendantSelector(contextSet, contextId); break; default: throw new IllegalArgumentException("Unsupported axis specified"); } return index.findElementsByTagName(ElementValue.ATTRIBUTE, docs, test.getName(), selector); } } } /** * The method <code>getChildren</code> * * @param context a <code>XQueryContext</code> value * @param contextSequence the context sequence * @return a <code>NodeSet</code> value */ protected Sequence getChildren(XQueryContext context, Sequence contextSequence) throws XPathException { if (!contextSequence.isPersistentSet()) { MemoryNodeSet nodes = contextSequence.toMemNodeSet(); return nodes.getChildren(test); } NodeSet contextSet = contextSequence.toNodeSet(); //TODO : understand this. I guess comments should be treated in a similar way ? -pb if (test.isWildcardTest() || test.getType() == Type.PROCESSING_INSTRUCTION) { // test is one out of *, text(), node() including processing-instruction(targetname) VirtualNodeSet vset = new VirtualNodeSet(context.getBroker(), axis, test, contextId, contextSet); vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId); return vset; } // IndexStatistics stats = (IndexStatistics) context.getBroker().getBrokerPool(). // getIndexManager().getIndexById(IndexStatistics.ID); // int parentDepth = stats.getMaxParentDepth(test.getName()); // LOG.debug("parentDepth for " + test.getName() + ": " + parentDepth); if (useDirectChildSelect) { NewArrayNodeSet result = new NewArrayNodeSet(); for (Iterator i = contextSet.iterator(); i.hasNext(); ) { NodeProxy p = (NodeProxy) i.next(); result.addAll(p.directSelectChild(test.getName(), contextId)); } return result; } else if (hasPreloadedData()) { DocumentSet docs = getDocumentSet(contextSet); synchronized (context) { // TODO : understand why this one is different from the other ones if (currentSet == null || currentDocs == null || (!optimized && !(docs == currentDocs || docs.equalDocs(currentDocs)))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } return currentSet.selectParentChild(contextSet, NodeSet.DESCENDANT, contextId); } } else { DocumentSet docs = getDocumentSet(contextSet); ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); if (contextSet instanceof ExtNodeSet && !contextSet.getProcessInReverseOrder()) { return index.findDescendantsByTagName(ElementValue.ELEMENT, test.getName(), axis, docs, (ExtNodeSet) contextSet, contextId); } else { // if (contextSet instanceof VirtualNodeSet) // ((VirtualNodeSet)contextSet).realize(); NodeSelector selector = new ChildSelector(contextSet, contextId); return index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), selector); } } } /** * The method <code>getDescendants</code> * * @param context a <code>XQueryContext</code> value * @param contextSequence the context sequence * @return a <code>NodeSet</code> value */ protected Sequence getDescendants(XQueryContext context, Sequence contextSequence) throws XPathException { if (!contextSequence.isPersistentSet()) { MemoryNodeSet nodes = contextSequence.toMemNodeSet(); return nodes.getDescendants(axis == Constants.DESCENDANT_SELF_AXIS, test); } NodeSet contextSet = contextSequence.toNodeSet(); //TODO : understand this. I guess comments should be treated in a similar way ? -pb if (test.isWildcardTest() || test.getType() == Type.PROCESSING_INSTRUCTION) { // test is one out of *, text(), node() including processing-instruction(targetname) VirtualNodeSet vset = new VirtualNodeSet(context.getBroker(), axis, test, contextId, contextSet); vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId); return vset; } else if (hasPreloadedData()) { DocumentSet docs = getDocumentSet(contextSet); synchronized (context) { // TODO : understand why this one is different from the other ones if (currentSet == null || currentDocs == null || (!optimized && !(docs == currentDocs || docs.equalDocs(currentDocs)))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } switch (axis) { case Constants.DESCENDANT_SELF_AXIS: NodeSet tempSet = currentSet.selectAncestorDescendant(contextSet, NodeSet.DESCENDANT, true, contextId); return tempSet; case Constants.DESCENDANT_AXIS: return currentSet.selectAncestorDescendant(contextSet, NodeSet.DESCENDANT, false, contextId); default: throw new IllegalArgumentException( "Unsupported axis specified"); } } } else { DocumentSet docs = contextSet.getDocumentSet(); ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) { context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); } if (contextSet instanceof ExtNodeSet) { return index.findDescendantsByTagName(ElementValue.ELEMENT, test.getName(), axis, docs, (ExtNodeSet) contextSet, contextId); } else { NodeSelector selector; switch (axis) { case Constants.DESCENDANT_SELF_AXIS: selector = new DescendantOrSelfSelector(contextSet, contextId); break; case Constants.DESCENDANT_AXIS: selector = new DescendantSelector(contextSet, contextId); break; default: throw new IllegalArgumentException("Unsupported axis specified"); } return index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), selector); } } } /** * The method <code>getSiblings</code> * * @param context a <code>XQueryContext</code> value * @param contextSequence a <code>NodeSet</code> value * @return a <code>NodeSet</code> value */ protected Sequence getSiblings(XQueryContext context, Sequence contextSequence) throws XPathException { if (!contextSequence.isPersistentSet()) { MemoryNodeSet nodes = contextSequence.toMemNodeSet(); if (axis == Constants.PRECEDING_SIBLING_AXIS) return nodes.getPrecedingSiblings(test); else return nodes.getFollowingSiblings(test); } NodeSet contextSet = contextSequence.toNodeSet(); //TODO : understand this. I guess comments should be treated in a similar way ? -pb if (test.getType() == Type.PROCESSING_INSTRUCTION) { VirtualNodeSet vset = new VirtualNodeSet(context.getBroker(), axis, test, contextId, contextSet); vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId); return vset; } if (test.isWildcardTest()) { NewArrayNodeSet result = new NewArrayNodeSet(contextSet.getLength()); try { for (Iterator i = contextSet.iterator(); i.hasNext();) { NodeProxy current = (NodeProxy) i.next(); NodeProxy parent = new NodeProxy(current.getDocument(), current.getNodeId().getParentId()); StreamFilter filter; if (axis == Constants.PRECEDING_SIBLING_AXIS) filter = new PrecedingSiblingFilter(test, current, result, contextId); else filter = new FollowingSiblingFilter(test, current, result, contextId); EmbeddedXMLStreamReader reader = context.getBroker().getXMLStreamReader(parent, false); reader.filter(filter); } } catch (IOException e) { throw new XPathException(this, e.getMessage(), e); } catch (XMLStreamException e) { throw new XPathException(this, e.getMessage(), e); } return result; } else { //TODO : no test on preloaded data ? DocumentSet docs = getDocumentSet(contextSet); synchronized (context) { if (currentSet == null || currentDocs == null || !(docs.equalDocs(currentDocs))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } switch (axis) { case Constants.PRECEDING_SIBLING_AXIS: return currentSet.selectPrecedingSiblings(contextSet, contextId); case Constants.FOLLOWING_SIBLING_AXIS: return currentSet.selectFollowingSiblings(contextSet, contextId); default: throw new IllegalArgumentException( "Unsupported axis specified"); } } } } private class SiblingVisitor implements NodeVisitor { private ExtNodeSet resultSet; private NodeProxy contextNode; public SiblingVisitor(ExtNodeSet resultSet) { this.resultSet = resultSet; } public void setContext(NodeProxy contextNode) { this.contextNode = contextNode; } public boolean visit(StoredNode current) { if (contextNode.getNodeId().getTreeLevel() == current.getNodeId().getTreeLevel()) { int cmp = current.getNodeId().compareTo(contextNode.getNodeId()); if (((axis == Constants.FOLLOWING_SIBLING_AXIS && cmp > 0) || (axis == Constants.PRECEDING_SIBLING_AXIS && cmp < 0)) && test.matches(current)) { NodeProxy sibling = resultSet.get((DocumentImpl) current.getOwnerDocument(), current.getNodeId()); if (sibling == null) { sibling = new NodeProxy((DocumentImpl) current.getOwnerDocument(), current.getNodeId(), current.getInternalAddress()); if (Expression.NO_CONTEXT_ID != contextId) { sibling.addContextNode(contextId, contextNode); } else sibling.copyContext(contextNode); resultSet.add(sibling); resultSet.setSorted(sibling.getDocument(), true); } else if (Expression.NO_CONTEXT_ID != contextId) sibling.addContextNode(contextId, contextNode); } } return true; } } /** * The method <code>getPreceding</code> * * @param context a <code>XQueryContext</code> value * @param contextSequence a <code>Sequence</code> value * @return a <code>NodeSet</code> value * @exception XPathException if an error occurs */ protected Sequence getPreceding(XQueryContext context, Sequence contextSequence) throws XPathException { int position = -1; if (hasPositionalPredicate) { Predicate pred = (Predicate) predicates.get(0); Sequence seq = pred.preprocess(); NumericValue v = (NumericValue)seq.itemAt(0); //Non integers return... nothing, not even an error ! if (!v.hasFractionalPart() && !v.isZero()) { position = v.getInt(); } } if (!contextSequence.isPersistentSet()) { MemoryNodeSet nodes = contextSequence.toMemNodeSet(); if (hasPositionalPredicate && position > -1) applyPredicate = false; return nodes.getPreceding(test, position); } NodeSet contextSet = contextSequence.toNodeSet(); //TODO : understand this. I guess comments should be treated in a similar way ? -pb if (test.getType() == Type.PROCESSING_INSTRUCTION) { VirtualNodeSet vset = new VirtualNodeSet(context.getBroker(), axis, test, contextId, contextSet); vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId); return vset; } if (test.isWildcardTest()) { try { NodeSet result = new NewArrayNodeSet(); for (Iterator i = contextSet.iterator(); i.hasNext();) { NodeProxy next = (NodeProxy) i.next(); NodeList cl = next.getDocument().getChildNodes(); for (int j = 0; j < cl.getLength(); j++) { StoredNode node = (StoredNode) cl.item(j); NodeProxy root = new NodeProxy(node); PrecedingFilter filter = new PrecedingFilter(test, next, result, contextId); EmbeddedXMLStreamReader reader = context.getBroker().getXMLStreamReader(root, false); reader.filter(filter); } } return result; } catch (XMLStreamException e) { throw new XPathException(this, e.getMessage(), e); } catch (IOException e) { throw new XPathException(this, e.getMessage(), e); } } else { //TODO : no test on preloaded data ? DocumentSet docs = getDocumentSet(contextSet); synchronized (context) { if (currentSet == null || currentDocs == null || !(docs.equalDocs(currentDocs))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } if (hasPositionalPredicate) { try { applyPredicate = false; return currentSet.selectPreceding(contextSet, position, contextId); } catch (UnsupportedOperationException e) { return currentSet.selectPreceding(contextSet, contextId); } } else return currentSet.selectPreceding(contextSet, contextId); } } } /** * The method <code>getFollowing</code> * * @param context a <code>XQueryContext</code> value * @param contextSequence a <code>Sequence</code> value * @return a <code>NodeSet</code> value * @exception XPathException if an error occurs */ protected Sequence getFollowing(XQueryContext context, Sequence contextSequence) throws XPathException { int position = -1; if (hasPositionalPredicate) { Predicate pred = (Predicate) predicates.get(0); Sequence seq = pred.preprocess(); NumericValue v = (NumericValue)seq.itemAt(0); //Non integers return... nothing, not even an error ! if (!v.hasFractionalPart() && !v.isZero()) { position = v.getInt(); } } if (!contextSequence.isPersistentSet()) { MemoryNodeSet nodes = contextSequence.toMemNodeSet(); if (hasPositionalPredicate && position > -1) applyPredicate = false; return nodes.getFollowing(test, position); } NodeSet contextSet = contextSequence.toNodeSet(); //TODO : understand this. I guess comments should be treated in a similar way ? -pb if (test.getType() == Type.PROCESSING_INSTRUCTION) { VirtualNodeSet vset = new VirtualNodeSet(context.getBroker(), axis, test, contextId, contextSet); vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId); return vset; } if (test.isWildcardTest() && test.getType() != Type.PROCESSING_INSTRUCTION) { // handle wildcard steps like following::node() try { NodeSet result = new NewArrayNodeSet(); for (Iterator i = contextSet.iterator(); i.hasNext();) { NodeProxy next = (NodeProxy) i.next(); NodeList cl = next.getDocument().getChildNodes(); for (int j = 0; j < cl.getLength(); j++) { StoredNode node = (StoredNode) cl.item(j); NodeProxy root = new NodeProxy(node); FollowingFilter filter = new FollowingFilter(test, next, result, contextId); EmbeddedXMLStreamReader reader = context.getBroker().getXMLStreamReader(root, false); reader.filter(filter); } } return result; } catch (XMLStreamException e) { throw new XPathException(this, e.getMessage(), e); } catch (IOException e) { throw new XPathException(this, e.getMessage(), e); } } else { //TODO : no test on preloaded data ? DocumentSet docs = getDocumentSet(contextSet); synchronized (context) { if (currentSet == null || currentDocs == null || !(docs.equalDocs(currentDocs))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } if (hasPositionalPredicate) { try { applyPredicate = false; return currentSet.selectFollowing(contextSet, position, contextId); } catch (UnsupportedOperationException e) { return currentSet.selectFollowing(contextSet, contextId); } } else return currentSet.selectFollowing(contextSet, contextId); } } } /** * The method <code>getAncestors</code> * * @param context a <code>XQueryContext</code> value * @param contextSequence a <code>Sequence</code> value * @return a <code>NodeSet</code> value */ protected Sequence getAncestors(XQueryContext context, Sequence contextSequence) throws XPathException { if (!contextSequence.isPersistentSet()) { MemoryNodeSet nodes = contextSequence.toMemNodeSet(); return nodes.getAncestors(axis == Constants.ANCESTOR_SELF_AXIS, test); } NodeSet contextSet = contextSequence.toNodeSet(); if (test.isWildcardTest()) { NodeSet result = new NewArrayNodeSet(); result.setProcessInReverseOrder(true); for (Iterator i = contextSet.iterator(); i.hasNext();) { NodeProxy current = (NodeProxy) i.next(); NodeProxy ancestor; if (axis == Constants.ANCESTOR_SELF_AXIS && test.matches(current)) { ancestor = new NodeProxy(current.getDocument(), current.getNodeId(), Node.ELEMENT_NODE, current.getInternalAddress()); NodeProxy t = result.get(ancestor); if (t == null) { if (Expression.NO_CONTEXT_ID != contextId) ancestor.addContextNode(contextId, current); else ancestor.copyContext(current); ancestor.addMatches(current); result.add(ancestor); } else { t.addContextNode(contextId, current); t.addMatches(current); } } NodeId parentID = current.getNodeId().getParentId(); while (parentID != null) { ancestor = new NodeProxy(current.getDocument(), parentID, Node.ELEMENT_NODE); // Filter out the temporary nodes wrapper element if (parentID != NodeId.DOCUMENT_NODE && !(parentID.getTreeLevel() == 1 && current.getDocument().getCollection().isTempCollection())) { if (test.matches(ancestor)) { NodeProxy t = result.get(ancestor); if (t == null) { if (Expression.NO_CONTEXT_ID != contextId) ancestor.addContextNode(contextId, current); else ancestor.copyContext(current); ancestor.addMatches(current); result.add(ancestor); } else { t.addContextNode(contextId, current); t.addMatches(current); } } } parentID = parentID.getParentId(); } } return result; } else if (hasPreloadedData()) { DocumentSet docs = getDocumentSet(contextSet); synchronized (context) { if (currentSet == null || currentDocs == null || (!optimized && !(docs == currentDocs || docs.equalDocs(currentDocs)))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } switch (axis) { case Constants.ANCESTOR_SELF_AXIS: return currentSet.selectAncestors(contextSet, true, contextId); case Constants.ANCESTOR_AXIS: return currentSet.selectAncestors(contextSet, false, contextId); default: throw new IllegalArgumentException( "Unsupported axis specified"); } } } else { DocumentSet docs = getDocumentSet(contextSet); ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); NodeSelector selector; switch (axis) { case Constants.ANCESTOR_SELF_AXIS: selector = new AncestorSelector(contextSet, contextId, true); break; case Constants.ANCESTOR_AXIS: selector = new AncestorSelector(contextSet, contextId, false); break; default: throw new IllegalArgumentException("Unsupported axis specified"); } return index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), selector); } } /** * The method <code>getParents</code> * * @param context a <code>XQueryContext</code> value * @param contextSequence a <code>Sequence</code> value * @return a <code>NodeSet</code> value */ protected Sequence getParents(XQueryContext context, Sequence contextSequence) throws XPathException { if (!contextSequence.isPersistentSet()) { MemoryNodeSet nodes = contextSequence.toMemNodeSet(); return nodes.getParents(test); } NodeSet contextSet = contextSequence.toNodeSet(); if (test.isWildcardTest()) { NodeSet temp = contextSet.getParents(contextId); NodeSet result = new NewArrayNodeSet(); NodeProxy p; for (Iterator i = temp.iterator(); i.hasNext(); ) { p = (NodeProxy) i.next(); if (test.matches(p)) { result.add(p); } } return result; } else if (hasPreloadedData()) { DocumentSet docs = getDocumentSet(contextSet); synchronized (context) { if (currentSet == null || currentDocs == null || (!optimized && !(docs == currentDocs || docs.equalDocs(currentDocs)))) { ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); currentSet = index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), null); currentDocs = docs; registerUpdateListener(); } return contextSet.selectParentChild(currentSet, NodeSet.ANCESTOR); } } else { DocumentSet docs = getDocumentSet(contextSet); ElementIndex index = context.getBroker().getElementIndex(); if (context.getProfiler().isEnabled()) context.getProfiler().message(this, Profiler.OPTIMIZATIONS, "OPTIMIZATION", "Using structural index '" + index.toString() + "'"); NodeSelector selector = new ParentSelector(contextSet, contextId); return index.findElementsByTagName(ElementValue.ELEMENT, docs, test.getName(), selector); } } /** * The method <code>getDocumentSet</code> * * @param contextSet a <code>NodeSet</code> value * @return a <code>DocumentSet</code> value */ protected DocumentSet getDocumentSet(NodeSet contextSet) { DocumentSet ds = getContextDocSet(); if (ds == null) ds = contextSet.getDocumentSet(); return ds; } /** * The method <code>getParent</code> * * @return an <code>Expression</code> value */ public Expression getParentExpression() { return this.parent; } /** * The method <code>setUseDirectAttrSelect</code> * * @param useDirectAttrSelect a <code>boolean</code> value */ public void setUseDirectAttrSelect(boolean useDirectAttrSelect) { this.useDirectAttrSelect = useDirectAttrSelect; } /** * The method <code>registerUpdateListener</code> * */ protected void registerUpdateListener() { if (listener == null) { listener = new UpdateListener() { public void documentUpdated(DocumentImpl document, int event) { synchronized (context) { cached = null; if (document == null || event == UpdateListener.ADD || event == UpdateListener.REMOVE) { // clear all currentDocs = null; currentSet = null; } else { if (currentDocs != null && currentDocs.contains(document.getDocId())) { currentDocs = null; currentSet = null; } } } } public void nodeMoved(NodeId oldNodeId, StoredNode newNode) { } public void unsubscribe() { LocationStep.this.listener = null; } public void debug() { LOG.debug("UpdateListener: Line: " + LocationStep.this.toString() + "; id: " + LocationStep.this.getExpressionId()); } }; context.registerUpdateListener(listener); } } /** * The method <code>accept</code> * * @param visitor an <code>ExpressionVisitor</code> value */ public void accept(ExpressionVisitor visitor) { visitor.visitLocationStep(this); } /* * (non-Javadoc) * * @see org.exist.xquery.Step#resetState() */ public void resetState(boolean postOptimization) { super.resetState(postOptimization); if (!postOptimization) { //TODO : preloadedData = false ? //No : introduces a regression in testMatchCount //TODO : Investigate... currentSet = null; currentDocs = null; optimized = false; cached = null; listener = null; } } private static class FollowingSiblingFilter implements StreamFilter { private NodeTest test; private NodeProxy referenceNode; private NodeSet result; private int contextId; private boolean isAfter = false; private FollowingSiblingFilter(NodeTest test, NodeProxy referenceNode, NodeSet result, int contextId) { this.test = test; this.referenceNode = referenceNode; this.result = result; this.contextId = contextId; } public boolean accept(XMLStreamReader reader) { if (reader.getEventType() == XMLStreamReader.END_ELEMENT) { return true; } NodeId refId = referenceNode.getNodeId(); NodeId currentId = (NodeId) reader.getProperty(EmbeddedXMLStreamReader.PROPERTY_NODE_ID); if (!isAfter) { isAfter = currentId.equals(refId); } else if (currentId.getTreeLevel() == refId.getTreeLevel() && test.matches(reader)) { NodeProxy sibling = result.get(referenceNode.getDocument(), currentId); if (sibling == null) { sibling = new NodeProxy(referenceNode.getDocument(), currentId, StaXUtil.streamType2DOM(reader.getEventType()), ((EmbeddedXMLStreamReader) reader).getCurrentPosition()); if (Expression.IGNORE_CONTEXT != contextId) { if (Expression.NO_CONTEXT_ID == contextId) { sibling.copyContext(referenceNode); } else { sibling.addContextNode(contextId, referenceNode); } } result.add(sibling); } else if (Expression.NO_CONTEXT_ID != contextId) sibling.addContextNode(contextId, referenceNode); } return true; } } private static class PrecedingSiblingFilter implements StreamFilter { private NodeTest test; private NodeProxy referenceNode; private NodeSet result; private int contextId; private PrecedingSiblingFilter(NodeTest test, NodeProxy referenceNode, NodeSet result, int contextId) { this.test = test; this.referenceNode = referenceNode; this.result = result; this.contextId = contextId; } public boolean accept(XMLStreamReader reader) { if (reader.getEventType() == XMLStreamReader.END_ELEMENT) { return true; } NodeId refId = referenceNode.getNodeId(); NodeId currentId = (NodeId) reader.getProperty(EmbeddedXMLStreamReader.PROPERTY_NODE_ID); if (currentId.equals(refId)) { return false; } else if (currentId.getTreeLevel() == refId.getTreeLevel() && test.matches(reader)) { NodeProxy sibling = result.get(referenceNode.getDocument(), currentId); if (sibling == null) { sibling = new NodeProxy(referenceNode.getDocument(), currentId, StaXUtil.streamType2DOM(reader.getEventType()), ((EmbeddedXMLStreamReader)reader).getCurrentPosition()); if (Expression.IGNORE_CONTEXT != contextId) { if (Expression.NO_CONTEXT_ID == contextId) { sibling.copyContext(referenceNode); } else { sibling.addContextNode(contextId, referenceNode); } } result.add(sibling); } else if (Expression.NO_CONTEXT_ID != contextId) sibling.addContextNode(contextId, referenceNode); } return true; } } private static class FollowingFilter implements StreamFilter { private NodeTest test; private NodeProxy referenceNode; private NodeSet result; private int contextId; private boolean isAfter = false; private FollowingFilter(NodeTest test, NodeProxy referenceNode, NodeSet result, int contextId) { this.test = test; this.referenceNode = referenceNode; this.result = result; this.contextId = contextId; } public boolean accept(XMLStreamReader reader) { if (reader.getEventType() == XMLStreamReader.END_ELEMENT) return true; NodeId refId = referenceNode.getNodeId(); NodeId currentId = (NodeId) reader.getProperty(EmbeddedXMLStreamReader.PROPERTY_NODE_ID); if (!isAfter) isAfter = currentId.compareTo(refId) > 0 && !currentId.isDescendantOf(refId); if (isAfter && !refId.isDescendantOf(currentId) && test.matches(reader)) { NodeProxy proxy = new NodeProxy(referenceNode.getDocument(), currentId, StaXUtil.streamType2DOM(reader.getEventType()), ((EmbeddedXMLStreamReader)reader).getCurrentPosition()); if (Expression.IGNORE_CONTEXT != contextId) { if (Expression.NO_CONTEXT_ID == contextId) { proxy.copyContext(referenceNode); } else { proxy.addContextNode(contextId, referenceNode); } } result.add(proxy); } return true; } } private static class PrecedingFilter implements StreamFilter { private NodeTest test; private NodeProxy referenceNode; private NodeSet result; private int contextId; private PrecedingFilter(NodeTest test, NodeProxy referenceNode, NodeSet result, int contextId) { this.test = test; this.referenceNode = referenceNode; this.result = result; this.contextId = contextId; } public boolean accept(XMLStreamReader reader) { if (reader.getEventType() == XMLStreamReader.END_ELEMENT) return true; NodeId refId = referenceNode.getNodeId(); NodeId currentId = (NodeId) reader.getProperty(EmbeddedXMLStreamReader.PROPERTY_NODE_ID); if (currentId.compareTo(refId) >= 0) return false; if (!refId.isDescendantOf(currentId) && test.matches(reader)) { NodeProxy proxy = new NodeProxy(referenceNode.getDocument(), currentId, StaXUtil.streamType2DOM(reader.getEventType()), ((EmbeddedXMLStreamReader)reader).getCurrentPosition()); if (Expression.IGNORE_CONTEXT != contextId) { if (Expression.NO_CONTEXT_ID == contextId) { proxy.copyContext(referenceNode); } else { proxy.addContextNode(contextId, referenceNode); } } result.add(proxy); } return true; } } }
package ar.app.display; import java.awt.*; import java.awt.event.ActionListener; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.util.concurrent.ExecutorService; import ar.*; import ar.app.util.ActionProvider; import ar.app.util.MostRecentOnlyExecutor; import ar.app.util.ZoomPanHandler; import ar.selectors.TouchesPixel; import ar.util.Axis; import ar.util.Util; /**Render and display exactly what fits on the screen. */ public class AggregatingDisplay extends ARComponent.Aggregating { protected static final long serialVersionUID = 1L; protected final ActionProvider aggregatesChangedProvider = new ActionProvider(); protected final TransferDisplay display; protected Aggregator<?,?> aggregator; protected Glyphset<?,?> dataset; private AffineTransform renderedTransform = new AffineTransform(); protected volatile boolean fullRender = false; protected volatile boolean renderError = false; protected volatile Aggregates<?> aggregates; protected ExecutorService renderPool = new MostRecentOnlyExecutor(1,"FullDisplay Render Thread"); protected final Renderer renderer; public AggregatingDisplay(Renderer renderer) { super(); this.renderer = renderer; display = new TransferDisplay(renderer); this.setLayout(new BorderLayout()); this.add(display, BorderLayout.CENTER); ZoomPanHandler.installOn(this); } /**Create a new instance. * */ public AggregatingDisplay(Aggregator<?,?> aggregator, Transfer<?,?> transfer, Glyphset<?,?> glyphs, Renderer renderer) { this(renderer); this.aggregator = aggregator; this.dataset = glyphs; display.transfer(transfer); ZoomPanHandler.installOn(this); } protected void finalize() {renderPool.shutdown();} public void addAggregatesChangedListener(ActionListener l) {aggregatesChangedProvider.addActionListener(l);} public Aggregates<?> refAggregates() {return display.refAggregates();} public void refAggregates(Aggregates<?> aggregates) { display.refAggregates(aggregates); } public Renderer renderer() {return renderer;} public Glyphset<?,?> dataset() {return dataset;} public void dataset(Glyphset<?,?> data, Aggregator<?,?> aggregator, Transfer<?,?> transfer) {dataset(data,aggregator, transfer, true);} public void dataset(Glyphset<?,?> data, Aggregator<?,?> aggregator, Transfer<?,?> transfer, boolean rerender) { this.dataset = data; this.aggregator = aggregator; this.transfer(transfer); aggregates(null, null, null); fullRender = rerender; renderError = false; if (rerender) {this.repaint();} } public Transfer<?,?> transfer() {return display.transfer();} public void transfer(Transfer<?,?> t) { display.transfer(t); } public Aggregator<?,?> aggregator() {return aggregator;} public Aggregates<?> transferAggregates() {return display.transferAggregates();} public Aggregates<?> aggregates() {return aggregates;} public void aggregates(Aggregates<?> aggregates, AffineTransform renderedTransform, Axis.Descriptor<?,?> axes) { display.aggregates(aggregates, renderedTransform, axes); display.refAggregates(null); this.renderedTransform=renderedTransform; this.aggregates = aggregates; fullRender=false; aggregatesChangedProvider.fireActionListeners(); } public void renderAgain() { fullRender=true; renderError=false; repaint(); } public void paintComponent(Graphics g) { Runnable action = null; if (renderer == null || dataset == null || dataset.isEmpty() || aggregator == null || renderError == true) { g.setColor(Color.GRAY); g.fillRect(0, 0, this.getWidth(), this.getHeight()); } else if (fullRender) { action = new AggregateRender(); renderPool.execute(action); fullRender = false; } } public String toString() {return String.format("AggregatingDisplay[Dataset: %1$s, Transfer: %2$s, Aggregator: %3$s]", dataset, display.transfer(), aggregator);} /**Use this transform to convert values from the absolute system * to the screen system. */ @Override public AffineTransform viewTransform() {return display.viewTransform();} @Override public AffineTransform renderTransform() {return new AffineTransform(renderedTransform);} @Override public void viewTransform(AffineTransform vt, boolean provisional) { //Only force full re-render if the zoom factor changed non-provisionally fullRender = !provisional && (renderedTransform == null || vt.getScaleX() != renderedTransform.getScaleX() || vt.getScaleY() != renderedTransform.getScaleY()); display.viewTransform(vt, provisional); repaint(); } public void zoomFit() { try { Rectangle2D content = (dataset == null ? null : dataset().bounds()); if (content ==null || content.isEmpty()) {return;} AffineTransform vt = Util.zoomFit(content, getWidth()-Axis.AXIS_SPACE, getHeight()-Axis.AXIS_SPACE); viewTransform(vt, false); } catch (Exception e) { //Essentially ignores zoom-fit errors...they are usually caused by under-specified state System.out.println("FYI e.printStackTrace(); } } public Rectangle2D dataBounds() {return dataset.bounds();} private final class AggregateRender implements Runnable { public void run() { long start = System.currentTimeMillis(); try { AffineTransform vt = viewTransform(); Rectangle databounds = vt.createTransformedShape(dataset.bounds()).getBounds(); AffineTransform rt = Util.zoomFit(dataset.bounds(), databounds.width, databounds.height); rt.scale(vt.getScaleX()/rt.getScaleX(), vt.getScaleY()/rt.getScaleY()); @SuppressWarnings({"rawtypes"}) Selector selector = TouchesPixel.make(dataset); @SuppressWarnings({"unchecked","rawtypes"}) Aggregates<?> a = renderer.aggregate(dataset, selector, (Aggregator) aggregator, rt, databounds.width, databounds.height); AggregatingDisplay.this.aggregates(a, rt, dataset.axisDescriptors()); long end = System.currentTimeMillis(); if (PERFORMANCE_REPORTING) { System.out.printf("%d ms (Base aggregates render on %d x %d grid)\n", (end-start), aggregates.highX()-aggregates.lowX(), aggregates.highY()-aggregates.lowY()); } } catch (Exception e) { renderError = true; String msg = e.getMessage() == null ? e.getClass().getName() : e.getMessage(); System.err.println(msg); e.printStackTrace(); } AggregatingDisplay.this.repaint(); } } }
package org.jgroups.blocks; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * A method call is the JavaGroup representation of a remote method. * It includes the name of the method (case sensitive) and a list of arguments. * A method call is serializable and can be passed over the wire. * @author Bela Ban * @version $Revision: 1.11 $ */ public class MethodCall implements Externalizable { static final long serialVersionUID=7873471327078957662L; /** the name of the method, case sensitive */ protected String method_name=null; /** the arguments of the method */ protected Object[] args=null; /** the class types, e.g. new Class[]{String.class, int.class} */ protected Class[] types=null; /** the signature, e.g. new String[]{String.class.getName(), int.class.getName()} */ protected String[] signature=null; /** the Method of the call */ protected Method method=null; protected static Log log=LogFactory.getLog(MethodCall.class); /** which mode to use */ protected short mode=OLD; /** infer the method from the arguments */ protected static final short OLD=1; /** explicitly ship the method, caller has to determine method himself */ protected static final short METHOD=2; /** use class information */ protected static final short TYPES=3; /** provide a signature, similar to JMX */ protected static final short SIGNATURE=4; /** * creates an empty method call, this is always invalid, until * <code>setName()</code> has been called */ public MethodCall() { } public MethodCall(Method method) { this(method, null); } public MethodCall(Method method, Object[] arguments) { init(method); if(arguments != null) args=arguments; } /** * * @param method_name * @param args * @deprecated Use one of the constructors that take class types as arguments */ public MethodCall(String method_name, Object[] args) { this.method_name=method_name; this.mode=OLD; this.args=args; } public MethodCall(String method_name, Object[] args, Class[] types) { this.method_name=method_name; this.args=args; this.types=types; this.mode=TYPES; } public MethodCall(String method_name, Object[] args, String[] signature) { this.method_name=method_name; this.args=args; this.signature=signature; this.mode=SIGNATURE; } void init(Method method) { this.method=method; this.mode=METHOD; method_name=method.getName(); } public int getMode() { return mode; } /** * returns the name of the method to be invoked using this method call object * @return a case sensitive name, can be null for an invalid method call */ public String getName() { return method_name; } /** * sets the name for this MethodCall and allowing you to reuse the same object for * a different method invokation of a different method * @param n - a case sensitive method name */ public void setName(String n) { method_name=n; } /** * returns an ordered list of arguments used for the method invokation * @return returns the list of ordered arguments */ public Object[] getArgs() { return args; } public void setArgs(Object[] args) { if(args != null) this.args=args; } public Method getMethod() { return method; } /** * * @param target_class * @return * @throws Exception */ Method findMethod(Class target_class) throws Exception { int len=args != null? args.length : 0; Method m; Method[] methods=target_class.getMethods(); for(int i=0; i < methods.length; i++) { m=methods[i]; if(m.getName().equals(method_name)) { if(m.getParameterTypes().length == len) return m; } } return null; } // Method findMethod(Class target_class) throws Exception { // int len=args != null? args.length : 0; // Class[] formal_parms=new Class[len]; // Method retval; // for(int i=0; i < len; i++) { // formal_parms[i]=args[i].getClass(); // /* getDeclaredMethod() is a bit faster, but only searches for methods in the current // class, not in superclasses */ // retval=target_class.getMethod(method_name, formal_parms); // return retval; /** * Invokes the method with the supplied arguments against the target object. * If a method lookup is provided, it will be used. Otherwise, the default * method lookup will be used. * @param target - the object that you want to invoke the method on * @return an object */ public Object invoke(Object target) throws Throwable { Class cl; Method meth=null; Object retval=null; if(method_name == null || target == null) { if(log.isErrorEnabled()) log.error("method name or target is null"); return null; } cl=target.getClass(); try { switch(mode) { case OLD: meth=findMethod(cl); break; case METHOD: if(this.method != null) meth=this.method; break; case TYPES: meth=cl.getMethod(method_name, types); break; case SIGNATURE: Class[] mytypes=null; if(signature != null) mytypes=getTypesFromString(cl, signature); meth=cl.getMethod(method_name, mytypes); break; default: if(log.isErrorEnabled()) log.error("mode " + mode + " is invalid"); break; } if(meth != null) { retval=meth.invoke(target, args); } else { if(log.isErrorEnabled()) log.error("method " + method_name + " not found"); } return retval; } catch(InvocationTargetException inv_ex) { throw inv_ex.getTargetException(); } catch(NoSuchMethodException no) { StringBuffer sb=new StringBuffer(); sb.append("found no method called ").append(method_name).append(" in class "); sb.append(cl.getName()).append(" with ("); if(args != null) { for(int i=0; i < args.length; i++) { if(i > 0) sb.append(", "); sb.append((args[i] != null)? args[i].getClass().getName() : "null"); } } sb.append(") formal parameters"); log.error(sb.toString()); throw no; } catch(Throwable e) { e.printStackTrace(System.err); if(log.isErrorEnabled()) log.error("exception=" + e); throw e; } } public Object invoke(Object target, Object[] args) throws Throwable { if(args != null) this.args=args; return invoke(target); } Class[] getTypesFromString(Class cl, String[] signature) throws Exception { String name; Class parameter; Class[] mytypes=new Class[signature.length]; for(int i=0; i < signature.length; i++) { name=signature[i]; if("long".equals(name)) parameter=long.class; else if("int".equals(name)) parameter=int.class; else if("short".equals(name)) parameter=short.class; else if("char".equals(name)) parameter=char.class; else if("byte".equals(name)) parameter=byte.class; else if("float".equals(name)) parameter=float.class; else if("double".equals(name)) parameter=double.class; else if("boolean".equals(name)) parameter=boolean.class; else parameter=Class.forName(name, false, cl.getClassLoader()); mytypes[i]=parameter; } return mytypes; } public String toString() { StringBuffer ret=new StringBuffer(); boolean first=true; ret.append(method_name).append('('); if(args != null) { for(int i=0; i < args.length; i++) { if(first) { first=false; } else { ret.append(", "); } ret.append(args[i]); } } ret.append(')'); return ret.toString(); } public String toStringDetails() { StringBuffer ret=new StringBuffer(); ret.append("MethodCall (name=" + method_name); ret.append(", number of args=" + (args != null? args.length : 0) + ')'); if(args != null) { ret.append("\nArgs:"); for(int i=0; i < args.length; i++) { ret.append("\n[" + args[i] + " (" + (args[i] != null? args[i].getClass().getName() : "null") + ")]"); } } return ret.toString(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(method_name); out.writeObject(args); out.writeShort(mode); switch(mode) { case OLD: break; case METHOD: out.writeObject(method.getParameterTypes()); out.writeObject(method.getDeclaringClass()); break; case TYPES: out.writeObject(types); break; case SIGNATURE: out.writeObject(signature); // out.writeInt(signature != null? signature.length : 0); // for(int i=0; i < signature.length; i++) { // String s=signature[i]; // out.writeUTF(s); break; default: if(log.isErrorEnabled()) log.error("mode " + mode + " is invalid"); break; } } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { method_name=in.readUTF(); args=(Object[])in.readObject(); mode=in.readShort(); switch(mode) { case OLD: break; case METHOD: Class[] parametertypes=(Class[])in.readObject(); Class declaringclass=(Class)in.readObject(); try { method=declaringclass.getMethod(method_name, parametertypes); } catch(NoSuchMethodException e) { throw new IOException(e.toString()); } break; case TYPES: types=(Class[])in.readObject(); break; case SIGNATURE: signature=(String[])in.readObject(); // int len=in.readInt(); // if(len > 0) { // signature=new String[len]; // for(int i=0; i < len; i++) { // signature[i]=in.readUTF(); break; default: if(log.isErrorEnabled()) log.error("mode " + mode + " is invalid"); break; } } }
package org.jgroups.protocols; import org.jgroups.Event; import org.jgroups.stack.Protocol; import org.jgroups.util.TimeScheduler; import java.util.Properties; import java.util.Set; import java.util.HashSet; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * All messages up the stack have to go through a barrier (read lock, RL). By default, the barrier is open. * When a CLOSE_BARRIER event is received, we close the barrier by acquiring a write lock (WL). This succeeds when all * previous messages have completed (by releasing their RLs). Thus, when we have acquired the WL, we know that there * are no pending messages processed.<br/> * When an OPEN_BARRIER event is received, we simply open the barrier again and let all messages pass in the up * direction. This is done by releasing the WL. * @author Bela Ban * @version $Id: BARRIER.java,v 1.8 2008/02/28 13:28:50 belaban Exp $ */ public class BARRIER extends Protocol { long max_close_time=60000; // how long can the barrier stay closed (in ms) ? 0 means forever final Lock lock=new ReentrantLock(); final AtomicBoolean barrier_closed=new AtomicBoolean(false); /** signals to waiting threads that the barrier is open again */ Condition barrier_opened=lock.newCondition(); Condition no_msgs_pending=lock.newCondition(); ConcurrentMap<Thread,Object> in_flight_threads=new ConcurrentHashMap<Thread,Object>(); Future barrier_opener_future=null; TimeScheduler timer; private static final Object NULL=new Object(); public String getName() { return "BARRIER"; } public boolean setProperties(Properties props) { String str; super.setProperties(props); str=props.getProperty("max_close_time"); if(str != null) { max_close_time=Long.parseLong(str); props.remove("max_close_time"); } if(!props.isEmpty()) { log.error("these properties are not recognized: " + props); return false; } return true; } public boolean isClosed() { return barrier_closed.get(); } public int getNumberOfInFlightThreads() { return in_flight_threads.size(); } public void init() throws Exception { super.init(); timer=stack.timer; } public void stop() { super.stop(); openBarrier(); } public void destroy() { super.destroy(); openBarrier(); } public Object down(Event evt) { switch(evt.getType()) { case Event.CLOSE_BARRIER: closeBarrier(); return null; case Event.OPEN_BARRIER: openBarrier(); return null; } return down_prot.down(evt); } public Object up(Event evt) { switch(evt.getType()) { case Event.MSG: Thread current_thread=Thread.currentThread(); in_flight_threads.put(current_thread, NULL); if(barrier_closed.get()) { lock.lock(); try { // Feb 28 2008 (Gray Watson): remove myself because barrier is closed in_flight_threads.remove(current_thread); while(barrier_closed.get()) { try { barrier_opened.await(); } catch(InterruptedException e) { } } } finally { // Feb 28 2008 (Gray Watson): barrier is now open, put myself back in_flight in_flight_threads.put(current_thread, NULL); lock.unlock(); } } try { return up_prot.up(evt); } finally { lock.lock(); try { if(in_flight_threads.remove(current_thread) == NULL && in_flight_threads.isEmpty() && barrier_closed.get()) { no_msgs_pending.signalAll(); } } finally { lock.unlock(); } } case Event.CLOSE_BARRIER: closeBarrier(); return null; case Event.OPEN_BARRIER: openBarrier(); return null; } return up_prot.up(evt); } /** Close the barrier. Temporarily remove all threads which are waiting or blocked, re-insert them after the call */ private void closeBarrier() { if(!barrier_closed.compareAndSet(false, true)) return; // barrier was already closed Set<Thread> threads=new HashSet<Thread>(); lock.lock(); try { // wait until all pending (= in-progress, runnable threads) msgs have returned in_flight_threads.remove(Thread.currentThread()); while(!in_flight_threads.isEmpty()) { for(Iterator<Thread> it=in_flight_threads.keySet().iterator(); it.hasNext();) { Thread thread=it.next(); Thread.State state=thread.getState(); if(state != Thread.State.RUNNABLE && state != Thread.State.NEW) { threads.add(thread); it.remove(); } } if(!in_flight_threads.isEmpty()) { try { no_msgs_pending.await(1000, TimeUnit.MILLISECONDS); } catch(InterruptedException e) { } } } } finally { for(Thread thread: threads) in_flight_threads.put(thread, NULL); lock.unlock(); } if(log.isTraceEnabled()) log.trace("barrier was closed"); if(max_close_time > 0) scheduleBarrierOpener(); } private void openBarrier() { lock.lock(); try { if(!barrier_closed.compareAndSet(true, false)) return; // barrier was already open barrier_opened.signalAll(); } finally { lock.unlock(); } if(log.isTraceEnabled()) log.trace("barrier was opened"); cancelBarrierOpener(); // cancels if running } private void scheduleBarrierOpener() { if(barrier_opener_future == null || barrier_opener_future.isDone()) { barrier_opener_future=timer.schedule(new Runnable() {public void run() {openBarrier();}}, max_close_time, TimeUnit.MILLISECONDS ); } } private void cancelBarrierOpener() { if(barrier_opener_future != null) { barrier_opener_future.cancel(true); barrier_opener_future=null; } } }
package eyamaz.bnbtweaks.asm; import static org.objectweb.asm.Opcodes.*; import net.minecraft.launchwrapper.IClassTransformer; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.*; import eyamaz.bnbtweaks.ModBnBTweaks; public class ClassTransformer implements IClassTransformer { @Override public byte[] transform(String name, String transformedName, byte[] bytes) { if (name.equals("glassmaker.extratic.common.RecipeHandler")) { ModBnBTweaks.Log.info("Patching ExtraTiC's RecipeHandler..."); ClassNode classNode = readClassFromBytes(bytes); MethodNode methodNode = findMethodNodeOfClass(classNode, "_addMeltingOreRecipe", "(Ljava/lang/String;Ljava/lang/String;II)V"); if (methodNode != null) { fixExtraTiCMelting(methodNode); } else throw new RuntimeException("Could not find _addMeltingOreRecipe(II) method in ExtraTiC RecipeHandler"); methodNode = findMethodNodeOfClass(classNode, "_addMeltingOreRecipe", "(Ljava/lang/String;Ljava/lang/String;III)V"); if (methodNode != null) { fixExtraTiCMelting(methodNode); } else throw new RuntimeException("Could not find _addMeltingOreRecipe(III) method in ExtraTiC RecipeHandler"); return writeClassToBytes(classNode); } if (name.equals("hostileworlds.dimension.gen.MapGenSchematics")) { ModBnBTweaks.Log.info("Patching HostileWorld's MapGenSchematics...."); ClassNode classNode = readClassFromBytes(bytes); MethodNode methodNode = findMethodNodeOfClass(classNode, "genTemple", "(Lnet/minecraft/world/World;II[B)V"); if (methodNode != null) { stopPyramidGeneration(methodNode); } else throw new RuntimeException("Could not find genTemple method in HostileWorlds MapGenSchematics"); return writeClassToBytes(classNode); } if (transformedName.equals("net.minecraft.block.material.MaterialPortal")) { boolean isObfuscated = !name.equals(transformedName); ModBnBTweaks.Log.info("Patching Minecraft MaterialPortal"); ClassNode classNode = readClassFromBytes(bytes); MethodNode methodNode = findMethodNodeOfClass(classNode, isObfuscated ? "a" : "isSolid", "()Z"); if (methodNode != null) { makePortalsSolidToFluid(methodNode); } else throw new RuntimeException("Could not find isSolid method in MaterialPortal"); return writeClassToBytes(classNode); } if (transformedName.equals("net.minecraft.tileentity.MobSpawnerBaseLogic")) { boolean isObfuscated = !name.equals(transformedName); ModBnBTweaks.Log.info("Patching Minecraft MobSpawnerBaseLogic"); ClassNode classNode = readClassFromBytes(bytes); MethodNode methodNode = findMethodNodeOfClass(classNode, isObfuscated ? "g" : "updateSpawner", "()V"); if (methodNode != null) { captureIsSpawningFromSpawner(methodNode); } else throw new RuntimeException("Could not find updateSpawner method in MobSpawnerBaseLogic"); return writeClassToBytes(classNode); } if (transformedName.equals("net.minecraft.entity.monster.EntityMob")) { boolean isObfuscated = !name.equals(transformedName); ModBnBTweaks.Log.info("Patching Minecraft EntityMob"); ClassNode classNode = readClassFromBytes(bytes); MethodNode methodNode = findMethodNodeOfClass(classNode, isObfuscated ? "bs" : "getCanSpawnHere", "()Z"); if (methodNode != null) { makeEntityMobIgnoreLightLevel(methodNode); } else throw new RuntimeException("Could not find getCanSpawnHere method in EntityMob"); return writeClassToBytes(classNode); } return bytes; } private ClassNode readClassFromBytes(byte[] bytes) { ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(bytes); classReader.accept(classNode, 0); return classNode; } private byte[] writeClassToBytes(ClassNode classNode) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classNode.accept(writer); return writer.toByteArray(); } private MethodNode findMethodNodeOfClass(ClassNode classNode, String methodName, String methodDesc) { for (MethodNode method : classNode.methods) { if (method.name.equals(methodName) && method.desc.equals(methodDesc)) { ModBnBTweaks.Log.info("Found target method: " + methodName); return method; } } return null; } private AbstractInsnNode findFirstInstruction(MethodNode method) { for (AbstractInsnNode instruction : method.instructions.toArray()) { if (instruction.getType() != AbstractInsnNode.LABEL && instruction.getType() != AbstractInsnNode.LINE) return instruction; } return null; } private AbstractInsnNode findFirstInstructionOfType(MethodNode method, int bytecode) { for (AbstractInsnNode instruction : method.instructions.toArray()) { if (instruction.getOpcode() == bytecode) return instruction; } return null; } private AbstractInsnNode findChronoInstructionOfType(MethodNode method, int bytecode, int number) { int i = 0; for (AbstractInsnNode instruction : method.instructions.toArray()) { if (instruction.getOpcode() == bytecode && ++i == number) return instruction; } return null; } public void fixExtraTiCMelting(MethodNode method) { AbstractInsnNode targetNode = findFirstInstructionOfType(method, ALOAD); InsnList toInject = new InsnList(); /* String par1 = ""; int par3 = 0; // equivalent to: if (par1.startsWith("ore")) par3 = tconstruct.util.config.PHConstruct.ingotsPerOre; */ toInject.add(new VarInsnNode(ALOAD, 0)); toInject.add(new LdcInsnNode("ore")); toInject.add(new MethodInsnNode(INVOKEVIRTUAL, String.class.getName().replace('.', '/'), "startsWith", "(Ljava/lang/String;)Z")); LabelNode labelIfNotStartsWith = new LabelNode(); toInject.add(new JumpInsnNode(IFEQ, labelIfNotStartsWith)); toInject.add(new FieldInsnNode(GETSTATIC, "tconstruct/util/config/PHConstruct", "ingotsPerOre", "I")); toInject.add(new VarInsnNode(ISTORE, 2)); toInject.add(labelIfNotStartsWith); method.instructions.insertBefore(targetNode, toInject); ModBnBTweaks.Log.info("Patched " + method.name); } public void stopPyramidGeneration(MethodNode method) { AbstractInsnNode targetNode = findFirstInstructionOfType(method, ALOAD); InsnList toInject = new InsnList(); //Add return statement to beginning of method toInject.add(new InsnNode(RETURN)); method.instructions.insertBefore(targetNode, toInject); ModBnBTweaks.Log.info("Patched " + method.name); } public void makePortalsSolidToFluid(MethodNode method) { AbstractInsnNode targetNode = findFirstInstructionOfType(method, ICONST_0); InsnList toInject = new InsnList(); //Change portals isSolid to return true, rather than false //Causing liquids to no longer break them toInject.add(new InsnNode(ICONST_1)); method.instructions.insert(targetNode, toInject); method.instructions.remove(targetNode); ModBnBTweaks.Log.info("Patched: " + method.name); } public void captureIsSpawningFromSpawner(MethodNode method) { AbstractInsnNode firstNode = findFirstInstruction(method); AbstractInsnNode lastNode = method.instructions.getLast(); if (firstNode == null || lastNode == null || lastNode.getOpcode() != RETURN) throw new RuntimeException("Could not find target nodes for MobSpawnerBaseLogic patch"); InsnList firstInject = new InsnList(); InsnList lastInject = new InsnList(); //Inject Hooks.isSpawningFromSpawner = true; to start //inject Hooks.isSpawningFromSpawner = false; to end firstInject.add(new InsnNode(ICONST_1)); firstInject.add(new FieldInsnNode(PUTSTATIC, "eyamaz/bnbtweaks/asm/Hooks", "isSpawningFromSpawner", "Z")); lastInject.add(new InsnNode(ICONST_0)); lastInject.add(new FieldInsnNode(PUTSTATIC, "eyamaz/bnbtweaks/asm/Hooks", "isSpawningFromSpawner", "Z")); method.instructions.insertBefore(firstNode, firstInject); method.instructions.insertBefore(lastNode, lastInject); ModBnBTweaks.Log.info("Patched: " + method.name); } public void makeEntityMobIgnoreLightLevel(MethodNode method) { AbstractInsnNode firstTargetNode = findChronoInstructionOfType(method, ALOAD, 2); AbstractInsnNode secondTargetNode = findChronoInstructionOfType(method, ALOAD, 3); if (firstTargetNode == null || secondTargetNode == null) throw new RuntimeException("Could not find target nodes for EntityMob patch"); InsnList firstInject = new InsnList(); InsnList secondInject = new InsnList(); //Inject hook to create //return this.worldObj.difficultySetting > 0 && (Hooks.isSpawningFromSpawner || this.isValidLightLevel()) && super.getCanSpawnHere(); firstInject.add(new FieldInsnNode(GETSTATIC, "eyamaz/bnbtweaks/asm/Hooks", "isSpawningFromSpawner", "Z")); LabelNode label = new LabelNode(); firstInject.add(new JumpInsnNode(IFNE, label)); secondInject.add(label); secondInject.add(new FrameNode(Opcodes.F_SAME, 0, null, 0, null)); method.instructions.insertBefore(firstTargetNode, firstInject); method.instructions.insertBefore(secondTargetNode, secondInject); ModBnBTweaks.Log.info("Patched: " + method.name); } }
package com.sunteam.ebook.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import android.text.TextUtils; import com.sunteam.ebook.entity.DiasyNode; import com.sunteam.ebook.entity.DiasySentenceNode; /** * Daisy * * @author wzp */ public class DaisyFileReaderUtils { private static final String TAG_BODY_START = "<body>"; private static final String TAG_BODY_END = "</body>"; //TAGncc.html private static final String TAG_H_START = "<h"; private static final String TAG_H_END = "</h"; private static final String TAG_A_START = "<a href=\""; private static final String TAG_A_END = "</a>"; //TAG*.smil private static final String TAG_TEXT_START = "<text"; private static final String TAG_TEXT_END = "/>"; private static final String TAG_AUDIO_START = "<audio"; private static final String TAG_AUDIO_END = "/>"; private static DaisyFileReaderUtils instance = null; private ArrayList<DiasyNode> mDiasyNodeList = new ArrayList<DiasyNode>(); private String mSentencePath = null; private String mSentenceData = null; public static DaisyFileReaderUtils getInstance() { if( null == instance ) { instance = new DaisyFileReaderUtils(); } return instance; } /** * * @param fatherSeq * @return */ public ArrayList<DiasyNode> getChildNodeList( int fatherSeq ) { ArrayList<DiasyNode> list = new ArrayList<DiasyNode>(); int size = mDiasyNodeList.size(); if( -1 == fatherSeq ) { for( int i = 0; i < size; i++ ) { DiasyNode node = mDiasyNodeList.get(i); if( 1 == node.level ) { list.add(node); } } } else { DiasyNode fatherNode = mDiasyNodeList.get(fatherSeq); for( int i = fatherSeq+1; i < size; i++ ) { DiasyNode node = mDiasyNodeList.get(i); if( fatherNode.seq == node.father ) { list.add(node); } } } return list; } public void init( final String fullpath ) { mDiasyNodeList.clear(); try { IdentifyEncoding ie = new IdentifyEncoding(); String strCharsetName = ie.GetEncodingName( fullpath ); File file = new File(fullpath); if( !file.exists() ) { return; } int length = (int)file.length(); if( 0 == length ) { return; } FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[length]; fis.read(buffer); fis.close(); String data = new String(buffer, strCharsetName); int start = data.indexOf(TAG_BODY_START); int end = data.lastIndexOf(TAG_BODY_END); if( ( -1 == start ) || ( -1 == end ) ) { //body return; } start += TAG_BODY_START.length(); while( true ) { start = data.indexOf(TAG_H_START, start); end = data.indexOf(TAG_H_END, start); if( ( -1 == start ) || ( -1 == end ) ) { break; } int oldEnd = end; String item = data.substring(start+TAG_H_START.length(), end); //item String[] splitItem = item.split(" "); start = item.indexOf(TAG_A_START); end = item.indexOf(TAG_A_END); String href = item.substring(start+TAG_A_START.length(), end); String[] splitHref = href.split("\">"); String[] splitStr = splitHref[0].split(" DiasyNode node = new DiasyNode(); node.seq = mDiasyNodeList.size(); node.level = Integer.parseInt(splitItem[0]); node.href = splitStr[0]; node.label = splitStr[1]; if( 1 == node.level ) { node.father = -1; } else { for( int i = node.seq-1; i >= 0; i { if( node.level-1 == mDiasyNodeList.get(i).level ) { node.father = mDiasyNodeList.get(i).seq; break; } } } node.name = getEscapeString(splitHref[1]); mDiasyNodeList.add(node); start = oldEnd+TAG_H_END.length(); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * * @param smilPath * lableName: () * @return */ public ArrayList<DiasySentenceNode> getDiasySentenceNodeList( String path, String smil, String lableName ) { ArrayList<DiasySentenceNode> list = new ArrayList<DiasySentenceNode>(); try { final String smilPath = path+"/"+smil; IdentifyEncoding ie = new IdentifyEncoding(); String strCharsetName = ie.GetEncodingName( smilPath ); File file = new File(smilPath); if( !file.exists() ) { return list; } int length = (int)file.length(); if( 0 == length ) { return list; } //smil FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[length]; fis.read(buffer); fis.close(); String data = new String(buffer, strCharsetName); int start = data.indexOf(TAG_BODY_START); int end = data.lastIndexOf(TAG_BODY_END); if( ( -1 == start ) || ( -1 == end ) ) { //body return list; } start += TAG_BODY_START.length(); while( true ) { start = data.indexOf(TAG_TEXT_START, start); end = data.indexOf(TAG_TEXT_END, start); if( ( -1 == start ) || ( -1 == end ) ) { break; } String txtItem = data.substring(start+TAG_TEXT_START.length(), end); //txt item String[] splitTextItem = txtItem.split(" "); if( ( null == splitTextItem ) || ( 0 == splitTextItem.length ) ) { break; } int i = 0; for( ; i < splitTextItem.length; i++ ) { if( splitTextItem[i].indexOf("src=\"") == 0 ) { break; } } start = end+TAG_TEXT_END.length(); if( i >= splitTextItem.length ) { continue; } String temp = splitTextItem[i].replaceAll("\"", " if( TextUtils.isEmpty(temp) ) { continue; } String[] splitText = temp.split(" if( ( null == splitText ) || ( splitText.length < 3 ) ) { continue; } DiasySentenceNode node = new DiasySentenceNode(); node.sentence = getEscapeString(getDaisySentence( path, splitText[1], splitText[2] )); start = getDaisySentenceAudioInfo(data, start, node); list.add(node); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return list; } /** * * @param sentencePath * lableName: * @return */ private String getDaisySentence( String path, String sentenceHref, String lableName ) { try { final String sentencePath = path + "/" + sentenceHref; if( sentencePath.equals(mSentencePath) ) { } else { IdentifyEncoding ie = new IdentifyEncoding(); String strCharsetName = ie.GetEncodingName( sentencePath ); File file = new File(sentencePath); if( !file.exists() ) { return ""; } int length = (int)file.length(); if( 0 == length ) { return ""; } //content FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[length]; fis.read(buffer); fis.close(); mSentencePath = sentencePath; mSentenceData = new String(buffer, strCharsetName); } String data = mSentenceData; int start = data.indexOf(TAG_BODY_START); int end = data.lastIndexOf(TAG_BODY_END); if( ( -1 == start ) || ( -1 == end ) ) { //body return ""; } start += TAG_BODY_START.length(); while( true ) { start = data.indexOf(lableName, start); if( -1 == start ) { return ""; } start += lableName.length(); start = data.indexOf(TAG_A_START, start); end = data.indexOf(TAG_A_END, start); if( ( -1 == start ) || ( -1 == end ) ) { return ""; } String sentenceItem = data.substring(start+TAG_A_START.length(), end); //sentence item String[] splitSentenceItem = sentenceItem.split(">"); if( ( null == splitSentenceItem ) || ( 2 != splitSentenceItem.length ) ) { return ""; } return splitSentenceItem[1]; } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return ""; } private int getDaisySentenceAudioInfo( String data, int offset, DiasySentenceNode node ) { int n = 0; while( true ) { int textStart = data.indexOf(TAG_TEXT_START, offset); int start = data.indexOf(TAG_AUDIO_START, offset); int end = data.indexOf(TAG_AUDIO_END, offset); if( ( -1 == start ) || ( -1 == end ) || ( textStart != -1 && start > textStart ) ) { break; } String audioItem = data.substring(start+TAG_AUDIO_START.length(), end); //audio item String[] splitAudioItem = audioItem.split(" "); if( ( null == splitAudioItem ) || ( 0 == splitAudioItem.length ) ) { break; } int i = 0; for( ; i < splitAudioItem.length; i++ ) { if( splitAudioItem[i].indexOf("src=\"") == 0 ) { String[] splitAudio = splitAudioItem[i].replaceAll("\"", "#").split("#"); node.audioFile = splitAudio[1]; } else if( splitAudioItem[i].indexOf("clip-begin=\"npt=") == 0 ) { if( 0 == n ) { String[] splitTime = splitAudioItem[i].replaceAll("s\"", "").split("="); node.startTime = (long)(Float.parseFloat(splitTime[2])*1000); } n++; } else if( splitAudioItem[i].indexOf("clip-end=\"npt=") == 0 ) { String[] splitTime = splitAudioItem[i].replaceAll("s\"", "").split("="); node.endTime = (long)(Float.parseFloat(splitTime[2])*1000); } } offset = end+TAG_AUDIO_END.length(); } return offset; } private String getEscapeString( String str ) { String name = ""; String[] splitUnicode = str.split("& if( (null == splitUnicode ) || ( 0 == splitUnicode.length) ) { return str; } else { for( int i = 0; i < splitUnicode.length; i++ ) { if( "".equals(splitUnicode[i]) ) { continue; } String ch = splitUnicode[i].substring(0, 1); if( "x".equals(ch) || "X".equals(ch) ) { int seq = splitUnicode[i].indexOf(";"); if( -1 == seq ) { name = splitUnicode[i]; continue; } String unicode = splitUnicode[i].substring(1, seq); try { int code = Integer.parseInt(unicode, 16); byte[] byteCode = new byte[2]; byteCode[0] = (byte) ((code&0x0000ff00)>>8); byteCode[1] = (byte) (code&0x000000ff); name += new String(byteCode, "utf-16be"); String temp = splitUnicode[i].substring(seq+1); if( null != temp ) { name += temp; } } catch( Exception e ) { e.printStackTrace(); name = splitUnicode[i]; } } else { int seq = splitUnicode[i].indexOf(";"); if( -1 == seq ) { name = splitUnicode[i]; continue; } String unicode = splitUnicode[i].substring(0, seq); try { int code = Integer.parseInt(unicode, 10); byte[] byteCode = new byte[2]; byteCode[0] = (byte) ((code&0x0000ff00)>>8); byteCode[1] = (byte) (code&0x000000ff); name += new String(byteCode, "utf-16be"); String temp = splitUnicode[i].substring(seq+1); if( null != temp ) { name += temp; } } catch( Exception e ) { e.printStackTrace(); name = splitUnicode[i]; } } } } return name; } }
package org.jgroups.protocols; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.PhysicalAddress; import org.jgroups.View; import org.jgroups.annotations.MBean; import org.jgroups.annotations.ManagedAttribute; import org.jgroups.annotations.ManagedOperation; import org.jgroups.annotations.Property; import org.jgroups.stack.IpAddress; import org.jgroups.stack.Protocol; import org.jgroups.util.*; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetAddress; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @MBean(description="Failure detection protocol which detects crashes or hangs of entire hosts and suspects " + "all cluster members on those hosts") public class FD_HOST extends Protocol { @Property(description="The command used to check a given host for liveness. Example: \"ping\". " + "If null, InetAddress.isReachable() will be used by default") protected String cmd; @Property(description="Max time (in ms) after which a host is suspected if it failed all liveness checks") protected long timeout=60000; @Property(description="The interval (in ms) at which the hosts are checked for liveness") protected long interval=20000; @Property(description="Max time (in ms) that a liveness check for a single host can take") protected long check_timeout=3000; @Property(description="Uses TimeService to get the current time rather than System.currentTimeMillis. Might get " + "removed soon, don't use !") protected boolean use_time_service=true; @ManagedAttribute(description="Number of liveness checks") protected int num_liveness_checks; @ManagedAttribute(description="Number of suspected events received") protected int num_suspect_events; protected final Set<Address> suspected_mbrs=new HashSet<Address>(); @ManagedAttribute(description="Shows whether there are currently any suspected members") protected volatile boolean has_suspected_mbrs; protected final BoundedList<Tuple<InetAddress,Long>> suspect_history=new BoundedList<Tuple<InetAddress,Long>>(20); protected Address local_addr; protected InetAddress local_host; protected final List<Address> members=new ArrayList<Address>(); /** The command to detect whether a target is alive */ protected PingCommand ping_command=new IsReachablePingCommand(); /** Map of hosts and their cluster members, updated on view changes. Used to suspect all members of a suspected host */ protected final Map<InetAddress,List<Address>> hosts=new HashMap<InetAddress,List<Address>>(); // Map of hosts and timestamps of last updates (ns) protected final ConcurrentMap<InetAddress, Long> timestamps=new ConcurrentHashMap<InetAddress,Long>(); /** Timer used to run the ping task on */ protected TimeScheduler timer; protected TimeService time_service; protected Future<?> ping_task_future; public FD_HOST pingCommand(PingCommand cmd) {this.ping_command=cmd; return this;} public void resetStats() { num_suspect_events=num_liveness_checks=0; suspect_history.clear(); } public void setCommand(String command) { this.cmd=command; ping_command=this.cmd != null? new ExternalPingCommand(cmd) : new IsReachablePingCommand(); } @ManagedOperation(description="Prints history of suspected hosts") public String printSuspectHistory() { StringBuilder sb=new StringBuilder(); for(Tuple<InetAddress,Long> tmp: suspect_history) { sb.append(new Date(tmp.getVal2())).append(": ").append(tmp.getVal1()).append("\n"); } return sb.toString(); } @ManagedOperation(description="Prints timestamps") public String printTimestamps() { return _printTimestamps(); } @ManagedAttribute(description="Whether the ping task is running") public boolean isPingerRunning() { Future<?> future=ping_task_future; return future != null && !future.isDone(); } @ManagedOperation(description="Prints the hosts and their associated cluster members") public String printHosts() { StringBuilder sb=new StringBuilder(); synchronized(hosts) { for(Map.Entry<InetAddress,List<Address>> entry: hosts.entrySet()) { sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); } } return sb.toString(); } @ManagedOperation(description="Checks whether the given host is alive") public boolean isAlive(String host) throws Exception { return ping_command != null && ping_command.isAlive(InetAddress.getByName(host), check_timeout); } @ManagedAttribute(description="Currently suspected members") public String getSuspectedMembers() {return suspected_mbrs.toString();} public void init() throws Exception { if(interval >= timeout) throw new IllegalArgumentException("interval (" + interval + ") has to be less than timeout (" + timeout + ")"); super.init(); if(cmd != null) ping_command=new ExternalPingCommand(cmd); timer=getTransport().getTimer(); if(timer == null) throw new Exception("timer not set"); time_service=getTransport().getTimeService(); if(time_service == null) log.warn("%s: time service is not available, using System.currentTimeMillis() instead", local_addr); else { if(time_service.interval() > timeout) { log.warn("%s: interval of time service (%d) is greater than timeout (%d), disabling time service", local_addr, time_service.interval(), timeout); use_time_service=false; } } suspected_mbrs.clear(); has_suspected_mbrs=false; } public void stop() { super.stop(); stopPingerTask(); suspected_mbrs.clear(); has_suspected_mbrs=false; } public Object down(Event evt) { switch(evt.getType()) { case Event.VIEW_CHANGE: View view=(View)evt.getArg(); handleView(view); break; case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); break; case Event.CONNECT: case Event.CONNECT_USE_FLUSH: case Event.CONNECT_WITH_STATE_TRANSFER: case Event.CONNECT_WITH_STATE_TRANSFER_USE_FLUSH: local_host=getHostFor(local_addr); break; case Event.DISCONNECT: Object retval=down_prot.down(evt); local_host=null; return retval; case Event.UNSUSPECT: Address mbr=(Address)evt.getArg(); unsuspect(mbr); break; } return down_prot.down(evt); } protected void handleView(View view) { List<Address> view_mbrs=view.getMembers(); boolean is_pinger=false; members.clear(); members.addAll(view_mbrs); Collection<InetAddress> current_hosts=null; synchronized(hosts) { hosts.clear(); for(Address mbr: view_mbrs) { InetAddress key=getHostFor(mbr); if(key == null) continue; List<Address> mbrs=hosts.get(key); if(mbrs == null) hosts.put(key, mbrs=new ArrayList<Address>()); mbrs.add(mbr); } is_pinger=isPinger(local_addr); current_hosts=new ArrayList<InetAddress>(hosts.keySet()); } if(suspected_mbrs.retainAll(view.getMembers())) has_suspected_mbrs=!suspected_mbrs.isEmpty(); timestamps.keySet().retainAll(current_hosts); current_hosts.remove(local_host); for(InetAddress host: current_hosts) timestamps.putIfAbsent(host, getTimestamp()); if(is_pinger) startPingerTask(); else { stopPingerTask(); timestamps.clear(); } } protected PhysicalAddress getPhysicalAddress(Address logical_addr) { return (PhysicalAddress)down(new Event(Event.GET_PHYSICAL_ADDRESS, logical_addr)); } protected InetAddress getHostFor(Address mbr) { PhysicalAddress phys_addr=getPhysicalAddress(mbr); return phys_addr instanceof IpAddress? ((IpAddress)phys_addr).getIpAddress() : null; } protected boolean isPinger(Address mbr) { InetAddress host=getHostFor(mbr); if(host == null) return false; // should not happen List<Address> mbrs=hosts.get(host); return mbrs != null && !mbrs.isEmpty() && mbrs.get(0).equals(mbr); } protected void startPingerTask() { if(ping_task_future == null || ping_task_future.isDone()) ping_task_future=timer.scheduleAtFixedRate(new PingTask(), interval, interval, TimeUnit.MILLISECONDS); } protected void stopPingerTask() { if(ping_task_future != null) { ping_task_future.cancel(false); ping_task_future=null; } } /** Called by ping task; will result in all members of host getting suspected */ protected void suspect(InetAddress host) { List<Address> suspects; suspect_history.add(new Tuple<InetAddress,Long>(host, System.currentTimeMillis())); // we need wall clock time here synchronized(hosts) { List<Address> tmp=hosts.get(host); suspects=tmp != null? new ArrayList<Address>(tmp) : null; } if(suspects != null) { log.debug("%s: suspecting host %s; suspected members: %s", local_addr, host, Util.printListWithDelimiter(suspects, ",")); suspect(suspects); } } protected void suspect(List<Address> suspects) { if(suspects == null || suspects.isEmpty()) return; num_suspect_events+=suspects.size(); final List<Address> eligible_mbrs=new ArrayList<Address>(); synchronized(this) { suspected_mbrs.addAll(suspects); eligible_mbrs.addAll(members); eligible_mbrs.removeAll(suspected_mbrs); has_suspected_mbrs=!suspected_mbrs.isEmpty(); } // Check if we're coord, then send up the stack if(local_addr != null && !eligible_mbrs.isEmpty()) { Address first=eligible_mbrs.get(0); if(local_addr.equals(first)) { log.debug("%s: suspecting %s", local_addr, suspected_mbrs); for(Address suspect: suspects) { up_prot.up(new Event(Event.SUSPECT, suspect)); down_prot.down(new Event(Event.SUSPECT, suspect)); } } } } /* protected void unsuspect(InetAddress host) { List<Address> suspects; synchronized(hosts) { List<Address> tmp=hosts.get(host); suspects=tmp != null? new ArrayList<Address>(tmp) : null; } if(suspects != null) { log.debug("%s: unsuspecting host %s; unsuspected members: %s", local_addr, host, Util.printListWithDelimiter(suspects, ",")); for(Address unsuspect: suspects) unsuspect(unsuspect); } }*/ protected boolean unsuspect(Address mbr) { if(mbr == null) return false; boolean do_unsuspect; synchronized(this) { do_unsuspect=!suspected_mbrs.isEmpty() && suspected_mbrs.remove(mbr); if(do_unsuspect) has_suspected_mbrs=!suspected_mbrs.isEmpty(); } if(do_unsuspect) { up_prot.up(new Event(Event.UNSUSPECT, mbr)); down_prot.down(new Event(Event.UNSUSPECT, mbr)); } return do_unsuspect; } protected String _printTimestamps() { StringBuilder sb=new StringBuilder(); long current_time=getTimestamp(); for(Map.Entry<InetAddress,Long> entry: timestamps.entrySet()) { sb.append(entry.getKey()).append(": "); sb.append(TimeUnit.SECONDS.convert(current_time - entry.getValue(), TimeUnit.NANOSECONDS)).append(" secs old\n"); } return sb.toString(); } protected void updateTimestampFor(InetAddress host) { timestamps.put(host, getTimestamp()); } /** Returns the age (in secs) of the given host */ protected long getAgeOf(InetAddress host) { Long ts=timestamps.get(host); return ts != null? TimeUnit.SECONDS.convert(getTimestamp() - ts, TimeUnit.NANOSECONDS) : -1; } protected long getTimestamp() { return use_time_service && time_service != null? time_service.timestamp() : System.nanoTime(); } /** Selected members run this task periodically. The task pings all hosts except self using ping_command. * When a host is not seen as alive, all members associated with that host are suspected */ protected class PingTask implements Runnable { public void run() { List<InetAddress> targets; synchronized(hosts) { targets=new ArrayList<InetAddress>(hosts.keySet()); } targets.remove(local_host); for(InetAddress target: targets) { try { // Ping each host boolean is_alive=ping_command.isAlive(target, check_timeout); num_liveness_checks++; if(is_alive) updateTimestampFor(target); else log.trace("%s: %s is not alive (age=%d secs)", local_addr, target, getAgeOf(target)); // Check timestamp long current_time=getTimestamp(); long timestamp=timestamps.get(target); long diff=TimeUnit.MILLISECONDS.convert(current_time - timestamp, TimeUnit.NANOSECONDS); if(diff >= timeout) suspect(target); } catch(Exception e) { log.error("%s: ping command failed: %s", local_addr, e); } } } } /** Command used to check whether a given host is alive, periodically called */ public interface PingCommand { /** * Checks whether a given host is alive * @param host The host to be checked for liveness * @param timeout Number of milliseconds to wait for the check to complete * @return true if the host is alive, else false */ boolean isAlive(InetAddress host, long timeout) throws Exception; } public static class IsReachablePingCommand implements PingCommand { public boolean isAlive(InetAddress host, long timeout) throws Exception { return host.isReachable((int)timeout); } } protected static class ExternalPingCommand implements PingCommand { protected final String cmd; public ExternalPingCommand(String cmd) { this.cmd=cmd; } public boolean isAlive(InetAddress host, long timeout) throws Exception { return CommandExecutor2.execute(cmd + " " + host.getHostAddress()) == 0; } } public static class CommandExecutor { public static int execute(String command) throws Exception { Process p=Runtime.getRuntime().exec(command); InputStream in=p.getInputStream(), err=p.getErrorStream(); try { Reader in_reader, err_reader; in_reader=new Reader(in); err_reader=new Reader(err); in_reader.start(); err_reader.start(); in_reader.join(); err_reader.join(); return p.exitValue(); } finally { Util.close(in); Util.close(err); } } static class Reader extends Thread { InputStreamReader in; Reader(InputStream in) { this.in=new InputStreamReader(in); } public void run() { int c; while(true) { try { c=in.read(); if(c == -1) break; // System.out.print((char)c); } catch(IOException e) { break; } } } } } public static class CommandExecutor2 { public static int execute(String command) throws Exception { Process p=Runtime.getRuntime().exec(command); return p.waitFor(); } } }
package org.jgroups.protocols; import org.jgroups.Address; import org.jgroups.annotations.Experimental; import org.jgroups.annotations.Property; import org.jgroups.annotations.Unsupported; import org.jgroups.util.Util; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import static java.lang.String.valueOf; /** * Discovery protocol using Amazon's S3 storage. The S3 access code reuses the example shipped by Amazon. * This protocol is unsupported and experimental ! * @author Bela Ban * @version $Id: S3_PING.java,v 1.8 2010/06/17 06:59:13 belaban Exp $ */ @Experimental @Unsupported public class S3_PING extends FILE_PING { @Property(description="The access key to AWS (S3)") protected String access_key=null; @Property(description="The secret access key to AWS (S3)") protected String secret_access_key=null; @Property(description="When non-null, we set location to prefix-UUID") protected String prefix=null; protected AWSAuthConnection conn=null; public void init() throws Exception { super.init(); if(access_key == null || secret_access_key == null) throw new IllegalArgumentException("access_key and secret_access_key must be non-null"); conn=new AWSAuthConnection(access_key, secret_access_key); if(prefix != null && prefix.length() > 0) { ListAllMyBucketsResponse bucket_list=conn.listAllMyBuckets(null); List buckets=bucket_list.entries; if(buckets != null) { boolean found=false; for(Object tmp: buckets) { if(tmp instanceof Bucket) { Bucket bucket=(Bucket)tmp; if(bucket.name.startsWith(prefix)) { location=bucket.name; found=true; } } } if(!found) { location=prefix + "-" + java.util.UUID.randomUUID().toString(); } } } if(!conn.checkBucketExists(location)) { conn.createBucket(location, AWSAuthConnection.LOCATION_DEFAULT, null).connection.getResponseMessage(); } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { remove(group_addr, local_addr); } }); } protected List<PingData> readAll(String clustername) { if(clustername == null) return null; List<PingData> retval=new ArrayList<PingData>(); try { ListBucketResponse rsp=conn.listBucket(location, clustername, null, null, null); if(rsp.entries != null) { for(Iterator<ListEntry> it=rsp.entries.iterator(); it.hasNext();) { ListEntry key=it.next(); GetResponse val=conn.get(location, key.key, null); if(val.object != null) { byte[] buf=val.object.data; if(buf != null) { try { PingData data=(PingData)Util.objectFromByteBuffer(buf); retval.add(data); } catch(Exception e) { log.error("failed marshalling buffer to address", e); } } } } } return retval; } catch(IOException ex) { log.error("failed reading addresses", ex); return retval; } } protected void writeToFile(PingData data, String clustername) { if(clustername == null || data == null) return; String filename=local_addr instanceof org.jgroups.util.UUID? ((org.jgroups.util.UUID)local_addr).toStringLong() : local_addr.toString(); String key=clustername + "/" + filename; try { Map headers=new TreeMap(); headers.put("Content-Type", Arrays.asList("text/plain")); byte[] buf=Util.objectToByteBuffer(data); S3Object val=new S3Object(buf, null); conn.put(location, key, val, headers).connection.getResponseMessage(); } catch(Exception e) { log.error("failed marshalling " + data + " to buffer", e); } } protected void remove(String clustername, Address addr) { if(clustername == null || addr == null) return; String filename=addr instanceof org.jgroups.util.UUID? ((org.jgroups.util.UUID)addr).toStringLong() : addr.toString(); String key=clustername + "/" + filename; try { Map headers=new TreeMap(); headers.put("Content-Type", Arrays.asList("text/plain")); conn.delete(location, key, headers).connection.getResponseMessage(); if(log.isTraceEnabled()) log.trace("removing " + location + "/" + key); } catch(Exception e) { log.error("failure removing data", e); } } /** * The following classes have been copied from Amazon's sample code */ static class AWSAuthConnection { public static final String LOCATION_DEFAULT=null; public static final String LOCATION_EU="EU"; private String awsAccessKeyId; private String awsSecretAccessKey; private boolean isSecure; private String server; private int port; private CallingFormat callingFormat; public AWSAuthConnection(String awsAccessKeyId, String awsSecretAccessKey) { this(awsAccessKeyId, awsSecretAccessKey, true); } public AWSAuthConnection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure) { this(awsAccessKeyId, awsSecretAccessKey, isSecure, Utils.DEFAULT_HOST); } public AWSAuthConnection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure, String server) { this(awsAccessKeyId, awsSecretAccessKey, isSecure, server, isSecure? Utils.SECURE_PORT : Utils.INSECURE_PORT); } public AWSAuthConnection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure, String server, int port) { this(awsAccessKeyId, awsSecretAccessKey, isSecure, server, port, CallingFormat.getSubdomainCallingFormat()); } public AWSAuthConnection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure, String server, CallingFormat format) { this(awsAccessKeyId, awsSecretAccessKey, isSecure, server, isSecure? Utils.SECURE_PORT : Utils.INSECURE_PORT, format); } /** * Create a new interface to interact with S3 with the given credential and connection * parameters * @param awsAccessKeyId Your user key into AWS * @param awsSecretAccessKey The secret string used to generate signatures for authentication. * @param isSecure use SSL encryption * @param server Which host to connect to. Usually, this will be s3.amazonaws.com * @param port Which port to use. * @param format Type of request Regular/Vanity or Pure Vanity domain */ public AWSAuthConnection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure, String server, int port, CallingFormat format) { this.awsAccessKeyId=awsAccessKeyId; this.awsSecretAccessKey=awsSecretAccessKey; this.isSecure=isSecure; this.server=server; this.port=port; this.callingFormat=format; } /** * Creates a new bucket. * @param bucket The name of the bucket to create. * @param headers A Map of String to List of Strings representing the http headers to pass (can be null). */ public Response createBucket(String bucket, Map headers) throws IOException { return createBucket(bucket, null, headers); } public Response createBucket(String bucket, String location, Map headers) throws IOException { String body; if(location == null) { body=null; } else if(LOCATION_EU.equals(location)) { if(!callingFormat.supportsLocatedBuckets()) throw new IllegalArgumentException("Creating location-constrained bucket with unsupported calling-format"); body="<CreateBucketConstraint><LocationConstraint>" + location + "</LocationConstraint></CreateBucketConstraint>"; } else throw new IllegalArgumentException("Invalid Location: " + location); // validate bucket name if(!Utils.validateBucketName(bucket, callingFormat)) throw new IllegalArgumentException("Invalid Bucket Name: " + bucket); HttpURLConnection request=makeRequest("PUT", bucket, "", null, headers); if(body != null) { request.setDoOutput(true); request.getOutputStream().write(body.getBytes("UTF-8")); } return new Response(request); } /** * Check if the specified bucket exists (via a HEAD request) * @param bucket The name of the bucket to check * @return true if HEAD access returned success */ public boolean checkBucketExists(String bucket) throws IOException { HttpURLConnection response=makeRequest("HEAD", bucket, "", null, null); int httpCode=response.getResponseCode(); if(httpCode >= 200 && httpCode < 300) return true; if(httpCode == HttpURLConnection.HTTP_NOT_FOUND) // bucket doesn't exist return false; throw new IOException("bucket '" + bucket + "' could not be accessed (rsp=" + httpCode + " (" + response.getResponseMessage() + "). Maybe the bucket is owned by somebody else or " + "the authentication failed"); } /** * Lists the contents of a bucket. * @param bucket The name of the bucket to create. * @param prefix All returned keys will start with this string (can be null). * @param marker All returned keys will be lexographically greater than * this string (can be null). * @param maxKeys The maximum number of keys to return (can be null). * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public ListBucketResponse listBucket(String bucket, String prefix, String marker, Integer maxKeys, Map headers) throws IOException { return listBucket(bucket, prefix, marker, maxKeys, null, headers); } /** * Lists the contents of a bucket. * @param bucket The name of the bucket to list. * @param prefix All returned keys will start with this string (can be null). * @param marker All returned keys will be lexographically greater than * this string (can be null). * @param maxKeys The maximum number of keys to return (can be null). * @param delimiter Keys that contain a string between the prefix and the first * occurrence of the delimiter will be rolled up into a single element. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public ListBucketResponse listBucket(String bucket, String prefix, String marker, Integer maxKeys, String delimiter, Map headers) throws IOException { Map pathArgs=Utils.paramsForListOptions(prefix, marker, maxKeys, delimiter); return new ListBucketResponse(makeRequest("GET", bucket, "", pathArgs, headers)); } /** * Deletes a bucket. * @param bucket The name of the bucket to delete. * @param headers A Map of String to List of Strings representing the http headers to pass (can be null). */ public Response deleteBucket(String bucket, Map headers) throws IOException { return new Response(makeRequest("DELETE", bucket, "", null, headers)); } /** * Writes an object to S3. * @param bucket The name of the bucket to which the object will be added. * @param key The name of the key to use. * @param object An S3Object containing the data to write. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public Response put(String bucket, String key, S3Object object, Map headers) throws IOException { HttpURLConnection request= makeRequest("PUT", bucket, Utils.urlencode(key), null, headers, object); request.setDoOutput(true); request.getOutputStream().write(object.data == null? new byte[]{} : object.data); return new Response(request); } /** * Creates a copy of an existing S3 Object. In this signature, we will copy the * existing metadata. The default access control policy is private; if you want * to override it, please use x-amz-acl in the headers. * @param sourceBucket The name of the bucket where the source object lives. * @param sourceKey The name of the key to copy. * @param destinationBucket The name of the bucket to which the object will be added. * @param destinationKey The name of the key to use. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). You may wish to set the x-amz-acl header appropriately. */ public Response copy(String sourceBucket, String sourceKey, String destinationBucket, String destinationKey, Map headers) throws IOException { S3Object object=new S3Object(new byte[]{}, new HashMap()); headers=headers == null? new HashMap() : new HashMap(headers); headers.put("x-amz-copy-source", Arrays.asList(sourceBucket + "/" + sourceKey)); headers.put("x-amz-metadata-directive", Arrays.asList("COPY")); return verifyCopy(put(destinationBucket, destinationKey, object, headers)); } /** * Creates a copy of an existing S3 Object. In this signature, we will replace the * existing metadata. The default access control policy is private; if you want * to override it, please use x-amz-acl in the headers. * @param sourceBucket The name of the bucket where the source object lives. * @param sourceKey The name of the key to copy. * @param destinationBucket The name of the bucket to which the object will be added. * @param destinationKey The name of the key to use. * @param metadata A Map of String to List of Strings representing the S3 metadata * for the new object. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). You may wish to set the x-amz-acl header appropriately. */ public Response copy(String sourceBucket, String sourceKey, String destinationBucket, String destinationKey, Map metadata, Map headers) throws IOException { S3Object object=new S3Object(new byte[]{}, metadata); headers=headers == null? new HashMap() : new HashMap(headers); headers.put("x-amz-copy-source", Arrays.asList(sourceBucket + "/" + sourceKey)); headers.put("x-amz-metadata-directive", Arrays.asList("REPLACE")); return verifyCopy(put(destinationBucket, destinationKey, object, headers)); } /** * Copy sometimes returns a successful response and starts to send whitespace * characters to us. This method processes those whitespace characters and * will throw an exception if the response is either unknown or an error. * @param response Response object from the PUT request. * @return The response with the input stream drained. * @throws IOException If anything goes wrong. */ private static Response verifyCopy(Response response) throws IOException { if(response.connection.getResponseCode() < 400) { byte[] body=GetResponse.slurpInputStream(response.connection.getInputStream()); String message=new String(body); if(message.contains("<Error")) { throw new IOException(message.substring(message.indexOf("<Error"))); } else if(message.contains("</CopyObjectResult>")) { // It worked! } else { throw new IOException("Unexpected response: " + message); } } return response; } /** * Reads an object from S3. * @param bucket The name of the bucket where the object lives. * @param key The name of the key to use. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public GetResponse get(String bucket, String key, Map headers) throws IOException { return new GetResponse(makeRequest("GET", bucket, Utils.urlencode(key), null, headers)); } /** * Deletes an object from S3. * @param bucket The name of the bucket where the object lives. * @param key The name of the key to use. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public Response delete(String bucket, String key, Map headers) throws IOException { return new Response(makeRequest("DELETE", bucket, Utils.urlencode(key), null, headers)); } /** * Get the requestPayment xml document for a given bucket * @param bucket The name of the bucket * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public GetResponse getBucketRequestPayment(String bucket, Map headers) throws IOException { Map pathArgs=new HashMap(); pathArgs.put("requestPayment", null); return new GetResponse(makeRequest("GET", bucket, "", pathArgs, headers)); } /** * Write a new requestPayment xml document for a given bucket * @param bucket The name of the bucket * @param requestPaymentXMLDoc * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public Response putBucketRequestPayment(String bucket, String requestPaymentXMLDoc, Map headers) throws IOException { Map pathArgs=new HashMap(); pathArgs.put("requestPayment", null); S3Object object=new S3Object(requestPaymentXMLDoc.getBytes(), null); HttpURLConnection request=makeRequest("PUT", bucket, "", pathArgs, headers, object); request.setDoOutput(true); request.getOutputStream().write(object.data == null? new byte[]{} : object.data); return new Response(request); } /** * Get the logging xml document for a given bucket * @param bucket The name of the bucket * @param headers A Map of String to List of Strings representing the http headers to pass (can be null). */ public GetResponse getBucketLogging(String bucket, Map headers) throws IOException { Map pathArgs=new HashMap(); pathArgs.put("logging", null); return new GetResponse(makeRequest("GET", bucket, "", pathArgs, headers)); } /** * Write a new logging xml document for a given bucket * @param loggingXMLDoc The xml representation of the logging configuration as a String * @param bucket The name of the bucket * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public Response putBucketLogging(String bucket, String loggingXMLDoc, Map headers) throws IOException { Map pathArgs=new HashMap(); pathArgs.put("logging", null); S3Object object=new S3Object(loggingXMLDoc.getBytes(), null); HttpURLConnection request=makeRequest("PUT", bucket, "", pathArgs, headers, object); request.setDoOutput(true); request.getOutputStream().write(object.data == null? new byte[]{} : object.data); return new Response(request); } /** * Get the ACL for a given bucket * @param bucket The name of the bucket where the object lives. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public GetResponse getBucketACL(String bucket, Map headers) throws IOException { return getACL(bucket, "", headers); } /** * Get the ACL for a given object (or bucket, if key is null). * @param bucket The name of the bucket where the object lives. * @param key The name of the key to use. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public GetResponse getACL(String bucket, String key, Map headers) throws IOException { if(key == null) key=""; Map pathArgs=new HashMap(); pathArgs.put("acl", null); return new GetResponse( makeRequest("GET", bucket, Utils.urlencode(key), pathArgs, headers) ); } /** * Write a new ACL for a given bucket * @param aclXMLDoc The xml representation of the ACL as a String * @param bucket The name of the bucket where the object lives. * @param headers A Map of String to List of Strings representing the http headers to pass (can be null). */ public Response putBucketACL(String bucket, String aclXMLDoc, Map headers) throws IOException { return putACL(bucket, "", aclXMLDoc, headers); } /** * Write a new ACL for a given object * @param aclXMLDoc The xml representation of the ACL as a String * @param bucket The name of the bucket where the object lives. * @param key The name of the key to use. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public Response putACL(String bucket, String key, String aclXMLDoc, Map headers) throws IOException { S3Object object=new S3Object(aclXMLDoc.getBytes(), null); Map pathArgs=new HashMap(); pathArgs.put("acl", null); HttpURLConnection request= makeRequest("PUT", bucket, Utils.urlencode(key), pathArgs, headers, object); request.setDoOutput(true); request.getOutputStream().write(object.data == null? new byte[]{} : object.data); return new Response(request); } public LocationResponse getBucketLocation(String bucket) throws IOException { Map pathArgs=new HashMap(); pathArgs.put("location", null); return new LocationResponse(makeRequest("GET", bucket, "", pathArgs, null)); } public ListAllMyBucketsResponse listAllMyBuckets(Map headers) throws IOException { return new ListAllMyBucketsResponse(makeRequest("GET", "", "", null, headers)); } /** * Make a new HttpURLConnection without passing an S3Object parameter. * Use this method for key operations that do require arguments * @param method The method to invoke * @param bucketName the bucket this request is for * @param key the key this request is for * @param pathArgs the * @param headers * @return * @throws MalformedURLException * @throws IOException */ private HttpURLConnection makeRequest(String method, String bucketName, String key, Map pathArgs, Map headers) throws IOException { return makeRequest(method, bucketName, key, pathArgs, headers, null); } /** * Make a new HttpURLConnection. * @param method The HTTP method to use (GET, PUT, DELETE) * @param bucket The bucket name this request affects * @param key The key this request is for * @param pathArgs parameters if any to be sent along this request * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). * @param object The S3Object that is to be written (can be null). */ private HttpURLConnection makeRequest(String method, String bucket, String key, Map pathArgs, Map headers, S3Object object) throws IOException { CallingFormat format=Utils.getCallingFormatForBucket(this.callingFormat, bucket); if(isSecure && format != CallingFormat.getPathCallingFormat() && bucket.contains(".")) { System.err.println("You are making an SSL connection, however, the bucket contains periods and the wildcard certificate will not match by default. Please consider using HTTP."); } // build the domain based on the calling format URL url=format.getURL(isSecure, server, this.port, bucket, key, pathArgs); HttpURLConnection connection=(HttpURLConnection)url.openConnection(); connection.setRequestMethod(method); // subdomain-style urls may encounter http redirects. // Ensure that redirects are supported. if(!connection.getInstanceFollowRedirects() && format.supportsLocatedBuckets()) throw new RuntimeException("HTTP redirect support required."); addHeaders(connection, headers); if(object != null) addMetadataHeaders(connection, object.metadata); addAuthHeader(connection, method, bucket, key, pathArgs); return connection; } /** * Add the given headers to the HttpURLConnection. * @param connection The HttpURLConnection to which the headers will be added. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ private static void addHeaders(HttpURLConnection connection, Map headers) { addHeaders(connection, headers, ""); } /** * Add the given metadata fields to the HttpURLConnection. * @param connection The HttpURLConnection to which the headers will be added. * @param metadata A Map of String to List of Strings representing the s3 * metadata for this resource. */ private static void addMetadataHeaders(HttpURLConnection connection, Map metadata) { addHeaders(connection, metadata, Utils.METADATA_PREFIX); } /** * Add the given headers to the HttpURLConnection with a prefix before the keys. * @param connection The HttpURLConnection to which the headers will be added. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). * @param prefix The string to prepend to each key before adding it to the connection. */ private static void addHeaders(HttpURLConnection connection, Map headers, String prefix) { if(headers != null) { for(Iterator i=headers.keySet().iterator(); i.hasNext();) { String key=(String)i.next(); for(Iterator j=((List)headers.get(key)).iterator(); j.hasNext();) { String value=(String)j.next(); connection.addRequestProperty(prefix + key, value); } } } } /** * Add the appropriate Authorization header to the HttpURLConnection. * @param connection The HttpURLConnection to which the header will be added. * @param method The HTTP method to use (GET, PUT, DELETE) * @param bucket the bucket name this request is for * @param key the key this request is for * @param pathArgs path arguments which are part of this request */ private void addAuthHeader(HttpURLConnection connection, String method, String bucket, String key, Map pathArgs) { if(connection.getRequestProperty("Date") == null) { connection.setRequestProperty("Date", httpDate()); } if(connection.getRequestProperty("Content-Type") == null) { connection.setRequestProperty("Content-Type", ""); } String canonicalString= Utils.makeCanonicalString(method, bucket, key, pathArgs, connection.getRequestProperties()); String encodedCanonical=Utils.encode(this.awsSecretAccessKey, canonicalString, false); connection.setRequestProperty("Authorization", "AWS " + this.awsAccessKeyId + ":" + encodedCanonical); } /** * Generate an rfc822 date for use in the Date HTTP header. */ public static String httpDate() { final String DateFormat="EEE, dd MMM yyyy HH:mm:ss "; SimpleDateFormat format=new SimpleDateFormat(DateFormat, Locale.US); format.setTimeZone(TimeZone.getTimeZone("GMT")); return format.format(new Date()) + "GMT"; } } static class ListEntry { /** * The name of the object */ public String key; /** * The date at which the object was last modified. */ public Date lastModified; /** * The object's ETag, which can be used for conditional GETs. */ public String eTag; /** * The size of the object in bytes. */ public long size; /** * The object's storage class */ public String storageClass; /** * The object's owner */ public Owner owner; public String toString() { return key; } } static class Owner { public String id; public String displayName; } static class Response { public HttpURLConnection connection; public Response(HttpURLConnection connection) throws IOException { this.connection=connection; } } static class GetResponse extends Response { public S3Object object; /** * Pulls a representation of an S3Object out of the HttpURLConnection response. */ public GetResponse(HttpURLConnection connection) throws IOException { super(connection); if(connection.getResponseCode() < 400) { Map metadata=extractMetadata(connection); byte[] body=slurpInputStream(connection.getInputStream()); this.object=new S3Object(body, metadata); } } /** * Examines the response's header fields and returns a Map from String to List of Strings * representing the object's metadata. */ private static Map extractMetadata(HttpURLConnection connection) { TreeMap metadata=new TreeMap(); Map headers=connection.getHeaderFields(); for(Iterator i=headers.keySet().iterator(); i.hasNext();) { String key=(String)i.next(); if(key == null) continue; if(key.startsWith(Utils.METADATA_PREFIX)) { metadata.put(key.substring(Utils.METADATA_PREFIX.length()), headers.get(key)); } } return metadata; } /** * Read the input stream and dump it all into a big byte array */ static byte[] slurpInputStream(InputStream stream) throws IOException { final int chunkSize=2048; byte[] buf=new byte[chunkSize]; ByteArrayOutputStream byteStream=new ByteArrayOutputStream(chunkSize); int count; while((count=stream.read(buf)) != -1) byteStream.write(buf, 0, count); return byteStream.toByteArray(); } } static class LocationResponse extends Response { String location; /** * Parse the response to a ?location query. */ public LocationResponse(HttpURLConnection connection) throws IOException { super(connection); if(connection.getResponseCode() < 400) { try { XMLReader xr=Utils.createXMLReader(); ; LocationResponseHandler handler=new LocationResponseHandler(); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(connection.getInputStream())); this.location=handler.loc; } catch(SAXException e) { throw new RuntimeException("Unexpected error parsing ListAllMyBuckets xml", e); } } else { this.location="<error>"; } } /** * Report the location-constraint for a bucket. * A value of null indicates an error; * the empty string indicates no constraint; * and any other value is an actual location constraint value. */ public String getLocation() { return location; } /** * Helper class to parse LocationConstraint response XML */ static class LocationResponseHandler extends DefaultHandler { String loc=null; private StringBuffer currText=null; public void startDocument() { } public void startElement(String uri, String name, String qName, Attributes attrs) { if(name.equals("LocationConstraint")) { this.currText=new StringBuffer(); } } public void endElement(String uri, String name, String qName) { if(name.equals("LocationConstraint")) { loc=this.currText.toString(); this.currText=null; } } public void characters(char ch[], int start, int length) { if(currText != null) this.currText.append(ch, start, length); } } } static class Bucket { /** * The name of the bucket. */ public String name; /** * The bucket's creation date. */ public Date creationDate; public Bucket() { this.name=null; this.creationDate=null; } public Bucket(String name, Date creationDate) { this.name=name; this.creationDate=creationDate; } public String toString() { return this.name; } } static class ListBucketResponse extends Response { /** * The name of the bucket being listed. Null if request fails. */ public String name=null; /** * The prefix echoed back from the request. Null if request fails. */ public String prefix=null; /** * The marker echoed back from the request. Null if request fails. */ public String marker=null; /** * The delimiter echoed back from the request. Null if not specified in * the request, or if it fails. */ public String delimiter=null; /** * The maxKeys echoed back from the request if specified. 0 if request fails. */ public int maxKeys=0; /** * Indicates if there are more results to the list. True if the current * list results have been truncated. false if request fails. */ public boolean isTruncated=false; /** * Indicates what to use as a marker for subsequent list requests in the event * that the results are truncated. Present only when a delimiter is specified. * Null if request fails. */ public String nextMarker=null; /** * A List of ListEntry objects representing the objects in the given bucket. * Null if the request fails. */ public List entries=null; /** * A List of CommonPrefixEntry objects representing the common prefixes of the * keys that matched up to the delimiter. Null if the request fails. */ public List commonPrefixEntries=null; public ListBucketResponse(HttpURLConnection connection) throws IOException { super(connection); if(connection.getResponseCode() < 400) { try { XMLReader xr=Utils.createXMLReader(); ListBucketHandler handler=new ListBucketHandler(); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(connection.getInputStream())); this.name=handler.getName(); this.prefix=handler.getPrefix(); this.marker=handler.getMarker(); this.delimiter=handler.getDelimiter(); this.maxKeys=handler.getMaxKeys(); this.isTruncated=handler.getIsTruncated(); this.nextMarker=handler.getNextMarker(); this.entries=handler.getKeyEntries(); this.commonPrefixEntries=handler.getCommonPrefixEntries(); } catch(SAXException e) { throw new RuntimeException("Unexpected error parsing ListBucket xml", e); } } } static class ListBucketHandler extends DefaultHandler { private String name=null; private String prefix=null; private String marker=null; private String delimiter=null; private int maxKeys=0; private boolean isTruncated=false; private String nextMarker=null; private boolean isEchoedPrefix=false; private List keyEntries=null; private ListEntry keyEntry=null; private List commonPrefixEntries=null; private CommonPrefixEntry commonPrefixEntry=null; private StringBuffer currText=null; private SimpleDateFormat iso8601Parser=null; public ListBucketHandler() { super(); keyEntries=new ArrayList(); commonPrefixEntries=new ArrayList(); this.iso8601Parser=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); this.iso8601Parser.setTimeZone(new SimpleTimeZone(0, "GMT")); this.currText=new StringBuffer(); } public void startDocument() { this.isEchoedPrefix=true; } public void endDocument() { // ignore } public void startElement(String uri, String name, String qName, Attributes attrs) { if(name.equals("Contents")) { this.keyEntry=new ListEntry(); } else if(name.equals("Owner")) { this.keyEntry.owner=new Owner(); } else if(name.equals("CommonPrefixes")) { this.commonPrefixEntry=new CommonPrefixEntry(); } } public void endElement(String uri, String name, String qName) { if(name.equals("Name")) { this.name=this.currText.toString(); } // this prefix is the one we echo back from the request else if(name.equals("Prefix") && this.isEchoedPrefix) { this.prefix=this.currText.toString(); this.isEchoedPrefix=false; } else if(name.equals("Marker")) { this.marker=this.currText.toString(); } else if(name.equals("MaxKeys")) { this.maxKeys=Integer.parseInt(this.currText.toString()); } else if(name.equals("Delimiter")) { this.delimiter=this.currText.toString(); } else if(name.equals("IsTruncated")) { this.isTruncated=Boolean.valueOf(this.currText.toString()); } else if(name.equals("NextMarker")) { this.nextMarker=this.currText.toString(); } else if(name.equals("Contents")) { this.keyEntries.add(this.keyEntry); } else if(name.equals("Key")) { this.keyEntry.key=this.currText.toString(); } else if(name.equals("LastModified")) { try { this.keyEntry.lastModified=this.iso8601Parser.parse(this.currText.toString()); } catch(ParseException e) { throw new RuntimeException("Unexpected date format in list bucket output", e); } } else if(name.equals("ETag")) { this.keyEntry.eTag=this.currText.toString(); } else if(name.equals("Size")) { this.keyEntry.size=Long.parseLong(this.currText.toString()); } else if(name.equals("StorageClass")) { this.keyEntry.storageClass=this.currText.toString(); } else if(name.equals("ID")) { this.keyEntry.owner.id=this.currText.toString(); } else if(name.equals("DisplayName")) { this.keyEntry.owner.displayName=this.currText.toString(); } else if(name.equals("CommonPrefixes")) { this.commonPrefixEntries.add(this.commonPrefixEntry); } // this is the common prefix for keys that match up to the delimiter else if(name.equals("Prefix")) { this.commonPrefixEntry.prefix=this.currText.toString(); } if(this.currText.length() != 0) this.currText=new StringBuffer(); } public void characters(char ch[], int start, int length) { this.currText.append(ch, start, length); } public String getName() { return this.name; } public String getPrefix() { return this.prefix; } public String getMarker() { return this.marker; } public String getDelimiter() { return this.delimiter; } public int getMaxKeys() { return this.maxKeys; } public boolean getIsTruncated() { return this.isTruncated; } public String getNextMarker() { return this.nextMarker; } public List getKeyEntries() { return this.keyEntries; } public List getCommonPrefixEntries() { return this.commonPrefixEntries; } } } static class CommonPrefixEntry { /** * The prefix common to the delimited keys it represents */ public String prefix; } static class ListAllMyBucketsResponse extends Response { /** * A list of Bucket objects, one for each of this account's buckets. Will be null if * the request fails. */ public List entries; public ListAllMyBucketsResponse(HttpURLConnection connection) throws IOException { super(connection); if(connection.getResponseCode() < 400) { try { XMLReader xr=Utils.createXMLReader(); ; ListAllMyBucketsHandler handler=new ListAllMyBucketsHandler(); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(connection.getInputStream())); this.entries=handler.getEntries(); } catch(SAXException e) { throw new RuntimeException("Unexpected error parsing ListAllMyBuckets xml", e); } } } static class ListAllMyBucketsHandler extends DefaultHandler { private List entries=null; private Bucket currBucket=null; private StringBuffer currText=null; private SimpleDateFormat iso8601Parser=null; public ListAllMyBucketsHandler() { super(); entries=new ArrayList(); this.iso8601Parser=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); this.iso8601Parser.setTimeZone(new SimpleTimeZone(0, "GMT")); this.currText=new StringBuffer(); } public void startDocument() { // ignore } public void endDocument() { // ignore } public void startElement(String uri, String name, String qName, Attributes attrs) { if(name.equals("Bucket")) { this.currBucket=new Bucket(); } } public void endElement(String uri, String name, String qName) { if(name.equals("Bucket")) { this.entries.add(this.currBucket); } else if(name.equals("Name")) { this.currBucket.name=this.currText.toString(); } else if(name.equals("CreationDate")) { try { this.currBucket.creationDate=this.iso8601Parser.parse(this.currText.toString()); } catch(ParseException e) { throw new RuntimeException("Unexpected date format in list bucket output", e); } } this.currText=new StringBuffer(); } public void characters(char ch[], int start, int length) { this.currText.append(ch, start, length); } public List getEntries() { return this.entries; } } } static class S3Object { public byte[] data; /** * A Map from String to List of Strings representing the object's metadata */ public Map metadata; public S3Object(byte[] data, Map metadata) { this.data=data; this.metadata=metadata; } } abstract static class CallingFormat { protected static CallingFormat pathCallingFormat=new PathCallingFormat(); protected static CallingFormat subdomainCallingFormat=new SubdomainCallingFormat(); protected static CallingFormat vanityCallingFormat=new VanityCallingFormat(); public abstract boolean supportsLocatedBuckets(); public abstract String getEndpoint(String server, int port, String bucket); public abstract String getPathBase(String bucket, String key); public abstract URL getURL(boolean isSecure, String server, int port, String bucket, String key, Map pathArgs) throws MalformedURLException; public static CallingFormat getPathCallingFormat() { return pathCallingFormat; } public static CallingFormat getSubdomainCallingFormat() { return subdomainCallingFormat; } public static CallingFormat getVanityCallingFormat() { return vanityCallingFormat; } private static class PathCallingFormat extends CallingFormat { public boolean supportsLocatedBuckets() { return false; } public String getPathBase(String bucket, String key) { return isBucketSpecified(bucket)? "/" + bucket + "/" + key : "/"; } public String getEndpoint(String server, int port, String bucket) { return server + ":" + port; } public URL getURL(boolean isSecure, String server, int port, String bucket, String key, Map pathArgs) throws MalformedURLException { String pathBase=isBucketSpecified(bucket)? "/" + bucket + "/" + key : "/"; String pathArguments=Utils.convertPathArgsHashToString(pathArgs); return new URL(isSecure? "https" : "http", server, port, pathBase + pathArguments); } private static boolean isBucketSpecified(String bucket) { return bucket != null && bucket.length() != 0; } } private static class SubdomainCallingFormat extends CallingFormat { public boolean supportsLocatedBuckets() { return true; } public String getServer(String server, String bucket) { return bucket + "." + server; } public String getEndpoint(String server, int port, String bucket) { return getServer(server, bucket) + ":" + port; } public String getPathBase(String bucket, String key) { return "/" + key; } public URL getURL(boolean isSecure, String server, int port, String bucket, String key, Map pathArgs) throws MalformedURLException { if(bucket == null || bucket.length() == 0) { //The bucket is null, this is listAllBuckets request String pathArguments=Utils.convertPathArgsHashToString(pathArgs); return new URL(isSecure? "https" : "http", server, port, "/" + pathArguments); } else { String serverToUse=getServer(server, bucket); String pathBase=getPathBase(bucket, key); String pathArguments=Utils.convertPathArgsHashToString(pathArgs); return new URL(isSecure? "https" : "http", serverToUse, port, pathBase + pathArguments); } } } private static class VanityCallingFormat extends SubdomainCallingFormat { public String getServer(String server, String bucket) { return bucket; } } } static class Utils { static final String METADATA_PREFIX="x-amz-meta-"; static final String AMAZON_HEADER_PREFIX="x-amz-"; static final String ALTERNATIVE_DATE_HEADER="x-amz-date"; public static final String DEFAULT_HOST="s3.amazonaws.com"; public static final int SECURE_PORT=443; public static final int INSECURE_PORT=80; /** * HMAC/SHA1 Algorithm per RFC 2104. */ private static final String HMAC_SHA1_ALGORITHM="HmacSHA1"; static String makeCanonicalString(String method, String bucket, String key, Map pathArgs, Map headers) { return makeCanonicalString(method, bucket, key, pathArgs, headers, null); } /** * Calculate the canonical string. When expires is non-null, it will be * used instead of the Date header. */ static String makeCanonicalString(String method, String bucketName, String key, Map pathArgs, Map headers, String expires) { StringBuilder buf=new StringBuilder(); buf.append(method + "\n"); // Add all interesting headers to a list, then sort them. "Interesting" // is defined as Content-MD5, Content-Type, Date, and x-amz- SortedMap interestingHeaders=new TreeMap(); if(headers != null) { for(Iterator i=headers.keySet().iterator(); i.hasNext();) { String hashKey=(String)i.next(); if(hashKey == null) continue; String lk=hashKey.toLowerCase(); // Ignore any headers that are not particularly interesting. if(lk.equals("content-type") || lk.equals("content-md5") || lk.equals("date") || lk.startsWith(AMAZON_HEADER_PREFIX)) { List s=(List)headers.get(hashKey); interestingHeaders.put(lk, concatenateList(s)); } } } if(interestingHeaders.containsKey(ALTERNATIVE_DATE_HEADER)) { interestingHeaders.put("date", ""); } // if the expires is non-null, use that for the date field. this // trumps the x-amz-date behavior. if(expires != null) { interestingHeaders.put("date", expires); } // these headers require that we still put a new line in after them, // even if they don't exist. if(!interestingHeaders.containsKey("content-type")) { interestingHeaders.put("content-type", ""); } if(!interestingHeaders.containsKey("content-md5")) { interestingHeaders.put("content-md5", ""); } // Finally, add all the interesting headers (i.e.: all that startwith x-amz- ;-)) for(Iterator i=interestingHeaders.keySet().iterator(); i.hasNext();) { String headerKey=(String)i.next(); if(headerKey.startsWith(AMAZON_HEADER_PREFIX)) { buf.append(headerKey).append(':').append(interestingHeaders.get(headerKey)); } else { buf.append(interestingHeaders.get(headerKey)); } buf.append("\n"); } // build the path using the bucket and key if(bucketName != null && bucketName.length() != 0) { buf.append("/" + bucketName); } // append the key (it might be an empty string) // append a slash regardless buf.append("/"); if(key != null) { buf.append(key); } // if there is an acl, logging or torrent parameter // add them to the string if(pathArgs != null) { if(pathArgs.containsKey("acl")) { buf.append("?acl"); } else if(pathArgs.containsKey("torrent")) { buf.append("?torrent"); } else if(pathArgs.containsKey("logging")) { buf.append("?logging"); } else if(pathArgs.containsKey("location")) { buf.append("?location"); } } return buf.toString(); } /** * Calculate the HMAC/SHA1 on a string. * @return Signature * @throws java.security.NoSuchAlgorithmException * If the algorithm does not exist. Unlikely * @throws java.security.InvalidKeyException * If the key is invalid. */ static String encode(String awsSecretAccessKey, String canonicalString, boolean urlencode) { // The following HMAC/SHA1 code for the signature is taken from the // AWS Platform's implementation of RFC2104 (amazon.webservices.common.Signature) // Acquire an HMAC/SHA1 from the raw key bytes. SecretKeySpec signingKey= new SecretKeySpec(awsSecretAccessKey.getBytes(), HMAC_SHA1_ALGORITHM); // Acquire the MAC instance and initialize with the signing key. Mac mac=null; try { mac=Mac.getInstance(HMAC_SHA1_ALGORITHM); } catch(NoSuchAlgorithmException e) { // should not happen throw new RuntimeException("Could not find sha1 algorithm", e); } try { mac.init(signingKey); } catch(InvalidKeyException e) { // also should not happen throw new RuntimeException("Could not initialize the MAC algorithm", e); } // Compute the HMAC on the digest, and set it. String b64=Base64.encodeBytes(mac.doFinal(canonicalString.getBytes())); if(urlencode) { return urlencode(b64); } else { return b64; } } static Map paramsForListOptions(String prefix, String marker, Integer maxKeys) { return paramsForListOptions(prefix, marker, maxKeys, null); } static Map paramsForListOptions(String prefix, String marker, Integer maxKeys, String delimiter) { Map argParams=new HashMap(); // these three params must be url encoded if(prefix != null) argParams.put("prefix", urlencode(prefix)); if(marker != null) argParams.put("marker", urlencode(marker)); if(delimiter != null) argParams.put("delimiter", urlencode(delimiter)); if(maxKeys != null) argParams.put("max-keys", Integer.toString(maxKeys.intValue())); return argParams; } /** * Converts the Path Arguments from a map to String which can be used in url construction * @param pathArgs a map of arguments * @return a string representation of pathArgs */ public static String convertPathArgsHashToString(Map pathArgs) { StringBuilder pathArgsString=new StringBuilder(); String argumentValue; boolean firstRun=true; if(pathArgs != null) { for(Iterator argumentIterator=pathArgs.keySet().iterator(); argumentIterator.hasNext();) { String argument=(String)argumentIterator.next(); if(firstRun) { firstRun=false; pathArgsString.append("?"); } else { pathArgsString.append("&"); } argumentValue=(String)pathArgs.get(argument); pathArgsString.append(argument); if(argumentValue != null) { pathArgsString.append("="); pathArgsString.append(argumentValue); } } } return pathArgsString.toString(); } static String urlencode(String unencoded) { try { return URLEncoder.encode(unencoded, "UTF-8"); } catch(UnsupportedEncodingException e) { // should never happen throw new RuntimeException("Could not url encode to UTF-8", e); } } static XMLReader createXMLReader() { try { return XMLReaderFactory.createXMLReader(); } catch(SAXException e) { // oops, lets try doing this (needed in 1.4) System.setProperty("org.xml.sax.driver", "org.apache.crimson.parser.XMLReaderImpl"); } try { // try once more return XMLReaderFactory.createXMLReader(); } catch(SAXException e) { throw new RuntimeException("Couldn't initialize a sax driver for the XMLReader"); } } /** * Concatenates a bunch of header values, seperating them with a comma. * @param values List of header values. * @return String of all headers, with commas. */ private static String concatenateList(List values) { StringBuilder buf=new StringBuilder(); for(int i=0, size=values.size(); i < size; ++i) { buf.append(((String)values.get(i)).replaceAll("\n", "").trim()); if(i != (size - 1)) { buf.append(","); } } return buf.toString(); } /** * Validate bucket-name */ static boolean validateBucketName(String bucketName, CallingFormat callingFormat) { if(callingFormat == CallingFormat.getPathCallingFormat()) { final int MIN_BUCKET_LENGTH=3; final int MAX_BUCKET_LENGTH=255; final String BUCKET_NAME_REGEX="^[0-9A-Za-z\\.\\-_]*$"; return null != bucketName && bucketName.length() >= MIN_BUCKET_LENGTH && bucketName.length() <= MAX_BUCKET_LENGTH && bucketName.matches(BUCKET_NAME_REGEX); } else { return isValidSubdomainBucketName(bucketName); } } static boolean isValidSubdomainBucketName(String bucketName) { final int MIN_BUCKET_LENGTH=3; final int MAX_BUCKET_LENGTH=63; // don't allow names that look like 127.0.0.1 final String IPv4_REGEX="^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$"; // dns sub-name restrictions final String BUCKET_NAME_REGEX="^[a-z0-9]([a-z0-9\\-\\_]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9\\-\\_]*[a-z0-9])?)*$"; // If there wasn't a location-constraint, then the current actual // restriction is just that no 'part' of the name (i.e. sequence // of characters between any 2 '.'s has to be 63) but the recommendation // is to keep the entire bucket name under 63. return null != bucketName && bucketName.length() >= MIN_BUCKET_LENGTH && bucketName.length() <= MAX_BUCKET_LENGTH && !bucketName.matches(IPv4_REGEX) && bucketName.matches(BUCKET_NAME_REGEX); } static CallingFormat getCallingFormatForBucket(CallingFormat desiredFormat, String bucketName) { CallingFormat callingFormat=desiredFormat; if(callingFormat == CallingFormat.getSubdomainCallingFormat() && !Utils.isValidSubdomainBucketName(bucketName)) { callingFormat=CallingFormat.getPathCallingFormat(); } return callingFormat; } } // NOTE: The following source code is the iHarder.net public domain // Base64 library and is provided here as a convenience. For updates, // problems, questions, etc. regarding this code, please visit: static class Base64 { /** * No options specified. Value is zero. */ public final static int NO_OPTIONS=0; /** * Specify encoding. */ public final static int ENCODE=1; /** * Specify decoding. */ public final static int DECODE=0; /** * Specify that data should be gzip-compressed. */ public final static int GZIP=2; /** * Don't break lines when encoding (violates strict Base64 specification) */ public final static int DONT_BREAK_LINES=8; /** * Maximum line length (76) of Base64 output. */ private final static int MAX_LINE_LENGTH=76; /** * The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN=(byte)'='; /** * The new line character (\n) as a byte. */ private final static byte NEW_LINE=(byte)'\n'; /** * Preferred encoding. */ private final static String PREFERRED_ENCODING="UTF-8"; /** * The 64 valid Base64 values. */ private static final byte[] ALPHABET; private static final byte[] _NATIVE_ALPHABET= /* May be something funny like EBCDIC */ { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** Determine which ALPHABET to use. */ static { byte[] __bytes; try { __bytes="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes(PREFERRED_ENCODING); } // end try catch(java.io.UnsupportedEncodingException use) { __bytes=_NATIVE_ALPHABET; // Fall back to native encoding } // end catch ALPHABET=__bytes; } // end static /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. */ private final static byte[] DECODABET= { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9 // Decimal 123 - 126 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; // I think I end up not using the BAD_ENCODING indicator. //private final static byte BAD_ENCODING = -9; // Indicates error in encoding private final static byte WHITE_SPACE_ENC=-5; // Indicates white space in encoding private final static byte EQUALS_SIGN_ENC=-1; // Indicates equals sign in encoding /** * Defeats instantiation. */ private Base64() { } /** * Encodes up to the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * The array <var>threeBytes</var> needs only be as big as * <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes) { encode3to4(threeBytes, 0, numSigBytes, b4, 0); return b4; } // end encode3to4 /** * Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset) { // 1 2 3 // 01234567890123456789012345678901 Bit position // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff=(numSigBytes > 0? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch(numSigBytes) { case 3: destination[destOffset]=ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1]=ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2]=ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3]=ALPHABET[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset]=ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1]=ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2]=ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3]=EQUALS_SIGN; return destination; case 1: destination[destOffset]=ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1]=ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2]=EQUALS_SIGN; destination[destOffset + 3]=EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return <tt>null</tt>. * The object is not GZip-compressed before being encoded. * @param serializableObject The object to encode * @return The Base64-encoded object * @since 1.4 */ public static String encodeObject(java.io.Serializable serializableObject) { return encodeObject(serializableObject, NO_OPTIONS); } // end encodeObject /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return <tt>null</tt>. * <p/> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p/> * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or * <p/> * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeObject(java.io.Serializable serializableObject, int options) { // Streams java.io.ByteArrayOutputStream baos=null; java.io.OutputStream b64os=null; java.io.ObjectOutputStream oos=null; java.util.zip.GZIPOutputStream gzos=null; // Isolate options int gzip=(options & GZIP); int dontBreakLines=(options & DONT_BREAK_LINES); try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); b64os=new Base64.OutputStream(baos, ENCODE | dontBreakLines); // GZip? if(gzip == GZIP) { gzos=new java.util.zip.GZIPOutputStream(b64os); oos=new java.io.ObjectOutputStream(gzos); } // end if: gzip else oos=new java.io.ObjectOutputStream(b64os); oos.writeObject(serializableObject); } // end try catch(java.io.IOException e) { e.printStackTrace(); return null; } // end catch finally { try { oos.close(); } catch(Exception e) { } try { gzos.close(); } catch(Exception e) { } try { b64os.close(); } catch(Exception e) { } try { baos.close(); } catch(Exception e) { } } // end finally // Return value according to relevant encoding. try { return new String(baos.toByteArray(), PREFERRED_ENCODING); } // end try catch(java.io.UnsupportedEncodingException uue) { return new String(baos.toByteArray()); } // end catch } // end encode /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * @param source The data to convert * @since 1.4 */ public static String encodeBytes(byte[] source) { return encodeBytes(source, 0, source.length, NO_OPTIONS); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p/> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p/> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p/> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * @param source The data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes(byte[] source, int options) { return encodeBytes(source, 0, source.length, options); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @since 1.4 */ public static String encodeBytes(byte[] source, int off, int len) { return encodeBytes(source, off, len, NO_OPTIONS); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p/> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p/> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p/> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes(byte[] source, int off, int len, int options) { // Isolate options int dontBreakLines=(options & DONT_BREAK_LINES); int gzip=(options & GZIP); // Compress? if(gzip == GZIP) { java.io.ByteArrayOutputStream baos=null; java.util.zip.GZIPOutputStream gzos=null; Base64.OutputStream b64os=null; try { // GZip -> Base64 -> ByteArray baos=new java.io.ByteArrayOutputStream(); b64os=new Base64.OutputStream(baos, ENCODE | dontBreakLines); gzos=new java.util.zip.GZIPOutputStream(b64os); gzos.write(source, off, len); gzos.close(); } // end try catch(java.io.IOException e) { e.printStackTrace(); return null; } // end catch finally { try { gzos.close(); } catch(Exception e) { } try { b64os.close(); } catch(Exception e) { } try { baos.close(); } catch(Exception e) { } } // end finally // Return value according to relevant encoding. try { return new String(baos.toByteArray(), PREFERRED_ENCODING); } // end try catch(java.io.UnsupportedEncodingException uue) { return new String(baos.toByteArray()); } // end catch } // end if: compress // Else, don't compress. Better not to use streams at all then. else { // Convert option to boolean in way that code likes it. boolean breakLines=dontBreakLines == 0; int len43=len * 4 / 3; byte[] outBuff=new byte[(len43) // Main 4:3 + ((len % 3) > 0? 4 : 0) // Account for padding + (breakLines? (len43 / MAX_LINE_LENGTH) : 0)]; // New lines int d=0; int e=0; int len2=len - 2; int lineLength=0; for(; d < len2; d+=3, e+=4) { encode3to4(source, d + off, 3, outBuff, e); lineLength+=4; if(breakLines && lineLength == MAX_LINE_LENGTH) { outBuff[e + 4]=NEW_LINE; e++; lineLength=0; } // end if: end of line } // en dfor: each piece of array if(d < len) { encode3to4(source, d + off, len - d, outBuff, e); e+=4; } // end if: some padding needed // Return value according to relevant encoding. try { return new String(outBuff, 0, e, PREFERRED_ENCODING); } // end try catch(java.io.UnsupportedEncodingException uue) { return new String(outBuff, 0, e); } // end catch } // end else: don't compress } // end encodeBytes /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset) { // Example: Dk== if(source[srcOffset + 2] == EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff=((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12); destination[destOffset]=(byte)(outBuff >>> 16); return 1; } // Example: DkL= else if(source[srcOffset + 3] == EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff=((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6); destination[destOffset]=(byte)(outBuff >>> 16); destination[destOffset + 1]=(byte)(outBuff >>> 8); return 2; } // Example: DkLE else { try { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff=((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6) | ((DECODABET[source[srcOffset + 3]] & 0xFF)); destination[destOffset]=(byte)(outBuff >> 16); destination[destOffset + 1]=(byte)(outBuff >> 8); destination[destOffset + 2]=(byte)(outBuff); return 3; } catch(Exception e) { System.out.println(valueOf(source[srcOffset]) + ": " + (DECODABET[source[srcOffset]])); System.out.println(valueOf(source[srcOffset + 1]) + ": " + (DECODABET[source[srcOffset + 1]])); System.out.println(valueOf(source[srcOffset + 2]) + ": " + (DECODABET[source[srcOffset + 2]])); System.out.println(String.valueOf(source[srcOffset + 3]) + ": " + (DECODABET[source[srcOffset + 3]])); return -1; } //e nd catch } } // end decodeToBytes /** * Very low-level access to decoding ASCII characters in * the form of a byte array. Does not support automatically * gunzipping or any other "fancy" features. * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @return decoded data * @since 1.3 */ public static byte[] decode(byte[] source, int off, int len) { int len34=len * 3 / 4; byte[] outBuff=new byte[len34]; // Upper limit on size of output int outBuffPosn=0; byte[] b4=new byte[4]; int b4Posn=0; int i=0; byte sbiCrop=0; byte sbiDecode=0; for(i=off; i < off + len; i++) { sbiCrop=(byte)(source[i] & 0x7f); // Only the low seven bits sbiDecode=DECODABET[sbiCrop]; if(sbiDecode >= WHITE_SPACE_ENC) // White space, Equals sign or better { if(sbiDecode >= EQUALS_SIGN_ENC) { b4[b4Posn++]=sbiCrop; if(b4Posn > 3) { outBuffPosn+=decode4to3(b4, 0, outBuff, outBuffPosn); b4Posn=0; // If that was the equals sign, break out of 'for' loop if(sbiCrop == EQUALS_SIGN) break; } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { System.err.println("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)"); return null; } // end else: } // each input character byte[] out=new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } // end decode /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * @param s the string to decode * @return the decoded data * @since 1.4 */ public static byte[] decode(String s) { byte[] bytes; try { bytes=s.getBytes(PREFERRED_ENCODING); } // end try catch(java.io.UnsupportedEncodingException uee) { bytes=s.getBytes(); } // end catch //</change> // Decode bytes=decode(bytes, 0, bytes.length); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) if(bytes != null && bytes.length >= 4) { int head=((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if(java.util.zip.GZIPInputStream.GZIP_MAGIC == head) { java.io.ByteArrayInputStream bais=null; java.util.zip.GZIPInputStream gzis=null; java.io.ByteArrayOutputStream baos=null; byte[] buffer=new byte[2048]; int length=0; try { baos=new java.io.ByteArrayOutputStream(); bais=new java.io.ByteArrayInputStream(bytes); gzis=new java.util.zip.GZIPInputStream(bais); while((length=gzis.read(buffer)) >= 0) { baos.write(buffer, 0, length); } // end while: reading input // No error? Get new bytes. bytes=baos.toByteArray(); } // end try catch(java.io.IOException e) { // Just return originally-decoded bytes } // end catch finally { try { baos.close(); } catch(Exception e) { } try { gzis.close(); } catch(Exception e) { } try { bais.close(); } catch(Exception e) { } } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @since 1.5 */ public static Object decodeToObject(String encodedObject) { // Decode and gunzip if necessary byte[] objBytes=decode(encodedObject); java.io.ByteArrayInputStream bais=null; java.io.ObjectInputStream ois=null; Object obj=null; try { bais=new java.io.ByteArrayInputStream(objBytes); ois=new java.io.ObjectInputStream(bais); obj=ois.readObject(); } // end try catch(java.io.IOException e) { e.printStackTrace(); obj=null; } // end catch catch(java.lang.ClassNotFoundException e) { e.printStackTrace(); obj=null; } // end catch finally { try { if(bais != null) bais.close(); } catch(Exception e) { } try { if(ois != null) ois.close(); } catch(Exception e) { } } // end finally return obj; } // end decodeObject /** * Convenience method for encoding data to a file. * @param dataToEncode byte array of data to encode in base64 form * @param filename Filename for saving encoded data * @return <tt>true</tt> if successful, <tt>false</tt> otherwise * @since 2.1 */ public static boolean encodeToFile(byte[] dataToEncode, String filename) { boolean success=false; Base64.OutputStream bos=null; try { bos=new Base64.OutputStream( new java.io.FileOutputStream(filename), Base64.ENCODE); bos.write(dataToEncode); success=true; } // end try catch(java.io.IOException e) { success=false; } // end catch: IOException finally { try { if(bos != null) bos.close(); } catch(Exception e) { } } // end finally return success; } // end encodeToFile /** * Convenience method for decoding data to a file. * @param dataToDecode Base64-encoded data as a string * @param filename Filename for saving decoded data * @return <tt>true</tt> if successful, <tt>false</tt> otherwise * @since 2.1 */ public static boolean decodeToFile(String dataToDecode, String filename) { boolean success=false; Base64.OutputStream bos=null; try { bos=new Base64.OutputStream( new java.io.FileOutputStream(filename), Base64.DECODE); bos.write(dataToDecode.getBytes(PREFERRED_ENCODING)); success=true; } // end try catch(java.io.IOException e) { success=false; } // end catch: IOException finally { try { if(bos != null) bos.close(); } catch(Exception e) { } } // end finally return success; } // end decodeToFile /** * Convenience method for reading a base64-encoded * file and decoding it. * @param filename Filename for reading encoded data * @return decoded byte array or null if unsuccessful * @since 2.1 */ public static byte[] decodeFromFile(String filename) { byte[] decodedData=null; Base64.InputStream bis=null; try { // Set up some useful variables java.io.File file=new java.io.File(filename); byte[] buffer=null; int length=0; int numBytes=0; // Check for size of file if(file.length() > Integer.MAX_VALUE) { System.err.println("File is too big for this convenience method (" + file.length() + " bytes)."); return null; } // end if: file too big for int index buffer=new byte[(int)file.length()]; // Open a stream bis=new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream(file)), Base64.DECODE); // Read until done while((numBytes=bis.read(buffer, length, 4096)) >= 0) length+=numBytes; // Save in a variable to return decodedData=new byte[length]; System.arraycopy(buffer, 0, decodedData, 0, length); } // end try catch(java.io.IOException e) { System.err.println("Error decoding from file " + filename); } // end catch: IOException finally { try { if(bis != null) bis.close(); } catch(Exception e) { } } // end finally return decodedData; } // end decodeFromFile /** * Convenience method for reading a binary file * and base64-encoding it. * @param filename Filename for reading binary data * @return base64-encoded string or null if unsuccessful * @since 2.1 */ public static String encodeFromFile(String filename) { String encodedData=null; Base64.InputStream bis=null; try { // Set up some useful variables java.io.File file=new java.io.File(filename); byte[] buffer=new byte[(int)(file.length() * 1.4)]; int length=0; int numBytes=0; // Open a stream bis=new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream(file)), Base64.ENCODE); // Read until done while((numBytes=bis.read(buffer, length, 4096)) >= 0) length+=numBytes; // Save in a variable to return encodedData=new String(buffer, 0, length, Base64.PREFERRED_ENCODING); } // end try catch(java.io.IOException e) { System.err.println("Error encoding from file " + filename); } // end catch: IOException finally { try { if(bis != null) bis.close(); } catch(Exception e) { } } // end finally return encodedData; } // end encodeFromFile /** * A {@link Base64.InputStream} will read data from another * <tt>java.io.InputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * @see Base64 * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters /** * Constructs a {@link Base64.InputStream} in DECODE mode. * @param in the <tt>java.io.InputStream</tt> from which to read data. * @since 1.3 */ public InputStream(java.io.InputStream in) { this(in, DECODE); } // end constructor /** * Constructs a {@link Base64.InputStream} in * either ENCODE or DECODE mode. * <p/> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p/> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * @param in the <tt>java.io.InputStream</tt> from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public InputStream(java.io.InputStream in, int options) { super(in); this.breakLines=(options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode=(options & ENCODE) == ENCODE; this.bufferLength=encode? 4 : 3; this.buffer=new byte[bufferLength]; this.position=-1; this.lineLength=0; } // end constructor /** * Reads enough of the input stream to convert * to/from Base64 and returns the next byte. * @return next byte * @since 1.3 */ public int read() throws java.io.IOException { // Do we need to get data? if(position < 0) { if(encode) { byte[] b3=new byte[3]; int numBinaryBytes=0; for(int i=0; i < 3; i++) { try { int b=in.read(); // If end of stream, b is -1. if(b >= 0) { b3[i]=(byte)b; numBinaryBytes++; } // end if: not end of stream } // end try: read catch(java.io.IOException e) { // Only a problem if we got no data at all. if(i == 0) throw e; } // end catch } // end for: each needed input byte if(numBinaryBytes > 0) { encode3to4(b3, 0, numBinaryBytes, buffer, 0); position=0; numSigBytes=4; } // end if: got data else { return -1; } // end else } // end if: encoding // Else decoding else { byte[] b4=new byte[4]; int i=0; for(i=0; i < 4; i++) { // Read four "meaningful" bytes: int b=0; do { b=in.read(); } while(b >= 0 && DECODABET[b & 0x7f] <= WHITE_SPACE_ENC); if(b < 0) break; // Reads a -1 if end of stream b4[i]=(byte)b; } // end for: each needed input byte if(i == 4) { numSigBytes=decode4to3(b4, 0, buffer, 0); position=0; } // end if: got four characters else if(i == 0) { return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException("Improperly padded Base64 input."); } // end } // end else: decode } // end else: get data // Got data? if(position >= 0) { // End of relevant data? if( /*!encode &&*/ position >= numSigBytes) return -1; if(encode && breakLines && lineLength >= MAX_LINE_LENGTH) { lineLength=0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b=buffer[position++]; if(position >= bufferLength) position=-1; return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { // When JDK1.4 is more accepted, use an assertion here. throw new java.io.IOException("Error in Base64 code reading stream."); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream * is reached or <var>len</var> bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ public int read(byte[] dest, int off, int len) throws java.io.IOException { int i; int b; for(i=0; i < len; i++) { b=read(); //if( b < 0 && i == 0 ) // return -1; if(b >= 0) dest[off + i]=(byte)b; else if(i == 0) return -1; else break; // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /** * A {@link Base64.OutputStream} will write data to another * <tt>java.io.OutputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * @see Base64 * @since 1.3 */ public static class OutputStream extends java.io.FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @since 1.3 */ public OutputStream(java.io.OutputStream out) { this(out, ENCODE); } // end constructor /** * Constructs a {@link Base64.OutputStream} in * either ENCODE or DECODE mode. * <p/> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p/> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 1.3 */ public OutputStream(java.io.OutputStream out, int options) { super(out); this.breakLines=(options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode=(options & ENCODE) == ENCODE; this.bufferLength=encode? 3 : 4; this.buffer=new byte[bufferLength]; this.position=0; this.lineLength=0; this.suspendEncoding=false; this.b4=new byte[4]; } // end constructor /** * Writes the byte to the output stream after * converting to/from Base64 notation. * When encoding, bytes are buffered three * at a time before the output stream actually * gets a write() call. * When decoding, bytes are buffered four * at a time. * @param theByte the byte to write * @since 1.3 */ public void write(int theByte) throws java.io.IOException { // Encoding suspended? if(suspendEncoding) { super.out.write(theByte); return; } // end if: supsended // Encode? if(encode) { buffer[position++]=(byte)theByte; if(position >= bufferLength) // Enough to encode. { out.write(encode3to4(b4, buffer, bufferLength)); lineLength+=4; if(breakLines && lineLength >= MAX_LINE_LENGTH) { out.write(NEW_LINE); lineLength=0; } // end if: end of line position=0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if(DECODABET[theByte & 0x7f] > WHITE_SPACE_ENC) { buffer[position++]=(byte)theByte; if(position >= bufferLength) // Enough to output. { int len=Base64.decode4to3(buffer, 0, b4, 0); out.write(b4, 0, len); //out.write( Base64.decode4to3( buffer ) ); position=0; } // end if: enough to output } // end if: meaningful base64 character else if(DECODABET[theByte & 0x7f] != WHITE_SPACE_ENC) { throw new java.io.IOException("Invalid character in Base64 data."); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write(int)} repeatedly until <var>len</var> * bytes are written. * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ public void write(byte[] theBytes, int off, int len) throws java.io.IOException { // Encoding suspended? if(suspendEncoding) { super.out.write(theBytes, off, len); return; } // end if: supsended for(int i=0; i < len; i++) { write(theBytes[off + i]); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. */ public void flushBase64() throws java.io.IOException { if(position > 0) { if(encode) { out.write(encode3to4(b4, buffer, position)); position=0; } // end if: encoding else { throw new java.io.IOException("Base64 input not properly padded."); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * @since 1.3 */ public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer=null; out=null; } // end close /** * Suspends encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * @since 1.5.1 */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding=true; } // end suspendEncoding /** * Resumes encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding=false; } // end resumeEncoding } // end inner class OutputStream } // end class Base64 }
package uk.ac.ebi.atlas.search; import autovalue.shaded.com.google.common.common.base.Throwables; import com.google.auto.value.AutoValue; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableSet; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.stream.MalformedJsonException; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Collection; import java.util.Iterator; import static org.apache.commons.lang3.StringUtils.isBlank; @AutoValue public abstract class SemanticQuery implements Iterable<SemanticQueryTerm> { private static final String OR_OPERATOR = " OR "; public abstract ImmutableSet<SemanticQueryTerm> terms(); public static SemanticQuery create(Collection<SemanticQueryTerm> queryTerms) { return new AutoValue_SemanticQuery(ImmutableSet.copyOf(queryTerms)); } public static SemanticQuery create() { return new AutoValue_SemanticQuery(ImmutableSet.<SemanticQueryTerm>of()); } public static SemanticQuery create(SemanticQueryTerm... queryTerms) { ImmutableSet.Builder<SemanticQueryTerm> builder = ImmutableSet.builder(); return new AutoValue_SemanticQuery(builder.add(queryTerms).build()); } public static SemanticQuery create(String queryTermValue) { return new AutoValue_SemanticQuery(ImmutableSet.of(SemanticQueryTerm.create(queryTermValue))); } @Override public Iterator<SemanticQueryTerm> iterator() { return terms().iterator(); } public boolean isEmpty() { for (SemanticQueryTerm term : terms()) { if (term.hasValue()) { return false; } } return true; } public boolean isNotEmpty() { for (SemanticQueryTerm term : terms()) { if (term.hasValue()) { return true; } } return false; } public int size() { return terms().size(); } public String toJson() { Gson gson = new Gson(); return gson.toJson(terms()); } public String toUrlEncodedJson(){ Gson gson = new Gson(); try { return URLEncoder.encode(gson.toJson(terms()), "UTF-8"); } catch(UnsupportedEncodingException e){ throw Throwables.propagate(e); } } public static SemanticQuery fromJson(String json) { if (isBlank(json)) { return create(); } Gson gson = new Gson(); return create(ImmutableSet.<SemanticQueryTerm>copyOf(gson.fromJson(json, AutoValue_SemanticQueryTerm[].class))); } public static SemanticQuery fromUrlEncodedJson(String json) throws UnsupportedEncodingException, MalformedJsonException { if (isBlank(json)) { return create(); } Gson gson = new Gson(); try { return create(ImmutableSet.<SemanticQueryTerm>copyOf(gson.fromJson(URLDecoder.decode(json, "UTF-8"), AutoValue_SemanticQueryTerm[].class))); } catch (NullPointerException | JsonSyntaxException e) { String geneQueryString = gson.fromJson(URLDecoder.decode(StringUtils.wrap(json, "\""), "UTF-8"), String.class); return create(ImmutableSet.of(SemanticQueryTerm.create(geneQueryString))); } } @Override public String toString() { return toJson(); } public String asGxaIndexQueryClause(){ return Joiner.on(OR_OPERATOR).join(Collections2.transform(terms(), new Function<SemanticQueryTerm,String>(){ @Nullable @Override public String apply(@Nullable SemanticQueryTerm semanticQueryTerm) { return semanticQueryTerm.asGxaIndexQueryLiteral(); } })); } public String asAnalyticsIndexQueryClause(){ return Joiner.on(OR_OPERATOR).join(Collections2.transform(terms(), new Function<SemanticQueryTerm,String>(){ @Nullable @Override public String apply(@Nullable SemanticQueryTerm semanticQueryTerm) { return semanticQueryTerm.asAnalyticsIndexQueryLiteral(); } })); } public String description() { return Joiner.on(OR_OPERATOR).join(Collections2.transform(terms(), new Function<SemanticQueryTerm, String>() { @Nullable @Override public String apply(@Nullable SemanticQueryTerm semanticQueryTerm) { return semanticQueryTerm.description(); } })); } }
package com.jme3.niftygui; import com.jme3.asset.AssetInfo; import com.jme3.asset.AssetKey; import com.jme3.asset.AssetManager; import com.jme3.audio.AudioRenderer; import com.jme3.input.InputManager; import com.jme3.post.SceneProcessor; import com.jme3.renderer.RenderManager; import com.jme3.renderer.Renderer; import com.jme3.renderer.ViewPort; import com.jme3.renderer.queue.RenderQueue; import com.jme3.texture.FrameBuffer; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.tools.TimeProvider; import de.lessvoid.nifty.tools.resourceloader.ResourceLoader; import de.lessvoid.nifty.tools.resourceloader.ResourceLocation; import java.io.InputStream; import java.net.URL; public class NiftyJmeDisplay implements SceneProcessor { protected boolean inited = false; protected Nifty nifty; protected AssetManager assetManager; protected RenderManager renderManager; protected RenderDeviceJme renderDev; protected InputSystemJme inputSys; protected SoundDeviceJme soundDev; protected Renderer renderer; protected ViewPort vp; protected ResourceLocationJme resourceLocation; protected int w, h; protected class ResourceLocationJme implements ResourceLocation { public InputStream getResourceAsStream(String path) { AssetKey<Object> key = new AssetKey<Object>(path); AssetInfo info = assetManager.locateAsset(key); return info.openStream(); } public URL getResource(String path) { throw new UnsupportedOperationException(); } } //Empty constructor needed for jMP to create replacement input system public NiftyJmeDisplay() { } public NiftyJmeDisplay(AssetManager assetManager, InputManager inputManager, AudioRenderer audioRenderer, ViewPort vp){ this.assetManager = assetManager; w = vp.getCamera().getWidth(); h = vp.getCamera().getHeight(); resourceLocation = new ResourceLocationJme(); ResourceLoader.removeAllResourceLocations(); ResourceLoader.addResourceLocation(resourceLocation); soundDev = new SoundDeviceJme(assetManager, audioRenderer); renderDev = new RenderDeviceJme(this); inputSys = new InputSystemJme(inputManager); if (inputManager != null) inputManager.addRawInputListener(inputSys); nifty = new Nifty(renderDev, soundDev, inputSys, new TimeProvider()); inputSys.setNifty(nifty); } public void initialize(RenderManager rm, ViewPort vp) { this.renderManager = rm; renderDev.setRenderManager(rm); inited = true; this.vp = vp; this.renderer = rm.getRenderer(); inputSys.setHeight(vp.getCamera().getHeight()); } public Nifty getNifty() { return nifty; } RenderDeviceJme getRenderDevice() { return renderDev; } AssetManager getAssetManager() { return assetManager; } RenderManager getRenderManager() { return renderManager; } int getHeight() { return h; } int getWidth() { return w; } Renderer getRenderer(){ return renderer; } public void reshape(ViewPort vp, int w, int h) { this.w = w; this.h = h; inputSys.setHeight(h); nifty.resolutionChanged(); } public boolean isInitialized() { return inited; } public void preFrame(float tpf) { } public void postQueue(RenderQueue rq) { // render nifty before anything else renderManager.setCamera(vp.getCamera(), true); //nifty.update(); nifty.render(false); renderManager.setCamera(vp.getCamera(), false); } public void postFrame(FrameBuffer out) { } public void cleanup() { inited = false; // nifty.exit(); } }
package performanceTests; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.Random; import stopwatch.StopWatch; import com.nativelibs4java.opencl.CLBuffer; import com.nativelibs4java.opencl.CLContext; import com.nativelibs4java.opencl.CLDevice; import com.nativelibs4java.opencl.CLMem.Usage; import com.nativelibs4java.opencl.CLPlatform; import com.nativelibs4java.opencl.CLQueue; import com.nativelibs4java.opencl.JavaCL; public class readTest { private static final int FACTOR = 8; private static final int ROUNDS = 5; private static final int SIZEOF_CL_INT = 4; public static void main(String[] args) { CLPlatform[] platforms = JavaCL.listGPUPoweredPlatforms(); CLDevice device = platforms[0].getBestDevice(); CLContext context = JavaCL.createContext(null, device); CLQueue cmdQ = context .createDefaultQueue(new CLDevice.QueueProperties[0]); final int MAX_COUNT = (int) Math.min(65536, device.getGlobalMemSize() / 8 / SIZEOF_CL_INT - 65536); System.out.println("Device: " + device.getName()); System.out.println("MAX_COUNT: " + MAX_COUNT); System.out.println(); Random ran = new Random(System.currentTimeMillis()); int count; StopWatch sw = new StopWatch("time", ""); double time; int[] buffer; CLBuffer<IntBuffer> clBuffer = context.createIntBuffer( Usage.InputOutput, 1); // many single read System.out.println("Many single reads"); for (count = 128; count <= MAX_COUNT; count *= FACTOR) { sw.reset(); System.out.println("\tIntValues: " + count); buffer = new int[count]; for (int i = 0; i < buffer.length; i++) buffer[i] = ran.nextInt(); clBuffer.release(); clBuffer = context.createIntBuffer(Usage.InputOutput, IntBuffer.wrap(buffer), true); sw.start(); for (int r = 0; r < ROUNDS; r++) { IntBuffer intBuffer = ByteBuffer .allocateDirect(1 * SIZEOF_CL_INT) .order(context.getByteOrder()).asIntBuffer(); for (int i = 0; i < count; i++) { clBuffer.read(cmdQ, i, 1, intBuffer, true); intBuffer.rewind(); buffer[i] = intBuffer.get(); } } sw.stop(); time = sw.getTime() / ROUNDS; System.out.println("\ttime: " + time); System.out.println("\ttime/value: " + time / count); System.out.println(); } // one big read System.out.println("One big single read"); for (count = 128; count <= MAX_COUNT; count *= FACTOR) { sw.reset(); System.out.println("\tIntValues: " + count); buffer = new int[count]; for (int i = 0; i < buffer.length; i++) buffer[i] = ran.nextInt(); clBuffer.release(); clBuffer = context.createIntBuffer(Usage.InputOutput, IntBuffer.wrap(buffer), true); sw.start(); for (int r = 0; r < ROUNDS; r++) { IntBuffer intBuffer = ByteBuffer .allocateDirect(count * SIZEOF_CL_INT) .order(context.getByteOrder()).asIntBuffer(); clBuffer.read(cmdQ, intBuffer, true); intBuffer.rewind(); for (int i = 0; i < count; i++) { buffer[i] = intBuffer.get(); } } sw.stop(); time = sw.getTime() / ROUNDS; System.out.println("\ttime: " + time); System.out.println("\ttime/value: " + time / count); System.out.println(); } // fix data, variable buffer size System.out.println("One single big read on different buffer size"); int bufferSize; for (count = 128; count <= MAX_COUNT; count *= FACTOR) { sw.reset(); bufferSize = count * 2; System.out.println("\tCLBuffer size: " + bufferSize); System.out.println("\tIntValues: " + count); buffer = new int[bufferSize]; for (int i = 0; i < buffer.length; i++) buffer[i] = ran.nextInt(); clBuffer.release(); clBuffer = context.createIntBuffer(Usage.InputOutput, IntBuffer.wrap(buffer), true); sw.start(); for (int r = 0; r < ROUNDS; r++) { IntBuffer intBuffer = ByteBuffer .allocateDirect(count * SIZEOF_CL_INT) .order(context.getByteOrder()).asIntBuffer(); clBuffer.read(cmdQ, 0, count, intBuffer, true); intBuffer.rewind(); for (int i = 0; i < count; i++) { buffer[i] = intBuffer.get(); } } sw.stop(); time = sw.getTime() / ROUNDS; System.out.println("\ttime: " + time); System.out.println("\ttime/value: " + time / count); System.out.println(); } // creation time System.out.println("Buffer creation time"); count = MAX_COUNT; for (count = 128; count <= MAX_COUNT; count *= FACTOR) { sw.reset(); System.out.println("\tIntValues: " + count); sw.start(); for (int r = 0; r < ROUNDS; r++) { clBuffer.release(); clBuffer = context.createIntBuffer(Usage.InputOutput, count); } sw.stop(); time = sw.getTime() / ROUNDS; System.out.println("\ttime: " + time); System.out.println("\ttime/value: " + time / count); System.out.println(); } } }
package org.jgroups.protocols; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.PhysicalAddress; import org.jgroups.annotations.Property; import org.jgroups.stack.IpAddress; import org.jgroups.util.Util; import org.jgroups.util.UUID; import org.jgroups.util.Promise; import java.util.*; /** * The TCPPING protocol layer retrieves the initial membership in answer to the * GMS's FIND_INITIAL_MBRS event. The initial membership is retrieved by * directly contacting other group members, sending point-to-point mebership * requests. The responses should allow us to determine the coordinator whom we * have to contact in case we want to join the group. When we are a server * (after having received the BECOME_SERVER event), we'll respond to TCPPING * requests with a TCPPING response. * <p> * The FIND_INITIAL_MBRS event will eventually be answered with a * FIND_INITIAL_MBRS_OK event up the stack. * <p> * The TCPPING protocol requires a static conifiguration, which assumes that you * to know in advance where to find other members of your group. For dynamic * discovery, use the PING protocol, which uses multicast discovery, or the * TCPGOSSIP protocol, which contacts a Gossip Router to acquire the initial * membership. * * @author Bela Ban * @version $Id: TCPPING.java,v 1.45 2009/05/28 12:06:34 vlada Exp $ */ public class TCPPING extends Discovery { private final static String NAME="TCPPING"; @Property(description="Number of ports to be probed for initial membership. Default is 1") private int port_range=1; @Property(name="initial_hosts", description="Comma delimeted list of hosts to be contacted for initial membership") private String hosts; /** * List of PhysicalAddresses */ private List<IpAddress> initial_hosts; public TCPPING() { return_entire_cache=false; } public String getName() { return NAME; } /** * Returns the list of initial hosts as configured by the user via XML. Note that the returned list is mutable, so * careful with changes ! * @return List<Address> list of initial hosts. This variable is only set after the channel has been created and * set Properties() has been called */ public List<IpAddress> getInitialHosts() { return initial_hosts; } public void setInitialHosts(String hosts) { this.hosts = hosts; } public int getPortRange() { return port_range; } public void setPortRange(int port_range) { this.port_range=port_range; } public void start() throws Exception { super.start(); initial_hosts = Util.parseCommaDelimetedHosts(hosts, port_range); } public void sendGetMembersRequest(String cluster_name, Promise promise) throws Exception{ PhysicalAddress physical_addr=(PhysicalAddress)down_prot.down(new Event(Event.GET_PHYSICAL_ADDRESS, local_addr)); PingData data=new PingData(local_addr, null, false, UUID.get(local_addr), Arrays.asList(physical_addr)); PingHeader hdr=new PingHeader(PingHeader.GET_MBRS_REQ, data, cluster_name); for(final Address addr: initial_hosts) { if(addr.equals(physical_addr)) continue; final Message msg = new Message(addr, null, null); msg.setFlag(Message.OOB); msg.putHeader(NAME, hdr); if(log.isTraceEnabled()) log.trace("[FIND_INITIAL_MBRS] sending PING request to " + msg.getDest()); timer.submit(new Runnable() { public void run() { try { down_prot.down(new Event(Event.MSG, msg)); } catch(Exception ex){ if(log.isErrorEnabled()) log.error("failed sending discovery request to " + addr, ex); } } }); } } }
package org.jgroups.protocols; import org.jgroups.*; import org.jgroups.annotations.*; import org.jgroups.conf.PropertyConverters; import org.jgroups.stack.AckReceiverWindow; import org.jgroups.stack.AckSenderWindow; import org.jgroups.stack.Protocol; import org.jgroups.stack.StaticInterval; import org.jgroups.util.*; import java.io.*; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * Reliable unicast layer. Uses acknowledgement scheme similar to TCP to provide lossless transmission * of unicast messages (for reliable multicast see NAKACK layer). When a message is sent to a peer for * the first time, we add the pair <peer_addr, Entry> to the hashtable (peer address is the key). All * messages sent to that peer will be added to hashtable.peer_addr.sent_msgs. When we receive a * message from a peer for the first time, another entry will be created and added to the hashtable * (unless already existing). Msgs will then be added to hashtable.peer_addr.received_msgs.<p> This * layer is used to reliably transmit point-to-point messages, that is, either messages sent to a * single receiver (vs. messages multicast to a group) or for example replies to a multicast message. The * sender uses an <code>AckSenderWindow</code> which retransmits messages for which it hasn't received * an ACK, the receiver uses <code>AckReceiverWindow</code> which keeps track of the lowest seqno * received so far, and keeps messages in order.<p> * Messages in both AckSenderWindows and AckReceiverWindows will be removed. A message will be removed from * AckSenderWindow when an ACK has been received for it and messages will be removed from AckReceiverWindow * whenever a message is received: the new message is added and then we try to remove as many messages as * possible (until we stop at a gap, or there are no more messages). * @author Bela Ban * @version $Id: UNICAST.java,v 1.132 2009/04/29 10:39:40 belaban Exp $ */ @MBean(description="Reliable unicast layer") @DeprecatedProperty(names={"immediate_ack", "use_gms", "enabled_mbrs_timeout", "eager_lock_release"}) public class UNICAST extends Protocol implements AckSenderWindow.RetransmitCommand, AgeOutCache.Handler<Address> { private static final String name="UNICAST"; private static final long DEFAULT_FIRST_SEQNO=1; @Property(description="Whether to loop back messages sent to self. Default is false") private boolean loopback=false; private long[] timeout= { 400, 800, 1600, 3200 }; // for AckSenderWindow: max time to wait for missing acks private long num_msgs_sent=0, num_msgs_received=0, num_bytes_sent=0, num_bytes_received=0; private long num_acks_sent=0, num_acks_received=0, num_xmit_requests_received=0; private final Vector<Address> members=new Vector<Address>(11); private final HashMap<Address,Entry> connections=new HashMap<Address,Entry>(11); private Address local_addr=null; private TimeScheduler timer=null; // used for retransmissions (passed to AckSenderWindow) private boolean started=false; /** <em>Regular</em> messages which have been added, but not removed */ private final AtomicInteger undelivered_msgs=new AtomicInteger(0); private long last_conn_id=0; @Property(description="Max number of milliseconds we try to retransmit a message to any given member. After that, " + "the connection is removed. Any new connection to that member will start with seqno #1 again. 0 disables this") protected long max_retransmit_time=60 * 1000L; private AgeOutCache<Address> cache=null; @ManagedAttribute public int getUndeliveredMessages() { return undelivered_msgs.get(); } /** All protocol names have to be unique ! */ public String getName() {return name;} public long[] getTimeout() {return timeout;} @Property(name="timeout",converter=PropertyConverters.LongArray.class) public void setTimeout(long[] val) { if(val != null) timeout=val; } @ManagedAttribute public String getLocalAddress() {return local_addr != null? local_addr.toString() : "null";} @ManagedAttribute public String getMembers() {return members != null? members.toString() : "[]";} @ManagedOperation public String printConnections() { StringBuilder sb=new StringBuilder(); for(Map.Entry<Address,Entry> entry: connections.entrySet()) { sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); } return sb.toString(); } @ManagedAttribute public long getNumMessagesSent() { return num_msgs_sent; } @ManagedAttribute public long getNumMessagesReceived() { return num_msgs_received; } @ManagedAttribute public long getNumBytesSent() { return num_bytes_sent; } @ManagedAttribute public long getNumBytesReceived() { return num_bytes_received; } @ManagedAttribute public long getNumAcksSent() { return num_acks_sent; } @ManagedAttribute public long getNumAcksReceived() { return num_acks_received; } @ManagedAttribute public long getNumberOfRetransmitRequestsReceived() { return num_xmit_requests_received; } @ManagedAttribute(writable=true) public long getMaxRetransmitTime() { return max_retransmit_time; } public void setMaxRetransmitTime(long max_retransmit_time) { this.max_retransmit_time=max_retransmit_time; if(cache != null && max_retransmit_time > 0) cache.setTimeout(max_retransmit_time); } @ManagedAttribute public int getAgeOutCacheSize() { return cache != null? cache.size() : 0; } @ManagedOperation public String printAgeOutCache() { return cache != null? cache.toString() : "n/a"; } public AgeOutCache getAgeOutCache() { return cache; } /** The number of messages in all Entry.sent_msgs tables (haven't received an ACK yet) */ @ManagedAttribute public int getNumberOfUnackedMessages() { int num=0; synchronized(connections) { for(Entry entry: connections.values()) { if(entry.sent_msgs != null) num+=entry.sent_msgs.size(); } } return num; } @ManagedOperation public String printUnackedMessages() { StringBuilder sb=new StringBuilder(); Entry e; Object member; synchronized(connections) { for(Map.Entry<Address,Entry> entry: connections.entrySet()) { member=entry.getKey(); e=entry.getValue(); sb.append(member).append(": "); if(e.sent_msgs != null) sb.append(e.sent_msgs.toString()).append("\n"); } } return sb.toString(); } @ManagedAttribute public int getNumberOfMessagesInReceiveWindows() { int num=0; synchronized(connections) { for(Entry entry: connections.values()) { if(entry.received_msgs != null) num+=entry.received_msgs.size(); } } return num; } public void resetStats() { num_msgs_sent=num_msgs_received=num_bytes_sent=num_bytes_received=num_acks_sent=num_acks_received=0; num_xmit_requests_received=0; } public Map<String, Object> dumpStats() { Map<String, Object> m=super.dumpStats(); m.put("unacked_msgs", printUnackedMessages()); m.put("num_msgs_sent", num_msgs_sent); m.put("num_msgs_received", num_msgs_received); m.put("num_bytes_sent", num_bytes_sent); m.put("num_bytes_received", num_bytes_received); m.put("num_acks_sent", num_acks_sent); m.put("num_acks_received", num_acks_received); m.put("num_xmit_requests_received", num_xmit_requests_received); m.put("num_unacked_msgs", getNumberOfUnackedMessages()); m.put("num_msgs_in_recv_windows", getNumberOfMessagesInReceiveWindows()); return m; } public void start() throws Exception { timer=getTransport().getTimer(); if(timer == null) throw new Exception("timer is null"); if(max_retransmit_time > 0) cache=new AgeOutCache(timer, max_retransmit_time, this); started=true; } public void stop() { started=false; removeAllConnections(); undelivered_msgs.set(0); } public Object up(Event evt) { Message msg; Address dst, src; UnicastHeader hdr; switch(evt.getType()) { case Event.MSG: msg=(Message)evt.getArg(); dst=msg.getDest(); if(dst == null || dst.isMulticastAddress()) // only handle unicast messages break; // pass up // changed from removeHeader(): we cannot remove the header because if we do loopback=true at the // transport level, we will not have the header on retransmit ! (bela Aug 22 2006) hdr=(UnicastHeader)msg.getHeader(name); if(hdr == null) break; src=msg.getSrc(); switch(hdr.type) { case UnicastHeader.DATA: // received regular message handleDataReceived(src, hdr.seqno, hdr.conn_id, hdr.first, msg); return null; // we pass the deliverable message up in handleDataReceived() case UnicastHeader.ACK: // received ACK for previously sent message handleAckReceived(src, hdr.seqno); break; case UnicastHeader.SEND_FIRST_SEQNO: handleResendingOfFirstMessage(src); break; default: log.error("UnicastHeader type " + hdr.type + " not known !"); break; } return null; } return up_prot.up(evt); // Pass up to the layer above us } public Object down(Event evt) { switch (evt.getType()) { case Event.MSG: // Add UnicastHeader, add to AckSenderWindow and pass down Message msg=(Message)evt.getArg(); Address dst=msg.getDest(); /* only handle unicast messages */ if (dst == null || dst.isMulticastAddress()) { break; } if(!started) { if(log.isTraceEnabled()) log.trace("discarded message as start() has not yet been called, message: " + msg); return null; } // if the dest is self --> pass the message back up if(loopback && local_addr != null && local_addr.equals(dst)) { msg.setSrc(local_addr); up_prot.up(evt); num_msgs_sent++; num_bytes_sent+=msg.getLength(); return null; } Entry entry; synchronized(connections) { entry=connections.get(dst); if(entry == null) { entry=new Entry(); connections.put(dst, entry); if(log.isTraceEnabled()) log.trace(local_addr + ": created connection to " + dst); if(cache != null && !members.contains(dst)) cache.add(dst); } } long seqno=-2; synchronized(entry) { // threads will only sync if they access the same entry try { seqno=entry.sent_msgs_seqno; boolean first=false; if(seqno == DEFAULT_FIRST_SEQNO) { // only happens on the first message entry.send_conn_id=getNewConnectionId(); first=true; } UnicastHeader hdr=new UnicastHeader(UnicastHeader.DATA, seqno, entry.send_conn_id, first); if(entry.sent_msgs == null) { // first msg to peer 'dst' entry.sent_msgs=new AckSenderWindow(this, new StaticInterval(timeout), timer, this.local_addr); // use the global timer } msg.putHeader(name, hdr); if(log.isTraceEnabled()) { StringBuilder sb=new StringBuilder(); sb.append(local_addr).append(" --> DATA(").append(dst).append(": #").append(seqno). append(", conn_id=").append(entry.send_conn_id).append(')'); log.trace(sb); } if(entry.sent_msgs != null) entry.sent_msgs.add(seqno, msg); // add *including* UnicastHeader, adds to retransmitter entry.sent_msgs_seqno++; } catch(Throwable t) { if(entry.sent_msgs != null) entry.sent_msgs.ack(seqno); // remove seqno again, so it is not transmitted throw new RuntimeException("failure adding msg " + msg + " to the retransmit table", t); } } // moved passing down of message out of the synchronized block: similar to NAKACK, we do *not* need // to send unicast messages in order of sequence numbers because they will be sorted into the correct // order at the receiver anyway. Of course, most of the time, the order will be correct (FIFO), so try { // we catch the exception in this case because the msg is in the XMIT table and will be retransmitted send(msg, evt); } catch(Throwable t) { log.warn("failed sending the message", t); } return null; // we already passed the msg down case Event.VIEW_CHANGE: // remove connections to peers that are not members anymore ! View view=(View)evt.getArg(); Vector<Address> new_members=view.getMembers(); Set<Address> non_members=new HashSet<Address>(connections.keySet()); synchronized(members) { members.clear(); if(new_members != null) members.addAll(new_members); non_members.removeAll(members); if(cache != null) { cache.removeAll(members); } } if(!non_members.isEmpty()) { if(log.isTraceEnabled()) log.trace("removing non members " + non_members); for(Address non_mbr: non_members) removeConnection(non_mbr); } break; case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); break; } return down_prot.down(evt); // Pass on to the layer below us } private void send(Message msg, Event evt) { down_prot.down(evt); num_msgs_sent++; num_bytes_sent+=msg.getLength(); } /** * Removes and resets from connection table (which is already locked). Returns true if member was found, * otherwise false. This method is public only so it can be invoked by unit testing, but should not otherwise be * used ! */ public boolean removeConnection(Address mbr) { Entry entry; synchronized(connections) { entry=connections.remove(mbr); } if(entry != null) { entry.reset(); return true; } else return false; } private void removeAllConnections() { synchronized(connections) { for(Entry entry: connections.values()) { entry.reset(); } connections.clear(); } } /** Called by AckSenderWindow to resend messages for which no ACK has been received yet */ public void retransmit(long seqno, Message msg) { if(log.isTraceEnabled()) log.trace(local_addr + " --> XMIT(" + msg.getDest() + ": #" + seqno + ')'); down_prot.down(new Event(Event.MSG, msg)); num_xmit_requests_received++; } /** * Called by AgeOutCache, to removed expired connections * @param key */ public void expired(Address key) { if(key != null) { if(log.isDebugEnabled()) log.debug("removing connection to " + key + " because it expired"); removeConnection(key); } } /** * Check whether the hashtable contains an entry e for <code>sender</code> (create if not). If * e.received_msgs is null and <code>first</code> is true: create a new AckReceiverWindow(seqno) and * add message. Set e.received_msgs to the new window. Else just add the message. */ private void handleDataReceived(Address sender, long seqno, long conn_id, boolean first, Message msg) { if(log.isTraceEnabled()) { StringBuilder sb=new StringBuilder(); sb.append(local_addr).append(" <-- DATA(").append(sender).append(": #").append(seqno); if(conn_id != 0) sb.append(", conn_id=").append(conn_id); sb.append(')'); log.trace(sb); } AckReceiverWindow win; synchronized(connections) { Entry entry=connections.get(sender); win=entry != null? entry.received_msgs : null; if(first) { if(entry == null || win == null) { win=createReceiverWindow(sender, entry, seqno, conn_id); } else { if(conn_id != entry.recv_conn_id) { if(log.isTraceEnabled()) log.trace(local_addr + ": conn_id=" + conn_id + " != " + entry.recv_conn_id + "; resetting receiver window"); win=createReceiverWindow(sender, entry, seqno, conn_id); } else { ; } } } else { if(win == null || entry.recv_conn_id != conn_id) { sendRequestForFirstSeqno(sender); return; // drop message } } } boolean added=win.add(seqno, msg); // entry.received_msgs is guaranteed to be non-null if we get here num_msgs_received++; num_bytes_received+=msg.getLength(); if(added && !msg.isFlagSet(Message.OOB)) undelivered_msgs.incrementAndGet(); if(win.smallerThanNextToRemove(seqno)) sendAck(msg.getSrc(), seqno); // message is passed up if OOB. Later, when remove() is called, we discard it. This affects ordering ! if(msg.isFlagSet(Message.OOB)) { if(added) up_prot.up(new Event(Event.MSG, msg)); Message oob_msg=win.removeOOBMessage(); if(oob_msg != null) sendAckForMessage(oob_msg); if(!(win.hasMessagesToRemove() && undelivered_msgs.get() > 0)) return; } if(!added && !win.hasMessagesToRemove()) { // no ack if we didn't add the msg (e.g. duplicate) return; } final AtomicBoolean processing=win.getProcessing(); if(!processing.compareAndSet(false, true)) { return; } // Try to remove (from the AckReceiverWindow) as many messages as possible as pass them up boolean released_processing=false; int num_regular_msgs_removed=0; // where lots of threads can come up to this point concurrently, but only 1 is allowed to pass at a time // We *can* deliver messages from *different* senders concurrently, e.g. reception of P1, Q1, P2, Q2 can result in // delivery of P1, Q1, Q2, P2: FIFO (implemented by UNICAST) says messages need to be delivered only in the // order in which they were sent by their senders try { while(true) { Message m=win.remove(processing); if(m == null) { released_processing=true; return; } if(m.isFlagSet(Message.OOB)) { continue; } num_regular_msgs_removed++; sendAckForMessage(m); up_prot.up(new Event(Event.MSG, m)); } } finally { // We keep track of regular messages that we added, but couldn't remove (because of ordering). // When we have such messages pending, then even OOB threads will remove and process them undelivered_msgs.addAndGet(-num_regular_msgs_removed); if(!released_processing) processing.set(false); } } private AckReceiverWindow createReceiverWindow(Address sender, Entry entry, long seqno, long conn_id) { if(entry == null) { entry=new Entry(); connections.put(sender, entry); } if(entry.received_msgs != null) entry.received_msgs.reset(); entry.received_msgs=new AckReceiverWindow(seqno); entry.recv_conn_id=conn_id; if(log.isTraceEnabled()) log.trace(local_addr + ": created receiver window for " + sender + " at seqno=#" + seqno + " for conn-id=" + conn_id); return entry.received_msgs; } /** Add the ACK to hashtable.sender.sent_msgs */ private void handleAckReceived(Address sender, long seqno) { Entry entry; AckSenderWindow win; if(log.isTraceEnabled()) log.trace(new StringBuilder().append(local_addr).append(" <-- ACK(").append(sender). append(": #").append(seqno).append(')')); synchronized(connections) { entry=connections.get(sender); } if(entry == null || entry.sent_msgs == null) return; win=entry.sent_msgs; win.ack(seqno); // removes message from retransmission num_acks_received++; } /** * We need to resend our first message with our conn_id * @param sender */ private void handleResendingOfFirstMessage(Address sender) { Entry entry; AckSenderWindow sender_win; Message rsp; if(log.isTraceEnabled()) log.trace(local_addr + " <-- SEND_FIRST_SEQNO(" + sender + ")"); synchronized(connections) { entry=connections.get(sender); sender_win=entry != null? entry.sent_msgs : null; if(sender_win == null) { if(log.isErrorEnabled()) log.error("sender window for " + sender + " not found"); return; } rsp=sender_win.getLowestMessage(); } if(rsp == null) { if(log.isWarnEnabled()) log.warn("didn't find any messages in my sender window for " + sender); return; } // We need to copy the UnicastHeader and put it back into the message because Message.copy() doesn't copy // the headers and therefore we'd modify the original message in the sender retransmission window Message copy=rsp.copy(); UnicastHeader hdr=(UnicastHeader)copy.getHeader(name); UnicastHeader newhdr=new UnicastHeader(hdr.type, hdr.seqno, entry.send_conn_id, true); copy.putHeader(name, newhdr); down_prot.down(new Event(Event.MSG, copy)); } private void sendAck(Address dst, long seqno) { Message ack=new Message(dst); // commented Jan 23 2008 (bela): TP.enable_unicast_bundling should decide whether we bundle or not, and *not* // the OOB flag ! Bundling UNICAST ACKs should be really fast ack.setFlag(Message.OOB); ack.putHeader(name, new UnicastHeader(UnicastHeader.ACK, seqno)); if(log.isTraceEnabled()) log.trace(new StringBuilder().append(local_addr).append(" --> ACK(").append(dst). append(": #").append(seqno).append(')')); down_prot.down(new Event(Event.MSG, ack)); num_acks_sent++; } private void sendAckForMessage(Message msg) { UnicastHeader hdr=msg != null? (UnicastHeader)msg.getHeader(name) : null; Address sender=msg != null? msg.getSrc() : null; if(hdr != null && sender != null) { sendAck(sender, hdr.seqno); } } private long getNewConnectionId() { long retval=System.currentTimeMillis(); synchronized(this) { if(last_conn_id == retval) retval++; last_conn_id=retval; return retval; } } private void sendRequestForFirstSeqno(Address dest) { Message msg=new Message(dest); msg.setFlag(Message.OOB); UnicastHeader hdr=new UnicastHeader(UnicastHeader.SEND_FIRST_SEQNO, 0); msg.putHeader(name, hdr); if(log.isTraceEnabled()) log.trace(local_addr + " --> SEND_FIRST_SEQNO(" + dest + ")"); down_prot.down(new Event(Event.MSG, msg)); } public static class UnicastHeader extends Header implements Streamable { public static final byte DATA = 0; public static final byte ACK = 1; public static final byte SEND_FIRST_SEQNO = 2; byte type=DATA; long seqno=0; long conn_id=0; boolean first=false; static final int serialized_size=Global.BYTE_SIZE * 2 + Global.LONG_SIZE * 2; private static final long serialVersionUID=-8983745221189309298L; public UnicastHeader() {} // used for externalization public UnicastHeader(byte type, long seqno) { this.type=type; this.seqno=seqno; } public UnicastHeader(byte type, long seqno, long conn_id) { this(type, seqno); this.conn_id=conn_id; } public UnicastHeader(byte type, long seqno, long conn_id, boolean first) { this(type, seqno, conn_id); this.first=first; } public String toString() { StringBuilder sb=new StringBuilder(); sb.append("[UNICAST: ").append(type2Str(type)).append(", seqno=").append(seqno); if(conn_id != 0) sb.append(", conn_id=").append(conn_id); if(first) sb.append(", first"); sb.append(']'); return sb.toString(); } public static String type2Str(byte t) { switch(t) { case DATA: return "DATA"; case ACK: return "ACK"; case SEND_FIRST_SEQNO: return "SEND_FIRST_SEQNO"; default: return "<unknown>"; } } public final int size() { return serialized_size; } public void writeExternal(ObjectOutput out) throws IOException { out.writeByte(type); out.writeLong(seqno); out.writeLong(conn_id); out.writeBoolean(first); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { type=in.readByte(); seqno=in.readLong(); conn_id=in.readLong(); first=in.readBoolean(); } public void writeTo(DataOutputStream out) throws IOException { out.writeByte(type); out.writeLong(seqno); out.writeLong(conn_id); out.writeBoolean(first); } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { type=in.readByte(); seqno=in.readLong(); conn_id=in.readLong(); first=in.readBoolean(); } } private static final class Entry { AckReceiverWindow received_msgs=null; // stores all msgs rcvd by a certain peer in seqno-order long recv_conn_id=0; AckSenderWindow sent_msgs=null; // stores (and retransmits) msgs sent by us to a certain peer long sent_msgs_seqno=DEFAULT_FIRST_SEQNO; // seqno for msgs sent by us long send_conn_id=0; void reset() { if(sent_msgs != null) sent_msgs.reset(); if(received_msgs != null) received_msgs.reset(); sent_msgs_seqno=DEFAULT_FIRST_SEQNO; } public String toString() { StringBuilder sb=new StringBuilder(); if(sent_msgs != null) sb.append("sent_msgs=").append(sent_msgs).append('\n'); if(received_msgs != null) sb.append("received_msgs=").append(received_msgs).append('\n'); sb.append("send_conn_id=" + send_conn_id + ", recv_conn_id=" + recv_conn_id + "\n"); return sb.toString(); } } }
package jkind.analysis; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayExpr; import jkind.lustre.ArrayType; import jkind.lustre.ArrayUpdateExpr; import jkind.lustre.BinaryExpr; import jkind.lustre.BoolExpr; import jkind.lustre.CastExpr; import jkind.lustre.CondactExpr; import jkind.lustre.Constant; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.NodeCallExpr; import jkind.lustre.Program; import jkind.lustre.RealExpr; import jkind.lustre.RecordAccessExpr; import jkind.lustre.RecordExpr; import jkind.lustre.RecordType; import jkind.lustre.RecordUpdateExpr; import jkind.lustre.SubrangeIntType; import jkind.lustre.TupleExpr; import jkind.lustre.TupleType; import jkind.lustre.Type; import jkind.lustre.TypeDef; import jkind.lustre.UnaryExpr; import jkind.lustre.VarDecl; import jkind.lustre.visitors.ExprVisitor; import jkind.lustre.visitors.TypeMapVisitor; import jkind.util.Util; /** * Assuming everything is well-typed, this class can be used to quickly * reconstruct the type of an expression (often useful during translations). * This class treats subrange types as integer types. */ public class TypeReconstructor implements ExprVisitor<Type> { private final Map<String, Type> typeTable = new HashMap<>(); private final Map<String, Type> constantTable = new HashMap<>(); private final Map<String, Type> variableTable = new HashMap<>(); private final Map<String, Node> nodeTable = new HashMap<>(); public TypeReconstructor(Program program) { populateTypeTable(program.types); populateConstantTable(program.constants); nodeTable.putAll(Util.getNodeTable(program.nodes)); } /** * This constructor is for use after user types, constants, and nodes have * all been inlined. */ public TypeReconstructor() { } private void populateTypeTable(List<TypeDef> typeDefs) { for (TypeDef def : typeDefs) { typeTable.put(def.id, resolveType(def.type)); } } private void populateConstantTable(List<Constant> constants) { for (Constant c : constants) { if (c.type == null) { constantTable.put(c.id, c.expr.accept(this)); } else { constantTable.put(c.id, resolveType(c.type)); } } } public void setNodeContext(Node node) { variableTable.clear(); for (VarDecl v : Util.getVarDecls(node)) { variableTable.put(v.id, resolveType(v.type)); } } @Override public Type visit(ArrayAccessExpr e) { ArrayType array = (ArrayType) e.array.accept(this); return array.base; } @Override public Type visit(ArrayExpr e) { return new ArrayType(e.elements.get(0).accept(this), e.elements.size()); } @Override public Type visit(ArrayUpdateExpr e) { return e.array.accept(this); } @Override public Type visit(BinaryExpr e) { switch (e.op) { case PLUS: case MINUS: case MULTIPLY: return e.left.accept(this); case DIVIDE: return NamedType.REAL; case INT_DIVIDE: case MODULUS: return NamedType.INT; case EQUAL: case NOTEQUAL: case GREATER: case LESS: case GREATEREQUAL: case LESSEQUAL: case OR: case AND: case XOR: case IMPLIES: return NamedType.BOOL; case ARROW: return e.left.accept(this); default: throw new IllegalArgumentException(); } } @Override public Type visit(BoolExpr e) { return NamedType.BOOL; } @Override public Type visit(CastExpr e) { return e.type; } @Override public Type visit(CondactExpr e) { return e.call.accept(this); } @Override public Type visit(IdExpr e) { if (variableTable.containsKey(e.id)) { return variableTable.get(e.id); } else if (constantTable.containsKey(e.id)) { return constantTable.get(e.id); } else { throw new IllegalArgumentException(); } } @Override public Type visit(IfThenElseExpr e) { return e.thenExpr.accept(this); } @Override public Type visit(IntExpr e) { return NamedType.INT; } @Override public Type visit(NodeCallExpr e) { Node node = nodeTable.get(e.node); List<Type> outputs = new ArrayList<>(); for (VarDecl output : node.outputs) { outputs.add(resolveType(output.type)); } return compressTypes(outputs); } private Type compressTypes(List<Type> types) { if (types.size() == 1) { return types.get(0); } return new TupleType(types); } @Override public Type visit(RealExpr e) { return NamedType.REAL; } @Override public Type visit(RecordAccessExpr e) { RecordType record = (RecordType) e.record.accept(this); return record.fields.get(e.field); } @Override public Type visit(RecordExpr e) { if (typeTable.containsKey(e.id)) { return typeTable.get(e.id); } else { // If user types have already been inlined, we reconstruct the type Map<String, Type> fields = new HashMap<>(); for (String field : e.fields.keySet()) { fields.put(field, e.fields.get(field).accept(this)); } return new RecordType(e.id, fields); } } @Override public Type visit(RecordUpdateExpr e) { return e.record.accept(this); } @Override public Type visit(TupleExpr e) { List<Type> types = new ArrayList<>(); for (Expr expr : e.elements) { types.add(expr.accept(this)); } return new TupleType(types); } @Override public Type visit(UnaryExpr e) { switch (e.op) { case NEGATIVE: return NamedType.INT; case NOT: return NamedType.BOOL; case PRE: return e.expr.accept(this); default: throw new IllegalArgumentException(); } } private Type resolveType(Type type) { return type.accept(new TypeMapVisitor() { @Override public Type visit(SubrangeIntType e) { return NamedType.INT; } @Override public Type visit(NamedType e) { if (e.isBuiltin()) { return e; } else { return typeTable.get(e.name); } } }); } }
package etomica.virial; import etomica.api.IAtomList; import etomica.api.IBox; import etomica.api.IRandom; import etomica.api.IVectorMutable; import etomica.integrator.mcmove.MCMoveAtom; import etomica.space.ISpace; import etomica.space.IVectorRandom; /** * Extension of MCMoveClusterAtom that moves only the second atom and only * along the x axis. The atom is moved in discrete steps such that its * position is always an integer multiple of the discrete step size. * * @author Andrew Schultz */ public class MCMoveClusterAtomDiscrete extends MCMoveAtom { public MCMoveClusterAtomDiscrete(IRandom random, ISpace _space, double dr) { super(random, null, _space); setStepSize(1.2); setStepSizeMin(2*dr); this.dr = dr; rPow = 0; } public void setBox(IBox p) { super.setBox(p); if (translationVectors == null) { translationVectors = new IVectorRandom[box.getLeafList().getAtomCount()-1]; for (int i=0; i<translationVectors.length; i++) { translationVectors[i] = (IVectorRandom)space.makeVector(); } } } public void setRPow(double newRPow) { rPow = newRPow; } public double getRPow() { return rPow; } public boolean doTrial() { uOld = ((BoxCluster)box).getSampleCluster().value((BoxCluster)box); int imax = (int)Math.ceil(stepSize / dr); int idr = random.nextInt(2*imax) - imax; if (idr >= 0) idr++; IVectorMutable p1 = box.getLeafList().getAtom(1).getPosition(); oldR = p1.getX(0); int iOldR = (int)Math.round(oldR/dr); newR = (iOldR + idr)*dr; p1.setX(0, newR); IAtomList leafAtoms = box.getLeafList(); for(int i=2; i<leafAtoms.getAtomCount(); i++) { translationVectors[i-1].setRandomCube(random); translationVectors[i-1].TE(0.5*stepSize); leafAtoms.getAtom(i).getPosition().PE(translationVectors[i-1]); } ((BoxCluster)box).trialNotify(); uNew = ((BoxCluster)box).getSampleCluster().value((BoxCluster)box); return true; } public double getA() { if (uOld == 0) return Double.POSITIVE_INFINITY; double ratio = uNew/uOld; // if rPow is given, use it (if r=0, we have trouble) if (rPow != 0) ratio *= Math.pow(Math.abs(newR/oldR), rPow); // we need to give r=0 double weight since we visit r=-1 and r=+1 else if (oldR == 0) ratio *= 0.5; else if (newR == 0) ratio *= 2; return ratio; } public double getB() { return 0; } public void rejectNotify() { IVectorMutable p1 = box.getLeafList().getAtom(1).getPosition(); p1.setX(0, oldR); IAtomList leafAtoms = box.getLeafList(); for(int i=2; i<leafAtoms.getAtomCount(); i++) { leafAtoms.getAtom(i).getPosition().ME(translationVectors[i-1]); } ((BoxCluster)box).rejectNotify(); } public void acceptNotify() { ((BoxCluster)box).acceptNotify(); } protected IVectorRandom[] translationVectors; protected double dr, oldR, newR, rPow; }
/* * $Id: JettyManager.java,v 1.15 2004-09-16 21:52:13 tlipkis Exp $ */ package org.lockss.jetty; import java.util.*; import org.lockss.app.*; import org.lockss.util.*; import org.lockss.daemon.*; import org.mortbay.http.*; import org.mortbay.util.Code; /** * Abstract base class for LOCKSS managers that use/start Jetty services. * Note: this class may be used in an environment where the LOCKSS app is * not running (<i>e.g.</i>, for {@link org.lockss.servlet.TinyUi}), so it * must not rely on any non-static app services, nor any other managers. */ public abstract class JettyManager extends BaseLockssManager implements ConfigurableManager { static final String PREFIX = Configuration.PREFIX + "jetty.debug"; static final String PARAM_JETTY_DEBUG = PREFIX; static final boolean DEFAULT_JETTY_DEBUG = false; static final String PARAM_JETTY_DEBUG_PATTERNS = PREFIX + ".patterns"; static final String PARAM_JETTY_DEBUG_VERBOSE = PREFIX + ".verbose"; static final int DEFAULT_JETTY_DEBUG_VERBOSE = 0; // static final String PARAM_JETTY_DEBUG_OPTIONS = PREFIX + ".options"; private static Logger log = Logger.getLogger("JettyMgr"); private static boolean jettyLogInited = false; private static Set portsInUse = Collections.synchronizedSet(new HashSet()); protected HttpServer runningServer; protected int runningOnPort = -1; public JettyManager() { } /** * start the manager. * @see org.lockss.app.LockssManager#startService() */ public void startService() { super.startService(); installJettyLog(); resetConfig(); } // synchronized on class private static synchronized void installJettyLog() { // install Jetty logger once only if (!jettyLogInited) { org.mortbay.util.Log.instance().add(new LoggerLogSink()); jettyLogInited = true; } } // Set Jetty debug properties from config params public void setConfig(Configuration config, Configuration prevConfig, Configuration.Differences changedKeys) { if (jettyLogInited) { if (changedKeys.contains(PARAM_JETTY_DEBUG)) { boolean deb = config.getBoolean(PARAM_JETTY_DEBUG, DEFAULT_JETTY_DEBUG); log.info("Turning Jetty DEBUG " + (deb ? "on." : "off.")); Code.setDebug(deb); } if (changedKeys.contains(PARAM_JETTY_DEBUG_PATTERNS)) { String pat = config.get(PARAM_JETTY_DEBUG_PATTERNS); log.info("Setting Jetty debug patterns to: " + pat); Code.setDebugPatterns(pat); } if (changedKeys.contains(PARAM_JETTY_DEBUG_VERBOSE)) { int ver = config.getInt(PARAM_JETTY_DEBUG_VERBOSE, DEFAULT_JETTY_DEBUG_VERBOSE); log.info("Setting Jetty verbosity to: " + ver); Code.setVerbose(ver); } } } long[] delayTime = {10 * Constants.SECOND, 60 * Constants.SECOND, 0}; protected boolean startServer(HttpServer server, int port) { try { for (int ix = 0; ix < delayTime.length; ix++) { try { server.start(); runningServer = server; runningOnPort(port); return true; } catch (org.mortbay.util.MultiException e) { log.debug("multi", e); log.debug2("first", e.getException(0)); log.warning("Addr in use, sleeping " + StringUtil.timeIntervalToString(delayTime[ix])); Deadline.in(delayTime[ix]).sleep(); } } } catch (Exception e) { log.warning("Couldn't start servlets", e); } return false; } public void stopServer() { try { if (runningServer != null) { runningOnPort(-1); runningServer.stop(); runningServer = null; } } catch (InterruptedException e) { log.warning("Interrupted while stopping server"); } } protected void runningOnPort(int port) { if (log.isDebug2()) { log.debug2("runningOnPort(" + port + "), in use: " + portsInUse); } if (runningOnPort > 0) { portsInUse.remove(new Integer(runningOnPort)); runningOnPort = -1; } if (port > 0) { portsInUse.add(new Integer(port)); runningOnPort = port; } } protected boolean isServerRunning() { return (runningOnPort > 0); } public static boolean isPortInUse(int port) { if (log.isDebug2()) { log.debug2("portsInUse(" + port + ") = " + portsInUse.contains(new Integer(port))); } return portsInUse.contains(new Integer(port)); } }
/* * $Id: DebugPanel.java,v 1.40 2014-03-23 17:11:02 tlipkis Exp $ */ package org.lockss.servlet; import javax.servlet.*; import java.io.*; import java.util.*; import java.sql.Connection; import java.sql.PreparedStatement; import org.mortbay.html.*; import org.lockss.app.*; import org.lockss.util.*; import org.lockss.metadata.MetadataManager; import org.lockss.poller.*; import org.lockss.crawler.*; import org.lockss.state.*; import org.lockss.config.*; import org.lockss.db.DbException; import org.lockss.db.DbManager; import org.lockss.remote.*; import org.lockss.plugin.*; import org.lockss.account.*; /** UI to invoke various daemon actions */ @SuppressWarnings("serial") public class DebugPanel extends LockssServlet { public static final String PREFIX = Configuration.PREFIX + "debugPanel."; /** * Priority for crawls started from the debug panel */ public static final String PARAM_CRAWL_PRIORITY = PREFIX + "crawlPriority"; private static final int DEFAULT_CRAWL_PRIORITY = 10; /** * Priority for crawls started from the debug panel */ public static final String PARAM_ENABLE_DEEP_CRAWL = PREFIX + "deepCrawlEnabled"; private static final boolean DEFAULT_ENABLE_DEEP_CRAWL = false; static final String KEY_ACTION = "action"; static final String KEY_MSG = "msg"; static final String KEY_NAME_SEL = "name_sel"; static final String KEY_NAME_TYPE = "name_type"; static final String KEY_AUID = "auid"; static final String KEY_URL = "url"; static final String KEY_REFETCH_DEPTH = "depth"; static final String ACTION_MAIL_BACKUP = "Mail Backup File"; static final String ACTION_THROW_IOEXCEPTION = "Throw IOException"; static final String ACTION_FIND_URL = "Find Preserved URL"; static final String ACTION_REINDEX_METADATA = "Reindex Metadata"; static final String ACTION_FORCE_REINDEX_METADATA = "Force Reindex Metadata"; static final String ACTION_START_V3_POLL = "Start V3 Poll"; static final String ACTION_FORCE_START_V3_POLL = "Force V3 Poll"; static final String ACTION_START_CRAWL = "Start Crawl"; static final String ACTION_FORCE_START_CRAWL = "Force Start Crawl"; static final String ACTION_START_DEEP_CRAWL = "Deep Crawl"; static final String ACTION_FORCE_START_DEEP_CRAWL = "Force Deep Crawl"; static final String ACTION_CRAWL_PLUGINS = "Crawl Plugins"; static final String ACTION_RELOAD_CONFIG = "Reload Config"; static final String ACTION_DISABLE_METADATA_INDEXING = "Disable Indexing"; /** Set of actions for which audit alerts shouldn't be generated */ static final Set noAuditActions = SetUtil.set(ACTION_FIND_URL); static final String COL2 = "colspan=2"; static final String COL2CENTER = COL2 + " align=center"; static Logger log = Logger.getLogger("DebugPanel"); private LockssDaemon daemon; private PluginManager pluginMgr; private PollManager pollManager; private CrawlManager crawlMgr; private ConfigManager cfgMgr; private DbManager dbMgr; private MetadataManager metadataMgr; private RemoteApi rmtApi; boolean showResult; boolean showForcePoll; boolean showForceCrawl; boolean showForceReindexMetadata; String formAuid; String formDepth = "100"; protected void resetLocals() { resetVars(); super.resetLocals(); } void resetVars() { formAuid = null; errMsg = null; statusMsg = null; showForcePoll = false; showForceCrawl = false; showForceReindexMetadata = false; } public void init(ServletConfig config) throws ServletException { super.init(config); daemon = getLockssDaemon(); pluginMgr = daemon.getPluginManager(); pollManager = daemon.getPollManager(); crawlMgr = daemon.getCrawlManager(); cfgMgr = daemon.getConfigManager(); rmtApi = daemon.getRemoteApi(); try { dbMgr = daemon.getDbManager(); metadataMgr = daemon.getMetadataManager(); } catch (IllegalArgumentException ex) {} } public void lockssHandleRequest() throws IOException { resetVars(); boolean showForm = true; String action = getParameter(KEY_ACTION); if (!StringUtil.isNullString(action)) { formAuid = getParameter(KEY_AUID); formDepth = getParameter(KEY_REFETCH_DEPTH); UserAccount acct = getUserAccount(); if (acct != null && !noAuditActions.contains(action)) { acct.auditableEvent("used debug panel action: " + action + " AU ID: " + formAuid); } } if (ACTION_MAIL_BACKUP.equals(action)) { doMailBackup(); } if (ACTION_RELOAD_CONFIG.equals(action)) { doReloadConfig(); } if (ACTION_THROW_IOEXCEPTION.equals(action)) { doThrow(); } if (ACTION_START_V3_POLL.equals(action)) { doV3Poll(); } if (ACTION_FORCE_START_V3_POLL.equals(action)) { forceV3Poll(); } if (ACTION_START_CRAWL.equals(action)) { doCrawl(false, false); } if (ACTION_FORCE_START_CRAWL.equals(action)) { doCrawl(true, false); } if (ACTION_START_DEEP_CRAWL.equals(action)) { doCrawl(false, true); } if (ACTION_FORCE_START_DEEP_CRAWL.equals(action)) { doCrawl(true, true); } if (ACTION_CRAWL_PLUGINS.equals(action)) { crawlPluginRegistries(); } if (ACTION_FIND_URL.equals(action)) { showForm = doFindUrl(); } if (ACTION_REINDEX_METADATA.equals(action)) { doReindexMetadata(); } if (ACTION_FORCE_REINDEX_METADATA.equals(action)) { forceReindexMetadata(); } if (ACTION_DISABLE_METADATA_INDEXING.equals(action)) { doDisableMetadataIndexing(); } if (showForm) { displayPage(); } } private void doMailBackup() { try { rmtApi.sendMailBackup(); } catch (Exception e) { errMsg = "Error: " + e.getMessage(); } } private void doReloadConfig() { cfgMgr.requestReload(); } private void doThrow() throws IOException { String msg = getParameter(KEY_MSG); throw new IOException(msg != null ? msg : "Test message"); } private void doReindexMetadata() { ArchivalUnit au = getAu(); if (au == null) return; try { startReindexingMetadata(au, false); } catch (RuntimeException e) { log.error("Can't reindex metadata", e); errMsg = "Error: " + e.toString(); } } private void forceReindexMetadata() { ArchivalUnit au = getAu(); if (au == null) return; try { startReindexingMetadata(au, true); } catch (RuntimeException e) { log.error("Can't reindex metadata", e); errMsg = "Error: " + e.toString(); } } private void doDisableMetadataIndexing() { ArchivalUnit au = getAu(); if (au == null) return; try { disableMetadataIndexing(au, false); } catch (RuntimeException e) { log.error("Can't disable metadata indexing", e); errMsg = "Error: " + e.toString(); } } private void doCrawl(boolean force, boolean deep) { ArchivalUnit au = getAu(); if (au == null) return; try { startCrawl(au, force, deep); } catch (CrawlManagerImpl.NotEligibleException.RateLimiter e) { errMsg = "AU has crawled recently (" + e.getMessage() + "). Click again to override."; showForceCrawl = true; return; } catch (CrawlManagerImpl.NotEligibleException e) { errMsg = "Can't enqueue crawl: " + e.getMessage(); } } private void crawlPluginRegistries() { StringBuilder sb = new StringBuilder(); for (ArchivalUnit au : pluginMgr.getAllRegistryAus()) { sb.append(au.getName()); sb.append(": "); try { startCrawl(au, true, false); sb.append("Queued."); } catch (CrawlManagerImpl.NotEligibleException e) { sb.append("Failed: "); sb.append(e.getMessage()); } sb.append("\n"); } statusMsg = sb.toString(); } private boolean startCrawl(ArchivalUnit au, boolean force, boolean deep) throws CrawlManagerImpl.NotEligibleException { CrawlManagerImpl cmi = (CrawlManagerImpl)crawlMgr; if (force) { RateLimiter limit = cmi.getNewContentRateLimiter(au); if (!limit.isEventOk()) { limit.unevent(); } } cmi.checkEligibleToQueueNewContentCrawl(au); String delayMsg = ""; String deepMsg = ""; try { cmi.checkEligibleForNewContentCrawl(au); } catch (CrawlManagerImpl.NotEligibleException e) { delayMsg = ", Start delayed due to: " + e.getMessage(); } Configuration config = ConfigManager.getCurrentConfig(); int pri = config.getInt(PARAM_CRAWL_PRIORITY, DEFAULT_CRAWL_PRIORITY); CrawlReq req; try { req = new CrawlReq(au); req.setPriority(pri); if (deep) { int d = Integer.parseInt(formDepth); if (d < 0) { errMsg = "Illegal refetch depth: " + d; return false; } req.setRefetchDepth(d); deepMsg = "Deep (" + req.getRefetchDepth() + ") "; } } catch (NumberFormatException e) { errMsg = "Illegal refetch depth: " + formDepth; return false; } catch (RuntimeException e) { log.error("Couldn't create CrawlReq: " + au, e); errMsg = "Couldn't create CrawlReq: " + e.toString(); return false; } cmi.startNewContentCrawl(req, null); statusMsg = deepMsg + "Crawl requested for " + au.getName() + delayMsg; return true; } private boolean startReindexingMetadata(ArchivalUnit au, boolean force) { if (metadataMgr == null) { errMsg = "Metadata processing is not enabled."; return false; } if (!force) { if (!AuUtil.hasCrawled(au)) { errMsg = "Au has never crawled. Click again to reindex metadata"; showForceReindexMetadata = true; return false; } AuState auState = AuUtil.getAuState(au); switch (auState.getSubstanceState()) { case No: errMsg = "Au has no substance. Click again to reindex metadata"; showForceReindexMetadata = true; return false; case Unknown: errMsg = "Unknown substance for Au. Click again to reindex metadata."; showForceReindexMetadata = true; return false; case Yes: // fall through } } // fully reindex metadata Connection conn = null; PreparedStatement insertPendingAuBatchStatement = null; try { conn = dbMgr.getConnection(); insertPendingAuBatchStatement = metadataMgr.getInsertPendingAuBatchStatement(conn); if (metadataMgr.enableAndAddAuToReindex(au, conn, insertPendingAuBatchStatement, false, true)) { statusMsg = "Reindexing metadata for " + au.getName(); return true; } } catch (DbException dbe) { log.error("Cannot reindex metadata for " + au.getName(), dbe); } finally { DbManager.safeCloseStatement(insertPendingAuBatchStatement); DbManager.safeRollbackAndClose(conn); } if (force) { errMsg = "Still cannot reindex metadata for " + au.getName(); } else { errMsg = "Cannot reindex metadata for " + au.getName(); } return false; } private boolean disableMetadataIndexing(ArchivalUnit au, boolean force) { if (metadataMgr == null) { errMsg = "Metadata processing is not enabled."; return false; } if (metadataMgr.disableAuIndexing(au)) { statusMsg = "Disabled metadata indexing for " + au.getName(); return true; } errMsg = "Cannot reindex metadata for " + au.getName(); return false; } private void doV3Poll() { ArchivalUnit au = getAu(); if (au == null) return; try { callV3ContentPoll(au); } catch (PollManager.NotEligibleException e) { errMsg = "AU is not eligible for poll: " + e.getMessage(); // errMsg = "Ineligible: " + e.getMessage() + // "<br>Click again to force new poll."; // showForcePoll = true; return; } catch (Exception e) { log.error("Can't start poll", e); errMsg = "Error: " + e.toString(); } } private void forceV3Poll() { ArchivalUnit au = getAu(); if (au == null) return; try { callV3ContentPoll(au); } catch (Exception e) { log.error("Can't start poll", e); errMsg = "Error: " + e.toString(); } } private void callV3ContentPoll(ArchivalUnit au) throws PollManager.NotEligibleException { log.debug("Enqueuing a V3 Content Poll on " + au.getName()); PollSpec spec = new PollSpec(au.getAuCachedUrlSet(), Poll.V3_POLL); pollManager.enqueueHighPriorityPoll(au, spec); statusMsg = "Enqueued V3 poll for " + au.getName(); } private boolean doFindUrl() throws IOException { String url = getParameter(KEY_URL); String redir = srvURL(AdminServletManager.SERVLET_DAEMON_STATUS, PropUtil.fromArgs("table", ArchivalUnitStatus.AUS_WITH_URL_TABLE_NAME, "key", url)); resp.setContentLength(0); // resp.sendRedirect(resp.encodeRedirectURL(redir)); resp.sendRedirect(redir); return false; } ArchivalUnit getAu() { if (StringUtil.isNullString(formAuid)) { errMsg = "Select an AU"; return null; } ArchivalUnit au = pluginMgr.getAuFromId(formAuid); if (au == null) { errMsg = "No such AU. Select an AU"; return null; } return au; } private void displayPage() throws IOException { Page page = newPage(); layoutErrorBlock(page); ServletUtil.layoutExplanationBlock(page, "Debug Actions"); page.add(makeForm()); page.add("<br>"); endPage(page); } private Element makeForm() { Composite comp = new Composite(); Form frm = new Form(srvURL(myServletDescr())); frm.method("POST"); frm.add("<br><center>"); Input reload = new Input(Input.Submit, KEY_ACTION, ACTION_RELOAD_CONFIG); setTabOrder(reload); frm.add(reload); frm.add(" "); Input backup = new Input(Input.Submit, KEY_ACTION, ACTION_MAIL_BACKUP); setTabOrder(backup); frm.add(backup); frm.add(" "); Input crawlplug = new Input(Input.Submit, KEY_ACTION, ACTION_CRAWL_PLUGINS); setTabOrder(crawlplug); frm.add(crawlplug); frm.add("</center>"); ServletDescr d1 = AdminServletManager.SERVLET_HASH_CUS; if (isServletRunnable(d1)) { frm.add("<br><center>"+srvLink(d1, d1.heading)+"</center>"); } Input findUrl = new Input(Input.Submit, KEY_ACTION, ACTION_FIND_URL); Input findUrlText = new Input(Input.Text, KEY_URL); findUrlText.setSize(50); setTabOrder(findUrl); setTabOrder(findUrlText); frm.add("<br><center>"+findUrl+" " + findUrlText + "</center>"); Input thrw = new Input(Input.Submit, KEY_ACTION, ACTION_THROW_IOEXCEPTION); Input thmsg = new Input(Input.Text, KEY_MSG); setTabOrder(thrw); setTabOrder(thmsg); frm.add("<br><center>"+thrw+" " + thmsg + "</center>"); frm.add("<br><center>AU Actions: select AU</center>"); Composite ausel = ServletUtil.layoutSelectAu(this, KEY_AUID, formAuid); frm.add("<br><center>"+ausel+"</center>"); setTabOrder(ausel); Input v3Poll = new Input(Input.Submit, KEY_ACTION, ( showForcePoll ? ACTION_FORCE_START_V3_POLL : ACTION_START_V3_POLL)); Input crawl = new Input(Input.Submit, KEY_ACTION, ( showForceCrawl ? ACTION_FORCE_START_CRAWL : ACTION_START_CRAWL)); frm.add("<br><center>"); frm.add(v3Poll); frm.add(" "); frm.add(crawl); if (metadataMgr != null) { Input reindex = new Input(Input.Submit, KEY_ACTION, ( showForceReindexMetadata ? ACTION_FORCE_REINDEX_METADATA : ACTION_REINDEX_METADATA)); frm.add(" "); frm.add(reindex); Input disableIndexing = new Input(Input.Submit, KEY_ACTION, ACTION_DISABLE_METADATA_INDEXING); frm.add(" "); frm.add(disableIndexing); } frm.add("</center>"); if (CurrentConfig.getBooleanParam(PARAM_ENABLE_DEEP_CRAWL, DEFAULT_ENABLE_DEEP_CRAWL)) { Input deepCrawl = new Input(Input.Submit, KEY_ACTION, ( showForceCrawl ? ACTION_FORCE_START_DEEP_CRAWL : ACTION_START_DEEP_CRAWL)); Input depthText = new Input(Input.Text, KEY_REFETCH_DEPTH, formDepth); depthText.setSize(4); setTabOrder(depthText); frm.add("<br><center>"+deepCrawl+" " + depthText + "</center>"); } comp.add(frm); return comp; } }
package org.myrobotlab.service; import java.io.IOException; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.openni.OpenNiData; import org.myrobotlab.openni.Skeleton; import org.slf4j.Logger; // TODO set pir sensor /** * * Sweety - The sweety robot service. Maintained by \@beetlejuice * */ public class Sweety extends Service { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(Sweety.class); transient public Arduino arduino; transient public WebkitSpeechRecognition ear; transient public WebGui webGui; transient public MarySpeech mouth; transient public Tracking tracker; transient public ProgramAB chatBot; transient public OpenNi openni; transient public Pid pid; transient public Pir pir; transient public HtmlFilter htmlFilter; // Right arm Servomotors transient public Servo rightShoulderServo; transient public Servo rightArmServo; transient public Servo rightBicepsServo; transient public Servo rightElbowServo; transient public Servo rightWristServo; // Left arm Servomotors transient public Servo leftShoulderServo; transient public Servo leftArmServo; transient public Servo leftBicepsServo; transient public Servo leftElbowServo; transient public Servo leftWristServo; // Right hand Servomotors transient public Servo rightThumbServo; transient public Servo rightIndexServo; transient public Servo rightMiddleServo; transient public Servo rightRingServo; transient public Servo rightPinkyServo; // Left hand Servomotors transient public Servo leftThumbServo; transient public Servo leftIndexServo; transient public Servo leftMiddleServo; transient public Servo leftRingServo; transient public Servo leftPinkyServo; // Head Servomotors transient public Servo neckTiltServo; transient public Servo neckPanServo; // Ultrasonic sensors transient public UltrasonicSensor USfront; transient public UltrasonicSensor USfrontRight; transient public UltrasonicSensor USfrontLeft; transient public UltrasonicSensor USback; transient public UltrasonicSensor USbackRight; transient public UltrasonicSensor USbackLeft; boolean copyGesture = false; boolean firstSkeleton = true; boolean saveSkeletonFrame = false; // arduino pins variables int rightMotorDirPin = 2; int rightMotorPwmPin = 3; int leftMotorDirPin = 4; int leftMotorPwmPin = 5; int backUltrasonicTrig = 22; int backUltrasonicEcho = 23; int back_leftUltrasonicTrig = 24; int back_leftUltrasonicEcho = 25; int back_rightUltrasonicTrig = 26; int back_rightUltrasonicEcho = 27; int front_leftUltrasonicTrig = 28; int front_leftUltrasonicEcho = 29; int frontUltrasonicTrig = 30; int frontUltrasonicEcho = 31; int front_rightUltrasonicTrig = 32; int front_rightUltrasonicEcho = 33; int SHIFT = 14; int LATCH = 15; int DATA = 16; int pirSensorPin = 17; int pin = 0; int min = 1; int max = 2; int rest = 3; // TODO Set pins and angles for each servomotors // variable for servomotors ( pin, min, max, rest ) //Right arm int rightShoulder[] = {34,1,2,3}; int rightArm[] = {35,1,2,3}; int rightBiceps[] = {36,1,2,3}; int rightElbow[] = {37,1,2,3}; int rightWrist[] = {38,1,2,3}; // Left arm int leftShoulder[] = {39,1,2,3}; int leftArm[] = {40,1,2,3}; int leftBiceps[] = {41,1,2,3}; int leftElbow[] = {42,1,2,3}; int leftWrist[] = {43,1,2,3}; // Right hand int rightThumb[] = {44,1,2,3}; int rightIndex[] = {45,1,2,3}; int rightMiddle[] = {46,1,2,3}; int rightRing[] = {47,1,2,3}; int rightPinky[] = {48,1,2,3}; // Left hand int leftThumb[] = {8,1,2,3}; int leftIndex[] = {9,1,2,3}; int leftMiddle[] = {10,1,2,3}; int leftRing[] = {11,1,2,3}; int leftPinky[] = {12,1,2,3}; // Head int neckTilt[] = {6,1,2,3}; int neckPan[] = {7,1,2,3}; /** * Check if a value of an array is -1 and if needed replace -1 by the old value * Exemple if rightArm[]={35,1,2,3} and user ask to change by {-1,1,2,3}, this method will return {35,1,2,3} * This method must receive an array of ten arrays. * If one of these arrays is less or more than four numbers length , it doesn't will be changed. */ int[][] changeArrayValues(int[][] valuesArray){ // valuesArray contain in 0,1,2,3,4 the news values and in 5,6,7,8,9 the old values for (int i = 0; i < 5; i++) { if (valuesArray[i].length ==4 ){ for (int j = 0; j < 3; j++) { if (valuesArray[i][j] == -1){ valuesArray[i][j] = valuesArray[i+5][j]; } } } else{ valuesArray[i]=valuesArray[i+5]; } } return valuesArray; } /** * Set pin, min, max, and rest for each servos. -1 mean in an array mean "no change" * Exemple setRightArm({39,1,2,3},{40,1,2,3},{41,1,2,3},{-1,1,2,3},{-1,1,2,3}) * Python exemple : sweety.setRightArm([1,0,180,90],[2,0,180,0],[3,180,90,90],[7,7,4,4],[8,5,8,1]) */ public void setRightArm(int[] shoulder, int[] arm, int[] biceps, int[] elbow, int[] wrist){ int[][] valuesArray = new int[][]{shoulder, arm, biceps, elbow,wrist,rightShoulder,rightArm,rightBiceps,rightElbow,rightWrist}; valuesArray = changeArrayValues(valuesArray); rightShoulder = valuesArray[0]; rightArm = valuesArray[1]; rightBiceps = valuesArray[2]; rightElbow = valuesArray[3]; rightWrist = valuesArray[4]; } /** * Same as setRightArm */ public void setLefttArm(int[] shoulder, int[] arm, int[] biceps, int[] elbow, int[] wrist){ int[][] valuesArray = new int[][]{shoulder, arm, biceps, elbow,wrist,leftShoulder,leftArm,leftBiceps,leftElbow,leftWrist}; valuesArray = changeArrayValues(valuesArray); leftShoulder = valuesArray[0]; leftArm = valuesArray[1]; leftBiceps = valuesArray[2]; leftElbow = valuesArray[3]; leftWrist = valuesArray[4]; } /** * Same as setRightArm */ public void setLeftHand(int[] thumb, int[] index, int[] middle, int[] ring, int[] pinky){ int[][] valuesArray = new int[][]{thumb, index, middle, ring, pinky, leftThumb, leftIndex, leftMiddle, leftRing, leftPinky}; valuesArray = changeArrayValues(valuesArray); leftThumb = valuesArray[0]; leftIndex = valuesArray[1]; leftMiddle = valuesArray[2]; leftRing = valuesArray[3]; leftPinky = valuesArray[4]; } /** * Same as setRightArm */ public void setRightHand(int[] thumb, int[] index, int[] middle, int[] ring, int[] pinky){ int[][] valuesArray = new int[][]{thumb, index, middle, ring, pinky, rightThumb, rightIndex, rightMiddle, rightRing, rightPinky}; valuesArray = changeArrayValues(valuesArray); rightThumb = valuesArray[0]; rightIndex = valuesArray[1]; rightMiddle = valuesArray[2]; rightRing = valuesArray[3]; rightPinky = valuesArray[4]; } // variables for speak / mouth sync public int delaytime = 3; public int delaytimestop = 5; public int delaytimeletter = 1; public static void main(String[] args) { LoggingFactory.init(Level.INFO); try { Runtime.start("sweety", "Sweety"); } catch (Exception e) { Logging.logError(e); } } public Sweety(String n) { super(n); arduino = (Arduino) createPeer("arduino"); chatBot = (ProgramAB) createPeer("chatBot"); htmlFilter = (HtmlFilter) createPeer("htmlFilter"); mouth = (MarySpeech) createPeer("mouth"); ear = (WebkitSpeechRecognition) createPeer("ear"); webGui = (WebGui) createPeer("webGui"); pir = (Pir) createPeer("pir"); } /** * Attach the servos to arduino pins * @throws Exception e */ public void attach() throws Exception { rightElbowServo.attach(arduino, rightElbow[pin]); rightShoulderServo.attach(arduino, rightShoulder[pin]); rightArmServo.attach(arduino, rightArm[pin]); rightBicepsServo.attach(arduino, rightBiceps[pin]); rightElbowServo.attach(arduino, rightElbow[pin]); rightWristServo.attach(arduino, rightWrist[pin]); leftShoulderServo.attach(arduino, leftShoulder[pin]); leftArmServo.attach(arduino, leftArm[pin]); leftBicepsServo.attach(arduino, leftBiceps[pin]); leftElbowServo.attach(arduino, leftElbow[pin]); leftWristServo.attach(arduino, leftWrist[pin]); rightThumbServo.attach(arduino, rightThumb[pin]); rightIndexServo.attach(arduino, rightIndex[pin]); rightMiddleServo.attach(arduino, rightMiddle[pin]); rightRingServo.attach(arduino, rightRing[pin]); rightPinkyServo.attach(arduino, rightPinky[pin]); leftThumbServo.attach(arduino, leftThumb[pin]); leftIndexServo.attach(arduino, leftIndex[pin]); leftMiddleServo.attach(arduino, leftMiddle[pin]); leftRingServo.attach(arduino, leftRing[pin]); leftPinkyServo.attach(arduino, leftPinky[pin]); neckTiltServo.attach(arduino, neckTilt[pin]); neckPanServo.attach(arduino, neckPan[pin]); } /** * Connect the arduino to a COM port . Exemple : connect("COM8") * @param port port * @throws IOException e */ public void connect(String port) throws IOException { arduino.connect(port); sleep(2000); arduino.pinMode(SHIFT, Arduino.OUTPUT); arduino.pinMode(LATCH, Arduino.OUTPUT); arduino.pinMode(DATA, Arduino.OUTPUT); arduino.pinMode(pirSensorPin, Arduino.INPUT); } /** * detach the servos from arduino pins */ public void detach() { rightElbowServo.detach(); rightShoulderServo.detach(); rightArmServo.detach(); rightBicepsServo.detach(); rightElbowServo.detach(); rightWristServo.detach(); leftShoulderServo.detach(); leftArmServo.detach(); leftBicepsServo.detach(); leftElbowServo.detach(); leftWristServo.detach(); rightThumbServo.detach(); rightIndexServo.detach(); rightMiddleServo.detach(); rightRingServo.detach(); rightPinkyServo.detach(); leftThumbServo.detach(); leftIndexServo.detach(); leftMiddleServo.detach(); leftRingServo.detach(); leftPinkyServo.detach(); neckTiltServo.detach(); neckPanServo.detach(); } /** * Move the head . Use : head(neckTiltAngle, neckPanAngle -1 mean * "no change" * @param neckTiltAngle tilt * @param neckPanAngle pan */ public void setHeadPosition(double neckTiltAngle, double neckPanAngle) { if (neckTiltAngle == -1) { neckTiltAngle = neckTiltServo.getPos(); } if (neckPanAngle == -1) { neckPanAngle = neckPanServo.getPos(); } neckTiltServo.moveTo(neckTiltAngle); neckPanServo.moveTo(neckPanAngle); } /** * Move the right arm . Use : setRightArm(shoulder angle, arm angle, biceps angle, * Elbow angle, wrist angle) -1 mean "no change" * @param shoulderAngle s * @param armAngle a * @param bicepsAngle b * @param ElbowAngle f * @param wristAngle w */ public void setRightArmPosition(double shoulderAngle, double armAngle, double bicepsAngle, double ElbowAngle, double wristAngle) { // TODO protect against self collision if (shoulderAngle == -1) { shoulderAngle = rightShoulderServo.getPos(); } if (armAngle == -1) { armAngle = rightArmServo.getPos(); } if (bicepsAngle == -1) { armAngle = rightBicepsServo.getPos(); } if (ElbowAngle == -1) { ElbowAngle = rightElbowServo.getPos(); } if (wristAngle == -1) { wristAngle = rightWristServo.getPos(); } rightShoulderServo.moveTo(shoulderAngle); rightArmServo.moveTo(armAngle); rightBicepsServo.moveTo(bicepsAngle); rightElbowServo.moveTo(ElbowAngle); rightWristServo.moveTo(wristAngle); } /* * Move the left arm . Use : setLeftArm(shoulder angle, arm angle, biceps angle, Elbow angle, * Elbow angle,wrist angle) -1 mean "no change" * @param shoulderAngle s * @param armAngle a * @param bicepsAngle b * @param ElbowAngle f * @param wristAngle w */ public void setLeftArmPosition(double shoulderAngle, double armAngle, double bicepsAngle, double ElbowAngle, double wristAngle) { // TODO protect against self collision with -> servoName.getPos() if (shoulderAngle == -1) { shoulderAngle = leftShoulderServo.getPos(); } if (armAngle == -1) { armAngle = leftArmServo.getPos(); } if (bicepsAngle == -1) { armAngle = leftBicepsServo.getPos(); } if (ElbowAngle == -1) { ElbowAngle = leftElbowServo.getPos(); } if (wristAngle == -1) { wristAngle = leftWristServo.getPos(); } leftShoulderServo.moveTo(shoulderAngle); leftArmServo.moveTo(armAngle); leftBicepsServo.moveTo(bicepsAngle); leftElbowServo.moveTo(ElbowAngle); leftWristServo.moveTo(wristAngle); } /* * Move the left hand . Use : setLeftHand(thumb angle, index angle, middle angle, ring angle, * pinky angle) -1 mean "no change" */ public void setLeftHandPosition(double thumbAngle, double indexAngle, double middleAngle, double ringAngle, double pinkyAngle) { if (thumbAngle == -1) { thumbAngle = leftThumbServo.getPos(); } if (indexAngle == -1) { indexAngle = leftIndexServo.getPos(); } if (middleAngle == -1) { middleAngle = leftMiddleServo.getPos(); } if (ringAngle == -1) { ringAngle = leftRingServo.getPos(); } if (pinkyAngle == -1) { pinkyAngle = leftPinkyServo.getPos(); } leftThumbServo.moveTo(thumbAngle); leftIndexServo.moveTo(indexAngle); leftMiddleServo.moveTo(middleAngle); leftRingServo.moveTo(ringAngle); leftPinkyServo.moveTo(pinkyAngle); } /* * Move the right hand . Use : setrightHand(thumb angle, index angle, middle angle, ring angle, * pinky angle) -1 mean "no change" */ public void setRightHandPosition(double thumbAngle, double indexAngle, double middleAngle, double ringAngle, double pinkyAngle) { if (thumbAngle == -1) { thumbAngle = rightThumbServo.getPos(); } if (indexAngle == -1) { indexAngle = rightIndexServo.getPos(); } if (middleAngle == -1) { middleAngle = rightMiddleServo.getPos(); } if (ringAngle == -1) { ringAngle = rightRingServo.getPos(); } if (pinkyAngle == -1) { pinkyAngle = rightPinkyServo.getPos(); } rightThumbServo.moveTo(thumbAngle); rightIndexServo.moveTo(indexAngle); rightMiddleServo.moveTo(middleAngle); rightRingServo.moveTo(ringAngle); rightPinkyServo.moveTo(pinkyAngle); } /* * Set the mouth attitude . choose : smile, notHappy, speechLess, empty. */ public void mouthState(String value) { if (value == "smile") { myShiftOut("11011100"); } else if (value == "notHappy") { myShiftOut("00111110"); } else if (value == "speechLess") { myShiftOut("10111100"); } else if (value == "empty") { myShiftOut("00000000"); } } /* * drive the motors . Speed &gt; 0 go forward . Speed &lt; 0 go backward . Direction * &gt; 0 go right . Direction &lt; 0 go left */ public void moveMotors(int speed, int direction) { int speedMin = 50; // min PWM needed for the motors boolean isMoving = false; int rightCurrentSpeed = 0; int leftCurrentSpeed = 0; if (speed < 0) { // Go backward arduino.analogWrite(rightMotorDirPin, 0); arduino.analogWrite(leftMotorDirPin, 0); speed = speed * -1; } else {// Go forward arduino.analogWrite(rightMotorDirPin, 255); arduino.analogWrite(leftMotorDirPin, 255); } if (direction > speedMin && speed > speedMin) {// move and turn to the // right if (isMoving) { arduino.analogWrite(rightMotorPwmPin, direction); arduino.analogWrite(leftMotorPwmPin, speed); } else { rightCurrentSpeed = speedMin; leftCurrentSpeed = speedMin; while (rightCurrentSpeed < speed && leftCurrentSpeed < direction) { if (rightCurrentSpeed < direction) { rightCurrentSpeed++; } if (leftCurrentSpeed < speed) { leftCurrentSpeed++; } arduino.analogWrite(rightMotorPwmPin, rightCurrentSpeed); arduino.analogWrite(leftMotorPwmPin, leftCurrentSpeed); sleep(20); } isMoving = true; } } else if (direction < (speedMin * -1) && speed > speedMin) {// move and // turn // the // left direction *= -1; if (isMoving) { arduino.analogWrite(leftMotorPwmPin, direction); arduino.analogWrite(rightMotorPwmPin, speed); } else { rightCurrentSpeed = speedMin; leftCurrentSpeed = speedMin; while (rightCurrentSpeed < speed && leftCurrentSpeed < direction) { if (rightCurrentSpeed < speed) { rightCurrentSpeed++; } if (leftCurrentSpeed < direction) { leftCurrentSpeed++; } arduino.analogWrite(rightMotorPwmPin, rightCurrentSpeed); arduino.analogWrite(leftMotorPwmPin, leftCurrentSpeed); sleep(20); } isMoving = true; } } else if (speed > speedMin) { // Go strait if (isMoving) { arduino.analogWrite(leftMotorPwmPin, speed); arduino.analogWrite(rightMotorPwmPin, speed); } else { int CurrentSpeed = speedMin; while (CurrentSpeed < speed) { CurrentSpeed++; arduino.analogWrite(rightMotorPwmPin, CurrentSpeed); arduino.analogWrite(leftMotorPwmPin, CurrentSpeed); sleep(20); } isMoving = true; } } else if (speed < speedMin && direction < speedMin * -1) {// turn left arduino.analogWrite(rightMotorDirPin, 255); arduino.analogWrite(leftMotorDirPin, 0); arduino.analogWrite(leftMotorPwmPin, speedMin); arduino.analogWrite(rightMotorPwmPin, speedMin); } else if (speed < speedMin && direction > speedMin) {// turn right arduino.analogWrite(rightMotorDirPin, 0); arduino.analogWrite(leftMotorDirPin, 255); arduino.analogWrite(leftMotorPwmPin, speedMin); arduino.analogWrite(rightMotorPwmPin, speedMin); } else {// stop arduino.analogWrite(leftMotorPwmPin, 0); arduino.analogWrite(rightMotorPwmPin, 0); isMoving = false; } } /** * Used to manage a shift register */ private void myShiftOut(String value) { arduino.digitalWrite(LATCH, 0); // Stop the copy for (int i = 0; i < 8; i++) { // Store the data if (value.charAt(i) == '1') { arduino.digitalWrite(DATA, 1); } else { arduino.digitalWrite(DATA, 0); } arduino.digitalWrite(SHIFT, 1); arduino.digitalWrite(SHIFT, 0); } arduino.digitalWrite(LATCH, 1); // copy } /** * Move the servos to show asked posture * @param pos pos */ public void posture(String pos) { if (pos == "rest") { setLeftArmPosition(leftShoulder[rest], leftArm[rest], leftBiceps[rest], leftElbow[rest], leftWrist[rest]); setRightArmPosition(rightShoulder[rest], rightArm[rest], rightBiceps[rest], rightElbow[rest], rightWrist[rest]); setLeftHandPosition(leftThumb[rest], leftIndex[rest], leftMiddle[rest], leftRing[rest], leftPinky[rest]); setRightHandPosition(rightThumb[rest], rightIndex[rest], rightMiddle[rest], rightRing[rest], rightPinky[rest]); setHeadPosition(neckTilt[rest], neckPan[rest]); } /* * Template else if (pos == ""){ setLeftArmPosition(, , , 85, 150); * setRightArmPosition(, , , 116, 10); setHeadPosition(75, 127, 75); } */ // TODO correct angles for posture else if (pos == "yes") { setLeftArmPosition(0, 95, 136, 85, 150); setRightArmPosition(155, 55, 5, 116, 10); setLeftHandPosition(-1, -1, -1, -1, -1); setRightHandPosition(-1, -1, -1, -1, -1); setHeadPosition(75, 85); } else if (pos == "concenter") { setLeftArmPosition(37, 116, 85, 85, 150); setRightArmPosition(109, 43, 54, 116, 10); setLeftHandPosition(-1, -1, -1, -1, -1); setRightHandPosition(-1, -1, -1, -1, -1); setHeadPosition(75, 85); } else if (pos == "showLeft") { setLeftArmPosition(68, 63, 160, 85, 150); setRightArmPosition(2, 76, 40, 116, 10); setLeftHandPosition(-1, -1, -1, -1, -1); setRightHandPosition(-1, -1, -1, -1, -1); setHeadPosition(75, 85); } else if (pos == "showRight") { setLeftArmPosition(145, 79, 93, 85, 150); setRightArmPosition(80, 110, 5, 116, 10); setLeftHandPosition(-1, -1, -1, -1, -1); setRightHandPosition(-1, -1, -1, -1, -1); setHeadPosition(75, 85); } else if (pos == "handsUp") { setLeftArmPosition(0, 79, 93, 85, 150); setRightArmPosition(155, 76, 40, 116, 10); setLeftHandPosition(-1, -1, -1, -1, -1); setRightHandPosition(-1, -1, -1, -1, -1); setHeadPosition(75, 85); } else if (pos == "carryBags") { setLeftArmPosition(145, 79, 93, 85, 150); setRightArmPosition(2, 76, 40, 116, 10); setLeftHandPosition(-1, -1, -1, -1, -1); setRightHandPosition(-1, -1, -1, -1, -1); setHeadPosition(75, 85); } } @Override public Sweety publishState() { super.publishState(); if (arduino != null)arduino.publishState(); if (rightShoulderServo != null)rightShoulderServo.publishState(); if (rightArmServo != null)rightArmServo.publishState(); if (rightBicepsServo != null) rightBicepsServo.publishState(); if (rightElbowServo != null) rightElbowServo.publishState(); if (rightWristServo != null)rightWristServo.publishState(); if (leftShoulderServo != null)leftShoulderServo.publishState(); if (leftArmServo != null)leftArmServo.publishState(); if (leftElbowServo != null)leftElbowServo.publishState(); if (leftBicepsServo != null)leftBicepsServo.publishState(); if (leftWristServo != null)leftWristServo.publishState(); if (rightThumbServo != null)neckTiltServo.publishState(); if (rightIndexServo != null)neckTiltServo.publishState(); if (rightMiddleServo != null)neckTiltServo.publishState(); if (rightRingServo != null)neckTiltServo.publishState(); if (rightPinkyServo != null)neckTiltServo.publishState(); if (leftThumbServo != null)neckTiltServo.publishState(); if (leftIndexServo != null)neckTiltServo.publishState(); if (leftMiddleServo != null)neckTiltServo.publishState(); if (leftRingServo != null)neckTiltServo.publishState(); if (leftPinkyServo != null)neckTiltServo.publishState(); if (neckTiltServo != null)neckTiltServo.publishState(); if (neckPanServo != null)neckPanServo.publishState(); return this; } /** * Say text and move mouth leds * @param text text being said */ public synchronized void saying(String text) { // Adapt mouth leds to words log.info("Saying :" + text); try { mouth.speak(text); } catch (Exception e) { Logging.logError(e); } } public synchronized void onStartSpeaking(String text) { sleep(15); boolean ison = false; String testword; String[] a = text.split(" "); for (int w = 0; w < a.length; w++) { testword = a[w]; char[] c = testword.toCharArray(); for (int x = 0; x < c.length; x++) { char s = c[x]; if ((s == 'a' || s == 'e' || s == 'i' || s == 'o' || s == 'u' || s == 'y') && !ison) { myShiftOut("00011100"); ison = true; sleep(delaytime); myShiftOut("00000100"); } else if (s == '.') { ison = false; myShiftOut("00000000"); sleep(delaytimestop); } else { ison = false; sleep(delaytimeletter); } } } } public synchronized void onEndSpeaking(String utterance) { myShiftOut("00000000"); } public void setdelays(Integer d1, Integer d2, Integer d3) { delaytime = d1; delaytimestop = d2; delaytimeletter = d3; } public void setLanguage(String lang){ mouth.setLanguage(lang); } public void setVoice(String voice){ mouth.setVoice(voice); } @Override public void startService() { super.startService(); arduino = (Arduino) startPeer("arduino"); chatBot = (ProgramAB) startPeer("chatBot"); htmlFilter = (HtmlFilter) startPeer("htmlFilter"); mouth = (MarySpeech) startPeer("mouth"); ear = (WebkitSpeechRecognition) startPeer("ear"); webGui = (WebGui) startPeer("webGui"); pir = (Pir) startPeer("pir"); pir.attach(arduino,pirSensorPin ); subscribe(mouth.getName(), "publishStartSpeaking"); subscribe(mouth.getName(), "publishEndSpeaking"); } public void startServos() { rightShoulderServo = (Servo) startPeer("rightShoulderServo"); rightArmServo = (Servo) startPeer("rightArmServo"); rightBicepsServo = (Servo) startPeer("rightBicepsServo"); rightElbowServo = (Servo) startPeer("rightElbowServo"); rightWristServo = (Servo) startPeer("rightWristServo"); leftShoulderServo = (Servo) startPeer("leftShoulderServo"); leftArmServo = (Servo) startPeer("leftArmServo"); leftBicepsServo = (Servo) startPeer("leftBicepsServo"); leftElbowServo = (Servo) startPeer("leftElbowServo"); leftWristServo = (Servo) startPeer("leftWristServo"); rightThumbServo = (Servo) startPeer("rightThumbServo"); rightIndexServo = (Servo) startPeer("rightIndexServo"); rightMiddleServo = (Servo) startPeer("rightMiddleServo"); rightRingServo = (Servo) startPeer("rightRingServo"); rightPinkyServo = (Servo) startPeer("rightPinkyServo"); leftThumbServo = (Servo) startPeer("leftThumbServo"); leftIndexServo = (Servo) startPeer("leftIndexServo"); leftMiddleServo = (Servo) startPeer("leftMiddleServo"); leftRingServo = (Servo) startPeer("leftRingServo"); leftPinkyServo = (Servo) startPeer("leftPinkyServo"); neckTiltServo = (Servo) startPeer("neckTiltServo"); neckPanServo = (Servo) startPeer("neckPanServo"); rightShoulderServo.setMinMax(rightShoulder[min], rightShoulder[max]); rightArmServo.setMinMax(rightArm[min], rightArm[max]); rightBicepsServo.setMinMax(rightBiceps[min], rightBiceps[max]); rightElbowServo.setMinMax(rightElbow[min], rightElbow[max]); rightWristServo.setMinMax(rightWrist[min], rightWrist[max]); leftShoulderServo.setMinMax(leftShoulder[min], leftShoulder[max]); leftArmServo.setMinMax(leftArm[min], leftArm[max]); leftBicepsServo.setMinMax(leftBiceps[min], leftBiceps[max]); leftElbowServo.setMinMax(leftElbow[min], leftElbow[max]); leftWristServo.setMinMax(leftWrist[min], leftWrist[max]); rightThumbServo.setMinMax(rightThumb[min], rightThumb[max]); rightIndexServo.setMinMax(rightIndex[min], rightIndex[max]); rightMiddleServo.setMinMax(rightMiddle[min], rightMiddle[max]); rightRingServo.setMinMax(rightRing[min], rightRing[max]); rightPinkyServo.setMinMax(rightPinky[min], rightPinky[max]); leftThumbServo.setMinMax(leftThumb[min], leftThumb[max]); leftIndexServo.setMinMax(leftIndex[min], leftIndex[max]); leftMiddleServo.setMinMax(leftMiddle[min], leftMiddle[max]); leftRingServo.setMinMax(leftRing[min], leftRing[max]); leftPinkyServo.setMinMax(leftPinky[min], leftPinky[max]); neckTiltServo.setMinMax(neckTilt[min], neckTilt[max]); neckPanServo.setMinMax(neckPan[min], neckPan[max]); } // TODO modify this function to fit new sweety head public void startTrack(String port, int CameraIndex) throws Exception { neckTiltServo.detach(); neckPanServo.detach(); tracker = (Tracking) startPeer("tracker"); // OLD WAY //leftTracker.y.setPin(39); // neckTilt //leftTracker.connect(port); tracker.connect(port, neckTilt[pin], neckPan[pin]); tracker.pid.invert("y"); tracker.opencv.setCameraIndex(CameraIndex); tracker.opencv.capture(); saying("tracking activated."); } /** * Start the ultrasonic sensors services * Start the tracking services * @param port port * @throws Exception e */ public void startUltraSonic(String port) throws Exception { USfront = (UltrasonicSensor) startPeer("USfront"); USfrontRight = (UltrasonicSensor) startPeer("USfrontRight"); USfrontLeft = (UltrasonicSensor) startPeer("USfrontLeft"); USback = (UltrasonicSensor) startPeer("USback"); USbackRight = (UltrasonicSensor) startPeer("USbackRight"); USbackLeft = (UltrasonicSensor) startPeer("USbackLeft"); USfront.attach(arduino, frontUltrasonicTrig, frontUltrasonicEcho); USfrontRight.attach(arduino, front_rightUltrasonicTrig, front_rightUltrasonicEcho); USfrontLeft.attach(arduino, front_leftUltrasonicTrig, front_leftUltrasonicEcho); USback.attach(arduino, backUltrasonicTrig, backUltrasonicEcho); USbackRight.attach(arduino, back_rightUltrasonicTrig, back_rightUltrasonicEcho); USbackLeft.attach(arduino, back_leftUltrasonicTrig, back_leftUltrasonicEcho); } /** * Stop the tracking services * @throws Exception e */ public void stopTrack() throws Exception { tracker.opencv.stopCapture(); tracker.releaseService(); neckTiltServo.attach(arduino, neckTilt[pin]); neckPanServo.attach(arduino, neckPan[pin]); saying("the tracking if stopped."); } public OpenNi startOpenNI() throws Exception { // TODO modify this function to fit new sweety /* * Start the Kinect service */ if (openni == null) { System.out.println("starting kinect"); openni = (OpenNi) startPeer("openni"); pid = (Pid) startPeer("pid"); pid.setMode("kinect", Pid.MODE_AUTOMATIC); pid.setOutputRange("kinect", -1, 1); pid.setPID("kinect", 10.0, 0.0, 1.0); pid.setControllerDirection("kinect", 0); // re-mapping of skeleton ! // openni.skeleton.leftElbow.mapXY(0, 180, 180, 0); openni.skeleton.rightElbow.mapXY(0, 180, 180, 0); // openni.skeleton.leftShoulder.mapYZ(0, 180, 180, 0); openni.skeleton.rightShoulder.mapYZ(0, 180, 180, 0); openni.skeleton.leftShoulder.mapXY(0, 180, 180, 0); // openni.skeleton.rightShoulder.mapXY(0, 180, 180, 0); openni.addListener("publishOpenNIData", this.getName(), "onOpenNIData"); // openni.addOpenNIData(this); } return openni; } public boolean copyGesture(boolean b) throws Exception { log.info("copyGesture {}", b); if (b) { if (openni == null) { openni = startOpenNI(); } System.out.println("copying gestures"); openni.startUserTracking(); } else { System.out.println("stop copying gestures"); if (openni != null) { openni.stopCapture(); firstSkeleton = true; } } copyGesture = b; return b; } public String captureGesture() { return captureGesture(null); } public String captureGesture(String gestureName) { StringBuffer script = new StringBuffer(); String indentSpace = ""; if (gestureName != null) { indentSpace = " "; script.append(String.format("def %s():\n", gestureName)); } script.append(indentSpace); script.append( String.format("Sweety.setRightArmPosition(%d,%d,%d,%d,%d)\n", rightShoulderServo.getPos(), rightArmServo.getPos(), rightBicepsServo.getPos(), rightElbowServo.getPos(), rightWristServo.getPos())); script.append(indentSpace); script .append(String.format("Sweety.setLeftArmPosition(%d,%d,%d,%d,%d)\n", leftShoulderServo.getPos(), leftArmServo.getPos(), leftBicepsServo.getPos(), leftElbowServo.getPos(), leftWristServo.getPos())); script.append(indentSpace); script.append(String.format("Sweety.setHeadPosition(%d,%d)\n", neckTiltServo.getPos(), neckPanServo.getPos())); send("python", "appendScript", script.toString()); return script.toString(); } public void onOpenNIData(OpenNiData data) { Skeleton skeleton = data.skeleton; if (firstSkeleton) { System.out.println("i see you"); firstSkeleton = false; } // TODO adapt for new design int LElbow = Math.round(skeleton.leftElbow.getAngleXY()) - (180 - leftElbow[max]); int Larm = Math.round(skeleton.leftShoulder.getAngleXY()) - (180 - leftArm[max]); int Lshoulder = Math.round(skeleton.leftShoulder.getAngleYZ()) + leftShoulder[min]; int RElbow = Math.round(skeleton.rightElbow.getAngleXY()) + rightElbow[min]; int Rarm = Math.round(skeleton.rightShoulder.getAngleXY()) + rightArm[min]; int Rshoulder = Math.round(skeleton.rightShoulder.getAngleYZ()) - (180 - rightShoulder[max]); // Move the left side setLeftArmPosition(Lshoulder, Larm, LElbow, -1, -1); // Move the right side setRightArmPosition(Rshoulder, Rarm, RElbow, -1, -1); } /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(Sweety.class.getCanonicalName()); meta.addDescription("service for the Sweety robot"); meta.addCategory("robot"); // put peer definitions in meta.addPeer("arduino", "Arduino", "arduino"); meta.addPeer("mouth", "MarySpeech", "sweetys mouth"); meta.addPeer("ear", "WebkitSpeechRecognition", "ear"); meta.addPeer("chatBot", "ProgramAB", "chatBot"); meta.addPeer("leftTracker", "Tracking", "leftTracker"); meta.addPeer("rightTracker", "Tracking", "rightTracker"); meta.addPeer("htmlFilter", "HtmlFilter", "htmlfilter"); meta.addPeer("webGui", "WebGui", "webGui"); meta.addPeer("USfront", "UltrasonicSensor", "USfront"); meta.addPeer("USfrontRight", "UltrasonicSensor", "USfrontRight"); meta.addPeer("USfrontLeft", "UltrasonicSensor", "USfrontLeft"); meta.addPeer("USback", "UltrasonicSensor", "USback"); meta.addPeer("USbackRight", "UltrasonicSensor", "USbackRight"); meta.addPeer("USbackLeft", "UltrasonicSensor", "USbackLeft"); meta.addPeer("rightShoulder", "Servo", "servo"); meta.addPeer("rightBiceps", "Servo", "servo"); meta.addPeer("rightArm", "Servo", "servo"); meta.addPeer("rightElbow", "Servo", "servo"); meta.addPeer("rightWrist", "Servo", "servo"); meta.addPeer("rightThumb", "Servo", "servo"); meta.addPeer("rightIndex", "Servo", "servo"); meta.addPeer("rightMiddle", "Servo", "servo"); meta.addPeer("rightRing", "Servo", "servo"); meta.addPeer("rightPinky", "Servo", "servo"); meta.addPeer("leftShoulder", "Servo", "servo"); meta.addPeer("leftBiceps", "Servo", "servo"); meta.addPeer("leftArm", "Servo", "servo"); meta.addPeer("leftElbow", "Servo", "servo"); meta.addPeer("leftWrist", "Servo", "servo"); meta.addPeer("leftThumb", "Servo", "servo"); meta.addPeer("leftIndex", "Servo", "servo"); meta.addPeer("leftMiddle", "Servo", "servo"); meta.addPeer("leftRing", "Servo", "servo"); meta.addPeer("leftPinky", "Servo", "servo"); meta.addPeer("neckTilt", "Servo", "servo"); meta.addPeer("neckPan", "Servo", "servo"); meta.addPeer("openni", "OpenNi", "openni"); meta.addPeer("pid", "Pid", "pid"); meta.addPeer("pir", "Pir", "pir"); return meta; } }
package org.myrobotlab.service; import java.io.IOException; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.openni.OpenNiData; import org.myrobotlab.openni.Skeleton; import org.slf4j.Logger; // TODO set pir sensor /** * * Sweety - The sweety robot service. Maintained by \@beetlejuice * */ public class Sweety extends Service { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(Sweety.class); transient public Arduino arduino; transient public WebkitSpeechRecognition ear; transient public WebGui webGui; transient public MarySpeech mouth; transient public Tracking tracker; transient public ProgramAB chatBot; transient public OpenNi openni; transient public Pid pid; transient public Pir pir; transient public HtmlFilter htmlFilter; // Right arm Servomotors transient public Servo rightShoulderServo; transient public Servo rightArmServo; transient public Servo rightBicepsServo; transient public Servo rightElbowServo; transient public Servo rightWristServo; // Left arm Servomotors transient public Servo leftShoulderServo; transient public Servo leftArmServo; transient public Servo leftBicepsServo; transient public Servo leftElbowServo; transient public Servo leftWristServo; // Right hand Servomotors transient public Servo rightThumbServo; transient public Servo rightIndexServo; transient public Servo rightMiddleServo; transient public Servo rightRingServo; transient public Servo rightPinkyServo; // Left hand Servomotors transient public Servo leftThumbServo; transient public Servo leftIndexServo; transient public Servo leftMiddleServo; transient public Servo leftRingServo; transient public Servo leftPinkyServo; // Head Servomotors transient public Servo neckTiltServo; transient public Servo neckPanServo; // Ultrasonic sensors transient public UltrasonicSensor USfront; transient public UltrasonicSensor USfrontRight; transient public UltrasonicSensor USfrontLeft; transient public UltrasonicSensor USback; transient public UltrasonicSensor USbackRight; transient public UltrasonicSensor USbackLeft; boolean copyGesture = false; boolean firstSkeleton = true; boolean saveSkeletonFrame = false; // arduino pins variables int rightMotorDirPin = 2; int rightMotorPwmPin = 3; int leftMotorDirPin = 4; int leftMotorPwmPin = 5; int backUltrasonicTrig = 22; int backUltrasonicEcho = 23; int back_leftUltrasonicTrig = 24; int back_leftUltrasonicEcho = 25; int back_rightUltrasonicTrig = 26; int back_rightUltrasonicEcho = 27; int front_leftUltrasonicTrig = 28; int front_leftUltrasonicEcho = 29; int frontUltrasonicTrig = 30; int frontUltrasonicEcho = 31; int front_rightUltrasonicTrig = 32; int front_rightUltrasonicEcho = 33; int SHIFT = 14; int LATCH = 15; int DATA = 16; int pirSensorPin = 17; int pin = 0; int min = 1; int max = 2; int rest = 3; // TODO Set pins and angles for each servomotors // variable for servomotors ( pin, min, max, rest ) //Right arm int rightShoulder[] = {34,1,2,3}; int rightArm[] = {35,1,2,3}; int rightBiceps[] = {36,1,2,3}; int rightElbow[] = {37,1,2,3}; int rightWrist[] = {38,1,2,3}; // Left arm int leftShoulder[] = {39,1,2,3}; int leftArm[] = {40,1,2,3}; int leftBiceps[] = {41,1,2,3}; int leftElbow[] = {42,1,2,3}; int leftWrist[] = {43,1,2,3}; // Right hand int rightThumb[] = {44,1,2,3}; int rightIndex[] = {45,1,2,3}; int rightMiddle[] = {46,1,2,3}; int rightRing[] = {47,1,2,3}; int rightPinky[] = {48,1,2,3}; // Left hand int leftThumb[] = {8,1,2,3}; int leftIndex[] = {9,1,2,3}; int leftMiddle[] = {10,1,2,3}; int leftRing[] = {11,1,2,3}; int leftPinky[] = {12,1,2,3}; // Head int neckTilt[] = {6,1,2,3}; int neckPan[] = {7,1,2,3}; /** * Check if a value of an array is -1 and if needed replace -1 by the old value * Exemple if rightArm[]={35,1,2,3} and user ask to change by {-1,1,2,3}, this method will return {35,1,2,3} * This method must receive an array of ten arrays. * If one of these arrays is less or more than four numbers length , it doesn't will be changed. */ int[][] changeArrayValues(int[][] valuesArray){ // valuesArray contain first the news values and after the old values for (int i = 0; i < (valuesArray.length / 2 ); i++) { if (valuesArray[i].length ==4 ){ for (int j = 0; j < 3; j++) { if (valuesArray[i][j] == -1){ valuesArray[i][j] = valuesArray[i+5][j]; } } } else{ valuesArray[i]=valuesArray[i+(valuesArray.length / 2 )]; } } return valuesArray; } /** * Set pin, min, max, and rest for each servos. -1 mean in an array mean "no change" * Exemple setRightArm({39,1,2,3},{40,1,2,3},{41,1,2,3},{-1,1,2,3},{-1,1,2,3}) * Python exemple : sweety.setRightArm([1,0,180,90],[2,0,180,0],[3,180,90,90],[7,7,4,4],[8,5,8,1]) */ public void setRightArm(int[] shoulder, int[] arm, int[] biceps, int[] elbow, int[] wrist){ int[][] valuesArray = new int[][]{shoulder, arm, biceps, elbow,wrist,rightShoulder,rightArm,rightBiceps,rightElbow,rightWrist}; valuesArray = changeArrayValues(valuesArray); rightShoulder = valuesArray[0]; rightArm = valuesArray[1]; rightBiceps = valuesArray[2]; rightElbow = valuesArray[3]; rightWrist = valuesArray[4]; } /** * Same as setRightArm */ public void setLefttArm(int[] shoulder, int[] arm, int[] biceps, int[] elbow, int[] wrist){ int[][] valuesArray = new int[][]{shoulder, arm, biceps, elbow,wrist,leftShoulder,leftArm,leftBiceps,leftElbow,leftWrist}; valuesArray = changeArrayValues(valuesArray); leftShoulder = valuesArray[0]; leftArm = valuesArray[1]; leftBiceps = valuesArray[2]; leftElbow = valuesArray[3]; leftWrist = valuesArray[4]; } /** * Same as setRightArm */ public void setLeftHand(int[] thumb, int[] index, int[] middle, int[] ring, int[] pinky){ int[][] valuesArray = new int[][]{thumb, index, middle, ring, pinky, leftThumb, leftIndex, leftMiddle, leftRing, leftPinky}; valuesArray = changeArrayValues(valuesArray); leftThumb = valuesArray[0]; leftIndex = valuesArray[1]; leftMiddle = valuesArray[2]; leftRing = valuesArray[3]; leftPinky = valuesArray[4]; } /** * Same as setRightArm */ public void setRightHand(int[] thumb, int[] index, int[] middle, int[] ring, int[] pinky){ int[][] valuesArray = new int[][]{thumb, index, middle, ring, pinky, rightThumb, rightIndex, rightMiddle, rightRing, rightPinky}; valuesArray = changeArrayValues(valuesArray); rightThumb = valuesArray[0]; rightIndex = valuesArray[1]; rightMiddle = valuesArray[2]; rightRing = valuesArray[3]; rightPinky = valuesArray[4]; } /** * Set pin, min, max, and rest for each servos. -1 mean in an array mean "no change" * Exemple setNeck({39,1,2,3},{40,1,2,3}) * Python exemple : sweety.setNeck([1,0,180,90],[2,0,180,0]) */ public void setHead(int[] tilt, int[] pan){ int[][] valuesArray = new int[][]{tilt, pan,neckTilt,neckPan}; valuesArray = changeArrayValues(valuesArray); neckTilt = valuesArray[0]; neckPan = valuesArray[1]; } // variables for speak / mouth sync public int delaytime = 3; public int delaytimestop = 5; public int delaytimeletter = 1; public static void main(String[] args) { LoggingFactory.init(Level.INFO); try { Runtime.start("sweety", "Sweety"); } catch (Exception e) { Logging.logError(e); } } public Sweety(String n) { super(n); } /** * Attach the servos to arduino pins * @throws Exception e */ public void attach() throws Exception { rightElbowServo.attach(arduino, rightElbow[pin]); rightShoulderServo.attach(arduino, rightShoulder[pin]); rightArmServo.attach(arduino, rightArm[pin]); rightBicepsServo.attach(arduino, rightBiceps[pin]); rightElbowServo.attach(arduino, rightElbow[pin]); rightWristServo.attach(arduino, rightWrist[pin]); leftShoulderServo.attach(arduino, leftShoulder[pin]); leftArmServo.attach(arduino, leftArm[pin]); leftBicepsServo.attach(arduino, leftBiceps[pin]); leftElbowServo.attach(arduino, leftElbow[pin]); leftWristServo.attach(arduino, leftWrist[pin]); rightThumbServo.attach(arduino, rightThumb[pin]); rightIndexServo.attach(arduino, rightIndex[pin]); rightMiddleServo.attach(arduino, rightMiddle[pin]); rightRingServo.attach(arduino, rightRing[pin]); rightPinkyServo.attach(arduino, rightPinky[pin]); leftThumbServo.attach(arduino, leftThumb[pin]); leftIndexServo.attach(arduino, leftIndex[pin]); leftMiddleServo.attach(arduino, leftMiddle[pin]); leftRingServo.attach(arduino, leftRing[pin]); leftPinkyServo.attach(arduino, leftPinky[pin]); neckTiltServo.attach(arduino, neckTilt[pin]); neckPanServo.attach(arduino, neckPan[pin]); } /** * Connect the arduino to a COM port . Exemple : connect("COM8") * @param port port * @throws IOException e */ public void connect(String port) throws IOException { arduino.connect(port); sleep(2000); arduino.pinMode(SHIFT, Arduino.OUTPUT); arduino.pinMode(LATCH, Arduino.OUTPUT); arduino.pinMode(DATA, Arduino.OUTPUT); arduino.pinMode(pirSensorPin, Arduino.INPUT); } /** * detach the servos from arduino pins */ public void detach() { rightElbowServo.detach(); rightShoulderServo.detach(); rightArmServo.detach(); rightBicepsServo.detach(); rightElbowServo.detach(); rightWristServo.detach(); leftShoulderServo.detach(); leftArmServo.detach(); leftBicepsServo.detach(); leftElbowServo.detach(); leftWristServo.detach(); rightThumbServo.detach(); rightIndexServo.detach(); rightMiddleServo.detach(); rightRingServo.detach(); rightPinkyServo.detach(); leftThumbServo.detach(); leftIndexServo.detach(); leftMiddleServo.detach(); leftRingServo.detach(); leftPinkyServo.detach(); neckTiltServo.detach(); neckPanServo.detach(); } /** * Move the head . Use : head(neckTiltAngle, neckPanAngle -1 mean * "no change" * @param neckTiltAngle tilt * @param neckPanAngle pan */ public void setHeadPosition(double neckTiltAngle, double neckPanAngle) { if (neckTiltAngle == -1) { neckTiltAngle = neckTiltServo.getPos(); } if (neckPanAngle == -1) { neckPanAngle = neckPanServo.getPos(); } neckTiltServo.moveTo(neckTiltAngle); neckPanServo.moveTo(neckPanAngle); } /** * Move the right arm . Use : setRightArm(shoulder angle, arm angle, biceps angle, * Elbow angle, wrist angle) -1 mean "no change" * @param shoulderAngle s * @param armAngle a * @param bicepsAngle b * @param ElbowAngle f * @param wristAngle w */ public void setRightArmPosition(double shoulderAngle, double armAngle, double bicepsAngle, double ElbowAngle, double wristAngle) { // TODO protect against self collision if (shoulderAngle == -1) { shoulderAngle = rightShoulderServo.getPos(); } if (armAngle == -1) { armAngle = rightArmServo.getPos(); } if (bicepsAngle == -1) { armAngle = rightBicepsServo.getPos(); } if (ElbowAngle == -1) { ElbowAngle = rightElbowServo.getPos(); } if (wristAngle == -1) { wristAngle = rightWristServo.getPos(); } rightShoulderServo.moveTo(shoulderAngle); rightArmServo.moveTo(armAngle); rightBicepsServo.moveTo(bicepsAngle); rightElbowServo.moveTo(ElbowAngle); rightWristServo.moveTo(wristAngle); } /* * Move the left arm . Use : setLeftArm(shoulder angle, arm angle, biceps angle, Elbow angle, * Elbow angle,wrist angle) -1 mean "no change" * @param shoulderAngle s * @param armAngle a * @param bicepsAngle b * @param ElbowAngle f * @param wristAngle w */ public void setLeftArmPosition(double shoulderAngle, double armAngle, double bicepsAngle, double ElbowAngle, double wristAngle) { // TODO protect against self collision with -> servoName.getPos() if (shoulderAngle == -1) { shoulderAngle = leftShoulderServo.getPos(); } if (armAngle == -1) { armAngle = leftArmServo.getPos(); } if (bicepsAngle == -1) { armAngle = leftBicepsServo.getPos(); } if (ElbowAngle == -1) { ElbowAngle = leftElbowServo.getPos(); } if (wristAngle == -1) { wristAngle = leftWristServo.getPos(); } leftShoulderServo.moveTo(shoulderAngle); leftArmServo.moveTo(armAngle); leftBicepsServo.moveTo(bicepsAngle); leftElbowServo.moveTo(ElbowAngle); leftWristServo.moveTo(wristAngle); } /* * Move the left hand . Use : setLeftHand(thumb angle, index angle, middle angle, ring angle, * pinky angle) -1 mean "no change" */ public void setLeftHandPosition(double thumbAngle, double indexAngle, double middleAngle, double ringAngle, double pinkyAngle) { if (thumbAngle == -1) { thumbAngle = leftThumbServo.getPos(); } if (indexAngle == -1) { indexAngle = leftIndexServo.getPos(); } if (middleAngle == -1) { middleAngle = leftMiddleServo.getPos(); } if (ringAngle == -1) { ringAngle = leftRingServo.getPos(); } if (pinkyAngle == -1) { pinkyAngle = leftPinkyServo.getPos(); } leftThumbServo.moveTo(thumbAngle); leftIndexServo.moveTo(indexAngle); leftMiddleServo.moveTo(middleAngle); leftRingServo.moveTo(ringAngle); leftPinkyServo.moveTo(pinkyAngle); } /* * Move the right hand . Use : setrightHand(thumb angle, index angle, middle angle, ring angle, * pinky angle) -1 mean "no change" */ public void setRightHandPosition(double thumbAngle, double indexAngle, double middleAngle, double ringAngle, double pinkyAngle) { if (thumbAngle == -1) { thumbAngle = rightThumbServo.getPos(); } if (indexAngle == -1) { indexAngle = rightIndexServo.getPos(); } if (middleAngle == -1) { middleAngle = rightMiddleServo.getPos(); } if (ringAngle == -1) { ringAngle = rightRingServo.getPos(); } if (pinkyAngle == -1) { pinkyAngle = rightPinkyServo.getPos(); } rightThumbServo.moveTo(thumbAngle); rightIndexServo.moveTo(indexAngle); rightMiddleServo.moveTo(middleAngle); rightRingServo.moveTo(ringAngle); rightPinkyServo.moveTo(pinkyAngle); } /* * Set the mouth attitude . choose : smile, notHappy, speechLess, empty. */ public void mouthState(String value) { if (value == "smile") { myShiftOut("11011100"); } else if (value == "notHappy") { myShiftOut("00111110"); } else if (value == "speechLess") { myShiftOut("10111100"); } else if (value == "empty") { myShiftOut("00000000"); } } /* * drive the motors . Speed &gt; 0 go forward . Speed &lt; 0 go backward . Direction * &gt; 0 go right . Direction &lt; 0 go left */ public void moveMotors(int speed, int direction) { int speedMin = 50; // min PWM needed for the motors boolean isMoving = false; int rightCurrentSpeed = 0; int leftCurrentSpeed = 0; if (speed < 0) { // Go backward arduino.analogWrite(rightMotorDirPin, 0); arduino.analogWrite(leftMotorDirPin, 0); speed = speed * -1; } else {// Go forward arduino.analogWrite(rightMotorDirPin, 255); arduino.analogWrite(leftMotorDirPin, 255); } if (direction > speedMin && speed > speedMin) {// move and turn to the // right if (isMoving) { arduino.analogWrite(rightMotorPwmPin, direction); arduino.analogWrite(leftMotorPwmPin, speed); } else { rightCurrentSpeed = speedMin; leftCurrentSpeed = speedMin; while (rightCurrentSpeed < speed && leftCurrentSpeed < direction) { if (rightCurrentSpeed < direction) { rightCurrentSpeed++; } if (leftCurrentSpeed < speed) { leftCurrentSpeed++; } arduino.analogWrite(rightMotorPwmPin, rightCurrentSpeed); arduino.analogWrite(leftMotorPwmPin, leftCurrentSpeed); sleep(20); } isMoving = true; } } else if (direction < (speedMin * -1) && speed > speedMin) {// move and // turn // the // left direction *= -1; if (isMoving) { arduino.analogWrite(leftMotorPwmPin, direction); arduino.analogWrite(rightMotorPwmPin, speed); } else { rightCurrentSpeed = speedMin; leftCurrentSpeed = speedMin; while (rightCurrentSpeed < speed && leftCurrentSpeed < direction) { if (rightCurrentSpeed < speed) { rightCurrentSpeed++; } if (leftCurrentSpeed < direction) { leftCurrentSpeed++; } arduino.analogWrite(rightMotorPwmPin, rightCurrentSpeed); arduino.analogWrite(leftMotorPwmPin, leftCurrentSpeed); sleep(20); } isMoving = true; } } else if (speed > speedMin) { // Go strait if (isMoving) { arduino.analogWrite(leftMotorPwmPin, speed); arduino.analogWrite(rightMotorPwmPin, speed); } else { int CurrentSpeed = speedMin; while (CurrentSpeed < speed) { CurrentSpeed++; arduino.analogWrite(rightMotorPwmPin, CurrentSpeed); arduino.analogWrite(leftMotorPwmPin, CurrentSpeed); sleep(20); } isMoving = true; } } else if (speed < speedMin && direction < speedMin * -1) {// turn left arduino.analogWrite(rightMotorDirPin, 255); arduino.analogWrite(leftMotorDirPin, 0); arduino.analogWrite(leftMotorPwmPin, speedMin); arduino.analogWrite(rightMotorPwmPin, speedMin); } else if (speed < speedMin && direction > speedMin) {// turn right arduino.analogWrite(rightMotorDirPin, 0); arduino.analogWrite(leftMotorDirPin, 255); arduino.analogWrite(leftMotorPwmPin, speedMin); arduino.analogWrite(rightMotorPwmPin, speedMin); } else {// stop arduino.analogWrite(leftMotorPwmPin, 0); arduino.analogWrite(rightMotorPwmPin, 0); isMoving = false; } } /** * Used to manage a shift register */ private void myShiftOut(String value) { arduino.digitalWrite(LATCH, 0); // Stop the copy for (int i = 0; i < 8; i++) { // Store the data if (value.charAt(i) == '1') { arduino.digitalWrite(DATA, 1); } else { arduino.digitalWrite(DATA, 0); } arduino.digitalWrite(SHIFT, 1); arduino.digitalWrite(SHIFT, 0); } arduino.digitalWrite(LATCH, 1); // copy } /** * Move the servos to show asked posture * @param pos pos */ public void posture(String pos) { if (pos == "rest") { setLeftArmPosition(leftShoulder[rest], leftArm[rest], leftBiceps[rest], leftElbow[rest], leftWrist[rest]); setRightArmPosition(rightShoulder[rest], rightArm[rest], rightBiceps[rest], rightElbow[rest], rightWrist[rest]); setLeftHandPosition(leftThumb[rest], leftIndex[rest], leftMiddle[rest], leftRing[rest], leftPinky[rest]); setRightHandPosition(rightThumb[rest], rightIndex[rest], rightMiddle[rest], rightRing[rest], rightPinky[rest]); setHeadPosition(neckTilt[rest], neckPan[rest]); } /* * Template else if (pos == ""){ setLeftArmPosition(, , , 85, 150); * setRightArmPosition(, , , 116, 10); setHeadPosition(75, 127, 75); } */ // TODO correct angles for posture else if (pos == "yes") { setLeftArmPosition(0, 95, 136, 85, 150); setRightArmPosition(155, 55, 5, 116, 10); setLeftHandPosition(-1, -1, -1, -1, -1); setRightHandPosition(-1, -1, -1, -1, -1); setHeadPosition(75, 85); } else if (pos == "concenter") { setLeftArmPosition(37, 116, 85, 85, 150); setRightArmPosition(109, 43, 54, 116, 10); setLeftHandPosition(-1, -1, -1, -1, -1); setRightHandPosition(-1, -1, -1, -1, -1); setHeadPosition(75, 85); } else if (pos == "showLeft") { setLeftArmPosition(68, 63, 160, 85, 150); setRightArmPosition(2, 76, 40, 116, 10); setLeftHandPosition(-1, -1, -1, -1, -1); setRightHandPosition(-1, -1, -1, -1, -1); setHeadPosition(75, 85); } else if (pos == "showRight") { setLeftArmPosition(145, 79, 93, 85, 150); setRightArmPosition(80, 110, 5, 116, 10); setLeftHandPosition(-1, -1, -1, -1, -1); setRightHandPosition(-1, -1, -1, -1, -1); setHeadPosition(75, 85); } else if (pos == "handsUp") { setLeftArmPosition(0, 79, 93, 85, 150); setRightArmPosition(155, 76, 40, 116, 10); setLeftHandPosition(-1, -1, -1, -1, -1); setRightHandPosition(-1, -1, -1, -1, -1); setHeadPosition(75, 85); } else if (pos == "carryBags") { setLeftArmPosition(145, 79, 93, 85, 150); setRightArmPosition(2, 76, 40, 116, 10); setLeftHandPosition(-1, -1, -1, -1, -1); setRightHandPosition(-1, -1, -1, -1, -1); setHeadPosition(75, 85); } } @Override public Sweety publishState() { super.publishState(); if (arduino != null)arduino.publishState(); if (rightShoulderServo != null)rightShoulderServo.publishState(); if (rightArmServo != null)rightArmServo.publishState(); if (rightBicepsServo != null) rightBicepsServo.publishState(); if (rightElbowServo != null) rightElbowServo.publishState(); if (rightWristServo != null)rightWristServo.publishState(); if (leftShoulderServo != null)leftShoulderServo.publishState(); if (leftArmServo != null)leftArmServo.publishState(); if (leftElbowServo != null)leftElbowServo.publishState(); if (leftBicepsServo != null)leftBicepsServo.publishState(); if (leftWristServo != null)leftWristServo.publishState(); if (rightThumbServo != null)neckTiltServo.publishState(); if (rightIndexServo != null)neckTiltServo.publishState(); if (rightMiddleServo != null)neckTiltServo.publishState(); if (rightRingServo != null)neckTiltServo.publishState(); if (rightPinkyServo != null)neckTiltServo.publishState(); if (leftThumbServo != null)neckTiltServo.publishState(); if (leftIndexServo != null)neckTiltServo.publishState(); if (leftMiddleServo != null)neckTiltServo.publishState(); if (leftRingServo != null)neckTiltServo.publishState(); if (leftPinkyServo != null)neckTiltServo.publishState(); if (neckTiltServo != null)neckTiltServo.publishState(); if (neckPanServo != null)neckPanServo.publishState(); return this; } /** * Say text and move mouth leds * @param text text being said */ public synchronized void saying(String text) { // Adapt mouth leds to words log.info("Saying :" + text); try { mouth.speak(text); } catch (Exception e) { Logging.logError(e); } } public synchronized void onStartSpeaking(String text) { sleep(15); boolean ison = false; String testword; String[] a = text.split(" "); for (int w = 0; w < a.length; w++) { testword = a[w]; char[] c = testword.toCharArray(); for (int x = 0; x < c.length; x++) { char s = c[x]; if ((s == 'a' || s == 'e' || s == 'i' || s == 'o' || s == 'u' || s == 'y') && !ison) { myShiftOut("00011100"); ison = true; sleep(delaytime); myShiftOut("00000100"); } else if (s == '.') { ison = false; myShiftOut("00000000"); sleep(delaytimestop); } else { ison = false; sleep(delaytimeletter); } } } } public synchronized void onEndSpeaking(String utterance) { myShiftOut("00000000"); } public void setdelays(Integer d1, Integer d2, Integer d3) { delaytime = d1; delaytimestop = d2; delaytimeletter = d3; } public void setLanguage(String lang){ mouth.setLanguage(lang); } public void setVoice(String voice){ mouth.setVoice(voice); } @Override public void startService() { super.startService(); arduino = (Arduino) Runtime.start("arduino","Arduino"); chatBot = (ProgramAB) Runtime.start("chatBot","ProgramAB"); htmlFilter = (HtmlFilter) Runtime.start("htmlFilter","HtmlFilter"); mouth = (MarySpeech) Runtime.start("mouth","MarySpeech"); ear = (WebkitSpeechRecognition) Runtime.start("ear","WebkitSpeechRecognition"); webGui = (WebGui) Runtime.start("webGui","WebGui"); pir = (Pir) Runtime.start("pir","Pir"); // configure services pir.attach(arduino,pirSensorPin ); // FIXME - there is likely an "attach" that does this... subscribe(mouth.getName(), "publishStartSpeaking"); subscribe(mouth.getName(), "publishEndSpeaking"); } public void startServos() { rightShoulderServo = (Servo) Runtime.start("rightShoulderServo","Servo"); rightArmServo = (Servo) Runtime.start("rightArmServo","Servo"); rightBicepsServo = (Servo) Runtime.start("rightBicepsServo","Servo"); rightElbowServo = (Servo) Runtime.start("rightElbowServo","Servo"); rightWristServo = (Servo) Runtime.start("rightWristServo","Servo"); leftShoulderServo = (Servo) Runtime.start("leftShoulderServo","Servo"); leftArmServo = (Servo) Runtime.start("leftArmServo","Servo"); leftBicepsServo = (Servo) Runtime.start("leftBicepsServo","Servo"); leftElbowServo = (Servo) Runtime.start("leftElbowServo","Servo"); leftWristServo = (Servo) Runtime.start("leftWristServo","Servo"); rightThumbServo = (Servo) Runtime.start("rightThumbServo","Servo"); rightIndexServo = (Servo) Runtime.start("rightIndexServo","Servo"); rightMiddleServo = (Servo) Runtime.start("rightMiddleServo","Servo"); rightRingServo = (Servo) Runtime.start("rightRingServo","Servo"); rightPinkyServo = (Servo) Runtime.start("rightPinkyServo","Servo"); leftThumbServo = (Servo) Runtime.start("leftThumbServo","Servo"); leftIndexServo = (Servo) Runtime.start("leftIndexServo","Servo"); leftMiddleServo = (Servo) Runtime.start("leftMiddleServo","Servo"); leftRingServo = (Servo) Runtime.start("leftRingServo","Servo"); leftPinkyServo = (Servo) Runtime.start("leftPinkyServo","Servo"); neckTiltServo = (Servo) Runtime.start("neckTiltServo","Servo"); neckPanServo = (Servo) Runtime.start("neckPanServo","Servo"); rightShoulderServo.setMinMax(rightShoulder[min], rightShoulder[max]); rightArmServo.setMinMax(rightArm[min], rightArm[max]); rightBicepsServo.setMinMax(rightBiceps[min], rightBiceps[max]); rightElbowServo.setMinMax(rightElbow[min], rightElbow[max]); rightWristServo.setMinMax(rightWrist[min], rightWrist[max]); leftShoulderServo.setMinMax(leftShoulder[min], leftShoulder[max]); leftArmServo.setMinMax(leftArm[min], leftArm[max]); leftBicepsServo.setMinMax(leftBiceps[min], leftBiceps[max]); leftElbowServo.setMinMax(leftElbow[min], leftElbow[max]); leftWristServo.setMinMax(leftWrist[min], leftWrist[max]); rightThumbServo.setMinMax(rightThumb[min], rightThumb[max]); rightIndexServo.setMinMax(rightIndex[min], rightIndex[max]); rightMiddleServo.setMinMax(rightMiddle[min], rightMiddle[max]); rightRingServo.setMinMax(rightRing[min], rightRing[max]); rightPinkyServo.setMinMax(rightPinky[min], rightPinky[max]); leftThumbServo.setMinMax(leftThumb[min], leftThumb[max]); leftIndexServo.setMinMax(leftIndex[min], leftIndex[max]); leftMiddleServo.setMinMax(leftMiddle[min], leftMiddle[max]); leftRingServo.setMinMax(leftRing[min], leftRing[max]); leftPinkyServo.setMinMax(leftPinky[min], leftPinky[max]); neckTiltServo.setMinMax(neckTilt[min], neckTilt[max]); neckPanServo.setMinMax(neckPan[min], neckPan[max]); } // TODO modify this function to fit new sweety head public void startTrack(String port, int CameraIndex) throws Exception { neckTiltServo.detach(); neckPanServo.detach(); tracker = (Tracking) Runtime.start("tracker","Tracking"); // OLD WAY //leftTracker.y.setPin(39); // neckTilt //leftTracker.connect(port); tracker.connect(port, neckTilt[pin], neckPan[pin]); tracker.pid.invert("y"); tracker.opencv.setCameraIndex(CameraIndex); tracker.opencv.capture(); saying("tracking activated."); } /** * Start the ultrasonic sensors services * Start the tracking services * @param port port * @throws Exception e */ public void startUltraSonic(String port) throws Exception { USfront = (UltrasonicSensor) Runtime.start("USfront","UltrasonicSensor"); USfrontRight = (UltrasonicSensor) Runtime.start("USfrontRight","UltrasonicSensor"); USfrontLeft = (UltrasonicSensor) Runtime.start("USfrontLeft","UltrasonicSensor"); USback = (UltrasonicSensor) Runtime.start("USback","UltrasonicSensor"); USbackRight = (UltrasonicSensor) Runtime.start("USbackRight","UltrasonicSensor"); USbackLeft = (UltrasonicSensor) Runtime.start("USbackLeft","UltrasonicSensor"); USfront.attach(arduino, frontUltrasonicTrig, frontUltrasonicEcho); USfrontRight.attach(arduino, front_rightUltrasonicTrig, front_rightUltrasonicEcho); USfrontLeft.attach(arduino, front_leftUltrasonicTrig, front_leftUltrasonicEcho); USback.attach(arduino, backUltrasonicTrig, backUltrasonicEcho); USbackRight.attach(arduino, back_rightUltrasonicTrig, back_rightUltrasonicEcho); USbackLeft.attach(arduino, back_leftUltrasonicTrig, back_leftUltrasonicEcho); } /** * Stop the tracking services * @throws Exception e */ public void stopTrack() throws Exception { tracker.opencv.stopCapture(); tracker.releaseService(); neckTiltServo.attach(arduino, neckTilt[pin]); neckPanServo.attach(arduino, neckPan[pin]); saying("the tracking if stopped."); } public OpenNi startOpenNI() throws Exception { // TODO modify this function to fit new sweety /* * Start the Kinect service */ if (openni == null) { System.out.println("starting kinect"); openni = (OpenNi) Runtime.start("openni","OpenNi"); pid = (Pid) Runtime.start("pid","Pid"); pid.setMode("kinect", Pid.MODE_AUTOMATIC); pid.setOutputRange("kinect", -1, 1); pid.setPID("kinect", 10.0, 0.0, 1.0); pid.setControllerDirection("kinect", 0); // re-mapping of skeleton ! // openni.skeleton.leftElbow.mapXY(0, 180, 180, 0); openni.skeleton.rightElbow.mapXY(0, 180, 180, 0); // openni.skeleton.leftShoulder.mapYZ(0, 180, 180, 0); openni.skeleton.rightShoulder.mapYZ(0, 180, 180, 0); openni.skeleton.leftShoulder.mapXY(0, 180, 180, 0); // openni.skeleton.rightShoulder.mapXY(0, 180, 180, 0); openni.addListener("publishOpenNIData", this.getName(), "onOpenNIData"); // openni.addOpenNIData(this); } return openni; } public boolean copyGesture(boolean b) throws Exception { log.info("copyGesture {}", b); if (b) { if (openni == null) { openni = startOpenNI(); } System.out.println("copying gestures"); openni.startUserTracking(); } else { System.out.println("stop copying gestures"); if (openni != null) { openni.stopCapture(); firstSkeleton = true; } } copyGesture = b; return b; } public String captureGesture() { return captureGesture(null); } public String captureGesture(String gestureName) { StringBuffer script = new StringBuffer(); String indentSpace = ""; if (gestureName != null) { indentSpace = " "; script.append(String.format("def %s():\n", gestureName)); } script.append(indentSpace); script.append( String.format("Sweety.setRightArmPosition(%d,%d,%d,%d,%d)\n", rightShoulderServo.getPos(), rightArmServo.getPos(), rightBicepsServo.getPos(), rightElbowServo.getPos(), rightWristServo.getPos())); script.append(indentSpace); script .append(String.format("Sweety.setLeftArmPosition(%d,%d,%d,%d,%d)\n", leftShoulderServo.getPos(), leftArmServo.getPos(), leftBicepsServo.getPos(), leftElbowServo.getPos(), leftWristServo.getPos())); script.append(indentSpace); script.append(String.format("Sweety.setHeadPosition(%d,%d)\n", neckTiltServo.getPos(), neckPanServo.getPos())); send("python", "appendScript", script.toString()); return script.toString(); } public void onOpenNIData(OpenNiData data) { Skeleton skeleton = data.skeleton; if (firstSkeleton) { System.out.println("i see you"); firstSkeleton = false; } // TODO adapt for new design int LElbow = Math.round(skeleton.leftElbow.getAngleXY()) - (180 - leftElbow[max]); int Larm = Math.round(skeleton.leftShoulder.getAngleXY()) - (180 - leftArm[max]); int Lshoulder = Math.round(skeleton.leftShoulder.getAngleYZ()) + leftShoulder[min]; int RElbow = Math.round(skeleton.rightElbow.getAngleXY()) + rightElbow[min]; int Rarm = Math.round(skeleton.rightShoulder.getAngleXY()) + rightArm[min]; int Rshoulder = Math.round(skeleton.rightShoulder.getAngleYZ()) - (180 - rightShoulder[max]); // Move the left side setLeftArmPosition(Lshoulder, Larm, LElbow, -1, -1); // Move the right side setRightArmPosition(Rshoulder, Rarm, RElbow, -1, -1); } /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, and dependencies * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(Sweety.class.getCanonicalName()); meta.addDescription("service for the Sweety robot"); meta.addCategory("robot"); return meta; } }
package org.racgupta.EasyCharts; /** * @author racgupta * */ public class Chart extends Region { private String title = "Line Chart"; private String titleCode; private Styles titleStyle; public String getTitleCode() { this.titleCode = "svg.append(\"text\").attr(\"x\","+getTotalWidth()/2+").attr(\"y\","+(0-getTopMargin()/2)+")"+ ".attr(\"text-anchor\", \"middle\")"+titleStyle.getStyles()+ ".text(\""+title+"\");\n"; return this.titleCode; } public Chart() { super(); titleStyle = new Styles(); titleStyle.setFontSize("14"); titleStyle.setFontFamily("sans-serif"); titleStyle.setTextDecoration("underline"); // TODO Auto-generated constructor stub } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public void setTitleStyle(Styles titleStyle) { this.titleStyle = titleStyle; } }
package x2x.translator.pragma; import exc.object.Xobject; import java.util.regex.*; public enum CLAWpragma { //directive LOOP_FUSION, LOOP_INTERCHANGE, LOOP_VECTOR, LOOP_EXTRACT, // loop-fusion FUSION_GROUP, ; private static final String CLAW_DIRECTIVE = "claw"; private static final String LOOP_FUSION_DIRECTIVE = "loop-fusion"; private static final String LOOP_INTERCHANGE_DIRECTIVE = "loop-interchange"; private static final String LOOP_VECTOR_DIRECTIVE = "loop-vector"; private static final String LOOP_EXTRACT_DIRECTIVE = "loop-extract"; private static final String OPTION_FUSION_GROUP = "group"; private static final String MULTIPLE_SPACES = " *"; private static final String INNER_OPTION = "\\(([^)]+)\\)"; private String name = null; public String getName() { if (name == null) name = toString().toLowerCase(); return name; } public static CLAWpragma getDirective(String pragma){ // TODO error handling String[] parts = pragma.split(" "); String directive = parts[1]; switch(directive){ case LOOP_FUSION_DIRECTIVE: return CLAWpragma.LOOP_FUSION; case LOOP_INTERCHANGE_DIRECTIVE: return CLAWpragma.LOOP_INTERCHANGE; case LOOP_VECTOR_DIRECTIVE: return CLAWpragma.LOOP_VECTOR; case LOOP_EXTRACT_DIRECTIVE: return CLAWpragma.LOOP_EXTRACT; default: return null; } } public static String getGroupOptionValue(String pragma){ if(getDirective(pragma) != CLAWpragma.LOOP_FUSION){ return null; } Matcher matchFullDirective = Pattern.compile(CLAW_DIRECTIVE + MULTIPLE_SPACES + LOOP_FUSION_DIRECTIVE + MULTIPLE_SPACES + OPTION_FUSION_GROUP + INNER_OPTION, Pattern.CASE_INSENSITIVE ).matcher(pragma); if(!matchFullDirective.matches()){ return null; } Matcher matchOption = Pattern.compile(INNER_OPTION, Pattern.CASE_INSENSITIVE).matcher(pragma); while(matchOption.find()) { return matchOption.group(1); } return null; } public static String getNewOrderOptionValue(String pragma){ if(getDirective(pragma) != CLAWpragma.LOOP_INTERCHANGE){ return null; } Matcher matchFullDirective = Pattern.compile(CLAW_DIRECTIVE + MULTIPLE_SPACES + LOOP_INTERCHANGE_DIRECTIVE + MULTIPLE_SPACES + INNER_OPTION, Pattern.CASE_INSENSITIVE).matcher(pragma); if(!matchFullDirective.matches()){ return null; } Matcher matchOption = Pattern.compile(INNER_OPTION, Pattern.CASE_INSENSITIVE).matcher(pragma); while(matchOption.find()) { return matchOption.group(1); } return null; } public static boolean startsWithClaw(String pragma){ if(pragma.startsWith(CLAW_DIRECTIVE)){ return true; } return false; } // Check the correctness of a claw directive // TODO correct error message public static boolean isValid(String pragma){ String[] parts = pragma.split(" "); if(parts.length < 2){ return false; } String claw = parts[0]; String directive = parts[1]; if(!claw.equals(CLAW_DIRECTIVE)){ return false; } switch(directive){ case LOOP_FUSION_DIRECTIVE: return isValidOption(CLAWpragma.LOOP_FUSION, null); case LOOP_INTERCHANGE_DIRECTIVE: return isValidOption(CLAWpragma.LOOP_INTERCHANGE, null); case LOOP_VECTOR_DIRECTIVE: return isValidOption(CLAWpragma.LOOP_VECTOR, null); case LOOP_EXTRACT_DIRECTIVE: return isValidOption(CLAWpragma.LOOP_EXTRACT, null); default: return false; } } // TODO check option according to the directive private static boolean isValidOption(CLAWpragma directive, String[] options){ return true; } public static CLAWpragma valueOf(Xobject x) { return valueOf(x.getString()); } public boolean isDirective(){ switch(this){ case LOOP_FUSION: case LOOP_INTERCHANGE: case LOOP_VECTOR: case LOOP_EXTRACT: return true; default: return false; } } public boolean isLoop(){ switch(this){ case LOOP_FUSION: case LOOP_INTERCHANGE: case LOOP_VECTOR: case LOOP_EXTRACT: return true; default: return false; } } }
package edu.umd.cs.findbugs; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * A DetectorFactory is responsible for creating instances of Detector objects * and for maintaining meta-information about the detector class. * * @see Detector * @author David Hovemeyer */ public class DetectorFactory { private final Class detectorClass; private boolean enabled; private final String speed; private String detailHTML; /** * Constructor. * @param detectorClass the Class object of the Detector * @param enabled true if the Detector is enabled by default, false if disabled * @param speed a string describing roughly how expensive the analysis performed * by the detector is; suggested values are "fast", "moderate", and "slow" */ public DetectorFactory(Class detectorClass, boolean enabled, String speed) { this.detectorClass = detectorClass; this.enabled = enabled; this.speed = speed; } private static final Class[] constructorArgTypes = new Class[]{BugReporter.class}; /** Is this factory enabled? */ public boolean isEnabled() { return enabled; } /** Set the enabled status of the factory. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** Get the speed of the Detector produced by this factory. */ public String getSpeed() { return speed; } /** Get an HTML document describing the Detector. */ public String getDetailHTML() { return detailHTML; } /** Set the HTML document describing the Detector. */ public void setDetailHTML(String detailHTML) { this.detailHTML = detailHTML; } /** * Create a Detector instance. * @param bugReporter the BugReported to be used to report bugs * @return the Detector */ public Detector create(BugReporter bugReporter) { try { Constructor constructor = detectorClass.getConstructor(constructorArgTypes); return (Detector) constructor.newInstance(new Object[] {bugReporter}); } catch (Exception e) { throw new RuntimeException("Could not instantiate Detector", e); } } /** * Get the short name of the Detector. * This is the name of the detector class without the package qualification. */ public String getShortName() { String className = detectorClass.getName(); int endOfPkg = className.lastIndexOf('.'); if (endOfPkg >= 0) className = className.substring(endOfPkg + 1); return className; } /** * Get the full name of the detector. * This is the name of the detector class, with package qualification. */ public String getFullName() { return detectorClass.getName(); } } // vim:ts=4
package edu.umd.cs.findbugs.ba.ch; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.generic.ArrayType; import org.apache.bcel.generic.BasicType; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.ReferenceType; import org.apache.bcel.generic.Type; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.ObjectTypeFactory; import edu.umd.cs.findbugs.ba.XClass; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.internalAnnotations.DottedClassName; import edu.umd.cs.findbugs.util.DualKeyHashMap; import edu.umd.cs.findbugs.util.MapCache; /** * Class for performing class hierarchy queries. * Does <em>not</em> require JavaClass objects to be in memory. * Instead, uses XClass objects. * * @author David Hovemeyer */ @javax.annotation.ParametersAreNonnullByDefault public class Subtypes2 { public static final boolean ENABLE_SUBTYPES2 = true; public static final boolean ENABLE_SUBTYPES2_FOR_COMMON_SUPERCLASS_QUERIES = true; //SystemProperties.getBoolean("findbugs.subtypes2.superclass"); public static final boolean DEBUG = SystemProperties.getBoolean("findbugs.subtypes2.debug"); public static final boolean DEBUG_QUERIES = SystemProperties.getBoolean("findbugs.subtypes2.debugqueries"); private final InheritanceGraph graph; private final Map<ClassDescriptor, ClassVertex> classDescriptorToVertexMap; private final Map<ClassDescriptor, SupertypeQueryResults> supertypeSetMap; private final Map<ClassDescriptor, Set<ClassDescriptor>> subtypeSetMap; private final Set<XClass> xclassSet; private final DualKeyHashMap<ReferenceType, ReferenceType, ReferenceType> firstCommonSuperclassQueryCache; private final ObjectType SERIALIZABLE; private final ObjectType CLONEABLE; /** * Object to record the results of a supertype search. */ private static class SupertypeQueryResults { private Set<ClassDescriptor> supertypeSet = new HashSet<ClassDescriptor>(); private boolean encounteredMissingClasses = false; public void addSupertype(ClassDescriptor classDescriptor) { supertypeSet.add(classDescriptor); } public void setEncounteredMissingClasses(boolean encounteredMissingClasses) { this.encounteredMissingClasses = encounteredMissingClasses; } public boolean containsType(ClassDescriptor possibleSupertypeClassDescriptor) throws ClassNotFoundException { if (supertypeSet.contains(possibleSupertypeClassDescriptor)) { return true; } else if (!encounteredMissingClasses) { return false; } else { // We don't really know which class was missing. // However, any missing classes will already have been reported. throw new ClassNotFoundException(); } } } /** * Constructor. */ public Subtypes2() { this.graph = new InheritanceGraph(); this.classDescriptorToVertexMap = new HashMap<ClassDescriptor, ClassVertex>(); this.supertypeSetMap = new MapCache<ClassDescriptor, SupertypeQueryResults>(500); this.subtypeSetMap = new MapCache<ClassDescriptor, Set<ClassDescriptor>>(500); this.xclassSet = new HashSet<XClass>(); this.SERIALIZABLE = ObjectTypeFactory.getInstance("java.io.Serializable"); this.CLONEABLE = ObjectTypeFactory.getInstance("java.lang.Cloneable"); this.firstCommonSuperclassQueryCache = new DualKeyHashMap<ReferenceType, ReferenceType, ReferenceType>(); } /** * @return Returns the graph. */ public InheritanceGraph getGraph() { return graph; } public static boolean instanceOf(@DottedClassName String dottedSubtype, @DottedClassName String dottedSupertype) { Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2(); ClassDescriptor subDescriptor = DescriptorFactory.createClassDescriptorFromDottedClassName(dottedSubtype); ClassDescriptor superDescriptor = DescriptorFactory.createClassDescriptorFromDottedClassName(dottedSupertype); try { return subtypes2.isSubtype(subDescriptor, superDescriptor); } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); return false; } } public static boolean instanceOf(ClassDescriptor subDescriptor, @DottedClassName String dottedSupertype) { Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2(); ClassDescriptor superDescriptor = DescriptorFactory.createClassDescriptorFromDottedClassName(dottedSupertype); try { return subtypes2.isSubtype(subDescriptor, superDescriptor); } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); return false; } } public static boolean instanceOf(JavaClass subtype, @DottedClassName String dottedSupertype) { Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2(); ClassDescriptor subDescriptor = DescriptorFactory.createClassDescriptor(subtype); ClassDescriptor superDescriptor = DescriptorFactory.createClassDescriptorFromDottedClassName(dottedSupertype); try { return subtypes2.isSubtype(subDescriptor, superDescriptor); } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); return false; } } /** * Add an application class, and its transitive supertypes, to the inheritance graph. * * @param appXClass application XClass to add to the inheritance graph */ public void addApplicationClass(XClass appXClass) { ClassVertex vertex = addClassAndGetClassVertex(appXClass); vertex.markAsApplicationClass(); } public boolean isApplicationClass(ClassDescriptor descriptor) { assert descriptor != null; try { return resolveClassVertex(descriptor).isApplicationClass(); } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); return true; } } /** * Add a class or interface, and its transitive supertypes, to the inheritance graph. * * @param xclass XClass to add to the inheritance graph */ public void addClass(XClass xclass) { addClassAndGetClassVertex(xclass); } /** * Add an XClass and all of its supertypes to * the InheritanceGraph. * * @param xclass an XClass * @return the ClassVertex representing the class in * the InheritanceGraph */ private ClassVertex addClassAndGetClassVertex(XClass xclass) { if (xclass == null) { throw new IllegalStateException(); } LinkedList<XClass> workList = new LinkedList<XClass>(); workList.add(xclass); while (!workList.isEmpty()) { XClass work = workList.removeFirst(); ClassVertex vertex = classDescriptorToVertexMap.get(work.getClassDescriptor()); if (vertex != null && vertex.isFinished()) { // This class has already been processed. continue; } if (vertex == null) { vertex = ClassVertex.createResolvedClassVertex(work.getClassDescriptor(), work); addVertexToGraph(work.getClassDescriptor(), vertex); } addSupertypeEdges(vertex, workList); vertex.setFinished(true); } return classDescriptorToVertexMap.get(xclass.getClassDescriptor()); } private void addVertexToGraph(ClassDescriptor classDescriptor, ClassVertex vertex) { assert classDescriptorToVertexMap.get(classDescriptor) == null; if (DEBUG) { System.out.println("Adding " + classDescriptor.toDottedClassName() + " to inheritance graph"); } graph.addVertex(vertex); classDescriptorToVertexMap.put(classDescriptor, vertex); if (vertex.isResolved()) { xclassSet.add(vertex.getXClass()); } if (vertex.isInterface()) { // There is no need to add additional worklist nodes because java/lang/Object has no supertypes. addInheritanceEdge(vertex, DescriptorFactory.instance().getClassDescriptor("java/lang/Object"), false, null); } } /** * Determine whether or not a given ReferenceType is a subtype of another. * Throws ClassNotFoundException if the question cannot be answered * definitively due to a missing class. * * @param type a ReferenceType * @param possibleSupertype another Reference type * @return true if <code>type</code> is a subtype of <code>possibleSupertype</code>, false if not * @throws ClassNotFoundException if a missing class prevents a definitive answer */ public boolean isSubtype(ReferenceType type, ReferenceType possibleSupertype) throws ClassNotFoundException { // Eliminate some easy cases if (type.equals(possibleSupertype)) { return true; } if (possibleSupertype.equals(ObjectType.OBJECT)) return true; if (type.equals(ObjectType.OBJECT)) return false; boolean typeIsObjectType = (type instanceof ObjectType); boolean possibleSupertypeIsObjectType = (possibleSupertype instanceof ObjectType); if (typeIsObjectType && possibleSupertypeIsObjectType) { // Both types are ordinary object (non-array) types. return isSubtype((ObjectType) type, (ObjectType) possibleSupertype); } boolean typeIsArrayType = (type instanceof ArrayType); boolean possibleSupertypeIsArrayType = (possibleSupertype instanceof ArrayType); if (typeIsArrayType) { // Check superclass/interfaces if (possibleSupertype.equals(SERIALIZABLE) || possibleSupertype.equals(CLONEABLE)) { return true; } // We checked all of the possible class/interface supertypes, // so if possibleSupertype is not an array type, // then we can definitively say no if (!possibleSupertypeIsArrayType) { return false; } // Check array/array subtype relationship ArrayType typeAsArrayType = (ArrayType) type; ArrayType possibleSupertypeAsArrayType = (ArrayType) possibleSupertype; // Must have same number of dimensions if (typeAsArrayType.getDimensions() < possibleSupertypeAsArrayType.getDimensions()) { return false; } Type possibleSupertypeBasicType = possibleSupertypeAsArrayType.getBasicType(); if (!(possibleSupertypeBasicType instanceof ObjectType)) { return false; } Type typeBasicType = typeAsArrayType.getBasicType(); // If dimensions differ, see if element types are compatible. if (typeAsArrayType.getDimensions() > possibleSupertypeAsArrayType.getDimensions()) { return isSubtype(new ArrayType(typeBasicType,typeAsArrayType.getDimensions() - possibleSupertypeAsArrayType.getDimensions() ), (ObjectType) possibleSupertypeBasicType); } // type's base type must be a subtype of possibleSupertype's base type. // Note that neither base type can be a non-ObjectType if we are to answer yes. if (!(typeBasicType instanceof ObjectType)) { return false; } return isSubtype((ObjectType) typeBasicType, (ObjectType) possibleSupertypeBasicType); } // OK, we've exhausted the possibilities now return false; } public boolean isSubtype(ClassDescriptor subDesc, ClassDescriptor superDesc) throws ClassNotFoundException { assert subDesc != null; assert superDesc != null; if (subDesc.equals(superDesc)) return true; try { SupertypeQueryResults supertypeQueryResults = getSupertypeQueryResults(subDesc); return supertypeQueryResults.containsType(superDesc); } catch (ClassNotFoundException e) { XClass xclass = AnalysisContext.currentXFactory().getXClass(subDesc); if (xclass != null && superDesc.equals(xclass.getSuperclassDescriptor())) return true; throw e; } } /** * Determine whether or not a given ObjectType is a subtype of another. * Throws ClassNotFoundException if the question cannot be answered * definitively due to a missing class. * * @param type a ReferenceType * @param possibleSupertype another Reference type * @return true if <code>type</code> is a subtype of <code>possibleSupertype</code>, false if not * @throws ClassNotFoundException if a missing class prevents a definitive answer */ public boolean isSubtype(ObjectType type, ObjectType possibleSupertype) throws ClassNotFoundException { if (DEBUG_QUERIES) { System.out.println("isSubtype: check " + type + " subtype of " + possibleSupertype); } if (type.equals(possibleSupertype)) { if (DEBUG_QUERIES) { System.out.println(" ==> yes, types are same"); } return true; } ClassDescriptor typeClassDescriptor = DescriptorFactory.getClassDescriptor(type); ClassDescriptor possibleSuperclassClassDescriptor = DescriptorFactory.getClassDescriptor(possibleSupertype); // In principle, we should be able to answer no if the ObjectType objects // are not equal and possibleSupertype is final. // However, internally FindBugs creates special "subtypes" of java.lang.String // These will end up resolving to the same ClassVertex as java.lang.String, // which will Do The Right Thing. if (false) { ClassVertex possibleSuperclassClassVertex = resolveClassVertex(possibleSuperclassClassDescriptor); if (possibleSuperclassClassVertex.isResolved() && possibleSuperclassClassVertex.getXClass().isFinal()) { if (DEBUG_QUERIES) { System.out.println(" ==> no, " + possibleSuperclassClassDescriptor + " is final"); } return false; } } // Get the supertype query results SupertypeQueryResults supertypeQueryResults = getSupertypeQueryResults(typeClassDescriptor); if (DEBUG_QUERIES) { System.out.println(" Superclass set: " + supertypeQueryResults.supertypeSet); } boolean isSubtype = supertypeQueryResults.containsType(possibleSuperclassClassDescriptor); if (DEBUG_QUERIES) { if (isSubtype) { System.out.println(" ==> yes, " + possibleSuperclassClassDescriptor + " is in superclass set"); } else { System.out.println(" ==> no, " + possibleSuperclassClassDescriptor + " is not in superclass set"); } } return isSubtype; } /** * Get the first common superclass of the given reference types. * Note that an interface type is never returned unless <code>a</code> and <code>b</code> are the * same type. Otherwise, we try to return as accurate a type as possible. * This method is used as the meet operator in TypeDataflowAnalysis, * and is intended to follow (more or less) the JVM bytecode verifier * semantics. * * <p>This method should be used in preference to the getFirstCommonSuperclass() * method in {@link ReferenceType}.</p> * * @param a a ReferenceType * @param b another ReferenceType * @return the first common superclass of <code>a</code> and <code>b</code> * @throws ClassNotFoundException */ public ReferenceType getFirstCommonSuperclass(ReferenceType a, ReferenceType b) throws ClassNotFoundException { // Easy case: same types if (a.equals(b)) { return a; } ReferenceType answer = checkFirstCommonSuperclassQueryCache(a, b); if (answer == null) { answer = computeFirstCommonSuperclassOfReferenceTypes(a, b); putFirstCommonSuperclassQueryCache(a, b, answer); } return answer; } private ReferenceType computeFirstCommonSuperclassOfReferenceTypes(ReferenceType a, ReferenceType b) throws ClassNotFoundException { boolean aIsArrayType = (a instanceof ArrayType); boolean bIsArrayType = (b instanceof ArrayType); if (aIsArrayType && bIsArrayType) { // Merging array types - kind of a pain. ArrayType aArrType = (ArrayType) a; ArrayType bArrType = (ArrayType) b; if (aArrType.getDimensions() == bArrType.getDimensions()) { return computeFirstCommonSuperclassOfSameDimensionArrays(aArrType, bArrType); } else { return computeFirstCommonSuperclassOfDifferentDimensionArrays(aArrType, bArrType); } } if (aIsArrayType || bIsArrayType) { // One of a and b is an array type, but not both. // Common supertype is Object. return ObjectType.OBJECT; } // Neither a nor b is an array type. // Find first common supertypes of ObjectTypes. return getFirstCommonSuperclass((ObjectType) a, (ObjectType) b); } /** * Get first common supertype of arrays with the same number of dimensions. * * @param aArrType an ArrayType * @param bArrType another ArrayType with the same number of dimensions * @return first common supertype * @throws ClassNotFoundException */ private ReferenceType computeFirstCommonSuperclassOfSameDimensionArrays(ArrayType aArrType, ArrayType bArrType) throws ClassNotFoundException { assert aArrType.getDimensions() == bArrType.getDimensions(); Type aBaseType = aArrType.getBasicType(); Type bBaseType = bArrType.getBasicType(); boolean aBaseIsObjectType = (aBaseType instanceof ObjectType); boolean bBaseIsObjectType = (bBaseType instanceof ObjectType); if (!aBaseIsObjectType || !bBaseIsObjectType) { assert (aBaseType instanceof BasicType) || (bBaseType instanceof BasicType); if (aArrType.getDimensions() > 1) { // E.g.: first common supertype of int[][] and WHATEVER[][] is Object[] return new ArrayType(Type.OBJECT, aArrType.getDimensions() - 1); } else { assert aArrType.getDimensions() == 1; // E.g.: first common supertype type of int[] and WHATEVER[] is Object return Type.OBJECT; } } else { assert (aBaseType instanceof ObjectType); assert (bBaseType instanceof ObjectType); // Base types are both ObjectTypes, and number of dimensions is same. // We just need to find the first common supertype of base types // and return a new ArrayType using that base type. ObjectType firstCommonBaseType = getFirstCommonSuperclass((ObjectType) aBaseType, (ObjectType) bBaseType); return new ArrayType(firstCommonBaseType, aArrType.getDimensions()); } } /** * Get the first common superclass of * arrays with different numbers of dimensions. * * @param aArrType an ArrayType * @param bArrType another ArrayType * @return ReferenceType representing first common superclass */ private ReferenceType computeFirstCommonSuperclassOfDifferentDimensionArrays(ArrayType aArrType, ArrayType bArrType) { assert aArrType.getDimensions() != bArrType.getDimensions(); boolean aBaseTypeIsPrimitive = (aArrType.getBasicType() instanceof BasicType); boolean bBaseTypeIsPrimitive = (bArrType.getBasicType() instanceof BasicType); if (aBaseTypeIsPrimitive || bBaseTypeIsPrimitive) { int minDimensions, maxDimensions; if (aArrType.getDimensions() < bArrType.getDimensions()) { minDimensions = aArrType.getDimensions(); maxDimensions = bArrType.getDimensions(); } else { minDimensions = bArrType.getDimensions(); maxDimensions = aArrType.getDimensions(); } if (minDimensions == 1) { // One of the types was something like int[]. // The only possible common supertype is Object. return Type.OBJECT; } else { // Weird case: e.g., // - first common supertype of int[][] and char[][][] is Object[] // because f.c.s. of int[] and char[][] is Object // - first common supertype of int[][][] and char[][][][][] is Object[][] // because f.c.s. of int[] and char[][][] is Object return new ArrayType(Type.OBJECT, maxDimensions - minDimensions); } } else { // Both a and b have base types which are ObjectTypes. // Since the arrays have different numbers of dimensions, the // f.c.s. will have Object as its base type. // E.g., f.c.s. of Cat[] and Dog[][] is Object[] return new ArrayType(Type.OBJECT, Math.min(aArrType.getDimensions(), bArrType.getDimensions())); } } /** * Get the first common superclass of the given object types. * Note that an interface type is never returned unless <code>a</code> and <code>b</code> are the * same type. Otherwise, we try to return as accurate a type as possible. * This method is used as the meet operator in TypeDataflowAnalysis, * and is intended to follow (more or less) the JVM bytecode verifier * semantics. * * <p>This method should be used in preference to the getFirstCommonSuperclass() * method in {@link ReferenceType}.</p> * * @param a an ObjectType * @param b another ObjectType * @return the first common superclass of <code>a</code> and <code>b</code> * @throws ClassNotFoundException */ public ObjectType getFirstCommonSuperclass(ObjectType a, ObjectType b) throws ClassNotFoundException { // Easy case if (a.equals(b)) { return a; } ObjectType firstCommonSupertype = (ObjectType) checkFirstCommonSuperclassQueryCache(a, b); if (firstCommonSupertype == null) { firstCommonSupertype = computeFirstCommonSuperclassOfObjectTypes(a, b); firstCommonSuperclassQueryCache.put(a, b, firstCommonSupertype); } return firstCommonSupertype; } private ObjectType computeFirstCommonSuperclassOfObjectTypes(ObjectType a, ObjectType b) throws ClassNotFoundException { ObjectType firstCommonSupertype; ClassDescriptor aDesc = DescriptorFactory.getClassDescriptor(a); ClassDescriptor bDesc = DescriptorFactory.getClassDescriptor(b); ClassVertex aVertex = resolveClassVertex(aDesc); ClassVertex bVertex = resolveClassVertex(bDesc); Set<ClassDescriptor> aSuperTypes = computeKnownSupertypes(aDesc); Set<ClassDescriptor> bSuperTypes = computeKnownSupertypes(bDesc); if (bSuperTypes.contains(aDesc)) return a; if (aSuperTypes.contains(bDesc)) return b; ArrayList<ClassVertex> aSuperList = getAllSuperclassVertices(aVertex); ArrayList<ClassVertex> bSuperList = getAllSuperclassVertices(bVertex); // Work backwards until the lists diverge. // The last element common to both lists is the first // common superclass. int aIndex = aSuperList.size() - 1; int bIndex = bSuperList.size() - 1; ClassVertex lastCommonInBackwardsSearch = null; while (aIndex >= 0 && bIndex >= 0) { if (aSuperList.get(aIndex) != bSuperList.get(bIndex)) { break; } lastCommonInBackwardsSearch = aSuperList.get(aIndex); aIndex bIndex } if (lastCommonInBackwardsSearch == null) firstCommonSupertype = ObjectType.OBJECT; else firstCommonSupertype = ObjectTypeFactory.getInstance(lastCommonInBackwardsSearch.getClassDescriptor().toDottedClassName()); if (firstCommonSupertype.equals(ObjectType.OBJECT)) { // see if we can't do better ClassDescriptor objDesc= DescriptorFactory.getClassDescriptor(ObjectType.OBJECT); aSuperTypes.retainAll(bSuperTypes); aSuperTypes.remove(objDesc); for(ClassDescriptor c : aSuperTypes) if (c.getPackageName().equals(aDesc.getPackageName()) || c.getPackageName().equals(bDesc.getPackageName())) return ObjectTypeFactory.getInstance(c.toDottedClassName()); for(ClassDescriptor c : aSuperTypes) return ObjectTypeFactory.getInstance(c.toDottedClassName()); } return firstCommonSupertype; } private void putFirstCommonSuperclassQueryCache(ReferenceType a, ReferenceType b, ReferenceType answer) { if (a.getSignature().compareTo(b.getSignature()) > 0) { ReferenceType tmp = a; a = b; b = tmp; } firstCommonSuperclassQueryCache.put(a, b, answer); } private ReferenceType checkFirstCommonSuperclassQueryCache(ReferenceType a, ReferenceType b) { if (a.getSignature().compareTo(b.getSignature()) > 0) { ReferenceType tmp = a; a = b; b = tmp; } return firstCommonSuperclassQueryCache.get(a, b); } /** * Get list of all superclasses of class represented by given class vertex, * in order, including the class itself (which is trivially its own superclass * as far as "first common superclass" queries are concerned.) * * @param vertex a ClassVertex * @return list of all superclass vertices in order */ private ArrayList<ClassVertex> getAllSuperclassVertices(ClassVertex vertex) throws ClassNotFoundException { ArrayList<ClassVertex> result = new ArrayList<ClassVertex>(); ClassVertex cur = vertex; while (cur != null) { if (!cur.isResolved()) { ClassDescriptor.throwClassNotFoundException(cur.getClassDescriptor()); } result.add(cur); cur = cur.getDirectSuperclass(); } return result; } /** * Get known subtypes of given class. * The set returned <em>DOES</em> include the class itself. * * @param classDescriptor ClassDescriptor naming a class * @return Set of ClassDescriptors which are the known subtypes of the class * @throws ClassNotFoundException */ public Set<ClassDescriptor> getSubtypes(ClassDescriptor classDescriptor) throws ClassNotFoundException { Set<ClassDescriptor> result = subtypeSetMap.get(classDescriptor); if (result == null) { result = computeKnownSubtypes(classDescriptor); subtypeSetMap.put(classDescriptor, result); } return result; } /** * Determine whether or not the given class has any known subtypes. * * @param classDescriptor ClassDescriptor naming a class * @return true if the class has subtypes, false if it has no subtypes * @throws ClassNotFoundException */ public boolean hasSubtypes(ClassDescriptor classDescriptor) throws ClassNotFoundException { Set<ClassDescriptor> subtypes = getDirectSubtypes(classDescriptor); if (DEBUG) { System.out.println("Direct subtypes of " + classDescriptor + " are " + subtypes); } return !subtypes.isEmpty(); } /** * Get known subtypes of given class. * * @param classDescriptor ClassDescriptor naming a class * @return Set of ClassDescriptors which are the known subtypes of the class * @throws ClassNotFoundException */ public Set<ClassDescriptor> getDirectSubtypes(ClassDescriptor classDescriptor) throws ClassNotFoundException { ClassVertex startVertex = resolveClassVertex(classDescriptor); Set<ClassDescriptor> result = new HashSet<ClassDescriptor>(); Iterator<InheritanceEdge> i = graph.incomingEdgeIterator(startVertex); while (i.hasNext()) { InheritanceEdge edge = i.next(); result.add(edge.getSource().getClassDescriptor()); } return result; } /** * Get the set of common subtypes of the two given classes. * * @param classDescriptor1 a ClassDescriptor naming a class * @param classDescriptor2 a ClassDescriptor naming another class * @return Set containing all common transitive subtypes of the two classes * @throws ClassNotFoundException */ public Set<ClassDescriptor> getTransitiveCommonSubtypes(ClassDescriptor classDescriptor1, ClassDescriptor classDescriptor2) throws ClassNotFoundException { Set<ClassDescriptor> subtypes1 = getSubtypes(classDescriptor1); Set<ClassDescriptor> result = new HashSet<ClassDescriptor>(subtypes1); Set<ClassDescriptor> subtypes2 = getSubtypes(classDescriptor2); result.retainAll(subtypes2); return result; } /** * Get Collection of all XClass objects (resolved classes) * seen so far. * * @return Collection of all XClass objects */ public Collection<XClass> getXClassCollection() { return Collections.<XClass>unmodifiableCollection(xclassSet); } /** * An in-progress traversal of one path from a class or interface * to java.lang.Object. */ private static class SupertypeTraversalPath { ClassVertex next; Set<ClassDescriptor> seen; public SupertypeTraversalPath(@CheckForNull ClassVertex next) { this.next = next; this.seen = new HashSet<ClassDescriptor>(); } @Override public String toString() { return next.toString() + ":" + seen; } public ClassVertex getNext() { return next; } public boolean hasBeenSeen(ClassDescriptor classDescriptor) { return seen.contains(classDescriptor); } public void markSeen(ClassDescriptor classDescriptor) { seen.add(classDescriptor); } public void setNext(ClassVertex next) { assert !hasBeenSeen(next.getClassDescriptor()); this.next = next; } public SupertypeTraversalPath fork(ClassVertex next) { SupertypeTraversalPath dup = new SupertypeTraversalPath(null); dup.seen.addAll(this.seen); dup.setNext(next); return dup; } } /** * Starting at the class or interface named by the given ClassDescriptor, * traverse the inheritance graph, exploring all paths from * the class or interface to java.lang.Object. * * @param start ClassDescriptor naming the class where the traversal should start * @param visitor an InheritanceGraphVisitor * @throws ClassNotFoundException */ public void traverseSupertypes(ClassDescriptor start, InheritanceGraphVisitor visitor) throws ClassNotFoundException { LinkedList<SupertypeTraversalPath> workList = new LinkedList<SupertypeTraversalPath>(); ClassVertex startVertex = resolveClassVertex(start); workList.addLast(new SupertypeTraversalPath(startVertex)); while (!workList.isEmpty()) { SupertypeTraversalPath cur = workList.removeFirst(); ClassVertex vertex = cur.getNext(); assert !cur.hasBeenSeen(vertex.getClassDescriptor()); cur.markSeen(vertex.getClassDescriptor()); if (!visitor.visitClass(vertex.getClassDescriptor(), vertex.getXClass())) { // Visitor doesn't want to continue on this path continue; } if (!vertex.isResolved()) { // Unknown class - so, we don't know its immediate supertypes continue; } // Advance to direct superclass ClassDescriptor superclassDescriptor = vertex.getXClass().getSuperclassDescriptor(); if (superclassDescriptor != null && traverseEdge(vertex, superclassDescriptor, false, visitor)) { addToWorkList(workList, cur, superclassDescriptor); } // Advance to directly-implemented interfaces for (ClassDescriptor ifaceDesc : vertex.getXClass().getInterfaceDescriptorList()) { if (traverseEdge(vertex, ifaceDesc, true, visitor)) { addToWorkList(workList, cur, ifaceDesc); } } } } private void addToWorkList( LinkedList<SupertypeTraversalPath> workList, SupertypeTraversalPath curPath, ClassDescriptor supertypeDescriptor) { ClassVertex vertex = classDescriptorToVertexMap.get(supertypeDescriptor); // The vertex should already have been added to the graph assert vertex != null; if (curPath.hasBeenSeen(vertex.getClassDescriptor())) { // This can only happen when the inheritance graph has a cycle return; } SupertypeTraversalPath newPath = curPath.fork(vertex); workList.addLast(newPath); } private boolean traverseEdge( ClassVertex vertex, @CheckForNull ClassDescriptor supertypeDescriptor, boolean isInterfaceEdge, InheritanceGraphVisitor visitor) { if (supertypeDescriptor == null) { // We reached java.lang.Object return false; } ClassVertex supertypeVertex = classDescriptorToVertexMap.get(supertypeDescriptor); if (supertypeVertex == null) { try { supertypeVertex = resolveClassVertex(supertypeDescriptor); } catch (ClassNotFoundException e) { supertypeVertex = addClassVertexForMissingClass(supertypeDescriptor, isInterfaceEdge); } } assert supertypeVertex != null; return visitor.visitEdge(vertex.getClassDescriptor(), vertex.getXClass(), supertypeDescriptor, supertypeVertex.getXClass()); } /** * Compute set of known subtypes of class named by given ClassDescriptor. * * @param classDescriptor a ClassDescriptor * @throws ClassNotFoundException */ private Set<ClassDescriptor> computeKnownSubtypes(ClassDescriptor classDescriptor) throws ClassNotFoundException { LinkedList<ClassVertex> workList = new LinkedList<ClassVertex>(); ClassVertex startVertex = resolveClassVertex(classDescriptor); workList.addLast(startVertex); Set<ClassDescriptor> result = new HashSet<ClassDescriptor>(); while (!workList.isEmpty()) { ClassVertex current = workList.removeFirst(); if (result.contains(current.getClassDescriptor())) { // Already added this class continue; } // Add class to the result result.add(current.getClassDescriptor()); // Add all known subtype vertices to the work list Iterator<InheritanceEdge> i = graph.incomingEdgeIterator(current); while (i.hasNext()) { InheritanceEdge edge = i.next(); workList.addLast(edge.getSource()); } } return result; } private Set<ClassDescriptor> computeKnownSupertypes(ClassDescriptor classDescriptor) throws ClassNotFoundException { LinkedList<ClassVertex> workList = new LinkedList<ClassVertex>(); ClassVertex startVertex = resolveClassVertex(classDescriptor); workList.addLast(startVertex); Set<ClassDescriptor> result = new HashSet<ClassDescriptor>(); while (!workList.isEmpty()) { ClassVertex current = workList.removeFirst(); if (result.contains(current.getClassDescriptor())) { // Already added this class continue; } // Add class to the result result.add(current.getClassDescriptor()); // Add all known subtype vertices to the work list Iterator<InheritanceEdge> i = graph.outgoingEdgeIterator(current); while (i.hasNext()) { InheritanceEdge edge = i.next(); workList.addLast(edge.getTarget()); } } return result; } /** * Look up or compute the SupertypeQueryResults for class * named by given ClassDescriptor. * * @param classDescriptor a ClassDescriptor * @return SupertypeQueryResults for the class named by the ClassDescriptor * @throws ClassNotFoundException */ public SupertypeQueryResults getSupertypeQueryResults(ClassDescriptor classDescriptor) { SupertypeQueryResults supertypeQueryResults = supertypeSetMap.get(classDescriptor); if (supertypeQueryResults == null) { supertypeQueryResults = computeSupertypes(classDescriptor); supertypeSetMap.put(classDescriptor, supertypeQueryResults); } return supertypeQueryResults; } /** * Compute supertypes for class named by given ClassDescriptor. * * @param classDescriptor a ClassDescriptor * @return SupertypeQueryResults containing known supertypes of the class * @throws ClassNotFoundException if the class can't be found */ private SupertypeQueryResults computeSupertypes(ClassDescriptor classDescriptor) // throws ClassNotFoundException { if (DEBUG_QUERIES) { System.out.println("Computing supertypes for " + classDescriptor.toDottedClassName()); } // Try to fully resolve the class and its superclasses/superinterfaces. ClassVertex typeVertex = optionallyResolveClassVertex(classDescriptor); // Create new empty SupertypeQueryResults. SupertypeQueryResults supertypeSet = new SupertypeQueryResults(); // Add all known superclasses/superinterfaces. // The ClassVertexes for all of them should be in the // InheritanceGraph by now. LinkedList<ClassVertex> workList = new LinkedList<ClassVertex>(); workList.addLast(typeVertex); while (!workList.isEmpty()) { ClassVertex vertex = workList.removeFirst(); supertypeSet.addSupertype(vertex.getClassDescriptor()); if (vertex.isResolved()) { if (DEBUG_QUERIES) { System.out.println(" Adding supertype " + vertex.getClassDescriptor().toDottedClassName()); } } else { if (DEBUG_QUERIES) { System.out.println( " Encountered unresolved class " + vertex.getClassDescriptor().toDottedClassName() + " in supertype query"); } supertypeSet.setEncounteredMissingClasses(true); } Iterator<InheritanceEdge> i = graph.outgoingEdgeIterator(vertex); while (i.hasNext()) { InheritanceEdge edge = i.next(); workList.addLast(edge.getTarget()); } } return supertypeSet; } /** * Resolve a class named by given ClassDescriptor and return * its resolved ClassVertex. * * @param classDescriptor a ClassDescriptor * @return resolved ClassVertex representing the class in the InheritanceGraph * @throws ClassNotFoundException if the class named by the ClassDescriptor does not exist */ private ClassVertex resolveClassVertex(ClassDescriptor classDescriptor) throws ClassNotFoundException { ClassVertex typeVertex = optionallyResolveClassVertex(classDescriptor); if (!typeVertex.isResolved()) { ClassDescriptor.throwClassNotFoundException(classDescriptor); } assert typeVertex.isResolved(); return typeVertex; } /** * @param classDescriptor * @return */ private ClassVertex optionallyResolveClassVertex(ClassDescriptor classDescriptor) { ClassVertex typeVertex = classDescriptorToVertexMap.get(classDescriptor); if (typeVertex == null) { // We have never tried to resolve this ClassVertex before. // Try to find the XClass for this class. XClass xclass = AnalysisContext.currentXFactory().getXClass(classDescriptor); if (xclass == null) { // Class we're trying to resolve doesn't exist. // XXX: unfortunately, we don't know if the missing class is a class or interface typeVertex = addClassVertexForMissingClass(classDescriptor, false); } else { // Add the class and all its superclasses/superinterfaces to the inheritance graph. // This will result in a resolved ClassVertex. typeVertex = addClassAndGetClassVertex(xclass); } } return typeVertex; } /** * Add supertype edges to the InheritanceGraph * for given ClassVertex. If any direct supertypes * have not been processed, add them to the worklist. * * @param vertex a ClassVertex whose supertype edges need to be added * @param workList work list of ClassVertexes that need to have * their supertype edges added */ private void addSupertypeEdges(ClassVertex vertex, LinkedList<XClass> workList) { XClass xclass = vertex.getXClass(); // Direct superclass ClassDescriptor superclassDescriptor = xclass.getSuperclassDescriptor(); if (superclassDescriptor != null) addInheritanceEdge(vertex, superclassDescriptor, false, workList); // Directly implemented interfaces for (ClassDescriptor ifaceDesc : xclass.getInterfaceDescriptorList()) { addInheritanceEdge(vertex, ifaceDesc, true, workList); } } /** * Add supertype edge to the InheritanceGraph. * * @param vertex source ClassVertex (subtype) * @param superclassDescriptor ClassDescriptor of a direct supertype * @param isInterfaceEdge true if supertype is (as far as we know) an interface * @param workList work list of ClassVertexes that need to have * their supertype edges added (null if no further work will be generated) */ private void addInheritanceEdge( ClassVertex vertex, ClassDescriptor superclassDescriptor, boolean isInterfaceEdge, @CheckForNull LinkedList<XClass> workList) { if (superclassDescriptor == null) { return; } ClassVertex superclassVertex = classDescriptorToVertexMap.get(superclassDescriptor); if (superclassVertex == null) { // Haven't encountered this class previously. XClass superclassXClass = AnalysisContext.currentXFactory().getXClass(superclassDescriptor); if (superclassXClass == null) { // Inheritance graph will be incomplete. // Add a dummy node to inheritance graph and report missing class. superclassVertex = addClassVertexForMissingClass(superclassDescriptor, isInterfaceEdge); } else { // Haven't seen this class before. superclassVertex = ClassVertex.createResolvedClassVertex(superclassDescriptor, superclassXClass); addVertexToGraph(superclassDescriptor, superclassVertex); if (workList != null) { // We'll want to recursively process the superclass. workList.addLast(superclassXClass); } } } assert superclassVertex != null; if (graph.lookupEdge(vertex, superclassVertex) == null) { if (DEBUG) { System.out.println(" Add edge " + vertex.getClassDescriptor().toDottedClassName() + " -> " + superclassDescriptor.toDottedClassName()); } graph.createEdge(vertex, superclassVertex); } } /** * Add a ClassVertex representing a missing class. * * @param missingClassDescriptor ClassDescriptor naming a missing class * @param isInterfaceEdge * @return the ClassVertex representing the missing class */ private ClassVertex addClassVertexForMissingClass(ClassDescriptor missingClassDescriptor, boolean isInterfaceEdge) { ClassVertex missingClassVertex = ClassVertex.createMissingClassVertex(missingClassDescriptor, isInterfaceEdge); missingClassVertex.setFinished(true); addVertexToGraph(missingClassDescriptor, missingClassVertex); AnalysisContext.currentAnalysisContext().getLookupFailureCallback().reportMissingClass(missingClassDescriptor); return missingClassVertex; } }
package edu.umd.cs.findbugs.detect; import edu.umd.cs.findbugs.*; import edu.umd.cs.findbugs.ba.*; import edu.umd.cs.findbugs.ba.bcp.*; import java.util.*; import org.apache.bcel.Constants; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; /* * Look for lazy initialization of fields which * are not volatile. This is quite similar to checking for * double checked locking, except that there is no lock. * * @author David Hovemeyer */ public final class LazyInit extends ByteCodePatternDetector implements StatelessDetector { private BugReporter bugReporter; private static final boolean DEBUG = SystemProperties.getBoolean("lazyinit.debug"); /** * The pattern to look for. */ private static ByteCodePattern pattern = new ByteCodePattern(); static { pattern .add(new Load("f", "val").label("start")) .add(new IfNull("val")) .add(new Wild(1, 1).label("createObject")) .add(new Store("f", pattern.dummyVariable()).label("end").dominatedBy("createObject")); } public LazyInit(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } @Override public BugReporter getBugReporter() { return bugReporter; } @Override public ByteCodePattern getPattern() { return pattern; } @Override public boolean prescreen(Method method, ClassContext classContext) { BitSet bytecodeSet = classContext.getBytecodeSet(method); if (bytecodeSet == null) return false; // The pattern requires a get/put pair accessing the same field. if (!(bytecodeSet.get(Constants.GETSTATIC) && bytecodeSet.get(Constants.PUTSTATIC)) && !(bytecodeSet.get(Constants.GETFIELD) && bytecodeSet.get(Constants.PUTFIELD))) return false; // If the method is synchronized, then we'll assume that // things are properly synchronized if (method.isSynchronized()) return false; return true; } @Override public void reportMatch(ClassContext classContext, Method method, ByteCodePatternMatch match) throws CFGBuilderException, DataflowAnalysisException { JavaClass javaClass = classContext.getJavaClass(); MethodGen methodGen = classContext.getMethodGen(method); CFG cfg = classContext.getCFG(method); try { // Get the variable referenced in the pattern instance. BindingSet bindingSet = match.getBindingSet(); Binding binding = bindingSet.lookup("f"); // Look up the field as an XField. // If it is volatile, then the instance is not a bug. FieldVariable field = (FieldVariable) binding.getVariable(); XField xfield = Hierarchy.findXField(field.getClassName(), field.getFieldName(), field.getFieldSig(), field.isStatic()); if (xfield == null) return; if (false && (xfield.getAccessFlags() & Constants.ACC_VOLATILE) != 0) return; // XXX: for now, ignore lazy initialization of instance fields if (!xfield.isStatic()) return; // Definitely ignore synthetic class$ fields if (xfield.getName().startsWith("class$") || xfield.getName().startsWith("array$")) { if (DEBUG) System.out.println("Ignoring field " + xfield.getName()); return; } // Ignore non-reference fields if (!xfield.getSignature().startsWith("[") && !xfield.getSignature().startsWith("L")) { if (DEBUG) System.out.println("Ignoring non-reference field " + xfield.getName()); return; } // TODO: Strings are safe to pass by data race in 1.5 // Get locations matching the beginning of the object creation, // and the final field store. PatternElementMatch createBegin = match.getFirstLabeledMatch("createObject"); PatternElementMatch store = match.getFirstLabeledMatch("end"); // Get all blocks // (1) dominated by the wildcard instruction matching // the beginning of the instructions creating the object, and // (2) postdominated by the field store // Exception edges are not considered in computing dominators/postdominators. // We will consider this to be all of the code that creates // the object. DominatorsAnalysis domAnalysis = classContext.getNonExceptionDominatorsAnalysis(method); PostDominatorsAnalysis postDomAnalysis = classContext.getNonExceptionPostDominatorsAnalysis(method); BitSet extent = domAnalysis.getAllDominatedBy(createBegin.getBasicBlock()); extent.and(postDomAnalysis.getAllDominatedBy(store.getBasicBlock())); //System.out.println("Extent: " + extent); if (DEBUG) System.out.println("Object creation extent: " + extent); // Check all instructions in the object creation extent // (1) to determine the common lock set, and // (2) to check for NEW and Invoke instructions that might create an object // We ignore matches where a lock is held consistently, // or if the extent does not appear to create a new object. LockDataflow lockDataflow = classContext.getLockDataflow(method); LockSet lockSet = null; boolean sawNEW = false, sawINVOKE = false; for (BasicBlock block : cfg.getBlocks(extent)) { for (Iterator<InstructionHandle> j = block.instructionIterator(); j.hasNext();) { InstructionHandle handle = j.next(); Location location = new Location(handle, block); // Keep track of whether we saw any instructions // that might actually have created a new object. Instruction ins = handle.getInstruction(); if (ins instanceof NEW) sawNEW = true; else if (ins instanceof InvokeInstruction) sawINVOKE = true; // Compute lock set intersection for all matched instructions. LockSet insLockSet = lockDataflow.getFactAtLocation(location); if (lockSet == null) { lockSet = new LockSet(); lockSet.copyFrom(insLockSet); } else lockSet.intersectWith(insLockSet); } } if (!(sawNEW || sawINVOKE)) return; if (lockSet == null) throw new IllegalStateException(); if (!lockSet.isEmpty()) return; // Compute the priority: // - ignore lazy initialization of instance fields // - when it's done in a public method, emit a high priority warning // - protected or default access method, emit a medium priority warning // - otherwise, low priority int priority = LOW_PRIORITY; boolean isDefaultAccess = (method.getAccessFlags() & (Constants.ACC_PUBLIC | Constants.ACC_PRIVATE | Constants.ACC_PROTECTED)) == 0; if (method.isPublic()) priority = NORMAL_PRIORITY; else if (method.isProtected() || isDefaultAccess) priority = NORMAL_PRIORITY; // Report the bug. InstructionHandle start = match.getLabeledInstruction("start"); InstructionHandle end = match.getLabeledInstruction("end"); String sourceFile = javaClass.getSourceFileName(); bugReporter.reportBug(new BugInstance(this, "LI_LAZY_INIT_STATIC", priority) .addClassAndMethod(methodGen, sourceFile) .addField(xfield).describe("FIELD_ON") .addSourceLine(classContext, methodGen, sourceFile, start, end)); } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } } } // vim:ts=4
package edu.umd.cs.findbugs.gui2; import edu.umd.cs.findbugs.BugAnnotation; import edu.umd.cs.findbugs.BugAnnotationWithSourceLines; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.ClassAnnotation; import edu.umd.cs.findbugs.FieldAnnotation; import edu.umd.cs.findbugs.FindBugs; import edu.umd.cs.findbugs.FindBugsDisplayFeatures; import edu.umd.cs.findbugs.I18N; import edu.umd.cs.findbugs.IGuiCallback; import edu.umd.cs.findbugs.MethodAnnotation; import edu.umd.cs.findbugs.Project; import edu.umd.cs.findbugs.ProjectPackagePrefixes; import edu.umd.cs.findbugs.SortedBugCollection; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.SourceFinder; import edu.umd.cs.findbugs.cloud.Cloud; import edu.umd.cs.findbugs.cloud.Cloud.CloudListener; import edu.umd.cs.findbugs.cloud.Cloud.SigninState; import edu.umd.cs.findbugs.filter.Filter; import edu.umd.cs.findbugs.filter.LastVersionMatcher; import edu.umd.cs.findbugs.filter.Matcher; import edu.umd.cs.findbugs.gui2.BugTreeModel.TreeModification; import edu.umd.cs.findbugs.log.ConsoleLogger; import edu.umd.cs.findbugs.log.LogSync; import edu.umd.cs.findbugs.log.Logger; import edu.umd.cs.findbugs.sourceViewer.NavigableTextPane; import edu.umd.cs.findbugs.util.LaunchBrowser; import edu.umd.cs.findbugs.util.Multiset; import javax.annotation.Nonnull; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.filechooser.FileFilter; import javax.swing.plaf.FontUIResource; import javax.swing.plaf.basic.BasicSplitPaneDivider; import javax.swing.plaf.basic.BasicSplitPaneUI; import javax.swing.plaf.basic.BasicTreeUI; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.text.JTextComponent; import javax.swing.text.TextAction; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.TreeSet; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Level; @SuppressWarnings("serial") /* * This is where it all happens... seriously... all of it... * All the menus are set up, all the listeners, all the frames, dockable window functionality * There is no one style used, no one naming convention, its all just kinda here. This is another one of those * classes where no one knows quite why it works. * <p> * The MainFrame is just that, the main application window where just about everything happens. */ public class MainFrame extends FBFrame implements LogSync, IGuiCallback { private AbstractExecutorService bugUpdateExecutor = new EventQueueExecutor(); static JButton newButton(String key, String name) { JButton b = new JButton(); edu.umd.cs.findbugs.L10N.localiseButton(b, key, name, false); return b; } static JMenuItem newJMenuItem(String key, String string, int vkF) { JMenuItem m = new JMenuItem(); edu.umd.cs.findbugs.L10N.localiseButton(m, key, string, false); m.setMnemonic(vkF); return m; } static JMenuItem newJMenuItem(String key, String string) { JMenuItem m = new JMenuItem(); edu.umd.cs.findbugs.L10N.localiseButton(m, key, string, true); return m; } static JMenu newJMenu(String key, String string) { JMenu m = new JMenu(); edu.umd.cs.findbugs.L10N.localiseButton(m, key, string, true); return m; } private static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(MainFrame.class.getName()); JTree tree; private BasicTreeUI treeUI; boolean userInputEnabled; static boolean isMacLookAndFeel() { return UIManager.getLookAndFeel().getClass().getName().startsWith("apple"); } static final String DEFAULT_SOURCE_CODE_MSG = edu.umd.cs.findbugs.L10N.getLocalString("msg.nosource_txt", "No available source"); static final int COMMENTS_TAB_STRUT_SIZE = 5; static final int COMMENTS_MARGIN = 5; static final int SEARCH_TEXT_FIELD_SIZE = 32; static final String TITLE_START_TXT = "FindBugs: "; private JTextField sourceSearchTextField = new JTextField(SEARCH_TEXT_FIELD_SIZE); private JButton findButton = newButton("button.find", "First"); private JButton findNextButton = newButton("button.findNext", "Next"); private JButton findPreviousButton = newButton("button.findPrev", "Previous"); public static final boolean DEBUG = SystemProperties.getBoolean("gui2.debug"); static final boolean MAC_OS_X = SystemProperties.getProperty("os.name").toLowerCase().startsWith("mac os x"); final static String WINDOW_MODIFIED = "windowModified"; NavigableTextPane sourceCodeTextPane = new NavigableTextPane(); private JScrollPane sourceCodeScrollPane; final CommentsArea comments; private SorterTableColumnModel sorter; private JTableHeader tableheader; private JLabel statusBarLabel = new JLabel(); private JLabel signedInLabel; private ImageIcon signedInIcon; private ImageIcon warningIcon; private JPanel summaryTopPanel; private final HTMLEditorKit htmlEditorKit = new HTMLEditorKit(); private final JEditorPane summaryHtmlArea = new JEditorPane(); private JScrollPane summaryHtmlScrollPane = new JScrollPane(summaryHtmlArea); final private FindBugsLayoutManagerFactory findBugsLayoutManagerFactory; final private FindBugsLayoutManager guiLayout; /* To change this value must use setProjectChanged(boolean b). * This is because saveProjectItemMenu is dependent on it for when * saveProjectMenuItem should be enabled. */ boolean projectChanged = false; final private JMenuItem reconfigMenuItem = newJMenuItem("menu.reconfig", "Reconfigure...", KeyEvent.VK_F); private JMenuItem redoAnalysis; BugLeafNode currentSelectedBugLeaf; BugAspects currentSelectedBugAspects; private JPopupMenu bugPopupMenu; private JPopupMenu branchPopupMenu; private static MainFrame instance; private RecentMenu recentMenuCache; private JMenu recentMenu; private JMenuItem preferencesMenuItem; private Project curProject = new Project(); private JScrollPane treeScrollPane; private JPanel treePanel; private Object lock = new Object(); private boolean newProject = false; final ProjectPackagePrefixes projectPackagePrefixes = new ProjectPackagePrefixes(); final CountDownLatch mainFrameInitialized = new CountDownLatch(1); private Class<?> osxAdapter; private Method osxPrefsEnableMethod; private Logger logger = new ConsoleLogger(this); SourceCodeDisplay displayer = new SourceCodeDisplay(this); private SaveType saveType = SaveType.NOT_KNOWN; FBFileChooser saveOpenFileChooser; FBFileChooser filterOpenFileChooser; @CheckForNull private File saveFile = null; enum SaveReturn {SAVE_SUCCESSFUL, SAVE_IO_EXCEPTION, SAVE_ERROR}; JMenuItem saveMenuItem = newJMenuItem("menu.save_item", "Save", KeyEvent.VK_S); public static void makeInstance(FindBugsLayoutManagerFactory factory) { if (instance != null) throw new IllegalStateException(); instance=new MainFrame(factory); instance.initializeGUI(); } public static MainFrame getInstance() { if (instance==null) throw new IllegalStateException(); return instance; } public static boolean isAvailable() { return instance != null; } private void initializeGUI() { SwingUtilities.invokeLater(new InitializeGUI()); } private MainFrame(FindBugsLayoutManagerFactory factory) { this.findBugsLayoutManagerFactory = factory; this.guiLayout = factory.getInstance(this); this.comments = new CommentsArea(this); FindBugsDisplayFeatures.setAbridgedMessages(true); } /** * Show About */ void about() { AboutDialog dialog = new AboutDialog(this, logger, true); dialog.setSize(600, 554); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } /** * Show Preferences */ void preferences() { saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); PreferencesFrame.getInstance().setLocationRelativeTo(MainFrame.this); PreferencesFrame.getInstance().setVisible(true); } /** * enable/disable preferences menu */ void enablePreferences(boolean b) { preferencesMenuItem.setEnabled(b); if (MAC_OS_X) { if (osxPrefsEnableMethod != null) { Object args[] = {Boolean.valueOf(b)}; try { osxPrefsEnableMethod.invoke(osxAdapter, args); } catch (Exception e) { System.err.println("Exception while enabling Preferences menu: " + e); } } } } /** * This method is called when the application is closing. This is either by * the exit menuItem or by clicking on the window's system menu. */ void callOnClose(){ comments.saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); if(projectChanged && !SystemProperties.getBoolean("findbugs.skipSaveChangesWarning")){ int value = JOptionPane.showConfirmDialog(MainFrame.this, getActionWithoutSavingMsg("closing"), edu.umd.cs.findbugs.L10N.getLocalString("msg.confirm_save_txt", "Do you want to save?"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if(value == JOptionPane.CANCEL_OPTION || value == JOptionPane.CLOSED_OPTION) return ; else if(value == JOptionPane.YES_OPTION){ if(saveFile == null){ if(!saveAs()) return; } else save(); } } GUISaveState.getInstance().setPreviousComments(comments.prevCommentsList); guiLayout.saveState(); GUISaveState.getInstance().setFrameBounds( getBounds() ); GUISaveState.getInstance().save(); if (this.bugCollection != null) { Cloud cloud = this.bugCollection.getCloud(); if (cloud != null) cloud.shutdown(); } System.exit(0); } /** * @return */ private String getActionWithoutSavingMsg(String action) { String msg = edu.umd.cs.findbugs.L10N.getLocalString("msg.you_are_"+action+"_without_saving_txt", null); if (msg != null) return msg; return edu.umd.cs.findbugs.L10N.getLocalString("msg.you_are_"+action+"_txt", "You are "+action) + " " + edu.umd.cs.findbugs.L10N.getLocalString("msg.without_saving_txt", "without saving. Do you want to save?"); } /* * A lot of if(false) here is for switching from special cases based on localSaveType * to depending on the SaveType.forFile(f) method. Can delete when sure works. */ JMenuItem createRecentItem(final File f, final SaveType localSaveType) { if (DEBUG) System.out.println("createRecentItem("+f+", "+localSaveType +")"); String name = f.getName(); final JMenuItem item=new JMenuItem(name); item.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { try { setCursor(new Cursor(Cursor.WAIT_CURSOR)); if (!f.exists()) { JOptionPane.showMessageDialog(null,edu.umd.cs.findbugs.L10N.getLocalString("msg.proj_not_found", "This project can no longer be found")); GUISaveState.getInstance().fileNotFound(f); return; } GUISaveState.getInstance().fileReused(f);//Move to front in GUISaveState, so it will be last thing to be removed from the list MainFrame.this.recentMenuCache.addRecentFile(f); if (!f.exists()) throw new IllegalStateException ("User used a recent projects menu item that didn't exist."); //Moved this outside of the thread, and above the line saveFile=f.getParentFile() //Since if this save goes on in the thread below, there is no way to stop the save from //overwriting the files we are about to load. if (curProject != null && projectChanged) { int response = JOptionPane.showConfirmDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_current_changes", "The current project has been changed, Save current changes?") ,edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_changes", "Save Changes?"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (response == JOptionPane.YES_OPTION) { if(saveFile != null) save(); else saveAs(); } else if (response == JOptionPane.CANCEL_OPTION) return; //IF no, do nothing. } SaveType st = SaveType.forFile(f); boolean result = true; switch(st){ case XML_ANALYSIS: result = openAnalysis(f, st); break; case FBP_FILE: result = openFBPFile(f); break; case FBA_FILE: result = openFBAFile(f); break; default: error("Wrong file type in recent menu item."); } if(!result){ JOptionPane.showMessageDialog(MainFrame.getInstance(), "There was an error in opening the file", "Recent Menu Opening Error", JOptionPane.WARNING_MESSAGE); } } finally { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); setSaveType(localSaveType); } } }); item.setFont(item.getFont().deriveFont(Driver.getFontSize())); return item; } BugCollection bugCollection; CloudListener userAnnotationListener = new CloudListener() { public void issueUpdated(BugInstance bug) { if (currentSelectedBugLeaf != null && currentSelectedBugLeaf.getBug() == bug) comments.updateCommentsFromLeafInformation(currentSelectedBugLeaf); } public void statusUpdated() { SwingUtilities.invokeLater(updateStatusBarRunner); } }; private Cloud.CloudStatusListener cloudStatusListener = new Cloud.CloudStatusListener() { public void handleIssueDataDownloadedEvent() { rebuildBugTreeIfSortablesDependOnCloud(); } public void handleStateChange(SigninState oldState, SigninState state) { rebuildBugTreeIfSortablesDependOnCloud(); } }; public void registerCloud(Project project, BugCollection collection, Cloud plugin) { assert collection.getCloud() == plugin; if (this.bugCollection == collection) { plugin.addListener(userAnnotationListener); plugin.addStatusListener(cloudStatusListener); } // setProjectAndBugCollectionInSwingThread(project, collection); } public void unregisterCloud(Project project, BugCollection collection, Cloud plugin) { assert collection.getCloud() == plugin; if (this.bugCollection == collection) { plugin.removeListener(userAnnotationListener); plugin.removeStatusListener(cloudStatusListener); } // Don't think we need to do this // setProjectAndBugCollectionInSwingThread(project, collection); } private void rebuildBugTreeIfSortablesDependOnCloud() { BugTreeModel bt=(BugTreeModel) (this.getTree().getModel()); List<Sortables> sortables = sorter.getOrderBeforeDivider(); if (sortables.contains(Sortables.DESIGNATION) || sortables.contains(Sortables.FIRST_SEEN) || sortables.contains(Sortables.FIRSTVERSION) || sortables.contains(Sortables.LASTVERSION)) { bt.rebuild(); } } public ExecutorService getBugUpdateExecutor() { return bugUpdateExecutor; } @SwingThread void setProjectWithNoBugCollection(Project project) { setProjectAndBugCollection(project, null); } @SwingThread void setBugCollection(BugCollection bugCollection) { setProjectAndBugCollection(bugCollection.getProject(), bugCollection); } @SwingThread private void setProjectAndBugCollection(@CheckForNull Project project, @CheckForNull BugCollection bugCollection) { if (DEBUG) { if (bugCollection == null) System.out.println("Setting bug collection to null"); else System.out.println("Setting bug collection; contains " + bugCollection.getCollection().size() + " bugs"); } acquireDisplayWait(); try { if (project != null) { Filter suppressionMatcher = project.getSuppressionFilter(); if (suppressionMatcher != null) { suppressionMatcher.softAdd(LastVersionMatcher.DEAD_BUG_MATCHER); } } if (this.bugCollection != bugCollection && this.bugCollection != null) { Cloud plugin = this.bugCollection.getCloud(); if (plugin != null) { plugin.removeListener(userAnnotationListener); plugin.removeStatusListener(cloudStatusListener); plugin.shutdown(); } } // setRebuilding(false); if (bugCollection != null) { setProject(project); this.bugCollection = bugCollection; displayer.clearCache(); Cloud plugin = bugCollection.getCloud(); if (plugin != null) { plugin.addListener(userAnnotationListener); plugin.addStatusListener(cloudStatusListener); } updateBugTree(); } setProjectChanged(false); Runnable runnable = new Runnable() { public void run() { PreferencesFrame.getInstance().updateFilterPanel(); reconfigMenuItem.setEnabled(true); comments.configureForCurrentCloud(); setViewMenu(); newProject(); clearSourcePane(); clearSummaryTab(); /* This is here due to a threading issue. It can only be called after * curProject has been changed. Since this method is called by both open methods * it is put here.*/ changeTitle(); }}; if (SwingUtilities.isEventDispatchThread()) runnable.run(); else SwingUtilities.invokeLater(runnable); } finally { releaseDisplayWait(); } } private void updateBugTree() { acquireDisplayWait(); try { BugTreeModel model = (BugTreeModel) getTree().getModel(); if (bugCollection != null) { BugSet bs = new BugSet(bugCollection); model.getOffListenerList(); model.changeSet(bs); if (bs.size() == 0 && bs.sizeUnfiltered() > 0) { warnUserOfFilters(); } } updateStatusBar(); changeTitle(); } finally { releaseDisplayWait(); } } void resetViewCache() { ((BugTreeModel) getTree().getModel()).clearViewCache(); } final Runnable updateStatusBarRunner = new Runnable() { public void run() { updateStatusBar(); }}; void updateProjectAndBugCollection(Project project, BugCollection bugCollection, BugTreeModel previousModel) { if (bugCollection != null) { displayer.clearCache(); BugSet bs = new BugSet(bugCollection); //Dont clear data, the data's correct, just get the tree off the listener lists. BugTreeModel model = (BugTreeModel) tree.getModel(); model.getOffListenerList(); model.changeSet(bs); //curProject=BugLoader.getLoadedProject(); setProjectChanged(true); } setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } /** * Changes the title based on curProject and saveFile. * */ public void changeTitle(){ Project project = getProject(); String name = project == null ? null : project.getProjectName(); if(name == null && saveFile != null) name = saveFile.getAbsolutePath(); if(name == null) name = Project.UNNAMED_PROJECT; String oldTitle = MainFrame.this.getTitle(); String newTitle = TITLE_START_TXT + name; if (oldTitle.equals(newTitle)) return; MainFrame.this.setTitle(newTitle); } /** * Creates popup menu for bugs on tree. * @return */ private JPopupMenu createBugPopupMenu() { JPopupMenu popupMenu = new JPopupMenu(); JMenuItem filterMenuItem = newJMenuItem("menu.filterBugsLikeThis", "Filter bugs like this"); filterMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); new NewFilterFromBug(currentSelectedBugLeaf.getBug()); setProjectChanged(true); MainFrame.getInstance().getTree().setSelectionRow(0);//Selects the top of the Jtree so the CommentsArea syncs up. } }); popupMenu.add(filterMenuItem); JMenu changeDesignationMenu = newJMenu("menu.changeDesignation", "Change bug designation"); int i = 0; int keyEvents [] = {KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4, KeyEvent.VK_5, KeyEvent.VK_6, KeyEvent.VK_7, KeyEvent.VK_8, KeyEvent.VK_9}; for(String key : I18N.instance().getUserDesignationKeys(true)) { String name = I18N.instance().getUserDesignation(key); comments.addDesignationItem(changeDesignationMenu, name, keyEvents[i++]); } popupMenu.add(changeDesignationMenu); return popupMenu; } boolean shouldDisplayIssueIgnoringPackagePrefixes(BugInstance b) { Project project = getProject(); Filter suppressionFilter = project.getSuppressionFilter(); if (null == bugCollection || suppressionFilter.match(b)) return false; return viewFilter.showIgnoringPackagePrefixes(b); } boolean shouldDisplayIssue(BugInstance b) { Project project = getProject(); Filter suppressionFilter = project.getSuppressionFilter(); if (null == bugCollection || suppressionFilter.match(b)) return false; return viewFilter.show(b); } /** * Creates the branch pop up menu that ask if the user wants * to hide all the bugs in that branch. * @return */ private JPopupMenu createBranchPopUpMenu(){ JPopupMenu popupMenu = new JPopupMenu(); JMenuItem filterMenuItem = newJMenuItem("menu.filterTheseBugs", "Filter these bugs"); filterMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { //TODO This code does a smarter version of filtering that is only possible for branches, and does so correctly //However, it is still somewhat of a hack, because if we ever add more tree listeners than simply the bugtreemodel, //They will not be called by this code. Using FilterActivity to notify all listeners will however destroy any //benefit of using the smarter deletion method. try { saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); int startCount; TreePath path=MainFrame.getInstance().getTree().getSelectionPath(); TreePath deletePath=path; startCount=((BugAspects)(path.getLastPathComponent())).getCount(); int count=((BugAspects)(path.getParentPath().getLastPathComponent())).getCount(); while(count==startCount) { deletePath=deletePath.getParentPath(); if (deletePath.getParentPath()==null)//We are at the top of the tree, don't let this be removed, rebuild tree from root. { Matcher m = currentSelectedBugAspects.getMatcher(); Filter suppressionFilter = MainFrame.getInstance().getProject().getSuppressionFilter(); suppressionFilter.addChild(m); PreferencesFrame.getInstance().updateFilterPanel(); FilterActivity.notifyListeners(FilterListener.Action.FILTERING, null); return; } count=((BugAspects)(deletePath.getParentPath().getLastPathComponent())).getCount(); } /* deletePath should now be a path to the highest ancestor branch with the same number of elements as the branch to be deleted in other words, the branch that we actually have to remove in order to correctly remove the selected branch. */ BugTreeModel model=MainFrame.getInstance().getBugTreeModel(); TreeModelEvent event=new TreeModelEvent(this,deletePath.getParentPath(), new int[]{model.getIndexOfChild(deletePath.getParentPath().getLastPathComponent(),deletePath.getLastPathComponent())}, new Object[]{deletePath.getLastPathComponent()}); Matcher m = currentSelectedBugAspects.getMatcher(); Filter suppressionFilter = MainFrame.getInstance().getProject().getSuppressionFilter(); suppressionFilter.addChild(m); PreferencesFrame.getInstance().updateFilterPanel(); model.sendEvent(event, TreeModification.REMOVE); // FilterActivity.notifyListeners(FilterListener.Action.FILTERING, null); setProjectChanged(true); MainFrame.getInstance().getTree().setSelectionRow(0);//Selects the top of the Jtree so the CommentsArea syncs up. } catch (RuntimeException e) { MainFrame.getInstance().showMessageDialog("Unable to create filter: " + e.getMessage()); } } }); popupMenu.add(filterMenuItem); JMenu changeDesignationMenu = newJMenu("menu.changeDesignation", "Change bug designation"); int i = 0; int keyEvents [] = {KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4, KeyEvent.VK_5, KeyEvent.VK_6, KeyEvent.VK_7, KeyEvent.VK_8, KeyEvent.VK_9}; for(String key : I18N.instance().getUserDesignationKeys(true)) { String name = I18N.instance().getUserDesignation(key); addDesignationItem(changeDesignationMenu, name, keyEvents[i++]); } popupMenu.add(changeDesignationMenu); return popupMenu; } /** * Creates the MainFrame's menu bar. * @return the menu bar for the MainFrame */ protected JMenuBar createMainMenuBar() { JMenuBar menuBar = new JMenuBar(); //Create JMenus for menuBar. JMenu fileMenu = newJMenu("menu.file_menu", "File"); fileMenu.setMnemonic(KeyEvent.VK_F); JMenu editMenu = newJMenu("menu.edit_menu", "Edit"); editMenu.setMnemonic(KeyEvent.VK_E); //Edit fileMenu JMenu object. JMenuItem openMenuItem = newJMenuItem("menu.open_item", "Open...", KeyEvent.VK_O); recentMenu = newJMenu("menu.recent", "Recent"); recentMenuCache=new RecentMenu(recentMenu); JMenuItem saveAsMenuItem = newJMenuItem("menu.saveas_item", "Save As...", KeyEvent.VK_A); JMenuItem importFilter = newJMenuItem("menu.importFilter_item", "Import filter..."); JMenuItem exportFilter = newJMenuItem("menu.exportFilter_item", "Export filter..."); JMenuItem exitMenuItem = null; if (!MAC_OS_X) { exitMenuItem = newJMenuItem("menu.exit", "Exit", KeyEvent.VK_X); exitMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ callOnClose(); } }); } JMenu windowMenu = guiLayout.createWindowMenu(); JMenuItem newProjectMenuItem = null; if (!FindBugs.noAnalysis) { newProjectMenuItem = newJMenuItem("menu.new_item", "New Project", KeyEvent.VK_N); attachAcceleratorKey(newProjectMenuItem, KeyEvent.VK_N); newProjectMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { newProjectMenu(); } }); } reconfigMenuItem.setEnabled(false); attachAcceleratorKey(reconfigMenuItem, KeyEvent.VK_F); reconfigMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); new NewProjectWizard(curProject); } }); JMenuItem mergeMenuItem = newJMenuItem("menu.mergeAnalysis", "Merge Analysis..."); mergeMenuItem.setEnabled(true); mergeMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ mergeAnalysis(); } }); if (!FindBugs.noAnalysis) { redoAnalysis = newJMenuItem("menu.rerunAnalysis", "Redo Analysis", KeyEvent.VK_R); redoAnalysis.setEnabled(false); attachAcceleratorKey(redoAnalysis, KeyEvent.VK_R); redoAnalysis.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ redoAnalysis(); } }); } openMenuItem.setEnabled(true); attachAcceleratorKey(openMenuItem, KeyEvent.VK_O); openMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ open(); } }); saveAsMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt) { saveAs(); } }); exportFilter.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt) { exportFilter(); } }); importFilter.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt) { importFilter(); } }); saveMenuItem.setEnabled(false); attachAcceleratorKey(saveMenuItem, KeyEvent.VK_S); saveMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt) { save(); } }); if (!FindBugs.noAnalysis) fileMenu.add(newProjectMenuItem); fileMenu.add(reconfigMenuItem); fileMenu.addSeparator(); fileMenu.add(openMenuItem); fileMenu.add(recentMenu); fileMenu.addSeparator(); fileMenu.add(importFilter); fileMenu.add(exportFilter); fileMenu.addSeparator(); fileMenu.add(saveAsMenuItem); fileMenu.add(saveMenuItem); if (!FindBugs.noAnalysis) { fileMenu.addSeparator(); fileMenu.add(redoAnalysis); } // fileMenu.add(mergeMenuItem); if (exitMenuItem != null) { fileMenu.addSeparator(); fileMenu.add(exitMenuItem); } menuBar.add(fileMenu); //Edit editMenu Menu object. JMenuItem cutMenuItem = new JMenuItem(new CutAction()); JMenuItem copyMenuItem = new JMenuItem(new CopyAction()); JMenuItem pasteMenuItem = new JMenuItem(new PasteAction()); preferencesMenuItem = newJMenuItem("menu.preferences_menu", "Filters/Suppressions..."); JMenuItem sortMenuItem = newJMenuItem("menu.sortConfiguration", "Sort Configuration..."); JMenuItem goToLineMenuItem = newJMenuItem("menu.gotoLine", "Go to line..."); attachAcceleratorKey(cutMenuItem, KeyEvent.VK_X); attachAcceleratorKey(copyMenuItem, KeyEvent.VK_C); attachAcceleratorKey(pasteMenuItem, KeyEvent.VK_V); preferencesMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ preferences(); } }); sortMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); SorterDialog.getInstance().setLocationRelativeTo(MainFrame.this); SorterDialog.getInstance().setVisible(true); } }); attachAcceleratorKey(goToLineMenuItem, KeyEvent.VK_L); goToLineMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ guiLayout.makeSourceVisible(); try{ int num = Integer.parseInt(JOptionPane.showInputDialog(MainFrame.this, "", edu.umd.cs.findbugs.L10N.getLocalString("dlg.go_to_line_lbl", "Go To Line") + ":", JOptionPane.QUESTION_MESSAGE)); displayer.showLine(num); } catch(NumberFormatException e){} }}); editMenu.add(cutMenuItem); editMenu.add(copyMenuItem); editMenu.add(pasteMenuItem); editMenu.addSeparator(); editMenu.add(goToLineMenuItem); editMenu.addSeparator(); //editMenu.add(selectAllMenuItem); // editMenu.addSeparator(); if (!MAC_OS_X) { // Preferences goes in Findbugs menu and is handled by OSXAdapter editMenu.add(preferencesMenuItem); } editMenu.add(sortMenuItem); menuBar.add(editMenu); if (windowMenu != null) menuBar.add(windowMenu); viewMenu = newJMenu("menu.view", "View"); setViewMenu(); menuBar.add(viewMenu); final ActionMap map = tree.getActionMap(); JMenu navMenu = newJMenu("menu.navigation", "Navigation"); addNavItem(map, navMenu, "menu.expand", "Expand", "expand", KeyEvent.VK_RIGHT ); addNavItem(map, navMenu, "menu.collapse", "Collapse", "collapse", KeyEvent.VK_LEFT); addNavItem(map, navMenu, "menu.up", "Up", "selectPrevious", KeyEvent.VK_UP ); addNavItem(map, navMenu, "menu.down", "Down", "selectNext", KeyEvent.VK_DOWN); menuBar.add(navMenu); JMenu designationMenu = newJMenu("menu.designation", "Designation"); int i = 0; int keyEvents [] = {KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4, KeyEvent.VK_5, KeyEvent.VK_6, KeyEvent.VK_7, KeyEvent.VK_8, KeyEvent.VK_9}; for(String key : I18N.instance().getUserDesignationKeys(true)) { String name = I18N.instance().getUserDesignation(key); addDesignationItem(designationMenu, name, keyEvents[i++]); } menuBar.add(designationMenu); if (!MAC_OS_X) { // On Mac, 'About' appears under Findbugs menu, so no need for it here JMenu helpMenu = newJMenu("menu.help_menu", "Help"); JMenuItem aboutItem = newJMenuItem("menu.about_item", "About FindBugs"); helpMenu.add(aboutItem); aboutItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { about(); } }); menuBar.add(helpMenu); } return menuBar; } static class ProjectSelector { public ProjectSelector(String projectName, String filter, int count) { this.projectName = projectName; this.filter = filter; this.count = count; } final String projectName; final String filter; final int count; @Override public String toString() { return String.format("%s -- [%d issues]", projectName, count); } } public void selectPackagePrefixByProject() { TreeSet<String> projects = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); Multiset<String> count = new Multiset<String>(); int total = 0; for (BugInstance b : bugCollection.getCollection()) if (shouldDisplayIssueIgnoringPackagePrefixes(b)){ TreeSet<String> projectsForThisBug = projectPackagePrefixes.getProjects(b.getPrimaryClass().getClassName()); projects.addAll(projectsForThisBug); count.addAll(projectsForThisBug); total++; } if (projects.size() == 0) { JOptionPane.showMessageDialog(this, "No issues in current view"); return; } ArrayList<ProjectSelector> selectors = new ArrayList<ProjectSelector>(projects.size() + 1); ProjectSelector everything = new ProjectSelector("all projects", "", total); selectors.add(everything); for (String projectName : projects) { ProjectPackagePrefixes.PrefixFilter filter = projectPackagePrefixes.getFilter(projectName); selectors.add(new ProjectSelector(projectName, filter.toString(), count.getCount(projectName))); } ProjectSelector choice = (ProjectSelector) JOptionPane.showInputDialog(null, "Choose a project to set appropriate package prefix(es)", "Select package prefixes by package", JOptionPane.QUESTION_MESSAGE, null, selectors.toArray(), everything); if (choice == null) return; textFieldForPackagesToDisplay.setText(choice.filter); viewFilter.setPackagesToDisplay(choice.filter); resetViewCache(); } JMenu viewMenu ; public void setViewMenu() { Cloud cloud = this.bugCollection == null ? null : this.bugCollection.getCloud(); viewMenu.removeAll(); if (cloud != null && cloud.supportsCloudSummaries()) { JMenuItem cloudReport = new JMenuItem("Cloud summary"); cloudReport.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayCloudReport(); } }); viewMenu.add(cloudReport); } if (projectPackagePrefixes.size() > 0 && this.bugCollection != null) { JMenuItem selectPackagePrefixMenu = new JMenuItem("Select class search strings by project..."); selectPackagePrefixMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectPackagePrefixByProject(); } }); viewMenu.add(selectPackagePrefixMenu); } if (viewMenu.getItemCount() > 0) viewMenu.addSeparator(); ButtonGroup rankButtonGroup = new ButtonGroup(); for(final ViewFilter.RankFilter r : ViewFilter.RankFilter.values()) { JRadioButtonMenuItem rbMenuItem = new JRadioButtonMenuItem(r.toString()); rankButtonGroup.add(rbMenuItem); if (r == ViewFilter.RankFilter.ALL) rbMenuItem.setSelected(true); rbMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { viewFilter.setRank(r); resetViewCache(); }}); viewMenu.add(rbMenuItem); } viewMenu.addSeparator(); if (cloud != null && cloud.getMode() == Cloud.Mode.COMMUNAL) { ButtonGroup overallClassificationButtonGroup = new ButtonGroup(); for (final ViewFilter.OverallClassificationFilter r : ViewFilter.OverallClassificationFilter.values()) { if (cloud != null && !r.supported(cloud)) continue; JRadioButtonMenuItem rbMenuItem = new JRadioButtonMenuItem(r.toString()); overallClassificationButtonGroup.add(rbMenuItem); if (r == ViewFilter.OverallClassificationFilter.ALL) rbMenuItem.setSelected(true); rbMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { viewFilter.setClassification(r); resetViewCache(); } }); viewMenu.add(rbMenuItem); } viewMenu.addSeparator(); } ButtonGroup evalButtonGroup = new ButtonGroup(); for(final ViewFilter.CloudFilter r : ViewFilter.CloudFilter.values()) { if (cloud != null && !r.supported(cloud)) continue; JRadioButtonMenuItem rbMenuItem = new JRadioButtonMenuItem(r.toString()); evalButtonGroup.add(rbMenuItem); if (r == ViewFilter.CloudFilter.ALL) rbMenuItem.setSelected(true); rbMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { viewFilter.setEvaluation(r); resetViewCache(); }}); viewMenu.add(rbMenuItem); } viewMenu.addSeparator(); ButtonGroup ageButtonGroup = new ButtonGroup(); for(final ViewFilter.FirstSeenFilter r : ViewFilter.FirstSeenFilter.values()) { JRadioButtonMenuItem rbMenuItem = new JRadioButtonMenuItem(r.toString()); ageButtonGroup.add(rbMenuItem); if (r == ViewFilter.FirstSeenFilter.ALL) rbMenuItem.setSelected(true); rbMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { viewFilter.setFirstSeen(r); resetViewCache(); }}); viewMenu.add(rbMenuItem); } } public void resetCommentsInputPane() { guiLayout.resetCommentsInputPane(); } ViewFilter viewFilter = new ViewFilter(this); /** * @param map * @param navMenu */ private void addNavItem(final ActionMap map, JMenu navMenu, String menuNameKey, String menuNameDefault, String actionName, int keyEvent) { JMenuItem toggleItem = newJMenuItem(menuNameKey, menuNameDefault); toggleItem.addActionListener(treeActionAdapter(map, actionName)); attachAcceleratorKey(toggleItem, keyEvent); navMenu.add(toggleItem); } ActionListener treeActionAdapter(ActionMap map, String actionName) { final Action selectPrevious = map.get(actionName); return new ActionListener() { public void actionPerformed(ActionEvent e) { e.setSource(tree); selectPrevious.actionPerformed(e); }}; } static void attachAcceleratorKey(JMenuItem item, int keystroke) { attachAcceleratorKey(item, keystroke, 0); } static void attachAcceleratorKey(JMenuItem item, int keystroke, int additionalMask) { // As far as I know, Mac is the only platform on which it is normal // practice to use accelerator masks such as Shift and Alt, so // if we're not running on Mac, just ignore them if (!MAC_OS_X && additionalMask != 0) { return; } item.setAccelerator(KeyStroke.getKeyStroke(keystroke, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | additionalMask)); } @SwingThread void expandTree() { expandTree(Integer.MAX_VALUE); } @SwingThread void expandTree(int max) { Debug.printf("expandTree(%d)\n", max); JTree jTree = getTree(); int i = 0; while (true) { int rows = jTree.getRowCount(); if (i >= rows || rows >= max) break; jTree.expandRow(i++); } } @SwingThread boolean leavesShown() { JTree jTree = getTree(); int rows = jTree.getRowCount(); for(int i = 0; i < rows; i++) { TreePath treePath = jTree.getPathForRow(i); Object lastPathComponent = treePath.getLastPathComponent(); if (lastPathComponent instanceof BugLeafNode) return true; } return false; } @SwingThread void expandToFirstLeaf(int max) { Debug.println("expand to first leaf"); if (leavesShown()) return; JTree jTree = getTree(); int i = 0; while (true) { int rows = jTree.getRowCount(); if (i >= rows || rows >= max) break; TreePath treePath = jTree.getPathForRow(i); Object lastPathComponent = treePath.getLastPathComponent(); if (lastPathComponent instanceof BugLeafNode) return; jTree.expandRow(i++); } } void newProject(){ clearSourcePane(); if (!FindBugs.noAnalysis) { if (curProject == null) redoAnalysis.setEnabled(false); else { List<String> fileList = curProject.getFileList(); redoAnalysis.setEnabled(!fileList.isEmpty()); } } if(newProject){ setProjectChanged(true); // setTitle(TITLE_START_TXT + Project.UNNAMED_PROJECT); saveFile = null; saveMenuItem.setEnabled(false); reconfigMenuItem.setEnabled(true); newProject=false; } } /** * This method is for when the user wants to open a file. */ private void importFilter() { filterOpenFileChooser.setDialogTitle(edu.umd.cs.findbugs.L10N.getLocalString("dlg.importFilter_ttl", "Import and merge filter...")); boolean retry = true; File f = null; while (retry) { retry = false; int value = filterOpenFileChooser.showOpenDialog(MainFrame.this); if (value != JFileChooser.APPROVE_OPTION) return; f = filterOpenFileChooser.getSelectedFile(); if (!f.exists()) { JOptionPane.showMessageDialog(filterOpenFileChooser, "No such file", "Invalid File", JOptionPane.WARNING_MESSAGE); retry = true; continue; } Filter filter; try { filter = Filter.parseFilter(f.getPath()); } catch (IOException e) { JOptionPane.showMessageDialog(filterOpenFileChooser, "Could not load filter."); retry = true; continue; } projectChanged = true; if (getProject().getSuppressionFilter() == null) { getProject().setSuppressionFilter(filter); } else { for (Matcher m : filter.getChildren()) getProject().getSuppressionFilter().addChild(m); } PreferencesFrame.getInstance().updateFilterPanel(); } } /** * This method is for when the user wants to open a file. */ private void open(){ saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); if (projectChanged) { int response = JOptionPane.showConfirmDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_current_changes", "The current project has been changed, Save current changes?") ,edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_changes", "Save Changes?"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (response == JOptionPane.YES_OPTION) { if (saveFile!=null) save(); else saveAs(); } else if (response == JOptionPane.CANCEL_OPTION) return; //IF no, do nothing. } boolean loading = true; SaveType fileType = SaveType.NOT_KNOWN; tryAgain: while (loading) { int value=saveOpenFileChooser.showOpenDialog(MainFrame.this); if(value!=JFileChooser.APPROVE_OPTION) return; loading = false; fileType = convertFilterToType(saveOpenFileChooser.getFileFilter()); final File f = saveOpenFileChooser.getSelectedFile(); if(!fileType.isValid(f)){ JOptionPane.showMessageDialog(saveOpenFileChooser, "That file is not compatible with the choosen file type", "Invalid File", JOptionPane.WARNING_MESSAGE); loading = true; continue; } switch (fileType) { case XML_ANALYSIS: if(!f.getName().endsWith(".xml")){ JOptionPane.showMessageDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("dlg.not_xml_data_lbl", "This is not a saved bug XML data file.")); loading=true; continue tryAgain; } if(!openAnalysis(f, fileType)){ //TODO: Deal if something happens when loading analysis JOptionPane.showMessageDialog(saveOpenFileChooser, "An error occurred while trying to load the analysis."); loading=true; continue tryAgain; } break; case FBP_FILE: if(!openFBPFile(f)){ //TODO: Deal if something happens when loading analysis JOptionPane.showMessageDialog(saveOpenFileChooser, "An error occurred while trying to load the analysis."); loading=true; continue tryAgain; } break; case FBA_FILE: if(!openFBAFile(f)){ //TODO: Deal if something happens when loading analysis JOptionPane.showMessageDialog(saveOpenFileChooser, "An error occurred while trying to load the analysis."); loading=true; continue tryAgain; } break; } } } /** * Method called to open FBA file. * @param f * @return */ private boolean openFBAFile(File f) { return openAnalysis(f, SaveType.FBA_FILE); } /** * Method called to open FBP file. * @param f * @return */ private boolean openFBPFile(File f) { if (!f.exists() || !f.canRead()) { return false; } prepareForFileLoad(f, SaveType.FBP_FILE); loadProjectFromFile(f); return true; } private boolean exportFilter() { if (getProject().getSuppressionFilter() == null) { JOptionPane.showMessageDialog(MainFrame.this,edu.umd.cs.findbugs.L10N.getLocalString("dlg.no_filter", "There is no filter")); return false; } filterOpenFileChooser.setDialogTitle(edu.umd.cs.findbugs.L10N.getLocalString("dlg.exportFilter_ttl", "Export filter...")); boolean retry = true; boolean alreadyExists = true; File f = null; while(retry){ retry = false; int value=filterOpenFileChooser.showSaveDialog(MainFrame.this); if (value!=JFileChooser.APPROVE_OPTION) return false; f = filterOpenFileChooser.getSelectedFile(); alreadyExists = f.exists(); if(alreadyExists){ int response = JOptionPane.showConfirmDialog(filterOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("dlg.file_exists_lbl", "This file already exists.\nReplace it?"), edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if(response == JOptionPane.OK_OPTION) retry = false; if(response == JOptionPane.CANCEL_OPTION){ retry = true; continue; } } Filter suppressionFilter = getProject().getSuppressionFilter(); try { suppressionFilter.writeEnabledMatchersAsXML(new FileOutputStream(f)); } catch (IOException e) { JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.saving_error_lbl", "An error occurred in saving.")); return false; } } return true; } private boolean saveAs(){ saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); saveOpenFileChooser.setDialogTitle(edu.umd.cs.findbugs.L10N.getLocalString("dlg.saveas_ttl", "Save as...")); if (curProject==null) { JOptionPane.showMessageDialog(MainFrame.this,edu.umd.cs.findbugs.L10N.getLocalString("dlg.no_proj_save_lbl", "There is no project to save")); return false; } boolean retry = true; SaveType fileType = SaveType.NOT_KNOWN; boolean alreadyExists = true; File f = null; while(retry){ retry = false; int value=saveOpenFileChooser.showSaveDialog(MainFrame.this); if (value!=JFileChooser.APPROVE_OPTION) return false; fileType = convertFilterToType(saveOpenFileChooser.getFileFilter()); if(fileType == SaveType.NOT_KNOWN){ Debug.println("Error! fileType == SaveType.NOT_KNOWN"); //This should never happen b/c saveOpenFileChooser can only display filters //given it. retry = true; continue; } f = saveOpenFileChooser.getSelectedFile(); f = convertFile(f, fileType); if(!fileType.isValid(f)){ JOptionPane.showMessageDialog(saveOpenFileChooser, "That file is not compatible with the chosen file type", "Invalid File", JOptionPane.WARNING_MESSAGE); retry = true; continue; } alreadyExists = fileAlreadyExists(f, fileType); if(alreadyExists){ int response = -1; switch(fileType){ case XML_ANALYSIS: response = JOptionPane.showConfirmDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("dlg.analysis_exists_lbl", "This analysis already exists.\nReplace it?"), edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); break; case FBP_FILE: response = JOptionPane.showConfirmDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("FB Project File already exists", "This FB project file already exists.\nDo you want to replace it?"), edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); break; case FBA_FILE: response = JOptionPane.showConfirmDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("FB Analysis File already exists", "This FB analysis file already exists.\nDo you want to replace it?"), edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); break; } if(response == JOptionPane.OK_OPTION) retry = false; if(response == JOptionPane.CANCEL_OPTION){ retry = true; continue; } } SaveReturn successful = SaveReturn.SAVE_ERROR; switch(fileType){ case XML_ANALYSIS: successful = saveAnalysis(f); break; case FBA_FILE: successful = saveFBAFile(f); break; case FBP_FILE: successful = saveFBPFile(f); break; } if (successful != SaveReturn.SAVE_SUCCESSFUL) { JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.saving_error_lbl", "An error occurred in saving.")); return false; } } assert f != null; // saveProjectMenuItem.setEnabled(false); saveMenuItem.setEnabled(false); setSaveType(fileType); saveFile = f; File xmlFile=f; addFileToRecent(xmlFile, getSaveType()); return true; } /* * Returns SaveType equivalent depending on what kind of FileFilter passed. */ private SaveType convertFilterToType(FileFilter f){ if (f instanceof FindBugsFileFilter) return ((FindBugsFileFilter)f).getSaveType(); return SaveType.NOT_KNOWN; } /* * Depending on File and SaveType determines if f already exists. Returns false if not * exist, true otherwise. For a project calls * OriginalGUI2ProjectFile.fileContainingXMLData(f).exists */ private boolean fileAlreadyExists(File f, SaveType fileType){ return f.exists(); } /* * If f is not of type FileType will convert file so it is. */ private File convertFile(File f, SaveType fileType){ //Checks that it has the correct file extension, makes a new file if it doesn't. if(!f.getName().endsWith(fileType.getFileExtension())) f = new File(f.getAbsolutePath() + fileType.getFileExtension()); return f; } private void save(){ File sFile = saveFile; assert sFile != null; saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); SaveReturn result = SaveReturn.SAVE_ERROR; switch(getSaveType()){ case XML_ANALYSIS: result = saveAnalysis(sFile); break; case FBA_FILE: result = saveFBAFile(sFile); break; case FBP_FILE: result = saveFBPFile(sFile); break; } if(result != SaveReturn.SAVE_SUCCESSFUL){ JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString( "dlg.saving_error_lbl", "An error occurred in saving.")); } } /** * @param saveFile2 * @return */ private SaveReturn saveFBAFile(File saveFile2) { return saveAnalysis(saveFile2); } /** * @param saveFile2 * @return */ private SaveReturn saveFBPFile(File saveFile2) { saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); try { getProject().writeXML(saveFile2); } catch (IOException e) { AnalysisContext.logError("Couldn't save FBP file to " + saveFile2, e); return SaveReturn.SAVE_IO_EXCEPTION; } setProjectChanged(false); return SaveReturn.SAVE_SUCCESSFUL; } enum BugCard {TREECARD, WAITCARD}; int waitCount = 0; final Object waitLock = new Object(); public void acquireDisplayWait() { synchronized(waitLock) { waitCount++; if (DEBUG) new RuntimeException("acquiring display wait, count " + waitCount).printStackTrace(System.out); if (waitCount == 1) showCard(BugCard.WAITCARD, new Cursor(Cursor.WAIT_CURSOR)); } } public void releaseDisplayWait() { synchronized(waitLock) { if (waitCount <= 0) throw new AssertionError("Can't decrease wait count; already zero"); waitCount if (DEBUG) new RuntimeException("releasing display wait, count " + waitCount).printStackTrace(System.out); if (waitCount == 0) showCard(BugCard.TREECARD, new Cursor(Cursor.DEFAULT_CURSOR)); } } // public void acquireDisplayLock() { // acquireDisplayWait(); // public void releaseDisplayLock() { // releaseDisplayWait(); private void showCard(final BugCard card, final Cursor cursor) { Runnable doRun = new Runnable() { public void run() { recentMenu.setEnabled(card == BugCard.TREECARD); tableheader.setReorderingAllowed(card == BugCard.TREECARD); enablePreferences(card == BugCard.TREECARD); setCursor(cursor); CardLayout layout = (CardLayout) cardPanel.getLayout(); layout.show(cardPanel, card.name()); if (card == BugCard.TREECARD) SorterDialog.getInstance().thaw(); else SorterDialog.getInstance().freeze(); } }; if (SwingUtilities.isEventDispatchThread()) doRun.run(); else SwingUtilities.invokeLater(doRun); } JPanel waitPanel, cardPanel; JPanel makeNavigationPanel(String packageSelectorLabel, JComponent packageSelector, JComponent treeHeader, JComponent tree) { JPanel topPanel = new JPanel(); topPanel.setMinimumSize(new Dimension(150,150)); topPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.ipadx = c.ipady = 3; c.insets = new Insets(6,6,6,6); c.gridx = 0; c.gridy = 0; c.fill=GridBagConstraints.NONE; JLabel label = new JLabel(packageSelectorLabel); topPanel.add(label, c); c.gridx = 1; c.fill=GridBagConstraints.HORIZONTAL; c.weightx = 1; topPanel.add(packageSelector, c); c.gridx = 0; c.gridwidth=2; c.gridy++; c.ipadx = c.ipady = 2; c.fill = GridBagConstraints.HORIZONTAL; topPanel.add(treeHeader, c); c.fill = GridBagConstraints.BOTH; c.gridy++; c.weighty = 1; c.ipadx = c.ipady = 0; c.insets = new Insets(0,0,0,0); topPanel.add(tree, c); return topPanel; } /** * * @return */ JPanel bugListPanel() { tableheader = new JTableHeader(); tableheader.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR)); //Listener put here for when user double clicks on sorting //column header SorterDialog appears. tableheader.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { Debug.println("tableheader.getReorderingAllowed() = " + tableheader.getReorderingAllowed()); if (!tableheader.getReorderingAllowed()) return; if (e.getClickCount()==2) SorterDialog.getInstance().setVisible(true); } @Override public void mouseReleased(MouseEvent arg0) { if (!tableheader.getReorderingAllowed()) return; BugTreeModel bt=(BugTreeModel) (MainFrame.this.getTree().getModel()); bt.checkSorter(); } }); sorter = GUISaveState.getInstance().getStarterTable(); tableheader.setColumnModel(sorter); tableheader.setToolTipText(edu.umd.cs.findbugs.L10N.getLocalString("tooltip.reorder_message", "Drag to reorder tree folder and sort order")); tree = new JTree(); treeUI = (BasicTreeUI) tree.getUI(); tree.setLargeModel(true); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setCellRenderer(new BugRenderer()); tree.setRowHeight((int)(Driver.getFontSize() + 7)); if (false) { System.out.println("Left indent had been " + treeUI.getLeftChildIndent()); System.out.println("Right indent had been " + treeUI.getRightChildIndent()); treeUI.setLeftChildIndent(30 ); treeUI.setRightChildIndent(30 ); } tree.setModel(new BugTreeModel(tree, sorter, new BugSet(new ArrayList<BugLeafNode>()))); setupTreeListeners(); setProject(new Project()); treeScrollPane = new JScrollPane(tree); treePanel = new JPanel(new BorderLayout()); treePanel.add(treeScrollPane, BorderLayout.CENTER); //New code to fix problem in Windows JTable t = new JTable(new DefaultTableModel(0, sortables().length)); t.setTableHeader(tableheader); if (false) { JScrollPane tableHeaderScrollPane = new JScrollPane(t); //This sets the height of the scrollpane so it is dependent on the fontsize. int num = (int) (Driver.getFontSize()); tableHeaderScrollPane.setPreferredSize(new Dimension(0, 0)); tableHeaderScrollPane.setMaximumSize(new Dimension(200, 5)); } //End of new code. //Changed code. textFieldForPackagesToDisplay = new JTextField(); ActionListener filterAction = new ActionListener() { public void actionPerformed(ActionEvent e) { try { viewFilter.setPackagesToDisplay(textFieldForPackagesToDisplay.getText()); resetViewCache(); } catch (IllegalArgumentException err) { JOptionPane.showMessageDialog(MainFrame.this, err.getMessage(), "Bad class search string", JOptionPane.ERROR_MESSAGE); } } }; textFieldForPackagesToDisplay.addActionListener(filterAction); JButton filterButton = new JButton("Filter"); filterButton.addActionListener(filterAction); JPanel filterPanel = new JPanel(); filterPanel.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 1; gbc.fill = GridBagConstraints.BOTH; gbc.gridy = 1; filterPanel.add(textFieldForPackagesToDisplay, gbc); gbc.weightx = 0; gbc.fill = GridBagConstraints.NONE; filterPanel.add(filterButton, gbc); filterPanel.setToolTipText("Only show classes containing the word(s) you specify"); JPanel sortablePanel = new JPanel(new GridBagLayout()); JLabel sortableLabel = new JLabel("Group bugs by:"); sortableLabel.setLabelFor(tableheader); gbc = new GridBagConstraints(); gbc.weightx = 0; gbc.gridy = 1; gbc.insets = new Insets(3,3,3,3); gbc.fill = GridBagConstraints.BOTH; sortablePanel.add(sortableLabel, gbc); gbc.weightx = 1; sortablePanel.add(tableheader, gbc); tableheader.setBorder(new LineBorder(Color.BLACK)); JPanel topPanel = makeNavigationPanel("Class name filter:", filterPanel, sortablePanel, treePanel); cardPanel = new JPanel(new CardLayout()); waitPanel = new JPanel(); waitPanel.setLayout(new BoxLayout(waitPanel, BoxLayout.Y_AXIS)); waitPanel.add(new JLabel("Please wait...")); waitStatusLabel = new JLabel(); waitPanel.add(waitStatusLabel); cardPanel.add(topPanel, BugCard.TREECARD.name()); cardPanel.add(waitPanel, BugCard.WAITCARD.name()); return cardPanel; } JTextField textFieldForPackagesToDisplay; public void newTree(final JTree newTree, final BugTreeModel newModel) { SwingUtilities.invokeLater(new Runnable() { public void run() { tree = newTree; tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setLargeModel(true); tree.setCellRenderer(new BugRenderer()); treePanel.remove(treeScrollPane); treeScrollPane = new JScrollPane(newTree); treePanel.add(treeScrollPane); setFontSizeHelper(Driver.getFontSize(), treeScrollPane); tree.setRowHeight((int)(Driver.getFontSize() + 7)); MainFrame.this.getContentPane().validate(); MainFrame.this.getContentPane().repaint(); setupTreeListeners(); newModel.openPreviouslySelected(((BugTreeModel)(tree.getModel())).getOldSelectedBugs()); MainFrame.this.expandTree(10); MainFrame.this.expandToFirstLeaf(14); MainFrame.this.getSorter().addColumnModelListener(newModel); FilterActivity.addFilterListener(newModel.bugTreeFilterListener); MainFrame.this.setSorting(true); } }); } private void setupTreeListeners() { if (false) tree.addTreeExpansionListener(new TreeExpansionListener(){ public void treeExpanded(TreeExpansionEvent event) { System.out.println("Tree expanded"); TreePath path = event.getPath(); Object lastPathComponent = path.getLastPathComponent(); int children = tree.getModel().getChildCount(lastPathComponent); if (children == 1) { Object o = tree.getModel().getChild(lastPathComponent, 0); if (o instanceof BugAspects) { final TreePath p = path.pathByAddingChild(o); SwingUtilities.invokeLater(new Runnable() { public void run() {try { System.out.println("auto expanding " + p); tree.expandPath(p); } catch (Exception e) { e.printStackTrace(); } }}); } } } public void treeCollapsed(TreeExpansionEvent event) { // do nothing }}); tree.addTreeSelectionListener(new TreeSelectionListener(){ public void valueChanged(TreeSelectionEvent selectionEvent) { TreePath path = selectionEvent.getNewLeadSelectionPath(); if (path != null) { saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); Object lastPathComponent = path.getLastPathComponent(); if (lastPathComponent instanceof BugLeafNode) { boolean beforeProjectChanged = projectChanged; currentSelectedBugLeaf = (BugLeafNode)lastPathComponent; currentSelectedBugAspects = null; syncBugInformation(); setProjectChanged(beforeProjectChanged); } else { boolean beforeProjectChanged = projectChanged; updateDesignationDisplay(); currentSelectedBugLeaf = null; currentSelectedBugAspects = (BugAspects)lastPathComponent; syncBugInformation(); setProjectChanged(beforeProjectChanged); } } // Debug.println("Tree selection count:" + tree.getSelectionCount()); if (tree.getSelectionCount() !=1) { Debug.println("Tree selection count not equal to 1, disabling comments tab" + selectionEvent); MainFrame.this.setUserCommentInputEnable(false); } } }); tree.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent e) { TreePath path = tree.getPathForLocation(e.getX(), e.getY()); if(path == null) return; if ((e.getButton() == MouseEvent.BUTTON3) || (e.getButton() == MouseEvent.BUTTON1 && e.isControlDown())){ if (tree.getModel().isLeaf(path.getLastPathComponent())){ tree.setSelectionPath(path); bugPopupMenu.show(tree, e.getX(), e.getY()); } else{ tree.setSelectionPath(path); if (!(path.getParentPath()==null))//If the path's parent path is null, the root was selected, dont allow them to filter out the root. branchPopupMenu.show(tree, e.getX(), e.getY()); } } } public void mousePressed(MouseEvent arg0) {} public void mouseReleased(MouseEvent arg0) {} public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} }); } void syncBugInformation (){ boolean prevProjectChanged = projectChanged; if (currentSelectedBugLeaf != null) { BugInstance bug = currentSelectedBugLeaf.getBug(); displayer.displaySource(bug, bug.getPrimarySourceLineAnnotation()); updateDesignationDisplay(); comments.updateCommentsFromLeafInformation(currentSelectedBugLeaf); updateSummaryTab(currentSelectedBugLeaf); } else if (currentSelectedBugAspects != null) { updateDesignationDisplay(); comments.updateCommentsFromNonLeafInformation(currentSelectedBugAspects); displayer.displaySource(null, null); clearSummaryTab(); } else { displayer.displaySource(null, null); clearSummaryTab(); } setProjectChanged(prevProjectChanged); } /** * Clears the source code text pane. * */ void clearSourcePane(){ SwingUtilities.invokeLater(new Runnable(){ public void run(){ setSourceTab("", null); sourceCodeTextPane.setDocument(SourceCodeDisplay.SOURCE_NOT_RELEVANT); } }); } /** * @param b */ private void setUserCommentInputEnable(boolean b) { comments.setUserCommentInputEnable(b); } /** * Creates the status bar of the GUI. * @return */ JPanel statusBar() { JPanel statusBar = new JPanel(); // statusBar.setBackground(Color.WHITE); statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED)); statusBar.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.fill = GridBagConstraints.BOTH; constraints.gridy = 0; constraints.weightx = 1; statusBar.add(statusBarLabel, constraints.clone()); constraints.weightx = 0; constraints.fill = GridBagConstraints.NONE; try { signedInIcon = loadImageResource("greencircle.png", 16, 16); warningIcon = loadImageResource("warningicon.png", 16, 16); } catch (IOException e) { LOGGER.log(Level.WARNING, "Could not load status icons", e); signedInIcon = null; warningIcon = null; } signedInLabel = new JLabel(); signedInLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); signedInLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { JPopupMenu menu = new JPopupMenu(); SigninState signinState = bugCollection.getCloud().getSigninState(); boolean isSignedIn = signinState == Cloud.SigninState.SIGNED_IN; final JCheckBoxMenuItem signInAuto = new JCheckBoxMenuItem("Sign in automatically"); signInAuto.setToolTipText("Saves your Cloud session for the next time you run FindBugs. " + "No personal information or passwords are saved."); signInAuto.setSelected(bugCollection.getCloud().isSavingSignInInformationEnabled()); signInAuto.setEnabled(isSignedIn); signInAuto.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { boolean checked = signInAuto.isSelected(); if (checked != bugCollection.getCloud().isSavingSignInInformationEnabled()) { System.out.println("checked: " + checked); bugCollection.getCloud().setSaveSignInInformation(checked); } } }); menu.add(signInAuto); switch (signinState) { case SIGNED_OUT: case UNAUTHENTICATED: case SIGNIN_FAILED: menu.add(new AbstractAction("Sign in") { public void actionPerformed(ActionEvent e) { try { bugCollection.getCloud().signIn(); } catch (IOException e1) { showMessageDialog("Sign-in error: " + e1.getMessage()); LOGGER.log(Level.SEVERE, "Could not sign in", e1); } } }); break; default: menu.add(new AbstractAction("Sign out") { public void actionPerformed(ActionEvent e) { bugCollection.getCloud().signOut(); } }).setEnabled(isSignedIn); } menu.show(e.getComponent(), e.getX(), e.getY()); } }); constraints.anchor = GridBagConstraints.EAST; constraints.insets = new Insets(0,5,0,5); statusBar.add(signedInLabel, constraints.clone()); signedInLabel.setVisible(false); JLabel logoLabel = new JLabel(); constraints.insets = new Insets(0,0,0,0); ImageIcon logoIcon = new ImageIcon(MainFrame.class.getResource("logo_umd.png")); logoLabel.setIcon(logoIcon); logoLabel.setPreferredSize(new Dimension(logoIcon.getIconWidth(), logoIcon.getIconHeight())); constraints.anchor = GridBagConstraints.WEST; statusBar.add(logoLabel, constraints.clone()); return statusBar; } private ImageIcon loadImageResource(String filename, int width, int height) throws IOException { return new ImageIcon(ImageIO.read(MainFrame.class.getResource(filename)).getScaledInstance(width, height, Image.SCALE_SMOOTH)); } private String join(String s1, String s2) { if (s1 == null || s1.length() == 0) return s2; if (s2 == null || s2.length() == 0) return s1; return s1 + "; " + s2; } @SwingThread void updateStatusBar() { int countFilteredBugs = BugSet.countFilteredBugs(); String msg = ""; if (countFilteredBugs == 1) { msg = " 1 " + edu.umd.cs.findbugs.L10N.getLocalString("statusbar.bug_hidden", "bug hidden by filters"); } else if (countFilteredBugs > 1) { msg = " " + countFilteredBugs + " " + edu.umd.cs.findbugs.L10N.getLocalString("statusbar.bugs_hidden", "bugs hidden by filters"); } boolean showLoggedInStatus = false; if (bugCollection != null) { Cloud plugin = bugCollection.getCloud(); if (plugin != null) { String pluginMsg = plugin.getStatusMsg(); if (pluginMsg != null && pluginMsg.length() > 1) msg = join(msg, pluginMsg); SigninState state = plugin.getSigninState(); if (state == SigninState.SIGNING_IN) { signedInLabel.setText("<html>FindBugs Cloud:<br> signing in"); signedInLabel.setIcon(null); showLoggedInStatus = true; } else if (state == Cloud.SigninState.SIGNED_IN) { signedInLabel.setText("<html>FindBugs Cloud:<br> signed in as " + plugin.getUser()); signedInLabel.setIcon(signedInIcon); showLoggedInStatus = true; } else if (state == SigninState.SIGNIN_FAILED) { signedInLabel.setText("<html>FindBugs Cloud:<br> sign-in failed"); signedInLabel.setIcon(warningIcon); showLoggedInStatus = true; } else if (state == SigninState.SIGNED_OUT || state == SigninState.UNAUTHENTICATED) { signedInLabel.setText("<html>FindBugs Cloud:<br> not signed in"); signedInLabel.setIcon(null); showLoggedInStatus = true; } } } signedInLabel.setVisible(showLoggedInStatus); if (errorMsg != null && errorMsg.length() > 0) msg = join(msg, errorMsg); waitStatusLabel.setText(msg); // should not be the URL if (msg.length() == 0) msg = "http://findbugs.sourceforge.net"; statusBarLabel.setText(msg); } volatile String errorMsg = ""; public void setErrorMessage(String errorMsg) { this.errorMsg = errorMsg; SwingUtilities.invokeLater(new Runnable(){ public void run() { updateStatusBar(); }}); } private void updateSummaryTab(BugLeafNode node) { final BugInstance bug = node.getBug(); SwingUtilities.invokeLater(new Runnable(){ public void run(){ summaryTopPanel.removeAll(); summaryTopPanel.add(bugSummaryComponent(bug.getAbridgedMessage(), bug)); for(BugAnnotation b : bug.getAnnotationsForMessage(true)) summaryTopPanel.add(bugSummaryComponent(b, bug)); summaryHtmlArea.setText(bug.getBugPattern().getDetailHTML()); summaryTopPanel.add(Box.createVerticalGlue()); summaryTopPanel.revalidate(); SwingUtilities.invokeLater(new Runnable(){ public void run(){ summaryHtmlScrollPane.getVerticalScrollBar().setValue(summaryHtmlScrollPane.getVerticalScrollBar().getMinimum()); } }); } }); } private void clearSummaryTab() { summaryHtmlArea.setText(""); summaryTopPanel.removeAll(); summaryTopPanel.revalidate(); } /** * Creates initial summary tab and sets everything up. * @return */ JSplitPane summaryTab() { int fontSize = (int) Driver.getFontSize(); summaryTopPanel = new JPanel(); summaryTopPanel.setLayout(new GridLayout(0,1)); summaryTopPanel.setBorder(BorderFactory.createEmptyBorder(2,4,2,4)); summaryTopPanel.setMinimumSize(new Dimension(fontSize * 50, fontSize*5)); JPanel summaryTopOuter = new JPanel(new BorderLayout()); summaryTopOuter.add(summaryTopPanel, BorderLayout.NORTH); summaryHtmlArea.setToolTipText(edu.umd.cs.findbugs.L10N.getLocalString("tooltip.longer_description", "This gives a longer description of the detected bug pattern")); summaryHtmlArea.setContentType("text/html"); summaryHtmlArea.setEditable(false); summaryHtmlArea.addHyperlinkListener(new javax.swing.event.HyperlinkListener() { public void hyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) { AboutDialog.editorPaneHyperlinkUpdate(evt); } }); setStyleSheets(); //JPanel temp = new JPanel(new BorderLayout()); //temp.add(summaryTopPanel, BorderLayout.CENTER); JScrollPane summaryScrollPane = new JScrollPane(summaryTopOuter); summaryScrollPane.getVerticalScrollBar().setUnitIncrement( (int)Driver.getFontSize() ); JSplitPane splitP = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, summaryScrollPane, summaryHtmlScrollPane); splitP.setDividerLocation(GUISaveState.getInstance().getSplitSummary()); splitP.setOneTouchExpandable(true); splitP.setUI(new BasicSplitPaneUI() { @Override public BasicSplitPaneDivider createDefaultDivider() { return new BasicSplitPaneDivider(this) { @Override public void setBorder(Border b) { } }; } }); splitP.setBorder(null); return splitP; } /** * Creates bug summary component. If obj is a string will create a JLabel * with that string as it's text and return it. If obj is an annotation * will return a JLabel with the annotation's toString(). If that * annotation is a SourceLineAnnotation or has a SourceLineAnnotation * connected to it and the source file is available will attach * a listener to the label. * @param obj * @param bug TODO * @return */ private Component bugSummaryComponent(String str, BugInstance bug){ JLabel label = new JLabel(); label.setFont(label.getFont().deriveFont(Driver.getFontSize())); label.setFont(label.getFont().deriveFont(Font.PLAIN)); label.setForeground(Color.BLACK); label.setText(str); SourceLineAnnotation link = bug.getPrimarySourceLineAnnotation(); if (link != null) label.addMouseListener(new BugSummaryMouseListener(bug, label, link)); return label; } private Component bugSummaryComponent(BugAnnotation value, BugInstance bug){ JLabel label = new JLabel(); label.setFont(label.getFont().deriveFont(Driver.getFontSize())); label.setFont(label.getFont().deriveFont(Font.PLAIN)); label.setForeground(Color.BLACK); ClassAnnotation primaryClass = bug.getPrimaryClass(); String sourceCodeLabel = edu.umd.cs.findbugs.L10N.getLocalString("summary.source_code", "source code."); String summaryLine = edu.umd.cs.findbugs.L10N.getLocalString("summary.line", "Line"); String summaryLines = edu.umd.cs.findbugs.L10N.getLocalString("summary.lines", "Lines"); String clickToGoToText = edu.umd.cs.findbugs.L10N.getLocalString("tooltip.click_to_go_to", "Click to go to"); if (value instanceof SourceLineAnnotation) { final SourceLineAnnotation link = (SourceLineAnnotation) value; if (sourceCodeExists(link)) { String srcStr = ""; int start = link.getStartLine(); int end = link.getEndLine(); if (start < 0 && end < 0) srcStr = sourceCodeLabel; else if (start == end) srcStr = " [" + summaryLine + " " + start + "]"; else if (start < end) srcStr = " [" + summaryLines + " " + start + " - " + end + "]"; label.setToolTipText(clickToGoToText + " " + srcStr); label.addMouseListener(new BugSummaryMouseListener(bug, label, link)); } label.setText(link.toString()); } else if (value instanceof BugAnnotationWithSourceLines) { BugAnnotationWithSourceLines note = (BugAnnotationWithSourceLines) value; final SourceLineAnnotation link = note.getSourceLines(); String srcStr = ""; if (link != null && sourceCodeExists(link)) { int start = link.getStartLine(); int end = link.getEndLine(); if (start < 0 && end < 0) srcStr = sourceCodeLabel; else if (start == end) srcStr = " [" + summaryLine + " " + start + "]"; else if (start < end) srcStr = " [" + summaryLines + " " + start + " - " + end + "]"; if (!srcStr.equals("")) { label.setToolTipText(clickToGoToText + " " + srcStr); label.addMouseListener(new BugSummaryMouseListener(bug, label, link)); } } String noteText; if (note == bug.getPrimaryMethod() || note == bug.getPrimaryField()) noteText = note.toString(); else noteText = note.toString(primaryClass); if (!srcStr.equals(sourceCodeLabel)) label.setText(noteText + srcStr); else label.setText(noteText); } else { label.setText(value.toString(primaryClass)); } return label; } /** * @author pugh */ private final class InitializeGUI implements Runnable { public void run() { setTitle("FindBugs"); try { guiLayout.initialize(); } catch(Exception e) { // If an exception was encountered while initializing, this may // be because of a bug in the particular look-and-feel selected // (as in sourceforge bug 1899648). In an attempt to recover // gracefully, this code reverts to the cross-platform look- // and-feel and attempts again to initialize the layout. if(!UIManager.getLookAndFeel().getName().equals("Metal")) { System.err.println("Exception caught initializing GUI; reverting to CrossPlatformLookAndFeel"); try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch(Exception e2) { System.err.println("Exception while setting CrossPlatformLookAndFeel: " + e2); throw new Error(e2); } guiLayout.initialize(); } else { throw new Error(e); } } bugPopupMenu = createBugPopupMenu(); branchPopupMenu = createBranchPopUpMenu(); comments.loadPrevCommentsList(GUISaveState.getInstance().getPreviousComments().toArray(new String[GUISaveState.getInstance().getPreviousComments().size()])); updateStatusBar(); setBounds(GUISaveState.getInstance().getFrameBounds()); Toolkit.getDefaultToolkit().setDynamicLayout(true); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); setJMenuBar(createMainMenuBar()); setVisible(true); //Initializes save and open filechooser. - Kristin saveOpenFileChooser = new FBFileChooser(); saveOpenFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); saveOpenFileChooser.setAcceptAllFileFilterUsed(false); saveOpenFileChooser.addChoosableFileFilter(FindBugsAnalysisFileFilter.INSTANCE); saveOpenFileChooser.addChoosableFileFilter(FindBugsFBPFileFilter.INSTANCE); saveOpenFileChooser.addChoosableFileFilter(FindBugsFBAFileFilter.INSTANCE); saveOpenFileChooser.setFileFilter(FindBugsAnalysisFileFilter.INSTANCE); filterOpenFileChooser = new FBFileChooser(); filterOpenFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); filterOpenFileChooser.setFileFilter(FindBugsFilterFileFilter.INSTANCE); //Sets the size of the tooltip to match the rest of the GUI. - Kristin JToolTip tempToolTip = tableheader.createToolTip(); UIManager.put( "ToolTip.font", new FontUIResource(tempToolTip.getFont().deriveFont(Driver.getFontSize()))); if (MAC_OS_X) { try { osxAdapter = Class.forName("edu.umd.cs.findbugs.gui2.OSXAdapter"); Class[] defArgs = {MainFrame.class}; Method registerMethod = osxAdapter.getDeclaredMethod("registerMacOSXApplication", defArgs); if (registerMethod != null) { registerMethod.invoke(osxAdapter, MainFrame.this); } defArgs[0] = boolean.class; osxPrefsEnableMethod = osxAdapter.getDeclaredMethod("enablePrefs", defArgs); enablePreferences(true); } catch (NoClassDefFoundError e) { // This will be thrown first if the OSXAdapter is loaded on a system without the EAWT // because OSXAdapter extends ApplicationAdapter in its def System.err.println("This version of Mac OS X does not support the Apple EAWT. Application Menu handling has been disabled (" + e + ")"); } catch (ClassNotFoundException e) { // This shouldn't be reached; if there's a problem with the OSXAdapter we should get the // above NoClassDefFoundError first. System.err.println("This version of Mac OS X does not support the Apple EAWT. Application Menu handling has been disabled (" + e + ")"); } catch (Exception e) { System.err.println("Exception while loading the OSXAdapter: " + e); e.printStackTrace(); if (DEBUG) { e.printStackTrace(); } } } String loadFromURL = SystemProperties.getOSDependentProperty("findbugs.loadBugsFromURL"); if (loadFromURL != null) { try { loadFromURL = SystemProperties.rewriteURLAccordingToProperties(loadFromURL); URL url = new URL(loadFromURL); loadAnalysis(url); } catch (MalformedURLException e1) { JOptionPane.showMessageDialog(MainFrame.this, "Error loading " + loadFromURL); } } addComponentListener(new ComponentAdapter(){ @Override public void componentResized(ComponentEvent e){ comments.resized(); } }); addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent e) { if(comments.hasFocus()) setProjectChanged(true); callOnClose(); } }); Driver.removeSplashScreen(); mainFrameInitialized.countDown(); } } public void waitUntilReady() throws InterruptedException { mainFrameInitialized.await(); } /** * Listens for when cursor is over the label and when it is clicked. * When the cursor is over the label will make the label text blue * and the cursor the hand cursor. When clicked will take the * user to the source code tab and to the lines of code connected * to the SourceLineAnnotation. * @author Kristin Stephens * */ private class BugSummaryMouseListener extends MouseAdapter{ private final BugInstance bugInstance; private final JLabel label; private final SourceLineAnnotation note; BugSummaryMouseListener(@NonNull BugInstance bugInstance, @NonNull JLabel label, @NonNull SourceLineAnnotation link){ this.bugInstance = bugInstance; this.label = label; this.note = link; } @Override public void mouseClicked(MouseEvent e) { displayer.displaySource(bugInstance, note); } @Override public void mouseEntered(MouseEvent e){ label.setForeground(Color.blue); setCursor(new Cursor(Cursor.HAND_CURSOR)); } @Override public void mouseExited(MouseEvent e){ label.setForeground(Color.black); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } /** * Checks if source code file exists/is available * @param note * @return */ private boolean sourceCodeExists(@Nonnull SourceLineAnnotation note){ try{ getProject().getSourceFinder().findSourceFile(note); }catch(FileNotFoundException e){ return false; }catch(IOException e){ return false; } return true; } private void setStyleSheets() { StyleSheet styleSheet = new StyleSheet(); styleSheet.addRule("body {font-size: " + Driver.getFontSize() +"pt}"); styleSheet.addRule("H1 {color: red; font-size: 120%; font-weight: bold;}"); styleSheet.addRule("code {font-family: courier; font-size: " + Driver.getFontSize() +"pt}"); styleSheet.addRule(" a:link { color: #0000FF; } "); styleSheet.addRule(" a:visited { color: #800080; } "); styleSheet.addRule(" a:active { color: #FF0000; text-decoration: underline; } "); htmlEditorKit.setStyleSheet(styleSheet); summaryHtmlArea.setEditorKit(htmlEditorKit); } JPanel createCommentsInputPanel() { return comments.createCommentsInputPanel(); } /** * Creates the source code panel, but does not put anything in it. * @param text * @return */ JPanel createSourceCodePanel() { Font sourceFont = new Font("Monospaced", Font.PLAIN, (int)Driver.getFontSize()); sourceCodeTextPane.setFont(sourceFont); sourceCodeTextPane.setEditable(false); sourceCodeTextPane.getCaret().setSelectionVisible(true); sourceCodeTextPane.setDocument(SourceCodeDisplay.SOURCE_NOT_RELEVANT); sourceCodeScrollPane = new JScrollPane(sourceCodeTextPane); sourceCodeScrollPane.getVerticalScrollBar().setUnitIncrement(20); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(sourceCodeScrollPane, BorderLayout.CENTER); panel.revalidate(); if (DEBUG) System.out.println("Created source code panel"); return panel; } JPanel createSourceSearchPanel() { GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); JPanel thePanel = new JPanel(); thePanel.setLayout(gridbag); findButton.setToolTipText("Find first occurrence"); findNextButton.setToolTipText("Find next occurrence"); findPreviousButton.setToolTipText("Find previous occurrence"); c.gridx = 0; c.gridy = 0; c.weightx = 1.0; c.insets = new Insets(0, 5, 0, 5); c.fill = GridBagConstraints.HORIZONTAL; gridbag.setConstraints(sourceSearchTextField, c); thePanel.add(sourceSearchTextField); //add the buttons findButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ searchSource(0); } }); c.gridx = 1; c.weightx = 0.0; c.fill = GridBagConstraints.NONE; gridbag.setConstraints(findButton, c); thePanel.add(findButton); findNextButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ searchSource(1); } }); c.gridx = 2; c.weightx = 0.0; c.fill = GridBagConstraints.NONE; gridbag.setConstraints(findNextButton, c); thePanel.add(findNextButton); findPreviousButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ searchSource(2); } }); c.gridx = 3; c.weightx = 0.0; c.fill = GridBagConstraints.NONE; gridbag.setConstraints(findPreviousButton, c); thePanel.add(findPreviousButton); return thePanel; } void searchSource(int type) { int targetLineNum = -1; String targetString = sourceSearchTextField.getText(); switch(type) { case 0: targetLineNum = displayer.find(targetString); break; case 1: targetLineNum = displayer.findNext(targetString); break; case 2: targetLineNum = displayer.findPrevious(targetString); break; } if(targetLineNum != -1) displayer.foundItem(targetLineNum); } /** * Sets the title of the source tabs for either docking or non-docking * versions. * @param title * @param bug TODO */ void setSourceTab(String title, @CheckForNull BugInstance bug){ JComponent label = guiLayout.getSourceViewComponent(); if (label != null) { URL u = null; if (bug != null) { Cloud plugin = this.bugCollection.getCloud(); if (plugin.supportsSourceLinks()) u = plugin.getSourceLink(bug); } if (u != null) addLink(label, u); else removeLink(label); } guiLayout.setSourceTitle(title); } URL sourceLink; boolean listenerAdded = false; void addLink(JComponent component, URL source) { this.sourceLink = source; component.setEnabled(true); if (!listenerAdded) { listenerAdded = true; component.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { URL u = sourceLink; if (u != null) LaunchBrowser.showDocument(u); } }); } component.setCursor(new Cursor(Cursor.HAND_CURSOR)); Cloud plugin = this.bugCollection.getCloud(); if (plugin != null) component.setToolTipText(plugin.getSourceLinkToolTip(null)); } void removeLink(JComponent component) { this.sourceLink = null; component.setEnabled(false); component.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); component.setToolTipText(""); } /** * Returns the SorterTableColumnModel of the MainFrame. * @return */ SorterTableColumnModel getSorter() { return sorter; } /* * This is overridden for changing the font size */ @Override public void addNotify(){ super.addNotify(); float size = Driver.getFontSize(); getJMenuBar().setFont(getJMenuBar().getFont().deriveFont(size)); for(int i = 0; i < getJMenuBar().getMenuCount(); i++){ for(int j = 0; j < getJMenuBar().getMenu(i).getMenuComponentCount(); j++){ Component temp = getJMenuBar().getMenu(i).getMenuComponent(j); temp.setFont(temp.getFont().deriveFont(size)); } } bugPopupMenu.setFont(bugPopupMenu.getFont().deriveFont(size)); setFontSizeHelper(size, bugPopupMenu.getComponents()); branchPopupMenu.setFont(branchPopupMenu.getFont().deriveFont(size)); setFontSizeHelper(size, branchPopupMenu.getComponents()); } public JTree getTree() { return tree; } public BugTreeModel getBugTreeModel() { return (BugTreeModel)getTree().getModel(); } static class CutAction extends TextAction { public CutAction() { super(edu.umd.cs.findbugs.L10N.getLocalString("txt.cut", "Cut")); } public void actionPerformed( ActionEvent evt ) { JTextComponent text = getTextComponent( evt ); if(text == null) return; text.cut(); } } static class CopyAction extends TextAction { public CopyAction() { super(edu.umd.cs.findbugs.L10N.getLocalString("txt.copy", "Copy")); } public void actionPerformed( ActionEvent evt ) { JTextComponent text = getTextComponent( evt ); if(text == null) return; text.copy(); } } static class PasteAction extends TextAction { public PasteAction() { super(edu.umd.cs.findbugs.L10N.getLocalString("txt.paste", "Paste")); } public void actionPerformed( ActionEvent evt ) { JTextComponent text = getTextComponent( evt ); if(text == null) return; text.paste(); } } /** * @return never null */ public synchronized Project getProject() { if(curProject == null){ curProject = new Project(); } return curProject; } public synchronized void setProject(Project p) { curProject=p; } public void setSorting(boolean b) { tableheader.setReorderingAllowed(b); } private void setSaveMenu() { File s = saveFile; saveMenuItem.setEnabled(projectChanged && s != null && getSaveType() != SaveType.FBP_FILE && s.exists()); } /** * Called when something in the project is changed and the change needs to be saved. * This method should be called instead of using projectChanged = b. */ public void setProjectChanged(boolean b){ if(curProject == null) return; if(projectChanged == b) return; projectChanged = b; setSaveMenu(); // if(projectDirectory != null && projectDirectory.exists()) // saveProjectMenuItem.setEnabled(b); getRootPane().putClientProperty(WINDOW_MODIFIED, Boolean.valueOf(b)); } public boolean getProjectChanged(){ return projectChanged; } /* * DO NOT use the projectDirectory variable to figure out the current project directory in this function * use the passed in value, as that variable may or may not have been set to the passed in value at this point. */ private SaveReturn saveProject(File dir) { if (!dir.mkdir()) { return SaveReturn.SAVE_IO_EXCEPTION; } File f = new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".xml"); File filtersAndSuppressions=new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".fas"); BugSaver.saveBugs(f,bugCollection, getProject()); try { getProjectSettings().save(new FileOutputStream(filtersAndSuppressions)); } catch (IOException e) { Debug.println(e); return SaveReturn.SAVE_IO_EXCEPTION; } setProjectChanged(false); return SaveReturn.SAVE_SUCCESSFUL; } /** * @param currentSelectedBugLeaf2 * @param currentSelectedBugAspects2 */ private void saveComments(BugLeafNode theNode, BugAspects theAspects) { comments.saveComments(theNode, theAspects); } void saveComments() { comments.saveComments(); } /** * Returns the color of the source code pane's background. * @return the color of the source code pane's background */ public Color getSourceColor(){ return sourceCodeTextPane.getBackground(); } /** * Show an error dialog. */ public void error(String message) { JOptionPane.showMessageDialog(this, message, "Error", JOptionPane.ERROR_MESSAGE); } /** * Write a message to the console window. * * @param message the message to write */ public void writeToLog(String message) { if (DEBUG) System.out.println(message); // consoleMessageArea.append(message); // consoleMessageArea.append("\n"); } /** * Save current analysis as file passed in. Return SAVE_SUCCESSFUL if save successful. */ /* * Method doesn't do much. This method is more if need to do other things in the future for * saving analysis. And to keep saving naming convention. */ private SaveReturn saveAnalysis(File f){ BugSaver.saveBugs(f, bugCollection, getProject()); setProjectChanged(false); return SaveReturn.SAVE_SUCCESSFUL; } /** * Opens the analysis. Also clears the source and summary panes. Makes comments enabled false. * Sets the saveType and adds the file to the recent menu. * @param f * @return whether the operation was successful */ public boolean openAnalysis(File f, SaveType saveType){ if (!f.exists() || !f.canRead()) { throw new IllegalArgumentException("Can't read " + f.getPath()); } prepareForFileLoad(f, saveType); loadAnalysis(f); return true; } public void openBugCollection(SortedBugCollection bugs){ acquireDisplayWait(); try { prepareForFileLoad(null, null); Project project = bugs.getProject(); project.setGuiCallback(MainFrame.this); BugLoader.addDeadBugMatcher(project); setProjectAndBugCollectionInSwingThread(project, bugs); } finally { releaseDisplayWait(); } } private void prepareForFileLoad(File f, SaveType saveType) { //This creates a new filters and suppressions so don't use the previoues one. createProjectSettings(); clearSourcePane(); clearSummaryTab(); comments.setUserCommentInputEnable(false); reconfigMenuItem.setEnabled(true); setProjectChanged(false); this.setSaveType(saveType); saveFile = f; addFileToRecent(f, saveType); } private void loadAnalysis(final File file) { Runnable runnable = new Runnable() { public void run() { acquireDisplayWait(); try { Project project = new Project(); project.setGuiCallback(MainFrame.this); project.setCurrentWorkingDirectory(file.getParentFile()); BugLoader.loadBugs(MainFrame.this, project, file); project.getSourceFinder(); // force source finder to be initialized updateBugTree(); } finally { releaseDisplayWait(); } } }; if (EventQueue.isDispatchThread()) new Thread(runnable, "Analysis loading thread").start(); else runnable.run(); return; } private void loadAnalysis(final URL url) { Runnable runnable = new Runnable() { public void run() { acquireDisplayWait(); try { Project project = new Project(); project.setGuiCallback(MainFrame.this); BugLoader.loadBugs(MainFrame.this, project, url); project.getSourceFinder(); // force source finder to be // initialized updateBugTree(); } finally { releaseDisplayWait(); } } }; if (EventQueue.isDispatchThread()) new Thread(runnable, "Analysis loading thread").start(); else runnable.run(); return; } /** * @param file * @return */ private void loadProjectFromFile(final File f) { Runnable runnable = new Runnable(){ public void run() { final Project project = BugLoader.loadProject(MainFrame.this, f); final BugCollection bc = project == null ? null : BugLoader.doAnalysis(project); updateProjectAndBugCollection(project, bc, null); setProjectAndBugCollectionInSwingThread(project, bc); } }; if (EventQueue.isDispatchThread()) new Thread(runnable).start(); else runnable.run(); return; } /** * Redo the analysis */ void redoAnalysis() { saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); acquireDisplayWait(); new Thread() { @Override public void run() { try { updateDesignationDisplay(); BugCollection bc=BugLoader.redoAnalysisKeepComments(getProject()); updateProjectAndBugCollection(getProject(), bc, null); } finally { releaseDisplayWait(); } } }.start(); } private void mergeAnalysis() { saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); acquireDisplayWait(); try { BugCollection bc=BugLoader.combineBugHistories(); setBugCollection(bc); } finally { releaseDisplayWait(); } } @SuppressWarnings({"deprecation"}) private ProjectSettings getProjectSettings() { return ProjectSettings.getInstance(); } @SuppressWarnings({"deprecation"}) private void loadProjectSettings(File fasFile) throws FileNotFoundException { ProjectSettings.loadInstance(new FileInputStream(fasFile)); } @SuppressWarnings({"deprecation"}) private void createProjectSettings() { ProjectSettings.newInstance(); } /** * This checks if the xmlFile is in the GUISaveState. If not adds it. Then adds the file * to the recentMenuCache. * @param xmlFile */ /* * If the file already existed, its already in the preferences, as well as * the recent projects menu items, only add it if they change the name, * otherwise everything we're storing is still accurate since all we're * storing is the location of the file. */ private void addFileToRecent(File xmlFile, SaveType st){ ArrayList<File> xmlFiles=GUISaveState.getInstance().getRecentFiles(); if (!xmlFiles.contains(xmlFile)) { GUISaveState.getInstance().addRecentFile(xmlFile); } MainFrame.this.recentMenuCache.addRecentFile(xmlFile); } private void newProjectMenu() { comments.saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); new NewProjectWizard(); newProject = true; } void updateDesignationDisplay() { comments.updateDesignationComboBox(); } void addDesignationItem(JMenu menu, final String menuName, int keyEvent) { comments.addDesignationItem(menu, menuName, keyEvent); } void warnUserOfFilters() { JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.everything_is_filtered", "All bugs in this project appear to be filtered out. \nYou may wish to check your filter settings in the preferences menu."), "Warning",JOptionPane.WARNING_MESSAGE); } /** * @param saveType The saveType to set. */ void setSaveType(SaveType saveType) { if (DEBUG && this.saveType != saveType) System.out.println("Changing save type from " + this.saveType + " to " + saveType); this.saveType = saveType; } /** * @return Returns the saveType. */ SaveType getSaveType() { return saveType; } public void showMessageDialogAndWait(final String message) throws InterruptedException { if (SwingUtilities.isEventDispatchThread()) JOptionPane.showMessageDialog(this, message); else try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { JOptionPane.showMessageDialog(MainFrame.this, message); } }); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } } public void showMessageDialog(final String message) { if (SwingUtilities.isEventDispatchThread()) JOptionPane.showMessageDialog(this, message); else SwingUtilities.invokeLater(new Runnable(){ public void run() { JOptionPane.showMessageDialog(MainFrame.this, message); }}); } public int showConfirmDialog(String message, String title, int optionType) { return JOptionPane.showConfirmDialog(this, message, title, optionType); } public int showConfirmDialog(String message, String title, String ok, String cancel) { return JOptionPane.showOptionDialog(this, message, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, new Object[] { ok, cancel }, ok); } void setProjectAndBugCollectionInSwingThread(final Project project, final BugCollection bc) { setProjectAndBugCollection(project, bc); } private JLabel waitStatusLabel; public Sortables[] getAvailableSortables() { Sortables[] sortables; ArrayList<Sortables> a = new ArrayList<Sortables>(Sortables.values().length); for(Sortables s : Sortables.values()) if (s.isAvailable(this)) a.add(s); sortables = new Sortables[a.size()]; a.toArray(sortables); return sortables; } public Sortables[] sortables() { return Sortables.values(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.IGuiCallback#progessMonitoredInputStream(java.io.File, java.lang.String) */ public InputStream getProgressMonitorInputStream(InputStream in, int length, String msg) { ProgressMonitorInputStream pmin = new ProgressMonitorInputStream(this, msg, in); ProgressMonitor pm = pmin.getProgressMonitor(); if (length > 0) pm.setMaximum(length); return pmin; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.IGuiCallback#showStatus(java.lang.String) */ public void showStatus(String msg) { guiLayout.setSourceTitle(msg); } public void displayNonmodelMessage(String title, String message) { DisplayNonmodelMessage.displayNonmodelMessage(title, message, this, true); } public void displayCloudReport() { Cloud cloud = this.bugCollection.getCloud(); if (cloud == null) { JOptionPane.showMessageDialog(this, "There is no cloud"); return; } cloud.waitUntilIssueDataDownloaded(); StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); cloud.printCloudSummary(writer, getDisplayedBugs(), viewFilter.getPackagePrefixes()); writer.close(); String report = stringWriter.toString(); DisplayNonmodelMessage.displayNonmodelMessage("Cloud summary", report, this, false); } public Iterable<BugInstance> getDisplayedBugs() { return new Iterable<BugInstance>(){ public Iterator<BugInstance> iterator() { return new ShownBugsIterator(); }}; } class ShownBugsIterator implements Iterator<BugInstance> { Iterator<BugInstance> base = bugCollection.getCollection().iterator(); boolean nextKnown; BugInstance next; /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { if (!nextKnown) { nextKnown = true; while (base.hasNext()) { next = base.next(); if (shouldDisplayIssue(next)) return true; } next = null; return false; } return next != null; } /* (non-Javadoc) * @see java.util.Iterator#next() */ public BugInstance next() { if (!hasNext()) throw new NoSuchElementException(); BugInstance result = next; next = null; nextKnown = false; return result; } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.IGuiCallback#showQuestionDialog(java.lang.String, java.lang.String, java.lang.String) */ public String showQuestionDialog(String message, String title, String defaultValue) { return (String) JOptionPane.showInputDialog(this, message, title, JOptionPane.QUESTION_MESSAGE, null, null, defaultValue); } public List<String> showForm(String message, String title, List<FormItem> items) { JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1; gbc.weighty = 0; gbc.gridwidth = 2; gbc.gridy = 1; gbc.insets = new Insets(5,5,5,5); panel.add(new JLabel(message), gbc); gbc.gridwidth = 1; for (FormItem item : items) { gbc.gridy++; panel.add(new JLabel(item.getLabel()), gbc); String defaultValue = item.getDefaultValue(); if (item.getPossibleValues() != null) { DefaultComboBoxModel model = new DefaultComboBoxModel(); JComboBox box = new JComboBox(model); item.setField(box); for (String possibleValue : item.getPossibleValues()) { model.addElement(possibleValue); } if (defaultValue == null) model.setSelectedItem(model.getElementAt(0)); else model.setSelectedItem(defaultValue); panel.add(box, gbc); } else { JTextField field = (item.isPassword() ? new JPasswordField() : new JTextField()); if (defaultValue != null) { field.setText(defaultValue); } item.setField(field); panel.add(field, gbc); } } int result = JOptionPane.showConfirmDialog(this, panel, title, JOptionPane.OK_CANCEL_OPTION); if (result != JOptionPane.OK_OPTION) return null; List<String> results = new ArrayList<String>(); for (FormItem item : items) { JComponent field = item.getField(); if (field instanceof JTextComponent) { JTextComponent textComponent = (JTextComponent) field; results.add(textComponent.getText()); } else if (field instanceof JComboBox) { JComboBox box = (JComboBox) field; results.add((String) box.getSelectedItem()); } } return results; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.IGuiCallback#showDocument(java.net.URL) */ public boolean showDocument(URL u) { return LaunchBrowser.showDocument(u); } private static class EventQueueExecutor extends AbstractExecutorService { public void shutdown() { } public List<Runnable> shutdownNow() { return Collections.emptyList(); } public boolean isShutdown() { return true; } public boolean isTerminated() { return true; } public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return true; } public void execute(Runnable command) { if (SwingUtilities.isEventDispatchThread()) { command.run(); return; } try { SwingUtilities.invokeAndWait(command); } catch (InterruptedException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.IGuiCallback#isHeadless() */ public boolean isHeadless() { return false; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.IGuiCallback#invokeInGUIThread(java.lang.Runnable) */ public void invokeInGUIThread(Runnable r) { SwingUtilities.invokeLater(r); } }
package packInterfazGrafica; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.Border; import packModelo.GestorEstadisticas; import packModelo.Sesion; public class VentanaHistorial extends JFrame { private static final long serialVersionUID = 1L; private JPanel norte, centro, sur; private JPanel panelConBoxLayout; private JLabel lblTitulo; private JPanel lista; private JPanel[] combinaciones; private JComboBox<String> tipos, usuarios; private JButton btnAtras; GestorEstadisticas gE = GestorEstadisticas.obtGestorEstadisticas(); private Dimension dimVentana = new Dimension(490, 500); /** * Launch the application. */ public static void main(String[] args) { new VentanaHistorial(); } /** * Create the frame. */ public VentanaHistorial() { gE = GestorEstadisticas.obtGestorEstadisticas(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(dimVentana); setLocationRelativeTo(null); norte = new JPanel(); add(norte, BorderLayout.NORTH); centro = new JPanel(); centro.setLayout(new BorderLayout()); add(centro, BorderLayout.CENTER); sur = new JPanel(); add(sur, BorderLayout.SOUTH); panelConBoxLayout = new JPanel(); BoxLayout box = new BoxLayout(panelConBoxLayout, BoxLayout.Y_AXIS); panelConBoxLayout.setLayout(box); getTituloVentanaTitulo(); crearNorte(Sesion.obtSesion().obtNombreUsuario(), 0); getSudokus(); getBtnAtras(); setVisible(true); } private void getTituloVentanaTitulo() { lblTitulo = new JLabel("Historial"); lblTitulo.setHorizontalAlignment(0); lblTitulo.setFont(new Font("Arial", Font.BOLD, 23)); lblTitulo.setOpaque(true); lblTitulo.setForeground(Color.black); Border paddingBorder = BorderFactory.createEmptyBorder(10,10,10,10); Border border = BorderFactory.createBevelBorder(0); lblTitulo.setBorder(BorderFactory.createCompoundBorder(border,paddingBorder)); norte.add(lblTitulo); } private void crearNorte(String pUs, int pTipo){ tipos = null; String[] valTipos = {"Sudokus", "Retos", "Premios"}; tipos = new JComboBox<String>(valTipos); tipos.setSelectedIndex(pTipo); tipos.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { centro.removeAll(); if(tipos.getSelectedItem() == "Sudokus"){ getSudokus(); }else if(tipos.getSelectedItem() == "Retos"){ getRetos(); }else{ getPremios(); } centro.updateUI(); crearNorte((String)usuarios.getSelectedItem(), tipos.getSelectedIndex()); } }); usuarios = null; String[] valUsus = gE.obtJugadores(); usuarios = new JComboBox<String>(valUsus); usuarios.setSelectedItem(pUs); usuarios.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { centro.removeAll(); if(tipos.getSelectedItem() == "Sudokus"){ getSudokus(); }else if(tipos.getSelectedItem() == "Retos"){ getRetos(); }else{ getPremios(); } centro.updateUI(); crearNorte((String)usuarios.getSelectedItem(), tipos.getSelectedIndex()); } }); JPanel centroNorte = new JPanel(new GridLayout(1,4)); JLabel est = new JLabel("Mostrar: "); est.setHorizontalAlignment((int) Component.CENTER_ALIGNMENT); JLabel est1 = new JLabel("Usuario: "); est1.setHorizontalAlignment((int) Component.CENTER_ALIGNMENT); centroNorte.add(est1); centroNorte.add(usuarios); centroNorte.add(est); centroNorte.add(tipos); centro.add(centroNorte, BorderLayout.NORTH); } private void getSudokus(){ String[][] com = new String[0][0]; com = gE.obtPuntSudokusJugados((String)usuarios.getSelectedItem()); lista = new JPanel(new GridLayout(com.length+1, 1)); lista.setAutoscrolls(false); JButton btnCompartir = null; if(com.length == 0){ JLabel txt = new JLabel("<html><big>No Existe Sudokus jugados por "+(String)usuarios.getSelectedItem()+"</big></html>"); txt.setHorizontalAlignment((int)Component.CENTER_ALIGNMENT); centro.add(txt); }else{ combinaciones = new JPanel[com.length+1]; for(int i = 0; i<com.length+1; i++){ combinaciones[i] = new JPanel(new GridLayout(1, 3)); combinaciones[i].setBackground(Color.WHITE); JLabel l1, l2; if(i==0){ l1 = new JLabel("<html><font SIZE=4><u>IdSudoku</u></font></html>"); l2 = new JLabel("<html><font SIZE=4><u>Puntuacion</u></font></html>"); }else{ l1 = new JLabel(com[i-1][0]); l2 = new JLabel(com[i-1][1]); btnCompartir = new JButton("Compartir"); btnCompartir.setActionCommand(String.valueOf(i)); btnCompartir.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int num = Integer.valueOf(e.getActionCommand()); getCompartir(num); } }); } l1.setHorizontalAlignment((int) Component.CENTER_ALIGNMENT); l2.setHorizontalAlignment((int) Component.CENTER_ALIGNMENT); combinaciones[i].add(l1); combinaciones[i].add(l2); if(i==0){ combinaciones[i].add(new JLabel()); }else{ combinaciones[i].add(btnCompartir); } lista.add(combinaciones[i]); JScrollPane scroll = new JScrollPane(lista); centro.add(scroll, BorderLayout.CENTER); centro.add(Box.createRigidArea(new Dimension(0, 15))); centro.add(scroll); } } } private void getRetos(){ String[][] com = gE.obtenerRetosFinalizados(); lista = new JPanel(new GridLayout(com.length+1, 1)); lista.setAutoscrolls(false); JButton btnCompartir = null; if(com.length == 0){ JLabel txt = new JLabel("<html><big>No Existe Retos finalizados</big></html>"); txt.setHorizontalAlignment((int)Component.CENTER_ALIGNMENT); centro.add(txt); }else{ combinaciones = new JPanel[com.length+1]; for(int i = 0; i<com.length+1; i++){ combinaciones[i] = new JPanel(new GridLayout(1, 5)); if(i==0){ combinaciones[i].add(new JLabel("<html><font SIZE=4><u>Usuario</u></font></html>")); combinaciones[i].add(new JLabel("<html><font SIZE=4><u>IdSudoku</u></font></html>")); combinaciones[i].add(new JLabel("<html><font SIZE=4><u>Puntuacion</u></font></html>")); combinaciones[i].add(new JLabel("<html><font SIZE=4><u>Estado</u></font></html>")); combinaciones[i].add(new JLabel()); }else{ combinaciones[i].add(new JLabel(com[i-1][0])); combinaciones[i].add(new JLabel(com[i-1][1])); combinaciones[i].add(new JLabel(com[i-1][2])); if(com[i-1][3] == "true"){ combinaciones[i].add(new JLabel("SUPERADO")); }else{ combinaciones[i].add(new JLabel("NO SUPERADO")); } btnCompartir = new JButton("Compartir"); btnCompartir.setActionCommand(String.valueOf(i)); btnCompartir.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int num = Integer.valueOf(e.getActionCommand()); getCompartir(num); } }); combinaciones[i].add(btnCompartir); } lista.add(combinaciones[i]); } JScrollPane scroll = new JScrollPane(lista); centro.setLayout(new BorderLayout()); centro.add(scroll, BorderLayout.CENTER); centro.add(Box.createRigidArea(new Dimension(0, 15))); centro.add(scroll); } } private void getPremios(){ String[][] com = gE.obtInfoPremios((String)usuarios.getSelectedItem()); lista = new JPanel(new GridLayout(com.length+1, 1)); lista.setAutoscrolls(false); JButton btnCompartir = null; if(com.length == 0){ JLabel txt = new JLabel("<html><big>Este usuario no ha obtenido ningun premio</big></html>"); txt.setHorizontalAlignment((int)Component.CENTER_ALIGNMENT); centro.add(txt); }else{ combinaciones = new JPanel[com.length+1]; for(int i = 0; i<com.length+1; i++){ combinaciones[i] = new JPanel(new GridLayout(1, 4)); combinaciones[i].setBackground(Color.WHITE); JLabel nom, obj, fech; if(i==0){ nom = new JLabel("<html><font SIZE=4><u>Premio</u></font></html>"); obj = new JLabel("<html><font SIZE=4><u>Objetivo</u></font></html>"); fech = new JLabel("<html><font SIZE=4><u>Fecha</u></font></html>"); }else{ nom = new JLabel("<html>"+com[i-1][0]+"</html>"); if(com[i-1][4].equals("Tiempo")){ obj = new JLabel("<html>Se ha completado el<br>sudoku "+com[i-1][3]+" en un<br>tiempo menor a "+com[i-1][2]+"</html>"); }else{ obj = new JLabel("<html>Se ha completado el<br> sudoku "+com[i-1][3]+" con una<br>puntuacion mayor a "+com[i-1][2]+"</html>"); } fech = new JLabel("<html>"+com[i-1][1]+"</html>"); btnCompartir = new JButton("Compartir"); btnCompartir.setActionCommand(String.valueOf(i)); btnCompartir.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int num = Integer.valueOf(e.getActionCommand()); getCompartir(num); } }); } nom.setHorizontalAlignment((int)Component.CENTER_ALIGNMENT); obj.setHorizontalAlignment((int)Component.CENTER_ALIGNMENT); fech.setHorizontalAlignment((int)Component.CENTER_ALIGNMENT); combinaciones[i].add(nom); combinaciones[i].add(obj); combinaciones[i].add(fech); if(i==0){ combinaciones[i].add(new JLabel()); }else{ combinaciones[i].add(btnCompartir); } lista.add(combinaciones[i]); } JScrollPane scroll = new JScrollPane(lista); centro.setLayout(new BorderLayout()); centro.add(scroll, BorderLayout.CENTER); centro.add(Box.createRigidArea(new Dimension(0, 15))); centro.add(scroll); } } private void getBtnAtras() { btnAtras = new JButton("Atras"); btnAtras.setEnabled(true); btnAtras.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(Sesion.obtSesion().obtNombreUsuario() == "Admin"){ new VentanaMenuPpalAdministrador(); }else{ new VentanaMenuPpalUsuario(); } dispose(); } }); JPanel panelBox = new JPanel(); panelBox.setLayout(new BoxLayout(panelBox, BoxLayout.Y_AXIS)); panelBox.add(Box.createRigidArea(new Dimension(5, 5))); panelBox.add(leftJustify(btnAtras)); sur.add(panelBox); } private void getCompartir(int num) { String textoAPoner; if(tipos.getSelectedItem().equals("Premios")){ JLabel jL = (JLabel) combinaciones[num].getComponent(0); String nom = jL.getText(); jL = (JLabel) combinaciones[num].getComponent(1); String obj = jL.getText(); textoAPoner="He conseguido el premio "+nom+" con el objetivo de '"+obj+"' en %23AdminEvoSudoku. ¿A que no lo consigues?"; }else if(tipos.getSelectedItem().equals("Retos")){ JLabel jL = (JLabel) combinaciones[num].getComponent(2); int punt = Integer.valueOf(jL.getText().trim()); jL = (JLabel) combinaciones[num].getComponent(1); int id = Integer.valueOf(jL.getText().trim()); jL = (JLabel) combinaciones[num].getComponent(0); String nombre = jL.getText().trim(); jL = (JLabel) combinaciones[num].getComponent(0); if(jL.getText().trim().equals("SUPERADO")){ textoAPoner="He ganado un reto al jugador "+nombre+" con una puntuacion de "+punt+" puntos en el% sudoku "+id+" de %23AdminEvoSudoku. ¿A que no lo superas?"; }else{ textoAPoner="He perdido un reto con el jugador "+nombre+" con una puntuacion de "+punt+" puntos en el% sudoku "+id+" de %23AdminEvoSudoku. ¿A que no lo superas?"; } }else{ JLabel jL = (JLabel) combinaciones[num].getComponent(1); int punt = Integer.valueOf(jL.getText().trim()); jL = (JLabel) combinaciones[num].getComponent(0); int id = Integer.valueOf(jL.getText().trim()); textoAPoner="He conseguido "+punt+" puntos al completar el sudoku "+id+" de %23AdminEvoSudoku. ¿A que no lo superas?"; } Sesion.obtSesion().compartir(quitarEspacios(textoAPoner)); } private String quitarEspacios(String pTxt){ String texto = ""; int i = 0; while(i<pTxt.length()){ if(pTxt.charAt(i) == ' '){ texto+="%20"; i++; }else if(pTxt.charAt(i) == '<'){ int j = 1; while(pTxt.charAt(i+j)!='>'){ j++; } i += j+1; if(j==3){ texto+="%20"; } }else{ texto+=pTxt.charAt(i); i++; } } return texto; } private Component leftJustify(JButton btn) { Box b = Box.createHorizontalBox(); b.add(btn); b.add( Box.createHorizontalGlue() ); return b; } }
public class Compute { public static final int[] BASE_PATTERN = {0, 1, 0, -1}; public Compute (boolean debug) { _debug = debug; } public int[] process (int[] input, int numberOfPhases) { int[] results = input; for (int i = 0; i < numberOfPhases; i++) { results = processPhase(input); //phaseInput = results; } return results; } private int[] processPhase (int[] input) { int[] results = new int[input.length]; /* for (int i = 0; i < input.length; i++) { int[] basePattern = getBasePattern(i+1); for (int j = 0; i < basePattern.length; j++) { int[] work = new int[input.length]; work[j] = input[j] * basePattern[j]; System.out.println(input[j]+"*"+basePattern[j]); } }*/ getBasePattern(1); return results; } /* * A reminder of the example ... * * 10-1010-10 * 01100-1-10 * 00111000 * 00011110 * 00001111 * 00000111 * 00000011 * 00000001 * * 10-1010-1010-1010-1 --> miss first digit [010-1010-1010-1] * 01100-1-1001100-1-1 --> miss first digit [001100-1-1] * 00111000-1-1-1000111000-1-1-1 --> miss first digit [000111000-1-1-1] * 00011110000-1-1-1-1000011110000-1-1-1-1 --> miss first digit [000011110000-1-1-1-1] * 00001111100000-1-1-1-1-1 --> miss first digit [000001111100000-1-1-1-1-1] */ private final int[] getBasePattern (int phase) { int[] data = new int[(BASE_PATTERN.length*phase) -1]; int basePtr = 0; int loop = 0; for (int i = 0; i < data.length; i++) { if (i == 0) loop = 1; data[i] = BASE_PATTERN[basePtr]; //if (_debug) System.out.println("Base pattern entry "+i+" is "+data[i]); loop++; if (loop == phase) { loop = 0; basePtr++; } } return data; } private boolean _debug; }
package yuku.alkitab.base.widget; import android.content.Context; import android.graphics.Typeface; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.BackgroundColorSpan; import android.text.style.ForegroundColorSpan; import android.text.style.LeadingMarginSpan; import android.text.style.StyleSpan; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView.BufferType; import yuku.alkitab.R; import yuku.alkitab.base.IsiActivity.AttributeListener; import yuku.alkitab.base.S; import yuku.alkitab.base.U; import yuku.alkitab.base.model.PericopeBlock; import yuku.alkitab.base.util.Appearances; import yuku.alkitab.base.widget.CallbackSpan.OnClickListener; /** * This has been completely superseded by {@link SingleViewVerseAdapter}, but because * of bugs in SEMC 2.3.x handsets, we must use this for those phones. */ public class LegacyVerseAdapter extends VerseAdapter { public static final String TAG = LegacyVerseAdapter.class.getSimpleName(); public LegacyVerseAdapter(Context context, OnClickListener paralelListener, AttributeListener attributeListener) { super(context, paralelListener, attributeListener); } @Override public synchronized View getView(int position, View convertView, ViewGroup parent) { // Harus tentukan apakah ini perikop ato ayat. int id = itemPointer_[position]; if (id >= 0) { // AYAT. bukan judul perikop. VerseItem res; String text = verseTextData_[id]; boolean withBookmark = attributeMap_ == null ? false : (attributeMap_[id] & 0x1) != 0; boolean withNote = attributeMap_ == null ? false : (attributeMap_[id] & 0x2) != 0; boolean withHighlight = attributeMap_ == null ? false : (attributeMap_[id] & 0x4) != 0; int highlightColor = withHighlight ? (highlightMap_ == null ? 0 : U.alphaMixHighlight(highlightMap_[id])) : 0; boolean checked = false; if (parent instanceof ListView) { checked = ((ListView) parent).isItemChecked(position); } // Udah ditentukan bahwa ini ayat dan bukan perikop, sekarang tinggal tentukan // apakah ayat ini pake formating biasa (tanpa menjorok dsb) atau ada formating if (text.length() > 0 && text.charAt(0) == '@') { // karakter kedua harus '@' juga, kalo bukan ada ngaco if (text.charAt(1) != '@') { throw new RuntimeException("Karakter kedua bukan @. Isi ayat: " + text); //$NON-NLS-1$ } if (convertView == null || convertView.getId() != R.layout.item_legacy_verse_tiled) { res = (VerseItem) LayoutInflater.from(context_).inflate(R.layout.item_legacy_verse_tiled, null); res.setId(R.layout.item_legacy_verse_tiled); } else { res = (VerseItem) convertView; } boolean rightAfterPericope = position > 0 && itemPointer_[position - 1] < 0; tiledVerseDisplay(res.findViewById(R.id.sebelahKiri), id + 1, text, highlightColor, checked, rightAfterPericope); } else { if (convertView == null || convertView.getId() != R.layout.item_legacy_verse_simple) { res = (VerseItem) LayoutInflater.from(context_).inflate(R.layout.item_legacy_verse_simple, null); res.setId(R.layout.item_legacy_verse_simple); } else { res = (VerseItem) convertView; } TextView lIsiAyat = (TextView) res.findViewById(R.id.lIsiAyat); simpleVerseDisplay(lIsiAyat, id + 1, text, highlightColor, checked); Appearances.applyTextAppearance(lIsiAyat); if (checked) lIsiAyat.setTextColor(0xff000000); // override with black! } View imgAttributeBookmark = res.findViewById(R.id.imgAtributBukmak); imgAttributeBookmark.setVisibility(withBookmark ? View.VISIBLE : View.GONE); if (withBookmark) { setClickListenerForBookmark(imgAttributeBookmark, chapter_1_, id + 1); } View imgAttributeNote = res.findViewById(R.id.imgAtributCatatan); imgAttributeNote.setVisibility(withNote ? View.VISIBLE : View.GONE); if (withNote) { setClickListenerForNote(imgAttributeNote, chapter_1_, id + 1); } return res; } else { // JUDUL PERIKOP. bukan ayat. View res; if (convertView == null || convertView.getId() != R.layout.item_pericope_header) { res = LayoutInflater.from(context_).inflate(R.layout.item_pericope_header, null); res.setId(R.layout.item_pericope_header); } else { res = convertView; } PericopeBlock pericopeBlock = pericopeBlocks_[-id - 1]; TextView lJudul = (TextView) res.findViewById(R.id.lJudul); TextView lXparalel = (TextView) res.findViewById(R.id.lXparalel); lJudul.setText(pericopeBlock.title); // matikan padding atas kalau position == 0 ATAU sebelum ini juga judul perikop if (position == 0 || itemPointer_[position - 1] < 0) { lJudul.setPadding(0, 0, 0, 0); } else { lJudul.setPadding(0, (int) (S.applied.fontSize2dp * density_), 0, 0); } Appearances.applyPericopeTitleAppearance(lJudul); // gonekan paralel kalo ga ada if (pericopeBlock.parallels.length == 0) { lXparalel.setVisibility(View.GONE); } else { lXparalel.setVisibility(View.VISIBLE); SpannableStringBuilder sb = new SpannableStringBuilder("("); //$NON-NLS-1$ int len = 1; int total = pericopeBlock.parallels.length; for (int i = 0; i < total; i++) { String parallel = pericopeBlock.parallels[i]; if (i > 0) { // paksa new line untuk pola2 paralel tertentu if ((total == 6 && i == 3) || (total == 4 && i == 2) || (total == 5 && i == 3)) { sb.append("; \n"); //$NON-NLS-1$ len += 3; } else { sb.append("; "); //$NON-NLS-1$ len += 2; } } sb.append(parallel); sb.setSpan(new CallbackSpan(parallel, parallelListener_), len, len + parallel.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); len += parallel.length(); } sb.append(')'); len += 1; lXparalel.setText(sb, BufferType.SPANNABLE); Appearances.applyPericopeParallelTextAppearance(lXparalel); } return res; } } public void tiledVerseDisplay(View res, int ayat_1, String text, int warnaStabilo, boolean checked, boolean rightAfterPericope) { // Don't forget to modify indexOfPenehel below too // @@ = start a verse containing tiles or formatting // @0 = start with indent 0 [tiler] // @1 = start with indent 1 [tiler] // @2 = start with indent 2 [tiler] // @3 = start with indent 3 [tiler] // @4 = start with indent 4 [tiler] // @6 = start of red text [formatting] // @5 = end of red text [formatting] // @9 = start of italic [formatting] // @7 = end of italic [formatting] // @8 = put a blank line to the next verse [formatting] // @^ = start-of-paragraph marker int parsingPos = 2; // we start after "@@" int indent = 0; boolean pleaseExit = false; boolean noTileYet = true; boolean verseNumberWritten = false; LinearLayout tileContainer = (LinearLayout) res.findViewById(R.id.tempatTehel); tileContainer.removeAllViews(); char[] text_c = text.toCharArray(); while (true) { // cari posisi penehel berikutnya int pos_until = indexOfTiler(text, parsingPos); if (pos_until == -1) { // abis pos_until = text_c.length; pleaseExit = true; } if (parsingPos == pos_until) { // di awal, belum ada apa2! } else { { // create a tile TextView tile = new TextView(context_); if (indent == 1) { tile.setPadding(S.applied.indentSpacing1 + (ayat_1 >= 100 ? S.applied.indentSpacingExtra : 0), 0, 0, 0); } else if (indent == 2) { tile.setPadding(S.applied.indentSpacing2 + (ayat_1 >= 100 ? S.applied.indentSpacingExtra : 0), 0, 0, 0); } else if (indent == 3) { tile.setPadding(S.applied.indentSpacing3 + (ayat_1 >= 100 ? S.applied.indentSpacingExtra : 0), 0, 0, 0); } else if (indent == 4) { tile.setPadding(S.applied.indentSpacing4 + (ayat_1 >= 100 ? S.applied.indentSpacingExtra : 0), 0, 0, 0); } // case: no tile yet and the first tile has 0 indent if (noTileYet && indent == 0) { // # kasih no ayat di depannya SpannableStringBuilder s = new SpannableStringBuilder(); String verse_s = String.valueOf(ayat_1); s.append(verse_s).append(' '); // special case: if @^ is at the beginning if (!rightAfterPericope && text_c[parsingPos] == '@' && text_c[parsingPos+1] == '^') { tile.setPadding(tile.getPaddingLeft(), S.applied.paragraphSpacingBefore, 0, 0); } appendFormattedText2(s, text, text_c, parsingPos, pos_until); if (!checked) { s.setSpan(new ForegroundColorSpan(S.applied.verseNumberColor), 0, verse_s.length(), 0); } s.setSpan(new LeadingMarginSpan.Standard(0, S.applied.indentParagraphRest), 0, s.length(), 0); if (warnaStabilo != 0) { s.setSpan(new BackgroundColorSpan(warnaStabilo), verse_s.length() + 1, s.length(), 0); } tile.setText(s, BufferType.SPANNABLE); // kasi tanda biar nanti ga tulis nomer ayat lagi verseNumberWritten = true; } else { SpannableStringBuilder s = new SpannableStringBuilder(); appendFormattedText2(s, text, text_c, parsingPos, pos_until); if (warnaStabilo != 0) { s.setSpan(new BackgroundColorSpan(warnaStabilo), 0, s.length(), 0); } tile.setText(s); } Appearances.applyTextAppearance(tile); if (checked) tile.setTextColor(0xff000000); // override with black! tileContainer.addView(tile); } noTileYet = false; } if (pleaseExit) break; char marker = text_c[pos_until + 1]; if (marker == '1') { indent = 1; } else if (marker == '2') { indent = 2; } else if (marker == '3') { indent = 3; } else if (marker == '4') { indent = 4; } parsingPos = pos_until + 2; } TextView lAyat = (TextView) res.findViewById(R.id.lAyat); if (verseNumberWritten) { lAyat.setText(""); //$NON-NLS-1$ } else { lAyat.setText(String.valueOf(ayat_1)); lAyat.setTypeface(S.applied.fontFace, S.applied.fontBold); lAyat.setTextSize(TypedValue.COMPLEX_UNIT_DIP, S.applied.fontSize2dp); lAyat.setIncludeFontPadding(false); lAyat.setTextColor(S.applied.verseNumberColor); if (checked) lAyat.setTextColor(0xff000000); } } /** * taro teks dari text[pos_from..pos_until] dengan format 6 atau 5 atau 9 atau 7 atau 8 ke s * * @param text_c * string yang dari posDari sampe sebelum posSampe hanya berisi 6 atau 5 atau 9 atau 7 atau 8 tanpa mengandung @ lain. */ private void appendFormattedText2(SpannableStringBuilder s, String text, char[] text_c, int pos_from, int pos_until) { int redStart = -1; // posisi basis s. -1 artinya belum ketemu int italicStart = -1; // posisi basis s. -1 artinya belum ketemu for (int i = pos_from; i < pos_until; i++) { // coba templok aja sampe ketemu @ berikutnya. Jadi jangan satu2. { int nextAtPos = text.indexOf('@', i); if (nextAtPos == -1) { // udah ga ada lagi, tumplekin semua dan keluar dari method ini s.append(text, i, pos_until); return; } else { // tumplekin sampe sebelum @ if (nextAtPos != i) { // kalo ga 0 panjangnya s.append(text, i, nextAtPos); } i = nextAtPos; } } i++; // satu char setelah @ if (i >= pos_until) { // out of bounds break; } char d = text_c[i]; if (d == '8') { s.append('\n'); continue; } if (d == '^' && i >= pos_from + 2) { // the other case where @^ happens at the beginning is already handled outside this method s.append("\n\n"); } if (d == '6') { // merah start redStart = s.length(); continue; } if (d == '9') { // italic start italicStart = s.length(); continue; } if (d == '5') { // merah ends if (redStart != -1) { s.setSpan(new ForegroundColorSpan(S.applied.fontRedColor), redStart, s.length(), 0); redStart = -1; // reset } continue; } if (d == '7') { // italic ends if (italicStart != -1) { s.setSpan(new StyleSpan(Typeface.ITALIC), italicStart, s.length(), 0); italicStart = -1; // reset } continue; } } } /** index of penehel berikutnya */ private int indexOfTiler(String text, int start) { int length = text.length(); while (true) { int pos = text.indexOf('@', start); if (pos == -1) { return -1; } else if (pos >= length - 1) { return -1; // tepat di akhir string, maka anggaplah tidak ada } else { char c = text.charAt(pos + 1); if (c >= '0' && c <= '4') { return pos; } else { start = pos + 2; } } } } static void simpleVerseDisplay(TextView lIsiAyat, int verse_1, String text, int highlightColor, boolean checked) { SpannableStringBuilder verse = new SpannableStringBuilder( "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" + //$NON-NLS-1$ "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" + //$NON-NLS-1$ "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" //$NON-NLS-1$ ); // pre-allocate verse.clear(); // nomer ayat String verse_s = String.valueOf(verse_1); verse.append(verse_s).append(' ').append(text); if (!checked) { verse.setSpan(new ForegroundColorSpan(S.applied.verseNumberColor), 0, verse_s.length(), 0); } // teks verse.setSpan(new LeadingMarginSpan.Standard(0, S.applied.indentParagraphRest), 0, verse.length(), 0); if (highlightColor != 0) { verse.setSpan(new BackgroundColorSpan(highlightColor), verse_s.length() + 1, verse.length(), 0); } lIsiAyat.setText(verse, BufferType.SPANNABLE); } }
package edu.vu.isis.ammo.launch.constants; /** * Static constants used throughout the application. * @author Demetri Miller * */ /* * IMPORTANT NOTE: The mimetype constants must match those in AmmoSource.java * in the Contacts app */ public class Constants { /** * Key to use when storing uris in intents. */ public static final String ROW_URI = "row_uri"; /** * Intent to load indiviual contact. */ public static final String INDIVIDUAL_CONTACT_ACTIVITY_LAUNCH = "edu.vu.isis.ammo.launch.individualcontactactivity.LAUNCH"; public static final String AMMO_ACCOUNT_TYPE = "edu.vu.isis.ammo"; public static final String AMMO_DEFAULT_ACCOUNT_NAME = "ammo"; public static final String AMMO_AUTHTOKEN_TYPE = "edu.vu.isis.ammo"; public static final String LDAP_MIME = "ammo/edu.vu.isis.ammo.launcher.contact_pull"; public static final String MIME_INSIGNIA = "vnd.android.cursor.item/insignia"; public static final String MIME_CALLSIGN = "vnd.android.cursor.item/callsign"; public static final String MIME_USERID = "vnd.android.cursor.item/userid"; public static final String MIME_USERID_NUM = "vnd.android.cursor.item/usernumber"; public static final String MIME_RANK = "vnd.android.cursor.item/rank"; public static final String MIME_UNIT_NAME = "vnd.android.cursor.item/unitname"; }
package peergos.server.space; import peergos.server.*; import peergos.server.corenode.*; import peergos.server.sql.*; import peergos.server.storage.*; import peergos.server.storage.admin.*; import peergos.server.util.*; import peergos.shared.*; import peergos.shared.corenode.*; import peergos.shared.mutable.*; import peergos.shared.storage.*; import java.sql.*; import java.time.*; import java.util.*; import java.util.function.*; public class QuotaCLI extends Builder { private static QuotaAdmin buildQuotaStore(Args a) { Supplier<Connection> dbConnectionPool = getDBConnector(a, "transactions-sql-file"); TransactionStore transactions = buildTransactionStore(a, dbConnectionPool); DeletableContentAddressedStorage localStorage = buildLocalStorage(a, transactions); JdbcIpnsAndSocial rawPointers = buildRawPointers(a, getDBConnector(a, "mutable-pointers-file", dbConnectionPool)); MutablePointers localPointers = UserRepository.build(localStorage, rawPointers); MutablePointersProxy proxingMutable = new HttpMutablePointers(buildP2pHttpProxy(a), getPkiServerId(a)); CoreNode core = buildCorenode(a, localStorage, transactions, rawPointers, localPointers, proxingMutable); return buildSpaceQuotas(a, localStorage, core, getDBConnector(a, "space-requests-sql-file", dbConnectionPool), getDBConnector(a, "quotas-sql-file", dbConnectionPool)); } private static void printQuota(String name, long quota) { System.out.println(name + " " + formatQuota(quota)); } private static String formatQuota(long quota) { long mb = quota / 1024 / 1024; if (mb == 0) return quota + " B"; if (mb < 1024) return mb + " MiB"; return mb/1024 + " GiB"; } public static final Command<Boolean> SET = new Command<>("set", "Set free quota for a user on this server", a -> { boolean paidStorage = a.hasArg("quota-admin-address"); if (paidStorage) throw new IllegalStateException("Quota CLI only valid on non paid instances"); SqlSupplier sqlCommands = getSqlCommands(a); Supplier<Connection> quotasDb = getDBConnector(a, "quotas-sql-file"); JdbcQuotas quotas = JdbcQuotas.build(quotasDb, sqlCommands); String name = a.getArg("username"); long quota = UserQuotas.parseQuota(a.getArg("quota")); quotas.setQuota(name, quota); return true; }, Arrays.asList( new Command.Arg("username", "The username to set the quota of", true), new Command.Arg("quota", "The quota in bytes or (k, m, g, t)", true), new Command.Arg("quotas-sql-file", "The filename for the quotas datastore", true, "quotas.sql") ) ); public static final Command<Boolean> REQUESTS = new Command<>("requests", "Show pending quota requests on this server", a -> { boolean paidStorage = a.hasArg("quota-admin-address"); if (paidStorage) throw new IllegalStateException("Quota CLI only valid on non paid instances"); SqlSupplier sqlCommands = getSqlCommands(a); Supplier<Connection> quotasDb = getDBConnector(a, "space-requests-sql-file"); JdbcSpaceRequests reqs = JdbcSpaceRequests.build(quotasDb, sqlCommands); List<QuotaControl.LabelledSignedSpaceRequest> raw = reqs.getSpaceRequests(); NetworkAccess net = Builder.buildLocalJavaNetworkAccess(a.getInt("port")).join(); List<DecodedSpaceRequest> allReqs = DecodedSpaceRequest.decodeSpaceRequests(raw, net.coreNode, net.dhtClient).join(); System.out.println("Quota requests:"); for (DecodedSpaceRequest req : allReqs) { LocalDateTime reqTime = LocalDateTime.ofEpochSecond(req.decoded.utcMillis, 0, ZoneOffset.UTC); String formattedQuota = formatQuota(req.decoded.getSizeInBytes()); System.out.println(req.getUsername() + " " + formattedQuota + " " + reqTime); } return true; }, Arrays.asList( new Command.Arg("quotas-sql-file", "The filename for the quotas datastore", true, "quotas.sql") ) ); public static final Command<Boolean> SHOW = new Command<>("show", "Show free quota of all users on this server", a -> { boolean paidStorage = a.hasArg("quota-admin-address"); if (paidStorage) throw new IllegalStateException("Quota CLI only valid on non paid instances"); SqlSupplier sqlCommands = getSqlCommands(a); Supplier<Connection> quotasDb = getDBConnector(a, "quotas-sql-file"); JdbcQuotas quotas = JdbcQuotas.build(quotasDb, sqlCommands); if (a.hasArg("username")) { String name = a.getArg("username"); printQuota(name, quotas.getQuota(name)); return true; } TreeMap<String, Long> all = new TreeMap<>(quotas.getQuotas()); all.forEach(QuotaCLI::printQuota); return true; }, Arrays.asList( new Command.Arg("username", "The user whose quota to show (or all users are shown)", false), new Command.Arg("quotas-sql-file", "The filename for the quotas datastore", true, "quotas.sql") ) ); public static final Command<Boolean> QUOTA = new Command<>("quota", "Manage free quota of users on this server", args -> { System.out.println("Run with -help to show options"); return null; }, Arrays.asList( new Command.Arg("print-log-location", "Whether to print the log file location at startup", false, "false"), new Command.Arg("log-to-file", "Whether to log to a file", false, "false"), new Command.Arg("log-to-console", "Whether to log to the console", false, "false") ), Arrays.asList(SHOW, SET, REQUESTS) ); }
package ucar.nc2; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import ucar.nc2.dataset.NetcdfDataset; import ucar.nc2.dt.grid.GridDataset; import ucar.unidata.test.util.TestDir; import java.io.IOException; import java.util.*; /** * Describe * * @author caron * @since 6/19/2014 */ @RunWith(Parameterized.class) public class TestHttpOpen { @Parameterized.Parameters public static Collection testUrls() { Object[][] data = new Object[][]{ {"http://"+ TestDir.threddsTestServer+"//thredds/fileServer/testdata/2004050412_eta_211.nc"}, {"http://"+TestDir.threddsTestServer+"//thredds/fileServer/testdata/2004050400_eta_211.nc"}, {"http://"+TestDir.threddsTestServer+"//thredds/fileServer/testdata/2004050312_eta_211.nc"}, {"http://"+TestDir.threddsTestServer+".//thredds/fileServer/testdata/2004050300_eta_211.nc"}, }; return Arrays.asList(data); } private final String url; public TestHttpOpen(String url) { this.url = url; } // HTTP = 4300 HTTP2 = 5500 msec 20-25% slower @Test public void testOpenDataset() throws IOException { long start = System.currentTimeMillis(); try (NetcdfDataset ncd = ucar.nc2.dataset.NetcdfDataset.openDataset(url)) { System.out.printf("%s%n", ncd.getLocation()); } finally { System.out.printf("**testOpenDataset took= %d msecs%n", (System.currentTimeMillis() - start)); } } @Test public void testOpenGrid() throws IOException { long start = System.currentTimeMillis(); try (GridDataset ncd = ucar.nc2.dt.grid.GridDataset.open(url)) { System.out.printf("%s%n", ncd.getLocation()); } finally { System.out.printf("**testOpenGrid took= %d msecs%n", (System.currentTimeMillis() - start)); } } @Test public void testReadData() throws IOException { long start = System.currentTimeMillis(); long totalBytes = 0; try (NetcdfFile ncfile = NetcdfFile.open(url)) { totalBytes = readAllData(ncfile); } finally { System.out.printf("**testRad Data took= %d msecs %d kbytes%n", (System.currentTimeMillis() - start), totalBytes / 1000); } } private long readAllData(NetcdfFile ncfile) throws IOException { System.out.println(" long total = 0; for (Variable v : ncfile.getVariables()) { long nbytes = v.getSize() * v.getElementSize(); System.out.println(" Try to read variable " + v.getFullName() + " " + nbytes); v.read(); total += v.getSize() * v.getElementSize(); } ncfile.close(); return total; } }
package kg.apc.charting; import java.awt.AlphaComposite; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.Toolkit; import java.awt.Window; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.AbstractMap; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.border.BevelBorder; import javax.swing.filechooser.FileNameExtensionFilter; import kg.apc.charting.plotters.AbstractRowPlotter; import kg.apc.charting.plotters.BarRowPlotter; import kg.apc.charting.plotters.CSplineRowPlotter; import kg.apc.charting.plotters.LineRowPlotter; import org.apache.jmeter.gui.GuiPackage; import org.apache.jorphan.gui.NumberRenderer; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; /** * * @author apc */ public class GraphPanelChart extends JComponent implements ClipboardOwner { BufferedImage cache = null; int cacheWitdh, cacheHeight; boolean cacheValid = false; //plotters BarRowPlotter barRowPlotter = null; LineRowPlotter lineRowPlotter = null; CSplineRowPlotter cSplineRowPlotter = null; AbstractRowPlotter currentPlotter = null; JPopupMenu popup = new JPopupMenu(); private static final String AD_TEXT = "http://apc.kg/plugins"; private static final String NO_SAMPLES = "Waiting for samples..."; private static final int spacing = 5; private static final int previewInset = 4; /* * Special type of graph were minY is forced to 0 and maxY is forced to 100 * to display percentage charts (eg cpu monitoring) */ public static final int CHART_PERCENTAGE = 0; public static final int CHART_DEFAULT = -1; private static final Logger log = LoggingManager.getLoggerForClass(); private Rectangle legendRect; private Rectangle xAxisRect; private Rectangle yAxisRect; private Rectangle chartRect; private static final Rectangle zeroRect = new Rectangle(); private AbstractMap<String, AbstractGraphRow> rows; private double maxYVal; private double minYVal; private long maxXVal; private long minXVal; private long currentXVal; private static final int gridLinesCount = 10; private NumberRenderer yAxisLabelRenderer; private NumberRenderer xAxisLabelRenderer; private long forcedMinX = -1; private int chartType = CHART_DEFAULT; // Message display in graphs. Used for perfmon error messages private String errorMessage = null; // Chart's gradient background end color private final static Color gradientColor = new Color(229, 236, 246); // Chart's Axis Color. For good results, use gradient color - (30, 30, 30) private final static Color axisColor = new Color(199, 206, 216); //save file path. We remember last folder used. private static String savePath = null; private ChartSettings chartSettings = new ChartSettings(); public ChartSettings getChartSettings() { return chartSettings; } private boolean reSetColors = false; //hover info private Window hoverWindow; //gap in pixels relative to mouse pointer position private final static int hoverGap = 20; //force positionning between 2 clicks private boolean forceHoverPosition = true; private JTextField hoverLabel; private int xHoverInfo = -1; private int yHoverInfo = -1; private HoverMotionListener motionListener = new HoverMotionListener(); public void setReSetColors(boolean reSetColors) { this.reSetColors = reSetColors; } private String xAxisLabel = "X axis label"; private String yAxisLabel = "Y axis label"; private int precisionLabel = -1; private int limitPointFactor = 1; private boolean displayPrecision = false; public void setDisplayPrecision(boolean displayPrecision) { this.displayPrecision = displayPrecision; } public void setxAxisLabel(String xAxisLabel) { this.xAxisLabel = xAxisLabel; } public void setYAxisLabel(String yAxisLabel) { this.yAxisLabel = yAxisLabel; } public void setPrecisionLabel(int precision) { this.precisionLabel = precision; } private void autoZoom_orig() { //row zooming if (!expendRows) { return; } Iterator<Entry<String, AbstractGraphRow>> it = rows.entrySet().iterator(); while (it.hasNext()) { Entry<String, AbstractGraphRow> row = it.next(); double[] minMax = row.getValue().getMinMaxY(chartSettings.getMaxPointPerRow()); if (minMax[1] > 0) { double zoomFactor = 1; rowsZoomFactor.put(row.getKey(), zoomFactor); while (minMax[1] * zoomFactor <= maxYVal) { rowsZoomFactor.put(row.getKey(), zoomFactor); zoomFactor = zoomFactor * 10; } } else { rowsZoomFactor.put(row.getKey(), 1.0); } } } private String getXAxisLabel() { String label; if (!displayPrecision) { label = xAxisLabel; } else { long granularity; if (chartSettings.getMaxPointPerRow() <= 0) { granularity = precisionLabel; } else { granularity = precisionLabel * limitPointFactor; } long min = granularity / 60000; long sec = (granularity % 60000) / 1000; long ms = (granularity % 60000) % 1000; label = xAxisLabel + " (granularity:"; if (min > 0) { label += " " + min + " min"; } if (sec > 0 || (min > 0 && ms > 0)) { if (min > 0) { label += ","; } label += " " + sec + " sec"; } if (ms > 0) { if (sec > 0 || min > 0) { label += ","; } label += " " + ms + " ms"; } label += ")"; } return label; } private boolean isPreview = false; public void setIsPreview(boolean isPreview) { this.isPreview = isPreview; if (!isPreview) { this.setComponentPopupMenu(popup); } else { this.setComponentPopupMenu(null); } } //relative time private long testStartTime = 0; public void setTestStartTime(long time) { testStartTime = time; } //row zooming private HashMap<String, Double> rowsZoomFactor = new HashMap<String, Double>(); private boolean expendRows = false; public void setExpendRows(boolean expendRows) { this.expendRows = expendRows; } /** * Creates new chart object with default parameters */ public GraphPanelChart(boolean allowCsvExport) { setBackground(Color.white); setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.lightGray, Color.darkGray)); yAxisLabelRenderer = new NumberRenderer(" xAxisLabelRenderer = new NumberRenderer(" legendRect = new Rectangle(); yAxisRect = new Rectangle(); xAxisRect = new Rectangle(); chartRect = new Rectangle(); //attempt to fix CMD in unix without X11 //no need to register anything in non GUI mode //second test required for unit test mode if (GuiPackage.getInstance() != null && !GraphicsEnvironment.isHeadless()) { registerPopup(allowCsvExport); hoverLabel = new JTextField(); hoverLabel.setEditable(false); hoverLabel.setOpaque(false); hoverLabel.setBorder(new BevelBorder(BevelBorder.RAISED)); hoverLabel.setFont(new java.awt.Font("Tahoma", 0, 11)); hoverWindow = new Window(SwingUtilities.windowForComponent(this)); hoverWindow.setBackground(gradientColor); hoverWindow.add(hoverLabel, BorderLayout.CENTER); registerHoverInfo(); } barRowPlotter = new BarRowPlotter(chartSettings, yAxisLabelRenderer); lineRowPlotter = new LineRowPlotter(chartSettings, yAxisLabelRenderer); cSplineRowPlotter = new CSplineRowPlotter(chartSettings, yAxisLabelRenderer); } public GraphPanelChart() { this(true); } public boolean isModelContainsRow(AbstractGraphRow row) { return rows.containsKey(row.getLabel()); } public void setChartType(int type) { chartType = type; } private boolean drawMessages(Graphics2D g) { if (errorMessage != null) { g.setColor(Color.RED); g.drawString(errorMessage, g.getClipBounds().width / 2 - g.getFontMetrics(g.getFont()).stringWidth(errorMessage) / 2, g.getClipBounds().height / 2); return true; } if (rows.isEmpty()) { g.setColor(Color.BLACK); g.drawString(NO_SAMPLES, g.getClipBounds().width / 2 - g.getFontMetrics(g.getFont()).stringWidth(NO_SAMPLES) / 2, g.getClipBounds().height / 2); return true; } return false; } private void getMinMaxDataValues() { maxXVal = 0L; maxYVal = 0L; minXVal = Long.MAX_VALUE; minYVal = Double.MAX_VALUE; Iterator<Entry<String, AbstractGraphRow>> it = rows.entrySet().iterator(); Entry<String, AbstractGraphRow> row = null; AbstractGraphRow rowValue = null; int barValue = 0; while (it.hasNext()) { row = it.next(); rowValue = row.getValue(); rowValue.setExcludeOutOfRangeValues(chartSettings.isPreventXAxisOverScaling()); if (!rowValue.isDrawOnChart()) { continue; } if (rowValue.getMaxX() > maxXVal) { maxXVal = rowValue.getMaxX(); } if (rowValue.getMinX() < minXVal) { minXVal = rowValue.getMinX(); } double[] rowMinMaxY = rowValue.getMinMaxY(chartSettings.getMaxPointPerRow()); if (rowMinMaxY[1] > maxYVal) { maxYVal = rowMinMaxY[1]; } if (rowMinMaxY[0] < minYVal) { //we draw only positives values minYVal = rowMinMaxY[0] >= 0 ? rowMinMaxY[0] : 0; } if (rowValue.isDrawBar()) { barValue = rowValue.getGranulationValue(); } } if (barValue > 0) { maxXVal += barValue; //find nice X steps double barPerSquare = (double) (maxXVal - minXVal) / (barValue * gridLinesCount); double step = Math.floor(barPerSquare) + 1; maxXVal = (long) (minXVal + step * barValue * gridLinesCount); } //maxYVal *= 1 + (double) 1 / (double) gridLinesCount; if (forcedMinX >= 0L) { minXVal = forcedMinX; } //prevent X and Y axis not initialized in case of no row displayed if (maxXVal == 0L || maxYVal == 0L || minXVal == Long.MAX_VALUE || minYVal == Double.MAX_VALUE) { minYVal = 0; maxYVal = 10; //we take last known row to get x range if (rowValue != null) { maxXVal = rowValue.getMaxX(); minXVal = rowValue.getMinX(); } } else if (chartSettings.isConfigOptimizeYAxis()) { computeChartSteps(); } else { minYVal = 0; } if (chartSettings.getForcedMaxY() > 0) { maxYVal = Math.max(chartSettings.getForcedMaxY(), minYVal + 1); } } /** * compute minY and step value to have better readable charts */ private void computeChartSteps() { //if special type if (chartType == GraphPanelChart.CHART_PERCENTAGE) { minYVal = 0; maxYVal = 100; return; } //try to find the best range... //first, avoid special cases where maxY equal or close to minY if (maxYVal - minYVal < 0.1) { maxYVal = minYVal + 1; } //real step double step = (maxYVal - minYVal) / gridLinesCount; int pow = -1; double factor = -1; boolean found = false; double testStep; //find a step close to the real one while (!found) { pow++; for (double f = 0; f < 10; f++) { testStep = Math.pow(10, pow) * f; if (testStep >= step) { factor = f; found = true; break; } } } //first proposal double foundStep = Math.pow(10, pow) * factor; //we shift to the closest lower minval to align with the step minYVal = minYVal - minYVal % foundStep; //check if step is still good with minY trimmed. If not, use next factor. if (minYVal + foundStep * gridLinesCount < maxYVal) { foundStep = Math.pow(10, pow) * (factor + (pow > 0 ? 0.5 : 1)); } //last visual optimization: find the optimal minYVal double trim = 10; while ((minYVal - minYVal % trim) + foundStep * gridLinesCount >= maxYVal && minYVal > 0) { minYVal = minYVal - minYVal % trim; trim = trim * 10; } //final calculation maxYVal = minYVal + foundStep * gridLinesCount; } private void setDefaultDimensions(Graphics g) { chartRect.setBounds(spacing, spacing, g.getClipBounds().width - spacing * 2, g.getClipBounds().height - spacing * 2); legendRect.setBounds(zeroRect); xAxisRect.setBounds(zeroRect); yAxisRect.setBounds(zeroRect); } private int getYLabelsMaxWidth(FontMetrics fm) { int ret = 0; for (int i = 0; i <= gridLinesCount; i++) { yAxisLabelRenderer.setValue((minYVal * gridLinesCount + i * (maxYVal - minYVal)) / gridLinesCount); int current = fm.stringWidth(yAxisLabelRenderer.getText()); if (current > ret) { ret = current; } } return ret; } private void calculateYAxisDimensions(Graphics g) { FontMetrics fm = g.getFontMetrics(g.getFont()); int axisWidth = getYLabelsMaxWidth(fm) + spacing * 3 + fm.getHeight(); yAxisRect.setBounds(chartRect.x, chartRect.y, axisWidth, chartRect.height); if (!isPreview) { chartRect.setBounds(chartRect.x + axisWidth, chartRect.y, chartRect.width - axisWidth, chartRect.height); } else { chartRect.setBounds(chartRect.x + previewInset, chartRect.y, chartRect.width, chartRect.height); } } private void calculateXAxisDimensions(Graphics g) { FontMetrics fm = g.getFontMetrics(g.getFont()); // we need to handle this and make Y axis wider int axisHeight; if (!isPreview) { axisHeight = 2 * fm.getHeight() + spacing;//labels plus name } else { axisHeight = spacing; } xAxisLabelRenderer.setValue(maxXVal); int axisEndSpace = fm.stringWidth(xAxisLabelRenderer.getText()) / 2; xAxisRect.setBounds(chartRect.x, chartRect.y + chartRect.height - axisHeight, chartRect.width, axisHeight); if (!isPreview) { chartRect.setBounds(chartRect.x, chartRect.y, chartRect.width - axisEndSpace, chartRect.height - axisHeight); } else { chartRect.setBounds(chartRect.x, chartRect.y, chartRect.width - 2 * previewInset, chartRect.height - (previewInset + 1)); //+1 because layout take one pixel } yAxisRect.setBounds(yAxisRect.x, yAxisRect.y, yAxisRect.width, chartRect.height); } public void invalidateCache() { cacheValid = false; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); int witdh = this.getWidth(); int height = this.getHeight(); if(cacheHeight != height || cacheWitdh != witdh) { cacheValid = false; } if(!cacheValid) { if(cache == null || cacheHeight != height || cacheWitdh != witdh) { cache = new BufferedImage(witdh, height, BufferedImage.TYPE_INT_ARGB); } Graphics2D g2d = cache.createGraphics(); g2d.setClip(0, 0, witdh, height); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawPanel(g2d); cacheValid = true; cacheHeight = height; cacheWitdh = witdh; } g.drawImage(cache, 0, 0, this); } private void drawPanel(Graphics2D g) { drawPanel(g, true); } private void drawPanel(Graphics2D g, boolean drawHoverInfo) { g.setColor(Color.white); if (chartSettings.isDrawGradient()) { GradientPaint gdp = new GradientPaint(0, 0, Color.white, 0, g.getClipBounds().height, gradientColor); g.setPaint(gdp); } g.fillRect(0, 0, g.getClipBounds().width, g.getClipBounds().height); paintAd(g); if (drawMessages(g)) { return; } setDefaultDimensions(g); getMinMaxDataValues(); autoZoom_orig(); paintLegend(g); calculateYAxisDimensions(g); calculateXAxisDimensions(g); paintYAxis(g); paintXAxis(g); paintChart(g); if (drawHoverInfo) { showHoverInfo(); } } private void paintLegend(Graphics g) { FontMetrics fm = g.getFontMetrics(g.getFont()); int rectH = fm.getHeight(); int rectW = rectH; Iterator<Entry<String, AbstractGraphRow>> it = rows.entrySet().iterator(); Entry<String, AbstractGraphRow> row; int currentX = chartRect.x; int currentY = chartRect.y; int legendHeight = it.hasNext() ? rectH + spacing : 0; ColorsDispatcher colors = null; if (reSetColors) { colors = new ColorsDispatcher(); } while (it.hasNext()) { row = it.next(); Color color = reSetColors ? colors.getNextColor() : row.getValue().getColor(); if (!row.getValue().isShowInLegend() || !row.getValue().isDrawOnChart()) { continue; } String rowLabel = row.getKey(); if (expendRows && rowsZoomFactor.get(row.getKey()) != null) { double zoomFactor = rowsZoomFactor.get(row.getKey()); if (zoomFactor != 1) { if (zoomFactor > 1) { int iZoomFactor = (int) zoomFactor; rowLabel = rowLabel + " (x" + iZoomFactor + ")"; } else { rowLabel = rowLabel + " (x" + zoomFactor + ")"; } } } // wrap row if overflowed if (currentX + rectW + spacing / 2 + fm.stringWidth(rowLabel) > g.getClipBounds().width) { currentY += rectH + spacing / 2; legendHeight += rectH + spacing / 2; currentX = chartRect.x; } // draw legend color box g.setColor(color); Composite oldComposite = null; boolean isBarChart = row.getValue().isDrawBar() && chartSettings.getChartType() == ChartSettings.CHART_TYPE_DEFAULT || chartSettings.getChartType() == ChartSettings.CHART_TYPE_BAR; if (isBarChart) { oldComposite = ((Graphics2D) g).getComposite(); ((Graphics2D) g).setComposite(chartSettings.getBarComposite()); } g.fillRect(currentX, currentY, rectW, rectH); if (isBarChart) { ((Graphics2D) g).setComposite(oldComposite); } g.setColor(Color.black); g.drawRect(currentX, currentY, rectW, rectH); // draw legend item label currentX += rectW + spacing / 2; g.drawString(rowLabel, currentX, (int) (currentY + rectH * 0.9)); currentX += fm.stringWidth(rowLabel) + spacing; } legendRect.setBounds(chartRect.x, chartRect.y, chartRect.width, legendHeight); chartRect.setBounds(chartRect.x, chartRect.y + legendHeight + spacing, chartRect.width, chartRect.height - legendHeight - spacing); } private void paintYAxis(Graphics g) { FontMetrics fm = g.getFontMetrics(g.getFont()); String valueLabel; int labelXPos; int gridLineY; // shift 2nd and more lines int shift = 0; // for strokes swapping Stroke oldStroke = ((Graphics2D) g).getStroke(); //draw markers g.setColor(axisColor); for (int n = 0; n <= gridLinesCount; n++) { gridLineY = chartRect.y + (int) ((gridLinesCount - n) * (double) chartRect.height / gridLinesCount); g.drawLine(chartRect.x - 3, gridLineY, chartRect.x + 3, gridLineY); } for (int n = 0; n <= gridLinesCount; n++) { //draw 2nd and more axis dashed and shifted if (n != 0) { ((Graphics2D) g).setStroke(chartSettings.getDashStroke()); shift = 7; } gridLineY = chartRect.y + (int) ((gridLinesCount - n) * (double) chartRect.height / gridLinesCount); // draw grid line with tick g.setColor(axisColor); g.drawLine(chartRect.x + shift, gridLineY, chartRect.x + chartRect.width, gridLineY); g.setColor(Color.black); // draw label if (!isPreview) { yAxisLabelRenderer.setValue((minYVal * gridLinesCount + n * (maxYVal - minYVal)) / gridLinesCount); valueLabel = yAxisLabelRenderer.getText(); labelXPos = yAxisRect.x + yAxisRect.width - fm.stringWidth(valueLabel) - spacing - spacing / 2; g.drawString(valueLabel, labelXPos, gridLineY + fm.getAscent() / 2); } } if (!isPreview) { Font oldFont = g.getFont(); g.setFont(g.getFont().deriveFont(Font.ITALIC)); // Create a rotation transformation for the font. AffineTransform fontAT = new AffineTransform(); int delta = g.getFontMetrics(g.getFont()).stringWidth(yAxisLabel); fontAT.rotate(-Math.PI / 2d); g.setFont(g.getFont().deriveFont(fontAT)); g.drawString(yAxisLabel, yAxisRect.x + 15, yAxisRect.y + yAxisRect.height / 2 + delta / 2); g.setFont(oldFont); } //restore stroke ((Graphics2D) g).setStroke(oldStroke); } private void paintXAxis(Graphics g) { FontMetrics fm = g.getFontMetrics(g.getFont()); String valueLabel; int labelXPos; int gridLineX; // shift 2nd and more lines int shift = 0; // for strokes swapping Stroke oldStroke = ((Graphics2D) g).getStroke(); g.setColor(axisColor); //draw markers for (int n = 0; n <= gridLinesCount; n++) { gridLineX = chartRect.x + (int) (n * ((double) chartRect.width / gridLinesCount)); g.drawLine(gridLineX, chartRect.y + chartRect.height - 3, gridLineX, chartRect.y + chartRect.height + 3); } for (int n = 0; n <= gridLinesCount; n++) { //draw 2nd and more axis dashed and shifted if (n != 0) { ((Graphics2D) g).setStroke(chartSettings.getDashStroke()); shift = 7; } gridLineX = chartRect.x + (int) (n * ((double) chartRect.width / gridLinesCount)); // draw grid line with tick g.setColor(axisColor); g.drawLine(gridLineX, chartRect.y + chartRect.height - shift, gridLineX, chartRect.y); g.setColor(Color.black); // draw label - keep decimal precision if range is too small double labelValue = minXVal + n * (double) (maxXVal - minXVal) / gridLinesCount; if ((maxXVal - minXVal < 2 * gridLinesCount) && (minXVal != maxXVal)) { xAxisLabelRenderer.setValue(labelValue); } else { xAxisLabelRenderer.setValue((long) labelValue); } valueLabel = xAxisLabelRenderer.getText(); labelXPos = gridLineX - fm.stringWidth(valueLabel) / 2; g.drawString(valueLabel, labelXPos, xAxisRect.y + fm.getAscent() + spacing); } Font oldFont = g.getFont(); g.setFont(g.getFont().deriveFont(Font.ITALIC)); //axis label g.drawString(getXAxisLabel(), chartRect.x + chartRect.width / 2 - g.getFontMetrics(g.getFont()).stringWidth(getXAxisLabel()) / 2, xAxisRect.y + 2 * fm.getAscent() + spacing + 3); g.setFont(oldFont); //restore stroke ((Graphics2D) g).setStroke(oldStroke); if (chartSettings.isDrawCurrentX()) { gridLineX = chartRect.x + (int) ((currentXVal - minXVal) * (double) chartRect.width / (maxXVal - minXVal)); g.setColor(Color.GRAY); g.drawLine(gridLineX, chartRect.y, gridLineX, chartRect.y + chartRect.height); g.setColor(Color.black); } } private void paintChart(Graphics g) { g.setColor(Color.yellow); Iterator<Entry<String, AbstractGraphRow>> it; ColorsDispatcher dispatcher = null; if (reSetColors) { dispatcher = new ColorsDispatcher(); } //first we get the aggregate point factor if maxpoint is > 0; limitPointFactor = 1; if (chartSettings.getMaxPointPerRow() > 0) { it = rows.entrySet().iterator(); while (it.hasNext()) { Entry<String, AbstractGraphRow> row = it.next(); int rowFactor = (int) Math.floor(row.getValue().size() / chartSettings.getMaxPointPerRow()) + 1; if (rowFactor > limitPointFactor) { limitPointFactor = rowFactor; } } } //paint rows in 2 phases. Raws with draw label are drawn after to have label on top it = rows.entrySet().iterator(); paintRows(g, dispatcher, it, false); it = rows.entrySet().iterator(); paintRows(g, dispatcher, it, true); } private void paintRows(Graphics g, ColorsDispatcher dispatcher, Iterator<Entry<String, AbstractGraphRow>> it, boolean rowsWithLabel) { while (it.hasNext()) { Entry<String, AbstractGraphRow> row = it.next(); if (row.getValue().isDrawOnChart() && row.getValue().isDrawValueLabel() == rowsWithLabel) { Color color = reSetColors ? dispatcher.getNextColor() : row.getValue().getColor(); paintRow(g, row.getValue(), row.getKey(), color); } } } private void paintRow(Graphics g, AbstractGraphRow row, String rowLabel, Color color) { if (row.isDrawLine() && chartSettings.getChartType() == ChartSettings.CHART_TYPE_DEFAULT || chartSettings.getChartType() == ChartSettings.CHART_TYPE_LINE) { currentPlotter = lineRowPlotter; } else if(row.isDrawBar() && chartSettings.getChartType() == ChartSettings.CHART_TYPE_DEFAULT || chartSettings.getChartType() == ChartSettings.CHART_TYPE_BAR) { currentPlotter = barRowPlotter; } else if(row.isDrawSpline() && chartSettings.getChartType() == ChartSettings.CHART_TYPE_DEFAULT || chartSettings.getChartType() == ChartSettings.CHART_TYPE_CSPLINE) { currentPlotter = cSplineRowPlotter; } if(currentPlotter != null) { double zoomFactor = 1; if (expendRows && rowsZoomFactor.get(rowLabel) != null) { zoomFactor = rowsZoomFactor.get(rowLabel); } currentPlotter.setBoundsValues(chartRect, minXVal, maxXVal, minYVal, maxYVal); currentPlotter.paintRow((Graphics2D)g, row, color, zoomFactor, limitPointFactor); } } /** * * @param aRows */ public void setRows(AbstractMap<String, AbstractGraphRow> aRows) { rows = aRows; } /** * @param yAxisLabelRenderer the yAxisLabelRenderer to set */ public void setyAxisLabelRenderer(NumberRenderer yAxisLabelRenderer) { this.yAxisLabelRenderer = yAxisLabelRenderer; } /** * @param xAxisLabelRenderer the xAxisLabelRenderer to set */ public void setxAxisLabelRenderer(NumberRenderer xAxisLabelRenderer) { this.xAxisLabelRenderer = xAxisLabelRenderer; } /** * @param currentX the currentX to set */ public void setCurrentX(long currentX) { this.currentXVal = currentX; } /** * * @param i */ public void setForcedMinX(long minX) { forcedMinX = minX; } //Paint the add the same color of the axis but with transparency private void paintAd(Graphics2D g) { Font oldFont = g.getFont(); g.setFont(g.getFont().deriveFont(10F)); g.setColor(axisColor); Composite oldComposite = g.getComposite(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f)); g.drawString(AD_TEXT, g.getClipBounds().width - g.getFontMetrics().stringWidth(AD_TEXT) - spacing, g.getFontMetrics().getHeight() - spacing + 1); g.setComposite(oldComposite); g.setFont(oldFont); } /* * Clear error messages */ public void clearErrorMessage() { errorMessage = null; } /* * Set error message if not null and not empty * @param msg the error message to set */ public void setErrorMessage(String msg) { if (msg != null && msg.trim().length() > 0) { errorMessage = msg; } } // Adding a popup menu to copy image in clipboard @Override public void lostOwnership(Clipboard clipboard, Transferable contents) { // do nothing } private Image getImage() { return (Image) getBufferedImage(this.getWidth(), this.getHeight()); } private BufferedImage getBufferedImage(int w, int h) { BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setClip(0, 0, w, h); drawPanel(g2, false); return image; } /** * Thanks to stephane.hoblingre */ private void registerPopup(boolean allowCsvExport) { this.setComponentPopupMenu(popup); JMenuItem itemCopy = new JMenuItem("Copy Image to Clipboard"); JMenuItem itemSave = new JMenuItem("Save Image as..."); JMenuItem itemExport = new JMenuItem("Export to CSV..."); itemCopy.addActionListener(new CopyAction()); itemSave.addActionListener(new SaveAction()); itemExport.addActionListener(new CsvExportAction()); popup.add(itemCopy); popup.add(itemSave); if (allowCsvExport) { popup.addSeparator(); popup.add(itemExport); } } private void registerHoverInfo() { addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent evt) { if (!isPreview && evt.getButton() == MouseEvent.BUTTON1) { forceHoverPosition = true; addMouseMotionListener(motionListener); chartMouseMoved(evt); } } @Override public void mouseReleased(java.awt.event.MouseEvent evt) { if (!isPreview) { hideHoverInfo(); removeMouseMotionListener(motionListener); } } @Override public void mouseExited(java.awt.event.MouseEvent evt) { if (!isPreview) { hideHoverInfo(); } } }); } private void hideHoverInfo() { hoverWindow.setVisible(false); xHoverInfo = -1; yHoverInfo = -1; } private synchronized void showHoverInfo() { if (isPreview || chartRect.width == 0 || chartRect.height == 0 || xHoverInfo == -1 || yHoverInfo == -1) { return; } long realX = minXVal + (maxXVal - minXVal) * (xHoverInfo - chartRect.x) / chartRect.width; double realY = minYVal + (maxYVal - minYVal) * (chartRect.height - yHoverInfo + chartRect.y) / chartRect.height; xAxisLabelRenderer.setValue(realX); yAxisLabelRenderer.setValue(realY); StringBuilder hoverInfo = new StringBuilder("("); hoverInfo.append(xAxisLabelRenderer.getText()); hoverInfo.append(" ; "); hoverInfo.append(yAxisLabelRenderer.getText()); hoverInfo.append(")"); hoverLabel.setText(hoverInfo.toString()); int labelWidth = hoverLabel.getPreferredSize().width + 5; int labelHeight = hoverLabel.getPreferredSize().height; if (hoverWindow.getWidth() < labelWidth || hoverWindow.getHeight() < labelHeight) { hoverWindow.setSize(labelWidth, labelHeight); } Point mousePos = MouseInfo.getPointerInfo().getLocation(); int hoverWindowX = mousePos.x + hoverGap; int hoverWindowY = mousePos.y + hoverGap; //we move window only if far from pointer to limit cpu double deltaX = Math.abs(hoverWindow.getLocation().getX() - hoverWindowX); double deltaY = Math.abs(hoverWindow.getLocation().getY() - hoverWindowY); if (forceHoverPosition || deltaX >= hoverGap || deltaY >= hoverGap) { //prevent out of screen int correctedX = Math.min(hoverWindowX, Toolkit.getDefaultToolkit().getScreenSize().width - hoverWindow.getSize().width); hoverWindow.setLocation(correctedX, hoverWindowY); forceHoverPosition = false; } } private void chartMouseMoved(java.awt.event.MouseEvent evt) { int x = evt.getX(); int y = evt.getY(); if (x >= chartRect.x && x <= (chartRect.x + chartRect.width) && y >= chartRect.y && y <= (chartRect.y + chartRect.height)) { xHoverInfo = x; yHoverInfo = y; showHoverInfo(); hoverWindow.setVisible(true); } else { hoverWindow.setVisible(false); xHoverInfo = -1; yHoverInfo = -1; } } public void setUseRelativeTime(boolean selected) { chartSettings.setUseRelativeTime(selected); if (selected) { setxAxisLabelRenderer(new DateTimeRenderer(DateTimeRenderer.HHMMSS, testStartTime)); } else { setxAxisLabelRenderer(new DateTimeRenderer(DateTimeRenderer.HHMMSS)); } } private class CopyAction implements ActionListener { @Override public void actionPerformed(final ActionEvent e) { Clipboard clipboard = getToolkit().getSystemClipboard(); Transferable transferable = new Transferable() { @Override public Object getTransferData(DataFlavor flavor) { if (isDataFlavorSupported(flavor)) { return getImage(); } return null; } @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[]{ DataFlavor.imageFlavor }; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return DataFlavor.imageFlavor.equals(flavor); } }; clipboard.setContents(transferable, GraphPanelChart.this); } } public void saveGraphToPNG(File file, int w, int h) throws IOException { log.info("Saving PNG to " + file.getAbsolutePath()); FileOutputStream fos = new FileOutputStream(file); ImageIO.write(getBufferedImage(w, h), "png", fos); fos.flush(); fos.close(); } public void saveGraphToCSV(File file) throws IOException { log.info("Saving CSV to " + file.getAbsolutePath()); GraphModelToCsvExporter exporter = new GraphModelToCsvExporter(rows, file, chartSettings.getConfigCsvSeparator(), xAxisLabel, xAxisLabelRenderer); exporter.writeCsvFile(); } private class SaveAction implements ActionListener { @Override public void actionPerformed(final ActionEvent e) { JFileChooser chooser = savePath != null ? new JFileChooser(new File(savePath)) : new JFileChooser(new File(".")); chooser.setFileFilter(new FileNameExtensionFilter("PNG Images", "png")); int returnVal = chooser.showSaveDialog(GraphPanelChart.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); if (!file.getAbsolutePath().toUpperCase().endsWith(".PNG")) { file = new File(file.getAbsolutePath() + ".png"); } savePath = file.getParent(); boolean doSave = true; if (file.exists()) { int choice = JOptionPane.showConfirmDialog(GraphPanelChart.this, "Do you want to overwrite " + file.getAbsolutePath() + "?", "Save Image as", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); doSave = (choice == JOptionPane.YES_OPTION); } if (doSave) { try { saveGraphToPNG(file, getWidth(), getHeight()); } catch (IOException ex) { JOptionPane.showConfirmDialog(GraphPanelChart.this, "Impossible to write the image to the file:\n" + ex.getMessage(), "Save Image as", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE); } } } } } private class CsvExportAction implements ActionListener { @Override public void actionPerformed(final ActionEvent e) { JFileChooser chooser = savePath != null ? new JFileChooser(new File(savePath)) : new JFileChooser(new File(".")); chooser.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv")); int returnVal = chooser.showSaveDialog(GraphPanelChart.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); if (!file.getAbsolutePath().toUpperCase().endsWith(".CSV")) { file = new File(file.getAbsolutePath() + ".csv"); } savePath = file.getParent(); boolean doSave = true; if (file.exists()) { int choice = JOptionPane.showConfirmDialog(GraphPanelChart.this, "Do you want to overwrite " + file.getAbsolutePath() + "?", "Export to CSV File", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); doSave = (choice == JOptionPane.YES_OPTION); } if (doSave) { try { saveGraphToCSV(file); } catch (IOException ex) { JOptionPane.showConfirmDialog(GraphPanelChart.this, "Impossible to write the CSV file:\n" + ex.getMessage(), "Export to CSV File", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE); } } } } } private class HoverMotionListener extends java.awt.event.MouseMotionAdapter { @Override public void mouseDragged(java.awt.event.MouseEvent evt) { chartMouseMoved(evt); } } }
package imagej.build; import imagej.build.minimaven.BuildEnvironment; import imagej.build.minimaven.Coordinate; import imagej.build.minimaven.MavenProject; import java.io.File; import java.io.PrintStream; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.Set; import java.util.Stack; import java.util.TreeSet; /** * The main-class for a simple and small drop-in replacement of Maven. * * Naturally, MiniMaven does not pretend to be as powerful as Maven. But it does the job * as far as ImageJ2 and Fiji are concerned, and it does not download half the internet * upon initial operation. * * @author Johannes Schindelin */ public class MiniMaven { private final static void usage() { System.err.println("Usage: MiniMaven [options...] [command]\n\n" + "Supported commands:\n" + "compile\n" + "\tcompile the project\n" + "jar\n" + "\tcompile the project into a .jar file\n" + "install\n" + "\tcompile & install the project and its dependencies\n" + "run\n" + "\trun the project\n" + "compile-and-run\n" + "\tcompile and run the project\n" + "clean\n" + "\tclean the project\n" + "get-dependencies\n" + "\tdownload the dependencies of the project\n" + "list\n" + "\tshow list of projects\n" + "dependency-tree\n" + "\tshow the tree of depending projects\n\n" + "Options:\n" + "-D<key>=<value>\n" + "\tset a system property"); System.exit(1); } public static void main(String[] args) throws Exception { int offset; for (offset = 0; offset < args.length && args[offset].charAt(0) == '-'; offset++) { final String option = args[offset]; if (option.startsWith("-D")) { final int equals = option.indexOf('=', 2); final String value; if (equals < 0) value = "true"; else value = option.substring(equals + 1); System.setProperty(option.substring(2, equals < 0 ? option.length() : equals), value); } else if (option.equals("-U")) { System.setProperty("minimaven.updateinterval", "0"); } else { System.err.println("Unknown command: " + option); usage(); } } String command = "compile-and-run"; if (args.length == offset + 1) command = args[offset]; else if (args.length > offset + 1) usage(); final PrintStream err = System.err; final BuildEnvironment env = new BuildEnvironment(err, "true".equals(getSystemProperty("minimaven.download.automatically", "true")), "true".equals(getSystemProperty("minimaven.verbose", "false")), "true".equals(getSystemProperty("minimaven.debug", "false"))); final MavenProject root = env.parse(new File("pom.xml"), null); final String artifactId = getSystemProperty("artifactId", root.getArtifactId().equals("pom-ij-base") || root.getArtifactId().equals("pom-imagej") ? "ij-app" : root.getArtifactId()); MavenProject pom = findPOM(root, artifactId); if (pom == null) { final String specifiedArtifactId = System.getProperty("artifactId"); if (specifiedArtifactId != null) { System.err.println("Could not find project for artifactId '" + artifactId + "'!"); System.exit(1); } pom = root; } if (command.equals("compile") || command.equals("build") || command.equals("compile-and-run")) { pom.build(); if (command.equals("compile-and-run")) command = "run"; else return; } else if (command.equals("jar") || command.equals("jars")) { if (!pom.getBuildFromSource()) { System.err.println("Cannot build " + pom + " from source"); System.exit(1); } pom.buildJar(); if (command.equals("jars")) pom.copyDependencies(pom.getTarget(), true); return; } else if (command.equals("install")) { pom.buildAndInstall(); return; } if (command.equals("clean")) pom.clean(); else if (command.equals("get") || command.equals("get-dependencies")) pom.downloadDependencies(); else if (command.equals("run")) { final String mainClass = getSystemProperty("mainClass", pom.getMainClass()); if (mainClass == null) { err.println("No main class specified in pom " + pom.getCoordinate()); System.exit(1); } final String[] paths = pom.getClassPath(false).split(File.pathSeparator); final URL[] urls = new URL[paths.length]; for (int i = 0; i < urls.length; i++) urls[i] = new URL("file:" + paths[i] + (paths[i].endsWith(".jar") ? "" : "/")); final URLClassLoader classLoader = new URLClassLoader(urls); // needed for sezpoz Thread.currentThread().setContextClassLoader(classLoader); final Class<?> clazz = classLoader.loadClass(mainClass); final Method main = clazz.getMethod("main", new Class[] { String[].class }); main.invoke(null, new Object[] { new String[0] }); } else if (command.equals("classpath")) err.println(pom.getClassPath(false)); else if (command.equals("list")) { final Set<MavenProject> result = new TreeSet<MavenProject>(); final Stack<MavenProject> stack = new Stack<MavenProject>(); stack.push(pom.getRoot()); while (!stack.empty()) { pom = stack.pop(); if (result.contains(pom) || !pom.getBuildFromSource()) continue; result.add(pom); for (MavenProject child : pom.getChildren()) stack.push(child); } for (final MavenProject pom2 : result) System.err.println(pom2); } else if (command.equals("dependency-tree")) { final MavenProject parent = pom.getParent(); if (parent != null) { err.println("(parent: " + parent.getGAV() + ")"); } showDependencyTree(err, pom, ""); } else { err.println("Unhandled command: " + command); usage(); } } protected static void showDependencyTree(final PrintStream err, final MavenProject pom, final String prefix) { err.println(prefix + pom.getGAV()); if ("pom".equals(pom.getPackaging())) { for (final MavenProject child : pom.getChildren()) { showDependencyTree(err, child, prefix + "\t"); } } else { for (final Coordinate coordinate : pom.getDirectDependencies()) try { final MavenProject dependency = pom.findPOM(coordinate, true, false); if (dependency == null) { err.println(prefix + coordinate.getGAV() + " (not found)"); } else { showDependencyTree(err, dependency, prefix + "\t"); } } catch (final Throwable t) { err.println(prefix + coordinate.getGAV() + ": " + t); } } } protected static void showTree(final PrintStream err, final MavenProject pom, final String prefix) { err.println(prefix + pom.getGAV()); final MavenProject[] children = pom.getChildren(); for (int i = 0; i < children.length; i++) { showTree(err, children[i], prefix + "\t"); } } protected static MavenProject findPOM(MavenProject root, String artifactId) { if (artifactId == null || artifactId.equals(root.getArtifactId())) return root; for (MavenProject child : root.getChildren()) { MavenProject pom = findPOM(child, artifactId); if (pom != null) return pom; } return null; } protected static String getSystemProperty(String key, String defaultValue) { String result = System.getProperty(key); return result == null ? defaultValue : result; } }
package io.leocad.dumbledroid.data; import io.leocad.dumbledroid.data.xml.Node; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.List; import java.util.Vector; import android.util.Log; public class XmlReflector { public static void reflectXmlRootNode(Object model, Node node) throws IllegalArgumentException, IllegalAccessException, InstantiationException { //Check if the root node is an array Class<?> modelClass = model.getClass(); Field rootNodeField = null; try { rootNodeField = modelClass.getDeclaredField(node.name); rootNodeField.setAccessible(true); } catch (NoSuchFieldException e) { } //The developer has declared a field to match the root node if (rootNodeField != null) { if (rootNodeField.getType() == List.class) { processListField(model, rootNodeField, node, null); } else { reflectXmlObject(model, node); } } else { //The developer has mapped the root node to the object itself reflectXmlObject(model, node); } } private static void reflectXmlObject(Object model, Node node) { Class<?> modelClass = model.getClass(); //Treat attributes like fields if (node.attributes != null) { for (String key : node.attributes.keySet()) { String value = node.attributes.get(key); try { Field field = modelClass.getDeclaredField(key); field.setAccessible(true); Class<?> type = field.getType(); if (type == String.class) { field.set(model, value); } else if (type == boolean.class || type == Boolean.class) { field.set(model, Boolean.valueOf(value)); } else if (type == int.class || type == Integer.class) { field.set(model, Integer.valueOf(value)); } else if (type == double.class || type == Double.class) { field.set(model, Double.valueOf(value)); } } catch (NoSuchFieldException e) { Log.w(XmlReflector.class.getName(), "Can not locate field named " + key); } catch (IllegalAccessException e) { Log.w(XmlReflector.class.getName(), "Can not access field named " + key); } } } if (node.subnodes != null) { for (int i = 0; i < node.subnodes.size(); i++) { Node subnode = node.subnodes.get(i); accessFieldAndProcess(model, modelClass, subnode, node); } } else { //This node has no children (hope it has a wife). accessFieldAndProcess(model, modelClass, node, null); } } private static void accessFieldAndProcess(Object model, Class<?> modelClass, Node node, Node parentNode) { try { Field field = modelClass.getDeclaredField(node.name); field.setAccessible(true); if (field.getType() == List.class) { processListField(model, field, node, parentNode); } else { processSingleField(model, field, node); } } catch (NoSuchFieldException e) { Log.w(XmlReflector.class.getName(), "Can not locate field named " + node.name); } catch (IllegalAccessException e) { Log.w(XmlReflector.class.getName(), "Can not access field named " + node.name); } catch (InstantiationException e) { Log.w(XmlReflector.class.getName(), "Can not create an instance of the type defined in the field named " + node.name); } } private static void processSingleField(Object model, Field field, Node node) throws IllegalArgumentException, IllegalAccessException, InstantiationException { Class<?> type = field.getType(); field.set(model, getObject(node, type)); } private static Object getObject(Node node, Class<?> type) throws InstantiationException { if (type == String.class) { return node.text; } else if (type == boolean.class || type == Boolean.class) { return Boolean.valueOf(node.text); } else if (type == int.class || type == Integer.class) { return Integer.valueOf(node.text); } else if (type == double.class || type == Double.class) { return Double.valueOf(node.text); } else { Object obj; try { obj = type.newInstance(); } catch (IllegalAccessException e) { e.printStackTrace(); return null; } reflectXmlObject(obj, node); return obj; } } private static void processListField(Object object, Field field, Node node, Node parentNode) throws IllegalArgumentException, IllegalAccessException, InstantiationException { ParameterizedType genericType = (ParameterizedType) field.getGenericType(); Class<?> childrenType = (Class<?>) genericType.getActualTypeArguments()[0]; field.set(object, getList(node, childrenType, parentNode)); } private static List<?> getList(Node node, Class<?> childrenType, Node parentNode) throws InstantiationException { /* * First, we need to determine which kind of list is this. In XML, we can have two kinds: * * Type 1: * <root> * <listChild> * <childMember1 /> * <childMember2 /> * </listChild> * <listChild> * <childMember1 /> * <childMember2 /> * </listChild> * </root> * * Type 2: * <root> * <list> * <listChild> * <childMember1 /> * <childMember2 /> * </listChild> * </list> * </root> * * To determine that, we must check if a node has siblings with the same name as it. If so, * it's a list of the type 1. */ List<Node> listNodes; if (parentNode == null) { //This is a root node and has no siblings. So it can only be a list of type 2 listNodes = node.subnodes; } else { //Defaults to type 1 listNodes = parentNode.getChildrenByName(node.name); if (listNodes.size() <= 1) { //Type 2 listNodes = node.subnodes; parentNode = node; } } if (listNodes != null) { List<Object> list = new Vector<Object>(listNodes.size()); for (int i = 0; i < listNodes.size(); i++) { Object child = null; Node subnode = listNodes.get(i); if (childrenType == List.class) { child = getList(subnode, childrenType, parentNode); } else { child = getObject(subnode, childrenType); } list.add(child); } return list; } else { Log.w(XmlReflector.class.getName(), "The field named " + node.name + " has no children nor namesakes and has been declared as a List. Will be null."); return null; } } }
package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * * @author Roi and Simon */ public class RobotShoot { private static boolean needsToBeWound; private static boolean needsToBeUnwound; private static boolean unwindMax; private static boolean latched; private static boolean windMax; public static double WIND_SPEED; private static Timer timerRelatch; public static final int ENCODER_REVOLUTIONS = 5; public static final double UNIWIND_SPEED = -.5; public static int revolutionsOfShooter; private static double time; private static double b; private static double rewindMaxRevolutions = 5; public static void initialize() { time = 0; b = 0; } /** * It is a test method to test the shooter */ public static void testShooter() { RobotShoot.automatedShoot(); } /** * This is an automated Shooter to be used */ public static void automatedShoot() { RobotShoot.releaseBall(); RobotShoot.unwindShooter(); RobotShoot.rewindShooter(); } /** * This releases the ball if it is loaded, and if it is not, it displays * that it is not. */ public static void releaseBall() { if (RobotPickUp.ifLoaded()) { RobotActuators.latch.set(false); SmartDashboard.putString("Success", "Ball has been shot"); } else { SmartDashboard.putString("Error", "Ball not loaded"); //or blink a light } } /** * it gets the encoder value of the shooter wheel * * @returns the encoderValue */ private static int getEncoderValue() { revolutionsOfShooter = RobotSensors.shooterWinchEncoder.get(); return revolutionsOfShooter; } /** * This will unwind the shooter if .5 seconds have passed, and until the * limit switch is reached or until it has exceeded the max number of * revolutions. */ public static void unwindShooter() { if (timerRelatch == null && !latched) { needsToBeUnwound = true; } } /** * It rewinds the shooter until the limit switch has been reached or again * max number of revolutions */ public static void rewindShooter() { if (!windMax) { needsToBeWound = true; } } /** * This will get all of the new values that we need as well as setting the * shooter speed */ public static void update() { if (timerRelatch != null) { b = timerRelatch.get(); if (time - b > 500) { RobotActuators.latch.set(true); timerRelatch = null; } } if (RobotShoot.getEncoderValue() >= rewindMaxRevolutions) { needsToBeUnwound = false; needsToBeWound = false; } if (needsToBeWound && latched) { RobotActuators.shooterWinch.set(WIND_SPEED); } if (needsToBeUnwound && !latched) { RobotActuators.shooterWinch.set(WIND_SPEED); } windMax = RobotSensors.shooterLoadedLim.get(); //SHOOTER_LOADED_LIM unwindMax = RobotSensors.shooterUnloadedLim.get(); //SHOOTER_UNLOADED_LIM latched = RobotSensors.shooterLatchedLim.get(); //SHOOTER_LATCHED_LIM } } //IF WE WANT A MANUAL SHOT YOU WILL NEED TO SET THE MOTOR IN TELEOP
package org.waterforpeople.mapping.app.web; import java.io.StringWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.waterforpeople.mapping.dao.AccessPointDao; import org.waterforpeople.mapping.dao.GeoRegionDAO; import org.waterforpeople.mapping.domain.AccessPoint; import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType; import org.waterforpeople.mapping.domain.GeoRegion; import org.waterforpeople.mapping.domain.TechnologyType; import com.gallatinsystems.common.Constants; import com.gallatinsystems.common.util.PropertyUtil; import com.gallatinsystems.framework.dao.BaseDAO; public class KMLGenerator { private static final Logger log = Logger.getLogger(KMLGenerator.class .getName()); private VelocityEngine engine; public static final String GOOGLE_EARTH_DISPLAY = "googleearth"; public static final String WATER_POINT_FUNCTIONING_GREEN_ICON_URL = "http://watermapmonitordev.appspot.com/images/iconGreen36.png"; public static final String WATER_POINT_FUNCTIONING_YELLOW_ICON_URL = "http://watermapmonitordev.appspot.com/images/iconYellow36.png"; public static final String WATER_POINT_FUNCTIONING_RED_ICON_URL = "http://watermapmonitordev.appspot.com/images/iconRed36.png"; public static final String WATER_POINT_FUNCTIONING_BLACK_ICON_URL = "http://watermapmonitordev.appspot.com/images/iconBlack36.png"; public static final String PUBLIC_INSTITUTION_FUNCTIONING_GREEN_ICON_URL = "http://watermapmonitordev.appspot.com/images/houseGreen36.png"; public static final String PUBLIC_INSTITUTION_FUNCTIONING_YELLOW_ICON_URL = "http://watermapmonitordev.appspot.com/images/houseYellow36.png"; public static final String PUBLIC_INSTITUTION_FUNCTIONING_RED_ICON_URL = "http://watermapmonitordev.appspot.com/images/houseRed36.png"; public static final String PUBLIC_INSTITUTION_FUNCTIONING_BLACK_ICON_URL = "http://watermapmonitordev.appspot.com/images/houseBlack36.png"; public static final String SCHOOL_INSTITUTION_FUNCTIONING_GREEN_ICON_URL = "http://watermapmonitordev.appspot.com/images/pencilGreen36.png"; public static final String SCHOOL_INSTITUTION_FUNCTIONING_YELLOW_ICON_URL = "http://watermapmonitordev.appspot.com/images/pencilYellow36.png"; public static final String SCHOOL_INSTITUTION_FUNCTIONING_RED_ICON_URL = "http://watermapmonitordev.appspot.com/images/pencilRed36.png"; public static final String SCHOOL_INSTITUTION_FUNCTIONING_BLACK_ICON_URL = "http://watermapmonitordev.appspot.com/images/pencilBlack36.png"; public KMLGenerator() { engine = new VelocityEngine(); engine.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogChute"); try { engine.init(); } catch (Exception e) { log.log(Level.SEVERE, "Could not initialize velocity", e); } } public static final String defaultPhotoCaption = new PropertyUtil().getProperty("defaultPhotoCaption"); public String generateRegionDocumentString(String regionVMName) { String regionKML = generateRegionOutlines(regionVMName); return regionKML; } /** * merges a hydrated context with a template identified by the templateName * passed in. * * @param context * @param templateName * @return * @throws Exception */ private String mergeContext(VelocityContext context, String templateName) throws Exception { Template t = engine.getTemplate(templateName); StringWriter writer = new StringWriter(); t.merge(context, writer); context = null; return writer.toString(); } public String generateDocument(String placemarksVMName) { try { VelocityContext context = new VelocityContext(); context.put("folderContents", generatePlacemarks(placemarksVMName, Constants.ALL_RESULTS)); context.put("regionPlacemark", generateRegionOutlines("Regions.vm")); return mergeContext(context, "Document.vm"); } catch (Exception ex) { log.log(Level.SEVERE, "Could create kml", ex); } return null; } public String generateDocument(String placemarksVMName, String countryCode) { try { VelocityContext context = new VelocityContext(); String placemarks = generatePlacemarks(placemarksVMName, countryCode); context.put("folderContents", placemarks); context.put("regionPlacemark", generateRegionOutlines("Regions.vm")); return mergeContext(context, "Document.vm"); } catch (Exception ex) { log.log(Level.SEVERE, "Could create kml", ex); } return null; } @SuppressWarnings("unused") private String generateFolderContents( HashMap<String, ArrayList<String>> contents, String vmName) throws Exception { VelocityContext context = new VelocityContext(); StringBuilder techFolders = new StringBuilder(); for (Entry<String, ArrayList<String>> techItem : contents.entrySet()) { String key = techItem.getKey(); StringBuilder sbFolderPl = new StringBuilder(); for (String placemark : techItem.getValue()) { sbFolderPl.append(placemark); } context.put("techFolderName", key); context.put("techPlacemarks", sbFolderPl); techFolders.append(mergeContext(context, "techFolders.vm")); } context.put("techFolders", techFolders.toString()); return mergeContext(context, vmName); } public void generateCountryOrderedPlacemarks(String vmName, String countryCode, String technologyType) { } public HashMap<String, ArrayList<String>> generateCountrySpecificPlacemarks( String vmName, String countryCode) { if (countryCode.equals("MW")) { HashMap<String, ArrayList<AccessPoint>> techMap = new HashMap<String, ArrayList<AccessPoint>>(); BaseDAO<TechnologyType> techDAO = new BaseDAO<TechnologyType>( TechnologyType.class); List<TechnologyType> techTypeList = (List<TechnologyType>) techDAO .list("all"); AccessPointDao apDao = new AccessPointDao(); List<AccessPoint> waterAPList = apDao.searchAccessPoints( countryCode, null, null, null, "WATER_POINT", null, null, null, null, null, "all"); for (TechnologyType techType : techTypeList) { // log.info("TechnologyType: " + techType.getName()); ArrayList<AccessPoint> techTypeAPList = new ArrayList<AccessPoint>(); for (AccessPoint item : waterAPList) { if (techType.getName().toLowerCase() .equals("unimproved waterpoint") && item.getTypeTechnologyString().toLowerCase() .contains("unimproved waterpoint")) { techTypeAPList.add(item); } else if (item.getTypeTechnologyString().equals( techType.getName())) { techTypeAPList.add(item); } } techMap.put(techType.getName(), techTypeAPList); } List<AccessPoint> sanitationAPList = apDao.searchAccessPoints( countryCode, null, null, null, "SANITATION_POINT", null, null, null, null, null, "all"); HashMap<String, AccessPoint> sanitationMap = new HashMap<String, AccessPoint>(); for (AccessPoint item : sanitationAPList) { sanitationMap.put(item.getGeocells().toString(), item); } sanitationAPList = null; HashMap<String, ArrayList<String>> techPlacemarksMap = new HashMap<String, ArrayList<String>>(); for (Entry<String, ArrayList<AccessPoint>> item : techMap .entrySet()) { String key = item.getKey(); ArrayList<String> placemarks = new ArrayList<String>(); for (AccessPoint waterAP : item.getValue()) { AccessPoint sanitationAP = sanitationMap.get(waterAP .getGeocells().toString()); if (sanitationAP != null) { placemarks.add(buildMainPlacemark(waterAP, sanitationAP, vmName)); } else { log.info("No matching sanitation point found for " + waterAP.getLatitude() + ":" + waterAP.getLongitude() + ":" + waterAP.getCommunityName()); } } techPlacemarksMap.put(key, placemarks); } return techPlacemarksMap; } return null; } private HashMap<String, String> loadContextBindings(AccessPoint waterAP, AccessPoint sanitationAP) { // log.info(waterAP.getCommunityCode()); try { HashMap<String, String> contextBindingsMap = new HashMap<String, String>(); if (waterAP.getCollectionDate() != null) { String timestamp = DateFormatUtils.formatUTC( waterAP.getCollectionDate(), DateFormatUtils.ISO_DATE_FORMAT.getPattern()); String formattedDate = DateFormat.getDateInstance( DateFormat.SHORT).format(waterAP.getCollectionDate()); contextBindingsMap.put("collectionDate", formattedDate); contextBindingsMap.put("timestamp", timestamp); String collectionYear = new SimpleDateFormat("yyyy") .format(waterAP.getCollectionDate()); contextBindingsMap.put("collectionYear", collectionYear); } else { // TODO: This block is a problem. We should never have data // without a collectionDate so this is a hack so it display // properly until I can sort out what to do with this data. String timestamp = DateFormatUtils.formatUTC(new Date(), DateFormatUtils.ISO_DATE_FORMAT.getPattern()); String formattedDate = DateFormat.getDateInstance( DateFormat.SHORT).format(new Date()); contextBindingsMap.put("collectionDate", formattedDate); contextBindingsMap.put("timestamp", timestamp); String collectionYear = new SimpleDateFormat("yyyy") .format(new Date()); contextBindingsMap.put("collectionYear", collectionYear); } contextBindingsMap.put("communityCode", encodeNullDefault(waterAP.getCommunityCode(), "Unknown")); contextBindingsMap.put("communityName", encodeNullDefault(waterAP.getCommunityName(), "Unknown")); contextBindingsMap.put( "typeOfWaterPointTechnology", encodeNullDefault(waterAP.getTypeTechnologyString(), "Unknown")); contextBindingsMap.put( "constructionDateOfWaterPoint", encodeNullDefault(waterAP.getConstructionDateYear(), "Unknown")); contextBindingsMap.put( "numberOfHouseholdsUsingWaterPoint", encodeNullDefault( waterAP.getNumberOfHouseholdsUsingPoint(), "Unknown")); contextBindingsMap.put("costPer20ML", encodeNullDefault(waterAP.getCostPer(), "Unknown")); contextBindingsMap.put( "farthestHouseholdFromWaterPoint", encodeNullDefault(waterAP.getFarthestHouseholdfromPoint(), "Unknown")); contextBindingsMap.put( "currentManagementStructureOfWaterPoint", encodeNullDefault( waterAP.getCurrentManagementStructurePoint(), "Unknown")); contextBindingsMap.put("waterSystemStatus", encodeStatusString(waterAP.getPointStatus())); contextBindingsMap.put("photoUrl", encodeNullDefault(waterAP.getPhotoURL(), "Unknown")); contextBindingsMap .put("waterPointPhotoCaption", encodeNullDefault(waterAP.getPointPhotoCaption(), "Unknown")); contextBindingsMap.put( "primarySanitationTechnology", encodeNullDefault(sanitationAP.getTypeTechnologyString(), "Unknown")); contextBindingsMap.put( "percentageOfHouseholdsWithImprovedSanitation", encodeNullDefault( sanitationAP.getNumberOfHouseholdsUsingPoint(), "Unknown")); contextBindingsMap.put("photoOfPrimarySanitationtechnology", encodeNullDefault(sanitationAP.getPhotoURL(), "Unknown")); contextBindingsMap.put( "sanitationPhotoCaption", encodeNullDefault(sanitationAP.getPointPhotoCaption(), "Unknown")); contextBindingsMap.put("footer", encodeNullDefault(waterAP.getFooter(), "Unknown")); contextBindingsMap.put( "longitude", encodeNullDefault(waterAP.getLongitude().toString(), "Unknown")); contextBindingsMap.put( "latitude", encodeNullDefault(waterAP.getLatitude().toString(), "Unknown")); contextBindingsMap.put("altitude", encodeNullDefault(waterAP.getAltitude().toString(), "0.0")); contextBindingsMap.put( "pinStyle", encodePinStyle(waterAP.getPointType(), waterAP.getPointStatus())); return contextBindingsMap; } catch (NullPointerException nex) { log.log(Level.SEVERE, "Could not load context bindings", nex); } return null; } private String buildMainPlacemark(AccessPoint waterAP, AccessPoint sanitationAP, String vmName) { HashMap<String, String> contextBindingsMap = loadContextBindings( waterAP, sanitationAP); VelocityContext context = new VelocityContext(); for (Map.Entry<String, String> entry : contextBindingsMap.entrySet()) { context.put(entry.getKey(), entry.getValue()); } StringBuilder sb = new StringBuilder(); String output = null; try { output = mergeContext(context, vmName); } catch (Exception e) { log.log(Level.SEVERE, "Could not build main placemark", e); } sb.append(output); return sb.toString(); } private String encodeNullDefault(Object value, String defaultMissingVal) { try { if (value != null) { return value.toString(); } else { return defaultMissingVal; } } catch (Exception ex) { // log.info("value that generated nex: " + value); log.log(Level.SEVERE, "Could not encode null default", ex); } return null; } public String generatePlacemarks(String vmName, String countryCode) { return generatePlacemarks(vmName, countryCode, GOOGLE_EARTH_DISPLAY); } public String generatePlacemarks(String vmName, String countryCode, String display) { StringBuilder sb = new StringBuilder(); AccessPointDao apDAO = new AccessPointDao(); List<AccessPoint> entries = null; if (countryCode.equals("all")) entries = apDAO.list(Constants.ALL_RESULTS); else entries = apDAO.searchAccessPoints(countryCode, null, null, null, null, null, null, null, null, null, Constants.ALL_RESULTS); // loop through accessPoints and bind to variables int i = 0; try { for (AccessPoint ap : entries) { if (!ap.getPointType().equals( AccessPoint.AccessPointType.SANITATION_POINT)) { try { VelocityContext context = new VelocityContext(); String pmContents = bindPlacemark(ap, "placemarkExternalMap.vm", display); if (ap.getCollectionDate() != null) { String timestamp = DateFormatUtils.formatUTC(ap .getCollectionDate(), DateFormatUtils.ISO_DATE_FORMAT .getPattern()); String formattedDate = DateFormat.getDateInstance( DateFormat.SHORT).format( ap.getCollectionDate()); context.put("collectionDate", formattedDate); context.put("timestamp", timestamp); String collectionYear = new SimpleDateFormat("yyyy") .format(ap.getCollectionDate()); context.put("collectionYear", collectionYear); } else { String timestamp = DateFormatUtils.formatUTC( new Date(), DateFormatUtils.ISO_DATE_FORMAT .getPattern()); String formattedDate = DateFormat.getDateInstance( DateFormat.SHORT).format(new Date()); context.put("collectionDate", formattedDate); context.put("timestamp", timestamp); } if (ap.getCommunityCode() != null) context.put("communityCode", ap.getCommunityCode()); else context.put("communityCode", "Unknown" + new Date()); // Need to check this if (ap.getPointType() != null) { context.put( "pinStyle", encodePinStyle(ap.getPointType(), ap.getPointStatus())); encodeStatusString(ap.getPointStatus(), context); } else { context.put("pinStyle", "waterpushpinblk"); } context.put("latitude", ap.getLatitude()); context.put("longitude", ap.getLongitude()); if (ap.getAltitude() == null) context.put("altitude", 0.0); else context.put("altitude", ap.getAltitude()); context.put("balloon", pmContents); String placemarkStr = mergeContext(context, vmName); sb.append(placemarkStr); i++; } catch (Exception e) { log.log(Level.INFO, "Error generating placemarks: " + ap.getCommunityCode(), e); } } } } catch (Exception ex) { log.log(Level.SEVERE, "Bad access point: " + entries.get(i + 1).toString()); } return sb.toString(); } public String bindPlacemark(AccessPoint ap, String vmName, String display) throws Exception { // if (ap.getCountryCode() != null && !ap.getCountryCode().equals("MW")) if (ap.getCountryCode() == null) ap.setCountryCode("Unknown"); if (ap.getCountryCode() != null) { VelocityContext context = new VelocityContext(); if (display != null) { context.put("display", display); } context.put("countryCode", ap.getCountryCode()); if (ap.getCollectionDate() != null) { String timestamp = DateFormatUtils.formatUTC( ap.getCollectionDate(), DateFormatUtils.ISO_DATE_FORMAT.getPattern()); String formattedDate = DateFormat.getDateInstance( DateFormat.SHORT).format(ap.getCollectionDate()); context.put("collectionDate", formattedDate); context.put("timestamp", timestamp); String collectionYear = new SimpleDateFormat("yyyy").format(ap .getCollectionDate()); context.put("collectionYear", collectionYear); } else { String timestamp = DateFormatUtils.formatUTC(new Date(), DateFormatUtils.ISO_DATE_FORMAT.getPattern()); String formattedDate = DateFormat.getDateInstance( DateFormat.SHORT).format(new Date()); context.put("collectionDate", formattedDate); context.put("timestamp", timestamp); } if (ap.getCommunityCode() != null) context.put("communityCode", ap.getCommunityCode()); else context.put("communityCode", "Unknown" + new Date()); if(ap.getWaterForPeopleProjectFlag()!=null){ context.put("waterForPeopleProject", encodeBooleanDisplay(ap.getWaterForPeopleProjectFlag())); }else{ context.put("waterForPeopleProject", "null"); } if(ap.getCurrentProblem()!=null){ context.put("currentProblem", ap.getCurrentProblem()); }else{ context.put("currentProblem", ap.getCurrentProblem()); } if(ap.getWaterForPeopleRole()!=null){ context.put("waterForPeopleRole", ap.getWaterForPeopleRole()); }else{ context.put("waterForPeopleRole", "null"); } if (ap.getPhotoURL() != null && ap.getPhotoURL().trim() != "") context.put("photoUrl", ap.getPhotoURL()); else context.put("photoUrl", "http://waterforpeople.s3.amazonaws.com/images/wfplogo.jpg"); if (ap.getPointType() != null) { if (ap.getPointType().equals( AccessPoint.AccessPointType.WATER_POINT)) { context.put("typeOfPoint", "Water"); context.put("type", "water"); } else if (ap.getPointType().equals( AccessPointType.SANITATION_POINT)) { context.put("typeOfPoint", "Sanitation"); context.put("type", "sanitation"); } else if (ap.getPointType().equals( AccessPointType.PUBLIC_INSTITUTION)) { context.put("typeOfPoint", "Public Institutions"); context.put("type", "public_institutions"); } else if (ap.getPointType().equals( AccessPointType.HEALTH_POSTS)) { context.put("typeOfPoint", "Health Posts"); context.put("type", "health_posts"); } else if (ap.getPointType().equals(AccessPointType.SCHOOL)) { context.put("typeOfPoint", "School"); context.put("type", "school"); } } else { context.put("typeOfPoint", "Water"); context.put("type", "water"); } if (ap.getTypeTechnologyString() == null) { context.put("primaryTypeTechnology", "Unknown"); } else { context.put("primaryTypeTechnology", ap.getTypeTechnologyString()); } if (ap.getHasSystemBeenDown1DayFlag() == null) { context.put("down1DayFlag", "Unknown"); } else { context.put("down1DayFlag", encodeBooleanDisplay(ap.getHasSystemBeenDown1DayFlag())); } if (ap.getInstitutionName() == null) { context.put("institutionName", "Unknown"); } else { context.put("institutionName", ap.getInstitutionName()); } if (ap.getExtimatedPopulation() != null) { context.put("estimatedPopulation", ap.getExtimatedPopulation()); } else { context.put("estimatedPopulation", "null"); } if (ap.getConstructionDateYear() == null || ap.getConstructionDateYear().trim().equals("")) { context.put("constructionDateOfWaterPoint", "Unknown"); } else { String constructionDateYear = ap.getConstructionDateYear(); if (constructionDateYear.contains(".0")) { constructionDateYear = constructionDateYear.replace(".0", ""); } context.put("constructionDateOfWaterPoint", constructionDateYear); } if (ap.getNumberOfHouseholdsUsingPoint() != null) { context.put("numberOfHouseholdsUsingWaterPoint", ap.getNumberOfHouseholdsUsingPoint()); } else { context.put("numberOfHouseholdsUsingWaterPoint", "null"); } if (ap.getCostPer() == null) { context.put("costPer", "N/A"); } else { context.put("costPer", ap.getCostPer()); } if (ap.getFarthestHouseholdfromPoint() == null || ap.getFarthestHouseholdfromPoint().trim().equals("")) { context.put("farthestHouseholdfromWaterPoint", "N/A"); } else { context.put("farthestHouseholdfromWaterPoint", ap.getFarthestHouseholdfromPoint()); } if (ap.getCurrentManagementStructurePoint() == null) { context.put("currMgmtStructure", "N/A"); } else { context.put("currMgmtStructure", ap.getCurrentManagementStructurePoint()); } if (ap.getPointPhotoCaption() == null || ap.getPointPhotoCaption().trim().equals("")) { context.put("waterPointPhotoCaption", defaultPhotoCaption); } else { context.put("waterPointPhotoCaption", ap.getPointPhotoCaption()); } if (ap.getCommunityName() == null) { context.put("communityName", "Unknown"); } else { context.put("communityName", ap.getCommunityName()); } if (ap.getHeader() == null) { context.put("header", "Water For People"); } else { context.put("header", ap.getHeader()); } if (ap.getFooter() == null) { context.put("footer", "Water For People"); } else { context.put("footer", ap.getFooter()); } if (ap.getPhotoName() == null) { context.put("photoName", "Water For People"); } else { context.put("photoName", ap.getPhotoName()); } // if (ap.getCountryCode() == "RW") { if (ap.getMeetGovtQualityStandardFlag() == null) { context.put("meetGovtQualityStandardFlag", "N/A"); } else { context.put("meetGovtQualityStandardFlag", encodeBooleanDisplay(ap .getMeetGovtQualityStandardFlag())); } // } else { // context.put("meetGovtQualityStandardFlag", "unknown"); if (ap.getMeetGovtQuantityStandardFlag() == null) { context.put("meetGovtQuantityStandardFlag", "N/A"); } else { context.put("meetGovtQuantityStandardFlag", encodeBooleanDisplay(ap .getMeetGovtQuantityStandardFlag())); } if (ap.getWhoRepairsPoint() == null) { context.put("whoRepairsPoint", "N/A"); } else { context.put("whoRepairsPoint", ap.getWhoRepairsPoint()); } if (ap.getSecondaryTechnologyString() == null) { context.put("secondaryTypeTechnology", "N/A"); } else { context.put("secondaryTypeTechnology", ap.getSecondaryTechnologyString()); } if (ap.getProvideAdequateQuantity() == null) { context.put("provideAdequateQuantity", "N/A"); } else { context.put("provideAdequateQuantity", encodeBooleanDisplay(ap.getProvideAdequateQuantity())); } if (ap.getBalloonTitle() == null) { context.put("title", "Water For People"); } else { context.put("title", ap.getBalloonTitle()); } if (ap.getProvideAdequateQuantity() == null) { context.put("provideAdequateQuantity", "N/A"); } else { context.put("provideAdequateQuantity", encodeBooleanDisplay(ap.getProvideAdequateQuantity())); } if (ap.getDescription() != null) context.put("description", ap.getDescription()); else context.put("description", "Unknown"); // Need to check this if (ap.getPointType() != null) { context.put("pinStyle", encodePinStyle(ap.getPointType(), ap.getPointStatus())); encodeStatusString(ap.getPointStatus(), context); } else { context.put("pinStyle", "waterpushpinblk"); } String output = mergeContext(context, vmName); context = null; return output; } return null; } public String generateRegionOutlines(String vmName) { StringBuilder sb = new StringBuilder(); GeoRegionDAO grDAO = new GeoRegionDAO(); List<GeoRegion> grList = grDAO.list(); try { if (grList != null && grList.size() > 0) { String currUUID = grList.get(0).getUuid(); VelocityContext context = new VelocityContext(); StringBuilder sbCoor = new StringBuilder(); // loop through GeoRegions and bind to variables for (int i = 0; i < grList.size(); i++) { GeoRegion gr = grList.get(i); if (currUUID.equals(gr.getUuid())) { sbCoor.append(gr.getLongitude() + "," + gr.getLatitiude() + "," + 0 + "\n"); } else { currUUID = gr.getUuid(); context.put("coordinateString", sbCoor.toString()); sb.append(mergeContext(context, vmName)); context = new VelocityContext(); sbCoor = new StringBuilder(); sbCoor.append(gr.getLongitude() + "," + gr.getLatitiude() + "," + 0 + "\n"); } } context.put("coordinateString", sbCoor.toString()); sb.append(mergeContext(context, vmName)); return sb.toString(); } } catch (Exception e) { log.log(Level.SEVERE, "Error generating region outlines", e); } return ""; } private String encodeBooleanDisplay(Boolean value) { if (value) { return "Yes"; } else { return "No"; } } private String encodePinStyle(AccessPointType type, AccessPoint.Status status) { String prefix = "water"; if (AccessPointType.SANITATION_POINT == type) { prefix = "sani"; } else if (AccessPointType.SCHOOL == type) { prefix = "schwater"; } else if (AccessPointType.PUBLIC_INSTITUTION == type) { prefix = "pubwater"; } if (AccessPoint.Status.FUNCTIONING_HIGH == status) { return prefix + "pushpingreen"; } else if (AccessPoint.Status.FUNCTIONING_OK == status || AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS == status) { return prefix + "pushpinyellow"; } else if (AccessPoint.Status.BROKEN_DOWN == status) { return prefix + "pushpinred"; } else if (AccessPoint.Status.NO_IMPROVED_SYSTEM == status) { return prefix + "pushpinblk"; } else { return prefix + "pushpinblk"; } } private String encodeStatusString(AccessPoint.Status status, VelocityContext context) { if (status != null) { if (AccessPoint.Status.FUNCTIONING_HIGH == status) { context.put("waterSystemStatus", "Meets Government Standards"); return "System Functioning and Meets Government Standards"; } else if (AccessPoint.Status.FUNCTIONING_OK == status || AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS == status) { context.put("waterSystemStatus", "Functioning but with Problems"); return "Functioning but with Problems"; } else if (AccessPoint.Status.BROKEN_DOWN == status) { context.put("waterSystemStatus", "Broken-down system"); return "Broken-down system"; } else if (AccessPoint.Status.NO_IMPROVED_SYSTEM == status) { context.put("waterSystemStatus", "No Improved System"); return "No Improved System"; } else { context.put("waterSystemStatus", "Unknown"); return "Unknown"; } } else { context.put("waterSystemStatus", "Unknown"); return "Unknown"; } } private String encodeStatusString(AccessPoint.Status status) { if (status == null) { return "Unknown"; } if (status.equals(AccessPoint.Status.FUNCTIONING_HIGH)) { return "System Functioning and Meets Government Standards"; } else if (status.equals(AccessPoint.Status.FUNCTIONING_OK) || status.equals(AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS)) { return "Functioning but with Problems"; } else if (status.equals(AccessPoint.Status.BROKEN_DOWN)) { return "Broken-down system"; } else if (status.equals(AccessPoint.Status.NO_IMPROVED_SYSTEM)) { return "No Improved System"; } else { return "Unknown"; } } }
package org.unitime.timetable.test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.unitime.commons.hibernate.util.HibernateUtil; import org.unitime.timetable.model.Assignment; import org.unitime.timetable.model.BuildingPref; import org.unitime.timetable.model.ClassInstructor; import org.unitime.timetable.model.Class_; import org.unitime.timetable.model.CourseOffering; import org.unitime.timetable.model.DatePattern; import org.unitime.timetable.model.Department; import org.unitime.timetable.model.DepartmentalInstructor; import org.unitime.timetable.model.DistributionObject; import org.unitime.timetable.model.DistributionPref; import org.unitime.timetable.model.InstrOfferingConfig; import org.unitime.timetable.model.InstructionalOffering; import org.unitime.timetable.model.Location; import org.unitime.timetable.model.RoomFeaturePref; import org.unitime.timetable.model.RoomGroupPref; import org.unitime.timetable.model.RoomPref; import org.unitime.timetable.model.SchedulingSubpart; import org.unitime.timetable.model.Session; import org.unitime.timetable.model.SolverGroup; import org.unitime.timetable.model.TimePattern; import org.unitime.timetable.model.TimePatternDays; import org.unitime.timetable.model.TimePatternTime; import org.unitime.timetable.model.TimePref; import org.unitime.timetable.model.dao.DepartmentDAO; import org.unitime.timetable.model.dao.SolverGroupDAO; import org.unitime.timetable.solver.CommitedClassAssignmentProxy; import net.sf.cpsolver.ifs.util.ToolBox; /** * @author Tomas Muller */ public class ExportPreferences { private static Log sLog = LogFactory.getLog(ExportPreferences.class); public CommitedClassAssignmentProxy proxy = new CommitedClassAssignmentProxy(); public Comparator ioCmp = null; public Comparator subpartCmp = null; public Comparator classCmp = null; public void exportDatePattern(Element parent, DatePattern datePattern) { sLog.info("Exporting "+datePattern.getName()); Element el = parent.addElement("datePattern"); el.addAttribute("uniqueId", datePattern.getUniqueId().toString()); el.addAttribute("name", datePattern.getName()); el.addAttribute("pattern", datePattern.getPattern()); el.addAttribute("visible", datePattern.isVisible().toString()); el.addAttribute("type", datePattern.getType().toString()); el.addAttribute("offset", datePattern.getOffset().toString()); } public void exportTimePattern(Element parent, TimePattern timePattern) { sLog.info("Exporting "+timePattern.getName()); Element el = parent.addElement("timePattern"); el.addAttribute("uniqueId", timePattern.getUniqueId().toString()); el.addAttribute("name", timePattern.getName()); el.addAttribute("minPerMtg", timePattern.getMinPerMtg().toString()); el.addAttribute("slotsPerMtg", timePattern.getSlotsPerMtg().toString()); el.addAttribute("nrMeetings", timePattern.getNrMeetings().toString()); el.addAttribute("visible", timePattern.isVisible().toString()); el.addAttribute("type", timePattern.getType().toString()); for (Iterator i=timePattern.getDays().iterator();i.hasNext();) { TimePatternDays d = (TimePatternDays)i.next(); el.addElement("dayCode").setText(d.getDayCode().toString()); } for (Iterator i=timePattern.getTimes().iterator();i.hasNext();) { TimePatternTime t = (TimePatternTime)i.next(); el.addElement("startSlot").setText(t.getStartSlot().toString()); } } public void exportSubpartStructure(Element parent, SchedulingSubpart s) { Element el = parent.addElement("schedulingSubpart"); el.addAttribute("uniqueId",s.getUniqueId().toString()); el.addAttribute("itype",s.getItypeDesc()); el.addAttribute("suffix",s.getSchedulingSubpartSuffix()); el.addAttribute("minutesPerWk",s.getMinutesPerWk().toString()); TreeSet subparts = new TreeSet(subpartCmp); subparts.addAll(s.getChildSubparts()); for (Iterator i=subparts.iterator();i.hasNext();) { exportSubpartStructure(el, (SchedulingSubpart)s); } TreeSet classes = new TreeSet(classCmp); classes.addAll(s.getClasses()); for (Iterator i=classes.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); Element x = el.addElement("class"); x.addAttribute("uniqueId", c.getUniqueId().toString()); if (c.getParentClass()!=null) x.addAttribute("parent", c.getParentClass().getUniqueId().toString()); x.addAttribute("expectedCapacity", c.getExpectedCapacity().toString()); x.addAttribute("maxExpectedCapacity", c.getMaxExpectedCapacity().toString()); x.addAttribute("roomRatio", c.getRoomRatio().toString()); x.addAttribute("nbrRooms", c.getNbrRooms().toString()); x.addAttribute("manager", c.getManagingDept().getDeptCode()); x.addAttribute("sectionNumber", String.valueOf(c.getSectionNumber())); } } public void exportInstructionalOffering(Element parent, InstructionalOffering io) throws Exception { sLog.info("Exporting "+io.getCourseName()); Element el = parent.addElement("instructionalOffering"); el.addAttribute("uniqueId", io.getUniqueId().toString()); el.addAttribute("subjectArea", io.getControllingCourseOffering().getSubjectAreaAbbv()); el.addAttribute("courseNbr", io.getControllingCourseOffering().getCourseNbr()); if (io.getInstrOfferingPermId()!=null) el.addAttribute("instrOfferingPermId", io.getInstrOfferingPermId().toString()); for (Iterator i=io.getCourseOfferings().iterator();i.hasNext();) { CourseOffering co = (CourseOffering)i.next(); Element x = el.addElement("courseOffering"); x.addAttribute("uniqueId",co.getUniqueId().toString()); x.addAttribute("subjectArea",co.getSubjectAreaAbbv()); x.addAttribute("courseNbr",co.getCourseNbr()); x.addAttribute("projectedDemand",co.getProjectedDemand().toString()); x.addAttribute("isControl",co.getIsControl().toString()); if (co.getPermId()!=null) x.addAttribute("permId",co.getPermId()); } for (Iterator i=io.getInstrOfferingConfigs().iterator();i.hasNext();) { InstrOfferingConfig c = (InstrOfferingConfig)i.next(); Element x = el.addElement("instrOfferingConfig"); x.addAttribute("uniqueId",c.getUniqueId().toString()); x.addAttribute("limit",c.getLimit().toString()); TreeSet subparts = new TreeSet(subpartCmp); subparts.addAll(c.getSchedulingSubparts()); for (Iterator j=subparts.iterator();j.hasNext();) { SchedulingSubpart s = (SchedulingSubpart)j.next(); if (s.getParentSubpart()==null) exportSubpartStructure(x, s); } } } public void exportClass(Element parent, Class_ clazz) throws Exception { sLog.info("Exporting "+clazz.getClassLabel()); Element el = parent.addElement("class"); el.addAttribute("uniqueId", clazz.getUniqueId().toString()); el.addAttribute("subjectArea", clazz.getSchedulingSubpart().getControllingCourseOffering().getSubjectAreaAbbv()); el.addAttribute("courseNbr", clazz.getSchedulingSubpart().getControllingCourseOffering().getCourseNbr()); el.addAttribute("itype", clazz.getSchedulingSubpart().getItypeDesc()); el.addAttribute("section", String.valueOf(clazz.getSectionNumber())); el.addAttribute("suffix", clazz.getSchedulingSubpart().getSchedulingSubpartSuffix()); el.addAttribute("manager", clazz.getManagingDept().getDeptCode()); el.addAttribute("expectedCapacity", clazz.getExpectedCapacity().toString()); el.addAttribute("numberOfRooms", clazz.getNbrRooms().toString()); el.addAttribute("maxExpectedCapacity", clazz.getMaxExpectedCapacity().toString()); el.addAttribute("roomRatio", clazz.getRoomRatio().toString()); el.addAttribute("notes", clazz.getNotes()); if (clazz.getDatePattern()!=null) el.addAttribute("datePattern", clazz.getDatePattern().getName()); el.addAttribute("deptCode", clazz.getControllingDept().getDeptCode()); for (Iterator i=clazz.getClassInstructors().iterator();i.hasNext();) { exportClassInstructor(el,(ClassInstructor)i.next()); } for (Iterator i=clazz.getPreferences(TimePref.class).iterator();i.hasNext();) { exportTimePref(el,(TimePref)i.next()); } for (Iterator i=clazz.getPreferences(RoomPref.class).iterator();i.hasNext();) { exportRoomPref(el,(RoomPref)i.next()); } for (Iterator i=clazz.getPreferences(BuildingPref.class).iterator();i.hasNext();) { exportBuildingPref(el,(BuildingPref)i.next()); } for (Iterator i=clazz.getPreferences(RoomFeaturePref.class).iterator();i.hasNext();) { exportRoomFeaturePref(el,(RoomFeaturePref)i.next()); } for (Iterator i=clazz.getPreferences(RoomGroupPref.class).iterator();i.hasNext();) { exportRoomGroupPref(el,(RoomGroupPref)i.next()); } Assignment assignment = proxy.getAssignment(clazz); if (assignment!=null) { el.addAttribute("assignedDays", assignment.getDays().toString()); el.addAttribute("assignedSlot", assignment.getStartSlot().toString()); el.addAttribute("assignedTimePattern", assignment.getTimePattern().getName()); Element r = el.addElement("assignedRooms"); for (Iterator i=assignment.getRooms().iterator();i.hasNext();) { Location location = (Location)i.next(); r.addElement("room").addAttribute("uniqueId",location.getUniqueId().toString()).addAttribute("name",location.getLabel()); } } } public void exportSchedulingSubpart(Element parent, SchedulingSubpart subpart) { sLog.info("Exporting "+subpart.getCourseName()+" "+subpart.getItypeDesc()+(subpart.getSchedulingSubpartSuffix().length()==0?"":" ("+subpart.getSchedulingSubpartSuffix()+")")); Element el = parent.addElement("schedulingSubpart"); el.addAttribute("uniqueId", subpart.getUniqueId().toString()); el.addAttribute("subjectArea", subpart.getControllingCourseOffering().getSubjectAreaAbbv()); el.addAttribute("courseNbr", subpart.getControllingCourseOffering().getCourseNbr()); el.addAttribute("itype", subpart.getItypeDesc()); el.addAttribute("suffix", subpart.getSchedulingSubpartSuffix()); el.addAttribute("manager", subpart.getManagingDept().getDeptCode()); el.addAttribute("minutesPerWk", subpart.getMinutesPerWk().toString()); if (subpart.getDatePattern()!=null) el.addAttribute("datePattern", subpart.getDatePattern().getName()); el.addAttribute("deptCode", subpart.getControllingDept().getDeptCode()); for (Iterator i=subpart.getPreferences(TimePref.class).iterator();i.hasNext();) { exportTimePref(el,(TimePref)i.next()); } for (Iterator i=subpart.getPreferences(RoomPref.class).iterator();i.hasNext();) { exportRoomPref(el,(RoomPref)i.next()); } for (Iterator i=subpart.getPreferences(BuildingPref.class).iterator();i.hasNext();) { exportBuildingPref(el,(BuildingPref)i.next()); } for (Iterator i=subpart.getPreferences(RoomFeaturePref.class).iterator();i.hasNext();) { exportRoomFeaturePref(el,(RoomFeaturePref)i.next()); } for (Iterator i=subpart.getPreferences(RoomGroupPref.class).iterator();i.hasNext();) { exportRoomGroupPref(el,(RoomGroupPref)i.next()); } } public void exportClassInstructor(Element parent, ClassInstructor classInstructor) { Element el = parent.addElement("instructor"); el.addAttribute("uniqueId", classInstructor.getInstructor().getUniqueId().toString()); el.addAttribute("isLead", classInstructor.isLead().toString()); el.addAttribute("percentShare", classInstructor.getPercentShare().toString()); el.addAttribute("puid", classInstructor.getInstructor().getExternalUniqueId()); } public void exportTimePref(Element parent, TimePref timePref) { Element el = parent.addElement("timePref"); el.addAttribute("uniqueId", timePref.getUniqueId().toString()); el.addAttribute("timePattern", timePref.getTimePattern().getName()); el.addAttribute("level", timePref.getPrefLevel().getPrefProlog()); el.addAttribute("preference", timePref.getPreference()); } public void exportRoomPref(Element parent, RoomPref roomPref) { Element el = parent.addElement("roomPref"); el.addAttribute("uniqueId", roomPref.getUniqueId().toString()); el.addAttribute("level", roomPref.getPrefLevel().getPrefProlog()); el.addAttribute("room", roomPref.getRoom().getLabel()); } public void exportBuildingPref(Element parent, BuildingPref bldgPref) { Element el = parent.addElement("buildingPref"); el.addAttribute("uniqueId", bldgPref.getUniqueId().toString()); el.addAttribute("level", bldgPref.getPrefLevel().getPrefProlog()); el.addAttribute("building", bldgPref.getBuilding().getAbbreviation()); } public void exportRoomFeaturePref(Element parent, RoomFeaturePref roomFeaturePref) { Element el = parent.addElement("roomFeaturePref"); el.addAttribute("uniqueId", roomFeaturePref.getUniqueId().toString()); el.addAttribute("level", roomFeaturePref.getPrefLevel().getPrefProlog()); el.addAttribute("feature", roomFeaturePref.getRoomFeature().getLabel()); } public void exportRoomGroupPref(Element parent, RoomGroupPref roomGroupPref) { Element el = parent.addElement("roomGroupPref"); el.addAttribute("uniqueId", roomGroupPref.getUniqueId().toString()); el.addAttribute("level", roomGroupPref.getPrefLevel().getPrefProlog()); el.addAttribute("group", roomGroupPref.getRoomGroup().getName()); } public void exportDistributionPref(Element parent, DistributionPref distributionPref) { sLog.info("Exporting "+distributionPref.getDistributionType().getLabel()); Element el = parent.addElement("distributionPref"); el.addAttribute("uniqueId", distributionPref.getUniqueId().toString()); el.addAttribute("level", distributionPref.getPrefLevel().getPrefProlog()); el.addAttribute("type", distributionPref.getDistributionType().getReference()); el.addAttribute("manager", ((Department)distributionPref.getOwner()).getDeptCode()); el.addAttribute("grouping", (distributionPref.getGrouping()==null?"0":distributionPref.getGrouping().toString())); for (Iterator i=distributionPref.getDistributionObjects().iterator();i.hasNext();) { DistributionObject dobj = (DistributionObject)i.next(); if (dobj.getPrefGroup() instanceof Class_) { Class_ clazz = (Class_)dobj.getPrefGroup(); Element x = el.addElement("class"); x.addAttribute("sequenceNumber", dobj.getSequenceNumber().toString()); x.addAttribute("uniqueId", clazz.getUniqueId().toString()); x.addAttribute("subjectArea", clazz.getSchedulingSubpart().getControllingCourseOffering().getSubjectAreaAbbv()); x.addAttribute("courseNbr", clazz.getSchedulingSubpart().getControllingCourseOffering().getCourseNbr()); x.addAttribute("itype", clazz.getSchedulingSubpart().getItypeDesc()); x.addAttribute("section", String.valueOf(clazz.getSectionNumber())); x.addAttribute("suffix", clazz.getSchedulingSubpart().getSchedulingSubpartSuffix()); } else if (dobj.getPrefGroup() instanceof SchedulingSubpart) { SchedulingSubpart subpart = (SchedulingSubpart)dobj.getPrefGroup(); Element x = el.addElement("schedulingSubpart"); x.addAttribute("sequenceNumber", dobj.getSequenceNumber().toString()); x.addAttribute("uniqueId", subpart.getUniqueId().toString()); x.addAttribute("subjectArea", subpart.getControllingCourseOffering().getSubjectAreaAbbv()); x.addAttribute("courseNbr", subpart.getControllingCourseOffering().getCourseNbr()); x.addAttribute("itype", subpart.getItypeDesc()); x.addAttribute("suffix", subpart.getSchedulingSubpartSuffix()); } } } public void exportInstructor(Element parent, DepartmentalInstructor instructorDept) { sLog.info("Exporting "+instructorDept.getNameLastFirst()+" ("+instructorDept.getDepartment().getDeptCode()+")"); Element el = parent.addElement("instructor"); el.addAttribute("uniqueId", instructorDept.getUniqueId().toString()); el.addAttribute("deptCode", instructorDept.getDepartment().getDeptCode()); el.addAttribute("puid", instructorDept.getExternalUniqueId()); for (Iterator i=instructorDept.getPreferences(TimePref.class).iterator();i.hasNext();) { exportTimePref(el,(TimePref)i.next()); } for (Iterator i=instructorDept.getPreferences(RoomPref.class).iterator();i.hasNext();) { exportRoomPref(el,(RoomPref)i.next()); } for (Iterator i=instructorDept.getPreferences(BuildingPref.class).iterator();i.hasNext();) { exportBuildingPref(el,(BuildingPref)i.next()); } for (Iterator i=instructorDept.getPreferences(RoomFeaturePref.class).iterator();i.hasNext();) { exportRoomFeaturePref(el,(RoomFeaturePref)i.next()); } for (Iterator i=instructorDept.getPreferences(RoomGroupPref.class).iterator();i.hasNext();) { exportRoomGroupPref(el,(RoomGroupPref)i.next()); } } public void exportInstructors(Element parent, Department dept) { List ids = (new DepartmentDAO()). getSession(). createQuery("select id from DepartmentalInstructor id where id.department.deptCode=:deptCode and id.department.sessionId=:sessionId"). setString("deptCode", dept.getDeptCode()). setLong("sessionId", dept.getSessionId().longValue()). list(); for (Iterator i=ids.iterator();i.hasNext();) { DepartmentalInstructor id = (DepartmentalInstructor)i.next(); exportInstructor(parent, id); } } public void exportAll(Long solverGroupId, File outFile) throws Exception { SolverGroup solverGroup = (new SolverGroupDAO()).get(solverGroupId); Session session = solverGroup.getSession(); Document document = DocumentHelper.createDocument(); Element root = document.addElement("export"); root.addAttribute("solverGroup", solverGroup.getUniqueId().toString()); root.addAttribute("solverGroupName", solverGroup.getName()); root.addAttribute("session", session.getUniqueId().toString()); root.addAttribute("academicYearTerm", session.getAcademicYearTerm()); root.addAttribute("academicInitiative", session.getAcademicInitiative()); for (Iterator i=TimePattern.findAll(session,null).iterator();i.hasNext();) { TimePattern t = (TimePattern)i.next(); exportTimePattern(root, t); } for (Iterator i=DatePattern.findAll(session,true,null,null).iterator();i.hasNext();) { DatePattern d = (DatePattern)i.next(); exportDatePattern(root, d); } classCmp = new Comparator() { public int compare(Object o1, Object o2) { Class_ c1 = (Class_)o1; Class_ c2 = (Class_)o2; int cmp = c1.getCourseName().compareTo(c2.getCourseName()); if (cmp!=0) return cmp; cmp = c1.getSchedulingSubpart().getItype().getItype().compareTo(c2.getSchedulingSubpart().getItype().getItype()); if (cmp!=0) return cmp; cmp = c1.getSchedulingSubpart().getSchedulingSubpartSuffix().compareTo(c2.getSchedulingSubpart().getSchedulingSubpartSuffix()); if (cmp!=0) return cmp; return c1.getUniqueId().compareTo(c2.getUniqueId()); } }; TreeSet classes = new TreeSet(classCmp); subpartCmp = new Comparator() { public int compare(Object o1, Object o2) { SchedulingSubpart s1 = (SchedulingSubpart)o1; SchedulingSubpart s2 = (SchedulingSubpart)o2; int cmp = s1.getCourseName().compareTo(s2.getCourseName()); if (cmp!=0) return cmp; cmp = s1.getItype().getItype().compareTo(s2.getItype().getItype()); if (cmp!=0) return cmp; return s1.getUniqueId().compareTo(s2.getUniqueId()); } }; TreeSet subparts = new TreeSet(subpartCmp); ioCmp = new Comparator() { public int compare(Object o1, Object o2) { InstructionalOffering i1 = (InstructionalOffering)o1; InstructionalOffering i2 = (InstructionalOffering)o2; int cmp = i1.getCourseName().compareTo(i2.getCourseName()); if (cmp!=0) return cmp; return i1.getUniqueId().compareTo(i2.getUniqueId()); } }; TreeSet offerings = new TreeSet(ioCmp); classes.addAll(solverGroup.getClasses()); for (Iterator i=classes.iterator();i.hasNext();) { Class_ c = (Class_)i.next(); exportClass(root, c); SchedulingSubpart s = c.getSchedulingSubpart(); offerings.add(s.getInstrOfferingConfig().getInstructionalOffering()); if (solverGroup.getDepartments().contains(s.getManagingDept())) { subparts.add(s); } } for (Iterator i=subparts.iterator();i.hasNext();) { SchedulingSubpart s = (SchedulingSubpart)i.next(); exportSchedulingSubpart(root, s); } for (Iterator i=offerings.iterator();i.hasNext();) { InstructionalOffering io = (InstructionalOffering)i.next(); exportInstructionalOffering(root, io); } for (Iterator i=solverGroup.getDepartments().iterator();i.hasNext();) { Department d = (Department)i.next(); exportInstructors(root, d); } for (Iterator i=solverGroup.getDistributionPreferences().iterator();i.hasNext();) { DistributionPref d = (DistributionPref)i.next(); exportDistributionPref(root, d); } FileOutputStream fos = null; try { fos = new FileOutputStream(outFile); (new XMLWriter(fos,OutputFormat.createPrettyPrint())).write(document); fos.flush();fos.close();fos=null; } finally { try { if (fos!=null) fos.close(); } catch (IOException e){} } } public static void main(String[] args) { // Example arguments: jdbc:oracle:thin:@tamarind.smas.purdue.edu:1521:sms8l 1 c:\\export.xml try { ToolBox.configureLogging(); HibernateUtil.configureHibernate(args[0]); (new ExportPreferences()).exportAll(new Long(args[1]), new File(args[2])); } catch (Exception e) { e.printStackTrace(); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.rlcommunity.critterbot.gui; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; import org.rlcommunity.critterbot.javadrops.clients.DiscoInterfaceClient; import org.rlcommunity.critterbot.javadrops.drops.CritterControlDrop; import org.rlcommunity.critterbot.javadrops.drops.CritterRewardDrop; import org.rlcommunity.critterbot.javadrops.drops.CritterStateDrop; import org.rlcommunity.critterbot.javadrops.drops.DropInterface; import org.rlcommunity.critterbot.javadrops.drops.SimulatorDrop; /** * * @author critterbot */ public class CritterVizMain { public static final int critterVizPort = 3444; public static final String critterVizHost = "localhost"; public static final int dropQueueSize = 32; public CritterStateDrop currentState; private CritterViz gui; public CritterVizMain() { currentState = new CritterStateDrop(); // Create a TCP server to talk with Disco InetAddress netAddr = null; try { netAddr = InetAddress.getByName(critterVizHost); } catch (UnknownHostException e) { System.err.println("Unknown hostname."); System.exit(1); } DiscoInterfaceClient discoClient = new DiscoInterfaceClient( netAddr, critterVizPort, dropQueueSize); // Start its thread discoClient.start(); // Create the central drop interface DropInterface dropInterface = new DropInterface(); // Add the disco server to the central drop interface dropInterface.addClient(discoClient); // Create a new agent //CritterVizMain me = new CritterVizMain(); runGUI(currentState,dropInterface); //me.runGUI(me.currentState,dropInterface); while (true) { // Receive drops from the simulator List<SimulatorDrop> drops = dropInterface.receiveDrops(); // Pass them on to the agent (this may be an empty list) for (SimulatorDrop d : drops) { observeDrop(d); } // Sleep for a little while to give the processor a break try { Thread.sleep(10); } catch (InterruptedException ex) { } } } private void runGUI(final CritterStateDrop state, final DropInterface di) { javax.swing.SwingUtilities.invokeLater( new Runnable() { public void run() { gui = new CritterViz(di); gui.setTitle("Critterbot GUI"); gui.setVisible(true); } } ); /*javax.swing.SwingUtilities.invokeLater( new Runnable() { public void run() { new CritterVizLogTag(di); } } );*/ } /** Receive a drop from the server. * We parse the drop depending on its type (it could be a reward or state * information/an observation). * * @param pDrop The received drop. */ public void observeDrop(SimulatorDrop pDrop) { // Determine what to do with the drop based on the drop type if (pDrop instanceof CritterStateDrop) { final CritterStateDrop stateDrop = (CritterStateDrop) pDrop; javax.swing.SwingUtilities.invokeLater( new Runnable() { public void run() { gui.updateDisplay(stateDrop); } } ); } else if (pDrop instanceof CritterRewardDrop) { } // An unfortunate side effect of the current Disco set up is that we // receive our own ControlDrop's else if (pDrop instanceof CritterControlDrop) { } } public static void main(String[] args) { new CritterVizMain(); } }
package org.hamcrest.core; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import java.lang.reflect.Array; /** * Is the value equal to another value, as tested by the * {@link java.lang.Object#equals} invokedMethod? */ public class IsEqual<T> extends BaseMatcher<T> { private final Object expectedValue; public IsEqual(T equalArg) { expectedValue = equalArg; } @Override public boolean matches(Object actualValue) { return areEqual(actualValue, expectedValue); } @Override public void describeTo(Description description) { description.appendValue(expectedValue); } private static boolean areEqual(Object actual, Object expected) { if (actual == null) { return expected == null; } if (expected != null && isArray(actual)) { return isArray(expected) && areArraysEqual(actual, expected); } return actual.equals(expected); } private static boolean areArraysEqual(Object actualArray, Object expectedArray) { return areArrayLengthsEqual(actualArray, expectedArray) && areArrayElementsEqual(actualArray, expectedArray); } private static boolean areArrayLengthsEqual(Object actualArray, Object expectedArray) { return Array.getLength(actualArray) == Array.getLength(expectedArray); } private static boolean areArrayElementsEqual(Object actualArray, Object expectedArray) { for (int i = 0; i < Array.getLength(actualArray); i++) { if (!areEqual(Array.get(actualArray, i), Array.get(expectedArray, i))) { return false; } } return true; } private static boolean isArray(Object o) { return o.getClass().isArray(); } /** * Creates a matcher that matches when the examined object is logically equal to the specified * <code>operand</code>, as determined by calling the {@link java.lang.Object#equals} method on * the <b>examined</b> object. * * <p>If the specified operand is <code>null</code> then the created matcher will only match if * the examined object's <code>equals</code> method returns <code>true</code> when passed a * <code>null</code> (which would be a violation of the <code>equals</code> contract), unless the * examined object itself is <code>null</code>, in which case the matcher will return a positive * match.</p> * * <p>The created matcher provides a special behaviour when examining <code>Array</code>s, whereby * it will match if both the operand and the examined object are arrays of the same length and * contain items that are equal to each other (according to the above rules) <b>in the same * indexes</b>.</p> * For example: * <pre> * assertThat("foo", equalTo("foo")); * assertThat(new String[] {"foo", "bar"}, equalTo(new String[] {"foo", "bar"})); * </pre> * */ public static <T> Matcher<T> equalTo(T operand) { return new IsEqual<>(operand); } /** * Creates an {@link org.hamcrest.core.IsEqual} matcher that does not enforce the values being * compared to be of the same static type. */ public static Matcher<Object> equalToObject(Object operand) { return new IsEqual<>(operand); } }
package com.health.visuals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import javax.xml.parsers.ParserConfigurationException; import org.jfree.chart.JFreeChart; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; import com.health.Table; import com.health.input.Input; import com.health.input.InputException; /** * Testing Histogram. * @author Lizzy Scholten * */ public class HistogramTest { private Table table; private String filePath; private String configPath; /** * Setup before testing. */ @Before public final void setUp() { filePath = "data/data_use/txtData.txt"; configPath = "data/configXmls" + "/admireTxtConfigIgnoreLast.xml"; } /** * Test whether the chart is indeed saved in file. * @throws IOException * io exception * @throws ParserConfigurationException * parser configuration exception * @throws SAXException * SAX exception * @throws InputException * input exception */ @Test public final void writeFileTest() throws IOException, ParserConfigurationException, SAXException, InputException { table = Input.readTable(filePath, configPath); final int bin = 10; JFreeChart chart = Histogram.createHist(table, "value", bin); Histogram.writeChartToPDF(chart, "HistogramTest"); File f = new File("HistogramTest.pdf"); assertTrue(f.exists()); } /** * Test that constructor cannot be called. * @throws Exception * exception */ @SuppressWarnings("rawtypes") @Test public final void constructorTest() throws Exception { Constructor[] ctors = Histogram.class.getDeclaredConstructors(); assertEquals("Histogram class should only have one constructor", 1, ctors.length); Constructor ctor = ctors[0]; assertFalse("Histogram class constructor should be inaccessible", ctor.isAccessible()); ctor.setAccessible(true); assertEquals("You'd expect the construct to return the expected type", Histogram.class, ctor.newInstance().getClass()); } /** * Test the visualization of the chart. * @throws IOException * io exception * @throws ParserConfigurationException * parser configuration exception * @throws SAXException * SAX exception * @throws InputException * input exception */ @Test public final void visualizeTest() throws IOException, ParserConfigurationException, SAXException, InputException { table = Input.readTable(filePath, configPath); final int bin = 10; JFreeChart chart = Histogram.createHist(table, "value", bin); Histogram.visualHist(chart); } }
package imagej.ij1bridge; import java.awt.Rectangle; import java.awt.image.ColorModel; import java.util.ArrayList; import ij.ImageStack; import ij.process.ImageProcessor; import imagej.Dimensions; import imagej.dataset.Dataset; import imagej.process.Index; // TODO - for performance could use planeRef's size/cache methods rather than querying dataset all the time /** BridgeStack will take data from a PlanarDataset and point into it so that ij1 can use it as an ImageStack and make changes to it */ public class BridgeStack extends ImageStack { private Dataset dataset; private ArrayList<Object> planeRefs; private int[] planeDims; private ProcessorFactory processorFactory; private Object[] planeRefCache; private final String outOfRange = "stack index out of range: "; private double min = Double.MAX_VALUE; private double max; private Rectangle roi; private ColorModel cm; private float[] cTable; public BridgeStack(Dataset ds, ProcessorFactory procFac) { this.dataset = ds; this.processorFactory = procFac; this.planeRefs = new ArrayList<Object>(); // TODO - relaxing for the moment since MetaData code not in place. do some kind of check later. //if (ds.getMetaData().getDirectAccessDimensionCount() != 2) int[] dimensions = ds.getDimensions(); int numPlanes = (int) Dimensions.getTotalPlanes(dimensions); if (numPlanes <= 0) throw new IllegalArgumentException("can't make a BridgeStack on a dataset that has 0 planes"); this.planeDims = new int[2]; this.planeDims[0] = dimensions[0]; this.planeDims[1] = dimensions[1]; int[] subDimensions = new int[dimensions.length-2]; for (int i = 0; i < subDimensions.length; i++) subDimensions[i] = dimensions[i+2]; if (subDimensions.length == 0) { this.planeRefs.add(this.dataset.getData()); } else { int[] origin = Index.create(dimensions.length-2); int[] position = Index.create(dimensions.length-2); while (Index.isValid(position, origin, subDimensions)) { Object planeRef = ds.getSubset(position).getData(); this.planeRefs.add(planeRef); Index.increment(position, origin, subDimensions); } } } // NOTE - index in range 0..n-1 private void insertSlice(int index, String sliceLabel, Object pixels) { Dataset newSubset = this.dataset.insertNewSubset(index); newSubset.setData(pixels); this.planeRefs.add(index, pixels); // update our cache setSliceLabel(sliceLabel, index+1); } // TODO - make processors event listeners for addition/deletion of subsets. fixup planePos if needed (or even have proc go away if possible) @Override public void addSlice(String sliceLabel, Object pixels) { int end = this.planeRefs.size(); insertSlice(end, sliceLabel, pixels); } // TODO - make processors event listeners for addition/deletion of subsets. fixup planePos if needed (or even have proc go away if possible) @Override public void addSlice(String sliceLabel, ImageProcessor ip) { if ((ip.getWidth() != getWidth()) || (ip.getHeight() != getHeight())) throw new IllegalArgumentException("Dimensions do not match"); if (this.planeRefs.size() == 0) // TODO - note this code will never evaluate to true for imglib datasets as imglib constituted 11-20-10 { this.cm = ip.getColorModel(); this.min = ip.getMin(); this.max = ip.getMax(); } addSlice(sliceLabel, ip.getPixels()); } // TODO - make processors event listeners for addition/deletion of subsets. fixup planePos if needed (or even have proc go away if possible) @Override public void addSlice(String sliceLabel, ImageProcessor ip, int n) { if (n<1 || n>this.planeRefs.size()) throw new IllegalArgumentException(outOfRange+n); insertSlice(n-1, sliceLabel, ip.getPixels()); } // TODO - make processors event listeners for addition/deletion of subsets. fixup planePos if needed (or even have proc go away if possible) @Override public void deleteSlice(int n) { if (n<1 || n>this.planeRefs.size()) throw new IllegalArgumentException(outOfRange+n); this.dataset.removeSubset(n-1); this.planeRefs.remove(n-1); this.planeRefCache = null; } // TODO - make processors event listeners for addition/deletion of subsets. fixup planePos if needed (or even have proc go away if possible) @Override public void deleteLastSlice() { int numPlanes = this.planeRefs.size(); if (numPlanes > 0) // TODO - imglib forces this to be true!!! should fail on deleting last plane. address with imglib people. { int lastPlane = numPlanes - 1; this.dataset.removeSubset(lastPlane); this.planeRefs.remove(lastPlane); this.planeRefCache = null; } } @Override public int getWidth() { return this.planeDims[0]; } @Override public int getHeight() { return this.planeDims[1]; } @Override public void setRoi(Rectangle roi) { this.roi = roi; } @Override public Rectangle getRoi() { if (this.roi==null) return new Rectangle(0, 0, getWidth(), getHeight()); return this.roi; } @Override /** Updates this stack so its attributes, such as min, max, calibration table and color model, are the same as 'ip'. */ public void update(ImageProcessor ip) { if (ip!=null) { this.min = ip.getMin(); this.max = ip.getMax(); this.cTable = ip.getCalibrationTable(); this.cm = ip.getColorModel(); } } @Override /** Returns the pixel array for the specified slice, were 1<=n<=nslices. */ public Object getPixels(int n) { if (n<1 || n>this.planeRefs.size()) throw new IllegalArgumentException(outOfRange+n); return this.planeRefs.get(n-1); } @Override /** Assigns a pixel array to the specified slice, were 1<=n<=nslices. */ public void setPixels(Object pixels, int n) { if (n<1 || n>this.planeRefs.size()) throw new IllegalArgumentException(outOfRange+n); int[] planePos = Index.getPlanePosition(this.dataset.getDimensions(), n-1); this.dataset.getSubset(planePos).setData(pixels); this.planeRefs.set(n-1, pixels); } @Override /** Returns the stack as an array of 1D pixel arrays. Note that the size of the returned array may be greater than the number of slices currently in the stack, with unused elements set to null. */ public Object[] getImageArray() { if ((this.planeRefCache == null) || (this.planeRefs.size() > this.planeRefCache.length)) { this.planeRefCache = new Object[this.planeRefs.size()]; } return this.planeRefs.toArray(this.planeRefCache); } @Override /** Returns the number of slices in this stack. */ public int getSize() { return this.planeRefs.size(); } @Override /** Returns the slice labels as an array of Strings. Returns null if the stack is empty. */ public String[] getSliceLabels() { if (this.planeRefs.size() == 0) return null; // NOTE - we will return a COPY of the labels. Users should access them readonly. // TODO - document. String[] labels = new String[this.planeRefs.size()]; for (int i = 0; i < labels.length; i++) { int[] planePos = Index.getPlanePosition(this.dataset.getDimensions(), i); labels[i] = this.dataset.getSubset(planePos).getMetaData().getLabel(); } return labels; } @Override /** Returns the label of the specified slice, were 1<=n<=nslices. Returns null if the slice does not have a label. For DICOM and FITS stacks, labels may contain header information. */ public String getSliceLabel(int n) { if (n<1 || n>this.planeRefs.size()) throw new IllegalArgumentException(outOfRange+n); int[] planePos = Index.getPlanePosition(this.dataset.getDimensions(), n-1); return this.dataset.getSubset(planePos).getMetaData().getLabel(); } @Override /** Returns a shortened version (up to the first 60 characters or first newline and suffix removed) of the label of the specified slice. Returns null if the slice does not have a label. */ public String getShortSliceLabel(int n) { String shortLabel = getSliceLabel(n); if (shortLabel == null) return null; int newline = shortLabel.indexOf('\n'); if (newline == 0) return null; if (newline > 0) shortLabel = shortLabel.substring(0, newline); int len = shortLabel.length(); if ((len>4) && (shortLabel.charAt(len-4) == '.') && (!Character.isDigit(shortLabel.charAt(len-1)))) shortLabel = shortLabel.substring(0,len-4); if (shortLabel.length() > 60) shortLabel = shortLabel.substring(0, 60); return shortLabel; } @Override /** Sets the label of the specified slice, were 1<=n<=nslices. */ public void setSliceLabel(String label, int n) { if (n<1 || n>this.planeRefs.size()) throw new IllegalArgumentException(outOfRange+n); int[] planePos = Index.getPlanePosition(this.dataset.getDimensions(), n-1); this.dataset.getSubset(planePos).getMetaData().setLabel(label); } @Override /** Returns an ImageProcessor for the specified slice, where 1<=n<=nslices. Returns null if the stack is empty. */ public ImageProcessor getProcessor(int n) { if (n<1 || n>this.planeRefs.size()) throw new IllegalArgumentException(outOfRange+n); int[] planePos = Index.getPlanePosition(this.dataset.getDimensions(), n-1); ImageProcessor ip = processorFactory.makeProcessor(planePos); // TODO : problem - what if we want one processor per plane and return it over and over. here we are hatching new all the time. if ((this.min != Double.MAX_VALUE) && (ip!=null)) ip.setMinAndMax(this.min, this.max); if (this.cTable!=null) ip.setCalibrationTable(this.cTable); return ip; } @Override /** Assigns a new color model to this stack. */ public void setColorModel(ColorModel cm) { this.cm = cm; } @Override /** Returns this stack's color model. May return null. */ public ColorModel getColorModel() { return this.cm; } @Override /** Returns true if this is a 3-slice RGB stack. */ public boolean isRGB() { if ((this.planeRefs.size()==3) && (this.planeRefs.get(0) instanceof byte[]) && ("Red".equals(getSliceLabel(1)))) return true; return false; } @Override /** Returns true if this is a 3-slice HSB stack. */ public boolean isHSB() { if ((this.planeRefs.size()==3) && ("Hue".equals(getSliceLabel(1)))) return true; return false; } @Override /** Returns true if this is a virtual (disk resident) stack. This method is overridden by the VirtualStack subclass. */ public boolean isVirtual() { return false; // TODO - assuming this means I am not a VirtualStack class. If it means something else then we'll need to query imglib } @Override /** Frees memory by deleting a few slices from the end of the stack. */ public void trim() { int n = (int)Math.round(Math.log(this.planeRefs.size())+1.0); for (int i=0; i<n; i++) { deleteLastSlice(); System.gc(); } } @Override public String toString() { String v = isVirtual()?"(V)":""; return ("stack["+getWidth()+"x"+getHeight()+"x"+getSize()+v+"]"); } @Override public void flush() { for (int i = 0; i < this.planeRefs.size(); i++) this.planeRefs.set(i, null); } }
package org.zstack.image; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.zstack.core.CoreGlobalProperty; import org.zstack.core.Platform; import org.zstack.core.asyncbatch.AsyncBatchRunner; import org.zstack.core.asyncbatch.LoopAsyncBatch; import org.zstack.core.asyncbatch.While; import org.zstack.core.cloudbus.*; import org.zstack.core.componentloader.PluginRegistry; import org.zstack.core.config.GlobalConfig; import org.zstack.core.config.GlobalConfigUpdateExtensionPoint; import org.zstack.core.db.*; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.core.defer.Defer; import org.zstack.core.defer.Deferred; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.core.notification.N; import org.zstack.core.thread.CancelablePeriodicTask; import org.zstack.core.thread.ThreadFacade; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.core.workflow.ShareFlow; import org.zstack.header.AbstractService; import org.zstack.header.core.AsyncLatch; import org.zstack.header.core.NoErrorCompletion; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.ErrorCodeList; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.identity.*; import org.zstack.header.image.*; import org.zstack.header.image.APICreateRootVolumeTemplateFromVolumeSnapshotEvent.Failure; import org.zstack.header.image.ImageConstant.ImageMediaType; import org.zstack.header.image.ImageDeletionPolicyManager.ImageDeletionPolicy; import org.zstack.header.managementnode.ManagementNodeReadyExtensionPoint; import org.zstack.header.message.APIMessage; import org.zstack.header.message.Message; import org.zstack.header.message.MessageReply; import org.zstack.header.message.NeedQuotaCheckMessage; import org.zstack.header.quota.QuotaConstant; import org.zstack.header.rest.RESTFacade; import org.zstack.header.search.SearchOp; import org.zstack.header.storage.backup.*; import org.zstack.header.storage.primary.PrimaryStorageVO; import org.zstack.header.storage.primary.PrimaryStorageVO_; import org.zstack.header.storage.snapshot.*; import org.zstack.header.vm.CreateTemplateFromVmRootVolumeMsg; import org.zstack.header.vm.CreateTemplateFromVmRootVolumeReply; import org.zstack.header.vm.VmInstanceConstant; import org.zstack.header.volume.*; import org.zstack.identity.AccountManager; import org.zstack.identity.QuotaUtil; import org.zstack.search.SearchQuery; import org.zstack.tag.TagManager; import org.zstack.utils.CollectionUtils; import org.zstack.utils.ObjectUtils; import org.zstack.utils.RunOnce; import org.zstack.utils.Utils; import org.zstack.utils.data.SizeUnit; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.function.Function; import org.zstack.utils.gson.JSONObjectUtil; import org.zstack.utils.logging.CLogger; import javax.persistence.Tuple; import javax.persistence.TypedQuery; import java.sql.Timestamp; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static org.zstack.core.Platform.operr; import static org.zstack.utils.CollectionDSL.list; public class ImageManagerImpl extends AbstractService implements ImageManager, ManagementNodeReadyExtensionPoint, ReportQuotaExtensionPoint, ResourceOwnerPreChangeExtensionPoint { private static final CLogger logger = Utils.getLogger(ImageManagerImpl.class); @Autowired private CloudBus bus; @Autowired private PluginRegistry pluginRgty; @Autowired private DatabaseFacade dbf; @Autowired private AccountManager acntMgr; @Autowired private ErrorFacade errf; @Autowired private TagManager tagMgr; @Autowired private ThreadFacade thdf; @Autowired private ResourceDestinationMaker destMaker; @Autowired private ImageDeletionPolicyManager deletionPolicyMgr; @Autowired protected RESTFacade restf; private Map<String, ImageFactory> imageFactories = Collections.synchronizedMap(new HashMap<>()); private static final Set<Class> allowedMessageAfterDeletion = new HashSet<>(); private Future<Void> expungeTask; static { allowedMessageAfterDeletion.add(ImageDeletionMsg.class); } @Override @MessageSafe public void handleMessage(Message msg) { if (msg instanceof ImageMessage) { passThrough((ImageMessage) msg); } else if (msg instanceof APIMessage) { handleApiMessage(msg); } else { handleLocalMessage(msg); } } private void handleLocalMessage(Message msg) { bus.dealWithUnknownMessage(msg); } private void handleApiMessage(Message msg) { if (msg instanceof APIAddImageMsg) { handle((APIAddImageMsg) msg); } else if (msg instanceof APIListImageMsg) { handle((APIListImageMsg) msg); } else if (msg instanceof APISearchImageMsg) { handle((APISearchImageMsg) msg); } else if (msg instanceof APIGetImageMsg) { handle((APIGetImageMsg) msg); } else if (msg instanceof APICreateRootVolumeTemplateFromRootVolumeMsg) { handle((APICreateRootVolumeTemplateFromRootVolumeMsg) msg); } else if (msg instanceof APICreateRootVolumeTemplateFromVolumeSnapshotMsg) { handle((APICreateRootVolumeTemplateFromVolumeSnapshotMsg) msg); } else if (msg instanceof APICreateDataVolumeTemplateFromVolumeMsg) { handle((APICreateDataVolumeTemplateFromVolumeMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(final APICreateDataVolumeTemplateFromVolumeMsg msg) { final APICreateDataVolumeTemplateFromVolumeEvent evt = new APICreateDataVolumeTemplateFromVolumeEvent(msg.getId()); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("create-data-volume-template-from-volume-%s", msg.getVolumeUuid())); chain.then(new ShareFlow() { List<BackupStorageInventory> backupStorage = new ArrayList<>(); ImageVO image; long actualSize; @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "get-actual-size-of-data-volume"; @Override public void run(final FlowTrigger trigger, Map data) { SyncVolumeSizeMsg smsg = new SyncVolumeSizeMsg(); smsg.setVolumeUuid(msg.getVolumeUuid()); bus.makeTargetServiceIdByResourceUuid(smsg, VolumeConstant.SERVICE_ID, msg.getVolumeUuid()); bus.send(smsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); return; } SyncVolumeSizeReply sr = reply.castReply(); actualSize = sr.getActualSize(); trigger.next(); } }); } }); flow(new Flow() { String __name__ = "create-image-in-database"; @Override public void run(FlowTrigger trigger, Map data) { SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class); q.select(VolumeVO_.format, VolumeVO_.size); q.add(VolumeVO_.uuid, Op.EQ, msg.getVolumeUuid()); Tuple t = q.findTuple(); String format = t.get(0, String.class); long size = t.get(1, Long.class); final ImageVO vo = new ImageVO(); vo.setUuid(msg.getResourceUuid() == null ? Platform.getUuid() : msg.getResourceUuid()); vo.setName(msg.getName()); vo.setDescription(msg.getDescription()); vo.setType(ImageConstant.ZSTACK_IMAGE_TYPE); vo.setMediaType(ImageMediaType.DataVolumeTemplate); vo.setSize(size); vo.setActualSize(actualSize); vo.setState(ImageState.Enabled); vo.setStatus(ImageStatus.Creating); vo.setFormat(format); vo.setUrl(String.format("volume://%s", msg.getVolumeUuid())); image = dbf.persistAndRefresh(vo); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName()); trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { if (image != null) { dbf.remove(image); } trigger.rollback(); } }); flow(new Flow() { String __name__ = "select-backup-storage"; @Override public void run(final FlowTrigger trigger, Map data) { final String zoneUuid = new Callable<String>() { @Override @Transactional(readOnly = true) public String call() { String sql = "select ps.zoneUuid" + " from PrimaryStorageVO ps, VolumeVO vol" + " where vol.primaryStorageUuid = ps.uuid" + " and vol.uuid = :volUuid"; TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class); q.setParameter("volUuid", msg.getVolumeUuid()); return q.getSingleResult(); } }.call(); if (msg.getBackupStorageUuids() == null) { AllocateBackupStorageMsg amsg = new AllocateBackupStorageMsg(); amsg.setRequiredZoneUuid(zoneUuid); amsg.setSize(actualSize); bus.makeLocalServiceId(amsg, BackupStorageConstant.SERVICE_ID); bus.send(amsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { backupStorage.add(((AllocateBackupStorageReply) reply).getInventory()); trigger.next(); } else { trigger.fail(errf.stringToOperationError("cannot find proper backup storage", reply.getError())); } } }); } else { List<AllocateBackupStorageMsg> amsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<AllocateBackupStorageMsg, String>() { @Override public AllocateBackupStorageMsg call(String arg) { AllocateBackupStorageMsg amsg = new AllocateBackupStorageMsg(); amsg.setRequiredZoneUuid(zoneUuid); amsg.setSize(actualSize); amsg.setBackupStorageUuid(arg); bus.makeLocalServiceId(amsg, BackupStorageConstant.SERVICE_ID); return amsg; } }); bus.send(amsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { List<ErrorCode> errs = new ArrayList<>(); for (MessageReply r : replies) { if (r.isSuccess()) { backupStorage.add(((AllocateBackupStorageReply) r).getInventory()); } else { errs.add(r.getError()); } } if (backupStorage.isEmpty()) { trigger.fail(operr("failed to allocate all backup storage[uuid:%s], a list of error: %s", msg.getBackupStorageUuids(), JSONObjectUtil.toJsonString(errs))); } else { trigger.next(); } } }); } } @Override public void rollback(FlowRollback trigger, Map data) { if (!backupStorage.isEmpty()) { List<ReturnBackupStorageMsg> rmsgs = CollectionUtils.transformToList(backupStorage, new Function<ReturnBackupStorageMsg, BackupStorageInventory>() { @Override public ReturnBackupStorageMsg call(BackupStorageInventory arg) { ReturnBackupStorageMsg rmsg = new ReturnBackupStorageMsg(); rmsg.setBackupStorageUuid(arg.getUuid()); rmsg.setSize(actualSize); bus.makeLocalServiceId(rmsg, BackupStorageConstant.SERVICE_ID); return rmsg; } }); bus.send(rmsgs, new CloudBusListCallBack(null) { @Override public void run(List<MessageReply> replies) { for (MessageReply r : replies) { BackupStorageInventory bs = backupStorage.get(replies.indexOf(r)); logger.warn(String.format("failed to return %s bytes to backup storage[uuid:%s]", acntMgr, bs.getUuid())); } } }); } trigger.rollback(); } }); flow(new NoRollbackFlow() { String __name__ = "create-data-volume-template-from-volume"; @Override public void run(final FlowTrigger trigger, Map data) { List<CreateDataVolumeTemplateFromDataVolumeMsg> cmsgs = CollectionUtils.transformToList(backupStorage, new Function<CreateDataVolumeTemplateFromDataVolumeMsg, BackupStorageInventory>() { @Override public CreateDataVolumeTemplateFromDataVolumeMsg call(BackupStorageInventory bs) { CreateDataVolumeTemplateFromDataVolumeMsg cmsg = new CreateDataVolumeTemplateFromDataVolumeMsg(); cmsg.setVolumeUuid(msg.getVolumeUuid()); cmsg.setBackupStorageUuid(bs.getUuid()); cmsg.setImageUuid(image.getUuid()); bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeConstant.SERVICE_ID, msg.getVolumeUuid()); return cmsg; } }); bus.send(cmsgs, new CloudBusListCallBack(msg) { @Override public void run(List<MessageReply> replies) { int fail = 0; String mdsum = null; ErrorCode err = null; String format = null; for (MessageReply r : replies) { BackupStorageInventory bs = backupStorage.get(replies.indexOf(r)); if (!r.isSuccess()) { logger.warn(String.format("failed to create data volume template from volume[uuid:%s] on backup storage[uuid:%s], %s", msg.getVolumeUuid(), bs.getUuid(), r.getError())); fail++; err = r.getError(); continue; } CreateDataVolumeTemplateFromDataVolumeReply reply = r.castReply(); ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setBackupStorageUuid(bs.getUuid()); ref.setStatus(ImageStatus.Ready); ref.setImageUuid(image.getUuid()); ref.setInstallPath(reply.getInstallPath()); dbf.persist(ref); if (mdsum == null) { mdsum = reply.getMd5sum(); } if (reply.getFormat() != null) { format = reply.getFormat(); } } int backupStorageNum = msg.getBackupStorageUuids() == null ? 1 : msg.getBackupStorageUuids().size(); if (fail == backupStorageNum) { ErrorCode errCode = operr("failed to create data volume template from volume[uuid:%s] on all backup storage%s. See cause for one of errors", msg.getVolumeUuid(), msg.getBackupStorageUuids()).causedBy(err); trigger.fail(errCode); } else { image = dbf.reload(image); if (format != null) { image.setFormat(format); } image.setMd5Sum(mdsum); image.setStatus(ImageStatus.Ready); image = dbf.updateAndRefresh(image); trigger.next(); } } }); } }); done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { evt.setInventory(ImageInventory.valueOf(image)); bus.publish(evt); } }); error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { evt.setError(errCode); bus.publish(evt); } }); } }).start(); } private void handle(final APICreateRootVolumeTemplateFromVolumeSnapshotMsg msg) { final APICreateRootVolumeTemplateFromVolumeSnapshotEvent evt = new APICreateRootVolumeTemplateFromVolumeSnapshotEvent(msg.getId()); SimpleQuery<VolumeSnapshotVO> q = dbf.createQuery(VolumeSnapshotVO.class); q.select(VolumeSnapshotVO_.format); q.add(VolumeSnapshotVO_.uuid, Op.EQ, msg.getSnapshotUuid()); String format = q.findValue(); final ImageVO vo = new ImageVO(); if (msg.getResourceUuid() != null) { vo.setUuid(msg.getResourceUuid()); } else { vo.setUuid(Platform.getUuid()); } vo.setName(msg.getName()); vo.setSystem(msg.isSystem()); vo.setDescription(msg.getDescription()); vo.setPlatform(ImagePlatform.valueOf(msg.getPlatform())); vo.setGuestOsType(vo.getGuestOsType()); vo.setStatus(ImageStatus.Creating); vo.setState(ImageState.Enabled); vo.setFormat(format); vo.setMediaType(ImageMediaType.RootVolumeTemplate); vo.setType(ImageConstant.ZSTACK_IMAGE_TYPE); vo.setUrl(String.format("volumeSnapshot://%s", msg.getSnapshotUuid())); dbf.persist(vo); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName()); SimpleQuery<VolumeSnapshotVO> sq = dbf.createQuery(VolumeSnapshotVO.class); sq.select(VolumeSnapshotVO_.volumeUuid, VolumeSnapshotVO_.treeUuid); sq.add(VolumeSnapshotVO_.uuid, Op.EQ, msg.getSnapshotUuid()); Tuple t = sq.findTuple(); String volumeUuid = t.get(0, String.class); String treeUuid = t.get(1, String.class); List<CreateTemplateFromVolumeSnapshotMsg> cmsgs = msg.getBackupStorageUuids().stream().map(bsUuid -> { CreateTemplateFromVolumeSnapshotMsg cmsg = new CreateTemplateFromVolumeSnapshotMsg(); cmsg.setSnapshotUuid(msg.getSnapshotUuid()); cmsg.setImageUuid(vo.getUuid()); cmsg.setVolumeUuid(volumeUuid); cmsg.setTreeUuid(treeUuid); cmsg.setBackupStorageUuid(bsUuid); String resourceUuid = volumeUuid != null ? volumeUuid : treeUuid; bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeSnapshotConstant.SERVICE_ID, resourceUuid); return cmsg; }).collect(Collectors.toList()); List<Failure> failures = new ArrayList<>(); AsyncLatch latch = new AsyncLatch(cmsgs.size(), new NoErrorCompletion(msg) { @Override public void done() { if (failures.size() == cmsgs.size()) { // failed on all ErrorCodeList error = errf.stringToOperationError(String.format("failed to create template from" + " the volume snapshot[uuid:%s] on backup storage[uuids:%s]", msg.getSnapshotUuid(), msg.getBackupStorageUuids()), failures.stream().map(f -> f.error).collect(Collectors.toList())); evt.setError(error); dbf.remove(vo); } else { ImageVO imvo = dbf.reload(vo); evt.setInventory(ImageInventory.valueOf(imvo)); logger.debug(String.format("successfully created image[uuid:%s, name:%s] from volume snapshot[uuid:%s]", imvo.getUuid(), imvo.getName(), msg.getSnapshotUuid())); } if (!failures.isEmpty()) { evt.setFailuresOnBackupStorage(failures); } bus.publish(evt); } }); RunOnce once = new RunOnce(); for (CreateTemplateFromVolumeSnapshotMsg cmsg : cmsgs) { bus.send(cmsg, new CloudBusCallBack(latch) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { synchronized (failures) { Failure failure = new Failure(); failure.error = reply.getError(); failure.backupStorageUuid = cmsg.getBackupStorageUuid(); failures.add(failure); } } else { CreateTemplateFromVolumeSnapshotReply cr = reply.castReply(); ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setBackupStorageUuid(cr.getBackupStorageUuid()); ref.setInstallPath(cr.getBackupStorageInstallPath()); ref.setStatus(ImageStatus.Ready); ref.setImageUuid(vo.getUuid()); dbf.persist(ref); once.run(() -> { vo.setSize(cr.getSize()); vo.setActualSize(cr.getActualSize()); vo.setStatus(ImageStatus.Ready); dbf.update(vo); }); } latch.ack(); } }); } } private void passThrough(ImageMessage msg) { ImageVO vo = dbf.findByUuid(msg.getImageUuid(), ImageVO.class); if (vo == null && allowedMessageAfterDeletion.contains(msg.getClass())) { ImageEO eo = dbf.findByUuid(msg.getImageUuid(), ImageEO.class); vo = ObjectUtils.newAndCopy(eo, ImageVO.class); } if (vo == null) { String err = String.format("Cannot find image[uuid:%s], it may have been deleted", msg.getImageUuid()); logger.warn(err); bus.replyErrorByMessageType((Message) msg, errf.instantiateErrorCode(SysErrors.RESOURCE_NOT_FOUND, err)); return; } ImageFactory factory = getImageFacotry(ImageType.valueOf(vo.getType())); Image img = factory.getImage(vo); img.handleMessage((Message) msg); } private void handle(final APICreateRootVolumeTemplateFromRootVolumeMsg msg) { FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("create-template-from-root-volume-%s", msg.getRootVolumeUuid())); chain.then(new ShareFlow() { ImageVO imageVO; VolumeInventory rootVolume; Long imageActualSize; List<BackupStorageInventory> targetBackupStorages = new ArrayList<>(); String zoneUuid; { VolumeVO rootvo = dbf.findByUuid(msg.getRootVolumeUuid(), VolumeVO.class); rootVolume = VolumeInventory.valueOf(rootvo); SimpleQuery<PrimaryStorageVO> q = dbf.createQuery(PrimaryStorageVO.class); q.select(PrimaryStorageVO_.zoneUuid); q.add(PrimaryStorageVO_.uuid, Op.EQ, rootVolume.getPrimaryStorageUuid()); zoneUuid = q.findValue(); } @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "get-volume-actual-size"; @Override public void run(final FlowTrigger trigger, Map data) { SyncVolumeSizeMsg msg = new SyncVolumeSizeMsg(); msg.setVolumeUuid(rootVolume.getUuid()); bus.makeTargetServiceIdByResourceUuid(msg, VolumeConstant.SERVICE_ID, rootVolume.getPrimaryStorageUuid()); bus.send(msg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); return; } SyncVolumeSizeReply sr = reply.castReply(); imageActualSize = sr.getActualSize(); trigger.next(); } }); } }); flow(new Flow() { String __name__ = "create-image-in-database"; public void run(FlowTrigger trigger, Map data) { SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class); q.add(VolumeVO_.uuid, Op.EQ, msg.getRootVolumeUuid()); final VolumeVO volvo = q.find(); String accountUuid = acntMgr.getOwnerAccountUuidOfResource(volvo.getUuid()); final ImageVO imvo = new ImageVO(); if (msg.getResourceUuid() != null) { imvo.setUuid(msg.getResourceUuid()); } else { imvo.setUuid(Platform.getUuid()); } imvo.setDescription(msg.getDescription()); imvo.setMediaType(ImageMediaType.RootVolumeTemplate); imvo.setState(ImageState.Enabled); imvo.setGuestOsType(msg.getGuestOsType()); imvo.setFormat(volvo.getFormat()); imvo.setName(msg.getName()); imvo.setSystem(msg.isSystem()); imvo.setPlatform(ImagePlatform.valueOf(msg.getPlatform())); imvo.setStatus(ImageStatus.Downloading); imvo.setType(ImageConstant.ZSTACK_IMAGE_TYPE); imvo.setUrl(String.format("volume://%s", msg.getRootVolumeUuid())); imvo.setSize(volvo.getSize()); imvo.setActualSize(imageActualSize); dbf.persist(imvo); acntMgr.createAccountResourceRef(accountUuid, imvo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, imvo.getUuid(), ImageVO.class.getSimpleName()); imageVO = imvo; trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { if (imageVO != null) { dbf.remove(imageVO); } trigger.rollback(); } }); flow(new Flow() { String __name__ = String.format("select-backup-storage"); @Override public void run(final FlowTrigger trigger, Map data) { if (msg.getBackupStorageUuids() == null) { AllocateBackupStorageMsg abmsg = new AllocateBackupStorageMsg(); abmsg.setRequiredZoneUuid(zoneUuid); abmsg.setSize(imageActualSize); bus.makeLocalServiceId(abmsg, BackupStorageConstant.SERVICE_ID); bus.send(abmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { targetBackupStorages.add(((AllocateBackupStorageReply) reply).getInventory()); trigger.next(); } else { trigger.fail(reply.getError()); } } }); } else { List<AllocateBackupStorageMsg> amsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<AllocateBackupStorageMsg, String>() { @Override public AllocateBackupStorageMsg call(String arg) { AllocateBackupStorageMsg abmsg = new AllocateBackupStorageMsg(); abmsg.setSize(imageActualSize); abmsg.setBackupStorageUuid(arg); bus.makeLocalServiceId(abmsg, BackupStorageConstant.SERVICE_ID); return abmsg; } }); bus.send(amsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { List<ErrorCode> errs = new ArrayList<>(); for (MessageReply r : replies) { if (r.isSuccess()) { targetBackupStorages.add(((AllocateBackupStorageReply) r).getInventory()); } else { errs.add(r.getError()); } } if (targetBackupStorages.isEmpty()) { trigger.fail(operr("unable to allocate backup storage specified by uuids%s, list errors are: %s", msg.getBackupStorageUuids(), JSONObjectUtil.toJsonString(errs))); } else { trigger.next(); } } }); } } @Override public void rollback(final FlowRollback trigger, Map data) { if (targetBackupStorages.isEmpty()) { trigger.rollback(); return; } List<ReturnBackupStorageMsg> rmsgs = CollectionUtils.transformToList(targetBackupStorages, new Function<ReturnBackupStorageMsg, BackupStorageInventory>() { @Override public ReturnBackupStorageMsg call(BackupStorageInventory arg) { ReturnBackupStorageMsg rmsg = new ReturnBackupStorageMsg(); rmsg.setBackupStorageUuid(arg.getUuid()); rmsg.setSize(imageActualSize); bus.makeLocalServiceId(rmsg, BackupStorageConstant.SERVICE_ID); return rmsg; } }); bus.send(rmsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { for (MessageReply r : replies) { if (!r.isSuccess()) { BackupStorageInventory bs = targetBackupStorages.get(replies.indexOf(r)); logger.warn(String.format("failed to return capacity[%s] to backup storage[uuid:%s], because %s", imageActualSize, bs.getUuid(), r.getError())); } } trigger.rollback(); } }); } }); flow(new NoRollbackFlow() { String __name__ = String.format("start-creating-template"); @Override public void run(final FlowTrigger trigger, Map data) { List<CreateTemplateFromVmRootVolumeMsg> cmsgs = CollectionUtils.transformToList(targetBackupStorages, new Function<CreateTemplateFromVmRootVolumeMsg, BackupStorageInventory>() { @Override public CreateTemplateFromVmRootVolumeMsg call(BackupStorageInventory arg) { CreateTemplateFromVmRootVolumeMsg cmsg = new CreateTemplateFromVmRootVolumeMsg(); cmsg.setRootVolumeInventory(rootVolume); cmsg.setBackupStorageUuid(arg.getUuid()); cmsg.setImageInventory(ImageInventory.valueOf(imageVO)); bus.makeTargetServiceIdByResourceUuid(cmsg, VmInstanceConstant.SERVICE_ID, rootVolume.getVmInstanceUuid()); return cmsg; } }); bus.send(cmsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { boolean success = false; ErrorCode err = null; for (MessageReply r : replies) { BackupStorageInventory bs = targetBackupStorages.get(replies.indexOf(r)); if (!r.isSuccess()) { logger.warn(String.format("failed to create image from root volume[uuid:%s] on backup storage[uuid:%s], because %s", msg.getRootVolumeUuid(), bs.getUuid(), r.getError())); err = r.getError(); continue; } CreateTemplateFromVmRootVolumeReply reply = (CreateTemplateFromVmRootVolumeReply) r; ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setBackupStorageUuid(bs.getUuid()); ref.setStatus(ImageStatus.Ready); ref.setImageUuid(imageVO.getUuid()); ref.setInstallPath(reply.getInstallPath()); dbf.persist(ref); imageVO.setStatus(ImageStatus.Ready); if (reply.getFormat() != null) { imageVO.setFormat(reply.getFormat()); } dbf.update(imageVO); imageVO = dbf.reload(imageVO); success = true; logger.debug(String.format("successfully created image[uuid:%s] from root volume[uuid:%s] on backup storage[uuid:%s]", imageVO.getUuid(), msg.getRootVolumeUuid(), bs.getUuid())); } if (success) { trigger.next(); } else { trigger.fail(operr("failed to create image from root volume[uuid:%s] on all backup storage, see cause for one of errors", msg.getRootVolumeUuid()).causedBy(err)); } } }); } }); flow(new Flow() { String __name__ = "copy-system-tag-to-image"; public void run(FlowTrigger trigger, Map data) { // find the rootimage and create some systemtag if it has SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class); q.add(VolumeVO_.uuid, SimpleQuery.Op.EQ, msg.getRootVolumeUuid()); q.select(VolumeVO_.vmInstanceUuid); String vmInstanceUuid = q.findValue(); if (tagMgr.hasSystemTag(vmInstanceUuid, ImageSystemTags.IMAGE_INJECT_QEMUGA.getTagFormat())) { tagMgr.createNonInherentSystemTag(imageVO.getUuid(), ImageSystemTags.IMAGE_INJECT_QEMUGA.getTagFormat(), ImageVO.class.getSimpleName()); } trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { trigger.rollback(); } }); flow(new NoRollbackFlow() { String __name__ = String.format("sync-image-size"); @Override public void run(final FlowTrigger trigger, Map data) { new While<>(targetBackupStorages).all((arg, completion) -> { SyncImageSizeMsg smsg = new SyncImageSizeMsg(); smsg.setBackupStorageUuid(arg.getUuid()); smsg.setImageUuid(imageVO.getUuid()); bus.makeTargetServiceIdByResourceUuid(smsg, ImageConstant.SERVICE_ID, imageVO.getUuid()); bus.send(smsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { completion.done(); } }); }).run(new NoErrorCompletion(trigger) { @Override public void done() { trigger.next(); } }); } }); done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { APICreateRootVolumeTemplateFromRootVolumeEvent evt = new APICreateRootVolumeTemplateFromRootVolumeEvent(msg.getId()); imageVO = dbf.reload(imageVO); ImageInventory iinv = ImageInventory.valueOf(imageVO); evt.setInventory(iinv); logger.warn(String.format("successfully create template[uuid:%s] from root volume[uuid:%s]", iinv.getUuid(), msg.getRootVolumeUuid())); bus.publish(evt); } }); error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { APICreateRootVolumeTemplateFromRootVolumeEvent evt = new APICreateRootVolumeTemplateFromRootVolumeEvent(msg.getId()); evt.setError(errCode); logger.warn(String.format("failed to create template from root volume[uuid:%s], because %s", msg.getRootVolumeUuid(), errCode)); bus.publish(evt); } }); } }).start(); } private void handle(APIGetImageMsg msg) { SearchQuery<ImageInventory> sq = new SearchQuery(ImageInventory.class); sq.addAccountAsAnd(msg); sq.add("uuid", SearchOp.AND_EQ, msg.getUuid()); List<ImageInventory> invs = sq.list(); APIGetImageReply reply = new APIGetImageReply(); if (!invs.isEmpty()) { reply.setInventory(JSONObjectUtil.toJsonString(invs.get(0))); } bus.reply(msg, reply); } private void handle(APISearchImageMsg msg) { SearchQuery<ImageInventory> sq = SearchQuery.create(msg, ImageInventory.class); sq.addAccountAsAnd(msg); String content = sq.listAsString(); APISearchImageReply reply = new APISearchImageReply(); reply.setContent(content); bus.reply(msg, reply); } private void handle(APIListImageMsg msg) { List<ImageVO> vos = dbf.listAll(ImageVO.class); List<ImageInventory> invs = ImageInventory.valueOf(vos); APIListImageReply reply = new APIListImageReply(); reply.setInventories(invs); bus.reply(msg, reply); } @Deferred private void handle(final APIAddImageMsg msg) { String imageType = msg.getType(); imageType = imageType == null ? DefaultImageFactory.type.toString() : imageType; final APIAddImageEvent evt = new APIAddImageEvent(msg.getId()); ImageVO vo = new ImageVO(); if (msg.getResourceUuid() != null) { vo.setUuid(msg.getResourceUuid()); } else { vo.setUuid(Platform.getUuid()); } if (!CoreGlobalProperty.UNIT_TEST_ON) { long imageSizeAsked = new ImageQuotaUtil().getLocalImageSizeOnBackupStorage(msg); vo.setActualSize(imageSizeAsked); } vo.setName(msg.getName()); vo.setDescription(msg.getDescription()); if (msg.getFormat().equals(ImageConstant.ISO_FORMAT_STRING)) { vo.setMediaType(ImageMediaType.ISO); } else { vo.setMediaType(ImageMediaType.valueOf(msg.getMediaType())); } vo.setType(imageType); vo.setSystem(msg.isSystem()); vo.setGuestOsType(msg.getGuestOsType()); vo.setFormat(msg.getFormat()); vo.setStatus(ImageStatus.Downloading); vo.setState(ImageState.Enabled); vo.setUrl(msg.getUrl()); vo.setDescription(msg.getDescription()); vo.setPlatform(ImagePlatform.valueOf(msg.getPlatform())); ImageFactory factory = getImageFacotry(ImageType.valueOf(imageType)); final ImageVO ivo = new SQLBatchWithReturn<ImageVO>() { @Override protected ImageVO scripts() { final ImageVO ivo = factory.createImage(vo, msg); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName()); return ivo; } }.execute(); List<ImageBackupStorageRefVO> refs = new ArrayList<>(); for (String uuid : msg.getBackupStorageUuids()) { ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setInstallPath(""); ref.setBackupStorageUuid(uuid); ref.setStatus(ImageStatus.Downloading); ref.setImageUuid(ivo.getUuid()); refs.add(ref); } dbf.updateCollection(refs); Defer.guard(() -> dbf.remove(ivo)); final ImageInventory inv = ImageInventory.valueOf(ivo); for (AddImageExtensionPoint ext : pluginRgty.getExtensionList(AddImageExtensionPoint.class)) { ext.preAddImage(inv); } final List<DownloadImageMsg> dmsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<DownloadImageMsg, String>() { @Override public DownloadImageMsg call(String arg) { DownloadImageMsg dmsg = new DownloadImageMsg(inv); dmsg.setBackupStorageUuid(arg); dmsg.setFormat(msg.getFormat()); dmsg.setSystemTags(msg.getSystemTags()); bus.makeTargetServiceIdByResourceUuid(dmsg, BackupStorageConstant.SERVICE_ID, arg); return dmsg; } }); CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), ext -> ext.beforeAddImage(inv)); new LoopAsyncBatch<DownloadImageMsg>(msg) { AtomicBoolean success = new AtomicBoolean(false); @Override protected Collection<DownloadImageMsg> collect() { return dmsgs; } @Override protected AsyncBatchRunner forEach(DownloadImageMsg dmsg) { return new AsyncBatchRunner() { @Override public void run(NoErrorCompletion completion) { ImageBackupStorageRefVO ref = Q.New(ImageBackupStorageRefVO.class) .eq(ImageBackupStorageRefVO_.imageUuid, ivo.getUuid()) .eq(ImageBackupStorageRefVO_.backupStorageUuid, dmsg.getBackupStorageUuid()) .find(); bus.send(dmsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { errors.add(reply.getError()); dbf.remove(ref); } else { DownloadImageReply re = reply.castReply(); ref.setStatus(ImageStatus.Ready); ref.setInstallPath(re.getInstallPath()); if (dbf.reload(ref) == null) { logger.debug(String.format("image[uuid: %s] has been deleted", ref.getImageUuid())); completion.done(); return; } dbf.update(ref); if (success.compareAndSet(false, true)) { // In case 'Platform' etc. is changed. ImageVO vo = dbf.reload(ivo); vo.setMd5Sum(re.getMd5sum()); vo.setSize(re.getSize()); vo.setActualSize(re.getActualSize()); vo.setStatus(ImageStatus.Ready); dbf.update(vo); } logger.debug(String.format("successfully downloaded image[uuid:%s, name:%s] to backup storage[uuid:%s]", inv.getUuid(), inv.getName(), dmsg.getBackupStorageUuid())); } completion.done(); } }); } }; } @Override protected void done() { // check if the database still has the record of the image // if there is no record, that means user delete the image during the downloading, // then we need to cleanup ImageVO vo = dbf.reload(ivo); if (vo == null) { evt.setError(operr("image [uuid:%s] has been deleted", ivo.getUuid())); SQL.New("delete from ImageBackupStorageRefVO where imageUuid = :uuid") .param("uuid", ivo.getUuid()) .execute(); bus.publish(evt); return; } if (success.get()) { final ImageInventory einv = ImageInventory.valueOf(vo); CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() { @Override public void run(AddImageExtensionPoint ext) { ext.afterAddImage(einv); } }); evt.setInventory(einv); } else { final ErrorCode err = errf.instantiateErrorCode(SysErrors.CREATE_RESOURCE_ERROR, String.format("Failed to download image[name:%s] on all backup storage%s.", inv.getName(), msg.getBackupStorageUuids()), errors); CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() { @Override public void run(AddImageExtensionPoint ext) { ext.failedToAddImage(inv, err); } }); dbf.remove(ivo); evt.setError(err); } bus.publish(evt); } }.start(); } @Override public String getId() { return bus.makeLocalServiceId(ImageConstant.SERVICE_ID); } private void populateExtensions() { for (ImageFactory f : pluginRgty.getExtensionList(ImageFactory.class)) { ImageFactory old = imageFactories.get(f.getType().toString()); if (old != null) { throw new CloudRuntimeException(String.format("duplicate ImageFactory[%s, %s] for type[%s]", f.getClass().getName(), old.getClass().getName(), f.getType())); } imageFactories.put(f.getType().toString(), f); } } @Override public boolean start() { populateExtensions(); installGlobalConfigUpdater(); return true; } private void installGlobalConfigUpdater() { ImageGlobalConfig.DELETION_POLICY.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startExpungeTask(); } }); ImageGlobalConfig.EXPUNGE_INTERVAL.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startExpungeTask(); } }); ImageGlobalConfig.EXPUNGE_PERIOD.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startExpungeTask(); } }); } private void startExpungeTask() { if (expungeTask != null) { expungeTask.cancel(true); } expungeTask = thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask() { private List<Tuple> getDeletedImageManagedByUs() { int qun = 1000; SimpleQuery q = dbf.createQuery(ImageBackupStorageRefVO.class); q.add(ImageBackupStorageRefVO_.status, Op.EQ, ImageStatus.Deleted); long amount = q.count(); int times = (int) (amount / qun) + (amount % qun != 0 ? 1 : 0); int start = 0; List<Tuple> ret = new ArrayList<Tuple>(); for (int i = 0; i < times; i++) { q = dbf.createQuery(ImageBackupStorageRefVO.class); q.select(ImageBackupStorageRefVO_.imageUuid, ImageBackupStorageRefVO_.lastOpDate, ImageBackupStorageRefVO_.backupStorageUuid); q.add(ImageBackupStorageRefVO_.status, Op.EQ, ImageStatus.Deleted); q.setLimit(qun); q.setStart(start); List<Tuple> ts = q.listTuple(); start += qun; for (Tuple t : ts) { String imageUuid = t.get(0, String.class); if (!destMaker.isManagedByUs(imageUuid)) { continue; } ret.add(t); } } return ret; } @Override public boolean run() { final List<Tuple> images = getDeletedImageManagedByUs(); if (images.isEmpty()) { logger.debug("[Image Expunge Task]: no images to expunge"); return false; } for (Tuple t : images) { String imageUuid = t.get(0, String.class); Timestamp date = t.get(1, Timestamp.class); String bsUuid = t.get(2, String.class); final Timestamp current = dbf.getCurrentSqlTime(); if (current.getTime() >= date.getTime() + TimeUnit.SECONDS.toMillis(ImageGlobalConfig.EXPUNGE_PERIOD.value(Long.class))) { ImageDeletionPolicy deletionPolicy = deletionPolicyMgr.getDeletionPolicy(imageUuid); if (ImageDeletionPolicy.Never == deletionPolicy) { logger.debug(String.format("the deletion policy[Never] is set for the image[uuid:%s] on the backup storage[uuid:%s]," + "don't expunge it", images, bsUuid)); continue; } ExpungeImageMsg msg = new ExpungeImageMsg(); msg.setImageUuid(imageUuid); msg.setBackupStorageUuid(bsUuid); bus.makeTargetServiceIdByResourceUuid(msg, ImageConstant.SERVICE_ID, imageUuid); bus.send(msg, new CloudBusCallBack(null) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { N.New(ImageVO.class, imageUuid).warn_("failed to expunge the image[uuid:%s] on the backup storage[uuid:%s], will try it later. %s", imageUuid, bsUuid, reply.getError()); } } }); } } return false; } @Override public TimeUnit getTimeUnit() { return TimeUnit.SECONDS; } @Override public long getInterval() { return ImageGlobalConfig.EXPUNGE_INTERVAL.value(Long.class); } @Override public String getName() { return "expunge-image"; } }); } @Override public boolean stop() { return true; } private ImageFactory getImageFacotry(ImageType type) { ImageFactory factory = imageFactories.get(type.toString()); if (factory == null) { throw new CloudRuntimeException(String.format("Unable to find ImageFactory with type[%s]", type)); } return factory; } @Override public void managementNodeReady() { startExpungeTask(); } @Override public List<Quota> reportQuota() { Quota.QuotaOperator checker = new Quota.QuotaOperator() { @Override public void checkQuota(APIMessage msg, Map<String, Quota.QuotaPair> pairs) { if (!new QuotaUtil().isAdminAccount(msg.getSession().getAccountUuid())) { if (msg instanceof APIAddImageMsg) { check((APIAddImageMsg) msg, pairs); } else if (msg instanceof APIRecoverImageMsg) { check((APIRecoverImageMsg) msg, pairs); } else if (msg instanceof APIChangeResourceOwnerMsg) { check((APIChangeResourceOwnerMsg) msg, pairs); } } else { if (msg instanceof APIChangeResourceOwnerMsg) { check((APIChangeResourceOwnerMsg) msg, pairs); } } } @Override public void checkQuota(NeedQuotaCheckMessage msg, Map<String, Quota.QuotaPair> pairs) { } @Override public List<Quota.QuotaUsage> getQuotaUsageByAccount(String accountUuid) { List<Quota.QuotaUsage> usages = new ArrayList<>(); ImageQuotaUtil.ImageQuota imageQuota = new ImageQuotaUtil().getUsed(accountUuid); Quota.QuotaUsage usage = new Quota.QuotaUsage(); usage.setName(ImageConstant.QUOTA_IMAGE_NUM); usage.setUsed(imageQuota.imageNum); usages.add(usage); usage = new Quota.QuotaUsage(); usage.setName(ImageConstant.QUOTA_IMAGE_SIZE); usage.setUsed(imageQuota.imageSize); usages.add(usage); return usages; } @Transactional(readOnly = true) private void check(APIChangeResourceOwnerMsg msg, Map<String, Quota.QuotaPair> pairs) { String currentAccountUuid = msg.getSession().getAccountUuid(); String resourceTargetOwnerAccountUuid = msg.getAccountUuid(); if (new QuotaUtil().isAdminAccount(resourceTargetOwnerAccountUuid)) { return; } SimpleQuery<AccountResourceRefVO> q = dbf.createQuery(AccountResourceRefVO.class); q.add(AccountResourceRefVO_.resourceUuid, Op.EQ, msg.getResourceUuid()); AccountResourceRefVO accResRefVO = q.find(); if (accResRefVO.getResourceType().equals(ImageVO.class.getSimpleName())) { long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue(); long imageSizeQuota = pairs.get(ImageConstant.QUOTA_IMAGE_SIZE).getValue(); long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid); long imageSizeUsed = new ImageQuotaUtil().getUsedImageSize(resourceTargetOwnerAccountUuid); ImageVO image = dbf.getEntityManager().find(ImageVO.class, msg.getResourceUuid()); long imageNumAsked = 1; long imageSizeAsked = image.getSize(); QuotaUtil.QuotaCompareInfo quotaCompareInfo; { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM; quotaCompareInfo.quotaValue = imageNumQuota; quotaCompareInfo.currentUsed = imageNumUsed; quotaCompareInfo.request = imageNumAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_SIZE; quotaCompareInfo.quotaValue = imageSizeQuota; quotaCompareInfo.currentUsed = imageSizeUsed; quotaCompareInfo.request = imageSizeAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } } } @Transactional(readOnly = true) private void check(APIRecoverImageMsg msg, Map<String, Quota.QuotaPair> pairs) { String currentAccountUuid = msg.getSession().getAccountUuid(); String resourceTargetOwnerAccountUuid = new QuotaUtil().getResourceOwnerAccountUuid(msg.getImageUuid()); long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue(); long imageSizeQuota = pairs.get(ImageConstant.QUOTA_IMAGE_SIZE).getValue(); long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid); long imageSizeUsed = new ImageQuotaUtil().getUsedImageSize(resourceTargetOwnerAccountUuid); ImageVO image = dbf.getEntityManager().find(ImageVO.class, msg.getImageUuid()); long imageNumAsked = 1; long imageSizeAsked = image.getSize(); QuotaUtil.QuotaCompareInfo quotaCompareInfo; { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM; quotaCompareInfo.quotaValue = imageNumQuota; quotaCompareInfo.currentUsed = imageNumUsed; quotaCompareInfo.request = imageNumAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_SIZE; quotaCompareInfo.quotaValue = imageSizeQuota; quotaCompareInfo.currentUsed = imageSizeUsed; quotaCompareInfo.request = imageSizeAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } } @Transactional(readOnly = true) private void check(APIAddImageMsg msg, Map<String, Quota.QuotaPair> pairs) { String currentAccountUuid = msg.getSession().getAccountUuid(); String resourceTargetOwnerAccountUuid = msg.getSession().getAccountUuid(); long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue(); long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid); long imageNumAsked = 1; QuotaUtil.QuotaCompareInfo quotaCompareInfo; { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM; quotaCompareInfo.quotaValue = imageNumQuota; quotaCompareInfo.currentUsed = imageNumUsed; quotaCompareInfo.request = imageNumAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } new ImageQuotaUtil().checkImageSizeQuotaUseHttpHead(msg, pairs); } }; Quota quota = new Quota(); quota.setOperator(checker); quota.addMessageNeedValidation(APIAddImageMsg.class); quota.addMessageNeedValidation(APIRecoverImageMsg.class); quota.addMessageNeedValidation(APIChangeResourceOwnerMsg.class); Quota.QuotaPair p = new Quota.QuotaPair(); p.setName(ImageConstant.QUOTA_IMAGE_NUM); p.setValue(QuotaConstant.QUOTA_IMAGE_NUM); quota.addPair(p); p = new Quota.QuotaPair(); p.setName(ImageConstant.QUOTA_IMAGE_SIZE); p.setValue(QuotaConstant.QUOTA_IMAGE_SIZE); quota.addPair(p); return list(quota); } @Override @Transactional(readOnly = true) public void resourceOwnerPreChange(AccountResourceRefInventory ref, String newOwnerUuid) { } }
package ru.ifmo.nds.jfb; import java.util.Arrays; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveAction; import java.util.concurrent.RecursiveTask; import ru.ifmo.nds.NonDominatedSorting; import ru.ifmo.nds.util.*; public abstract class JFBBase extends NonDominatedSorting { private static final int FORK_JOIN_THRESHOLD = 400; // Shared resources (int[] indices from super also belongs here) int[] ranks; // Data which is immutable throughout the actual sorting. private double[][] points; double[][] transposedPoints; int maximalMeaningfulRank; // Data which is interval-shared between threads. private double[] temporary; // also used in 2D-only sweep private SplitMergeHelper splitMerge; private HybridAlgorithmWrapper.Instance hybrid; private ForkJoinPool pool; private final int allowedThreads; private final String nameAddend; JFBBase(int maximumPoints, int maximumDimension, int allowedThreads, HybridAlgorithmWrapper hybridWrapper, String nameAddend) { super(maximumPoints, maximumDimension); if (!hybridWrapper.supportsMultipleThreads()) { allowedThreads = 1; } this.nameAddend = nameAddend + ", hybrid: " + hybridWrapper.getName(); if (allowedThreads != 1 && makesSenseRunInParallel(maximumPoints, maximumDimension)) { pool = allowedThreads > 1 ? new ForkJoinPool(allowedThreads) : new ForkJoinPool(); } else { pool = null; // current thread only execution } this.allowedThreads = allowedThreads > 0 ? allowedThreads : -1; temporary = new double[maximumPoints]; ranks = new int[maximumPoints]; if (maximumDimension > 2) { points = new double[maximumPoints][]; transposedPoints = new double[maximumDimension][maximumPoints]; splitMerge = new SplitMergeHelper(maximumPoints); hybrid = hybridWrapper.create(ranks, indices, points, transposedPoints); } } @Override protected void closeImpl() { temporary = null; ranks = null; points = null; transposedPoints = null; splitMerge = null; if (pool != null) { pool.shutdown(); pool = null; } hybrid = null; } @Override public String getName() { return "Jensen-Fortin-Buzdalov, " + getThreadDescription() + ", " + nameAddend; } @Override protected final void sortChecked(double[][] points, int[] ranks, int maximalMeaningfulRank) { final int n = points.length; final int dim = points[0].length; Arrays.fill(ranks, 0); ArrayHelper.fillIdentity(indices, n); sorter.lexicographicalSort(points, indices, 0, n, dim); this.maximalMeaningfulRank = maximalMeaningfulRank; if (dim == 2) { // 2: Special case: binary search. twoDimensionalCase(points, ranks); } else { // 3: General case. // 3.1: Moving points in a sorted order to internal structures final int newN = ArraySorter.retainUniquePoints(points, indices, this.points, ranks); Arrays.fill(this.ranks, 0, newN, 0); // 3.2: Transposing points. This should fit in cache for reasonable dimensions. for (int i = 0; i < newN; ++i) { for (int j = 0; j < dim; ++j) { transposedPoints[j][i] = this.points[i][j]; } } postTransposePointHook(newN); ArrayHelper.fillIdentity(indices, newN); // 3.3: Calling the actual sorting if (pool != null && makesSenseRunInParallel(n, dim)) { RecursiveAction action = new RecursiveAction() { @Override protected void compute() { helperA(0, newN, dim - 1); } }; pool.invoke(action); } else { helperA(0, newN, dim - 1); } // 3.4: Applying the results back. After that, the argument "ranks" array stops being abused. for (int i = 0; i < n; ++i) { ranks[i] = this.ranks[ranks[i]]; this.points[i] = null; } } } public static int kickOutOverflowedRanks(int[] indices, int[] ranks, int maximalMeaningfulRank, int from, int until) { int newUntil = from; for (int i = from; i < until; ++i) { int ii = indices[i]; if (ranks[ii] <= maximalMeaningfulRank) { indices[newUntil] = ii; ++newUntil; } } return newUntil; } protected void postTransposePointHook(int newN) {} protected abstract int sweepA(int from, int until); protected abstract int sweepB(int goodFrom, int goodUntil, int weakFrom, int weakUntil, int tempFrom); private int helperA(int from, int until, int obj) { int n = until - from; if (n <= 2) { if (n == 2) { int goodIndex = indices[from]; int weakIndex = indices[from + 1]; int goodRank = ranks[goodIndex]; if (ranks[weakIndex] <= goodRank && DominanceHelper.strictlyDominatesAssumingLexicographicallySmaller(points[goodIndex], points[weakIndex], obj)) { ranks[weakIndex] = 1 + goodRank; if (goodRank >= maximalMeaningfulRank) { return from + 1; } } } return until; } else { while (obj > 1) { int hookResponse = hybrid.helperAHook(from, until, obj, maximalMeaningfulRank); if (hookResponse >= 0) { return hookResponse; } if (ArrayHelper.transplantAndCheckIfSame(transposedPoints[obj], indices, from, until, temporary, from)) { --obj; } else { double median = ArrayHelper.destructiveMedian(temporary, from, until); long split = splitMerge.splitInThree(transposedPoints[obj], indices, from, from, until, median); int startMid = SplitMergeHelper.extractMid(split); int startRight = SplitMergeHelper.extractRight(split); int newStartMid = helperA(from, startMid, obj); --obj; int newStartRight = helperB(from, newStartMid, startMid, startRight, obj, from); newStartRight = helperA(startMid, newStartRight, obj); int newUntil = helperB(from, newStartMid, startRight, until, obj, from); newUntil = helperB(startMid, newStartRight, startRight, newUntil, obj, from); ++obj; newUntil = helperA(startRight, newUntil, obj); return splitMerge.mergeThree(indices, from, from, newStartMid, startMid, newStartRight, startRight, newUntil); } } return sweepA(from, until); } } public static int updateByPoint(int[] ranks, int[] indices, double[][] points, int maximalMeaningfulRank, int pointIndex, int from, int until, int obj) { int ri = ranks[pointIndex]; if (ri == maximalMeaningfulRank) { return updateByPointCritical(ranks, indices, points, maximalMeaningfulRank, pointIndex, from, until, obj); } else { updateByPointNormal(ranks, indices, points, pointIndex, ri, from, until, obj); return until; } } private static void updateByPointNormal(int[] ranks, int[] indices, double[][] points, int pointIndex, int pointRank, int from, int until, int obj) { double[] pt = points[pointIndex]; for (int i = from; i < until; ++i) { int ii = indices[i]; if (ranks[ii] <= pointRank && DominanceHelper.strictlyDominatesAssumingLexicographicallySmaller(pt, points[ii], obj)) { ranks[ii] = pointRank + 1; } } } private static int updateByPointCritical(int[] ranks, int[] indices, double[][] points, int maximalMeaningfulRank, int pointIndex, int from, int until, int obj) { int minOverflow = until; double[] pt = points[pointIndex]; for (int i = from; i < until; ++i) { int ii = indices[i]; if (DominanceHelper.strictlyDominatesAssumingLexicographicallySmaller(pt, points[ii], obj)) { ranks[ii] = maximalMeaningfulRank + 1; if (minOverflow > i) { minOverflow = i; } } } return kickOutOverflowedRanks(indices, ranks, maximalMeaningfulRank, minOverflow, until); } private int helperBWeak1Generic(int weak, int wi, int obj, int rw, int rw0, double[] wp, int goodMin, int goodMax) { for (int i = goodMax; i >= goodMin; --i) { int gi = indices[i]; int gr = ranks[gi]; if (rw <= gr && DominanceHelper.strictlyDominatesAssumingLexicographicallySmaller(points[gi], wp, obj)) { rw = gr + 1; if (rw > maximalMeaningfulRank) { ranks[wi] = rw; return weak; } } } if (rw != rw0) { ranks[wi] = rw; } return weak + 1; } private int helperBWeak1Rank0(int weak, int wi, int obj, double[] wp, int goodMin, int goodMax) { for (int i = goodMax; i >= goodMin; --i) { int gi = indices[i]; if (DominanceHelper.strictlyDominatesAssumingLexicographicallySmaller(points[gi], wp, obj)) { int newRank = ranks[gi] + 1; if (newRank > maximalMeaningfulRank) { ranks[wi] = newRank; return weak; } return helperBWeak1Generic(weak, wi, obj, newRank, 0, wp, goodMin, i - 1); } } return weak + 1; } private int helperBWeak1(int goodFrom, int goodUntil, int weak, int obj) { int wi = indices[weak]; int rw = ranks[wi]; double[] wp = points[wi]; if (rw == 0) { return helperBWeak1Rank0(weak, wi, obj, wp, goodFrom, goodUntil - 1); } else { return helperBWeak1Generic(weak, wi, obj, rw, rw, wp, goodFrom, goodUntil - 1); } } private RecursiveTask<Integer> helperBAsync(final int goodFrom, final int goodUntil, final int weakFrom, final int weakUntil, final int obj, final int tempFrom) { return new RecursiveTask<Integer>() { @Override protected Integer compute() { return helperB(goodFrom, goodUntil, weakFrom, weakUntil, obj, tempFrom); } }; } private int helperB(int goodFrom, int goodUntil, int weakFrom, int weakUntil, int obj, int tempFrom) { if (goodUntil - goodFrom > 0 && weakUntil - weakFrom > 0) { goodUntil = ArrayHelper.findLastWhereNotGreater(indices, goodFrom, goodUntil, indices[weakUntil - 1]); weakFrom = ArrayHelper.findWhereNotSmaller(indices, weakFrom, weakUntil, indices[goodFrom]); } int goodN = goodUntil - goodFrom; int weakN = weakUntil - weakFrom; if (goodN > 0 && weakN > 0) { if (goodN == 1) { return updateByPoint(ranks, indices, points, maximalMeaningfulRank, indices[goodFrom], weakFrom, weakUntil, obj); } else if (weakN == 1) { return helperBWeak1(goodFrom, goodUntil, weakFrom, obj); } else { while (obj > 1) { int hookResponse = hybrid.helperBHook(goodFrom, goodUntil, weakFrom, weakUntil, obj, tempFrom, maximalMeaningfulRank); if (hookResponse >= 0) { return hookResponse; } double[] currentPoints = transposedPoints[obj]; switch (ArrayHelper.transplantAndDecide(currentPoints, indices, goodFrom, goodUntil, weakFrom, weakUntil, temporary, tempFrom)) { case ArrayHelper.TRANSPLANT_LEFT_NOT_GREATER: --obj; break; case ArrayHelper.TRANSPLANT_RIGHT_SMALLER: return weakUntil; case ArrayHelper.TRANSPLANT_GENERAL_CASE: double median = ArrayHelper.destructiveMedian(temporary, tempFrom, tempFrom + goodUntil - goodFrom + weakUntil - weakFrom); long goodSplit = splitMerge.splitInThree(currentPoints, indices, tempFrom, goodFrom, goodUntil, median); int goodMidL = SplitMergeHelper.extractMid(goodSplit); int goodMidR = SplitMergeHelper.extractRight(goodSplit); long weakSplit = splitMerge.splitInThree(currentPoints, indices, tempFrom, weakFrom, weakUntil, median); int weakMidL = SplitMergeHelper.extractMid(weakSplit); int weakMidR = SplitMergeHelper.extractRight(weakSplit); int tempMid = tempFrom + goodMidL - goodFrom + weakMidL - weakFrom; --obj; int newWeakUntil = helperB(goodFrom, goodMidL, weakMidR, weakUntil, obj, tempFrom); newWeakUntil = helperB(goodMidL, goodMidR, weakMidR, newWeakUntil, obj, tempFrom); int newWeakMidR = helperB(goodFrom, goodMidL, weakMidL, weakMidR, obj, tempFrom); newWeakMidR = helperB(goodMidL, goodMidR, weakMidL, newWeakMidR, obj, tempFrom); ++obj; ForkJoinTask<Integer> newWeakMidLTask = null; if (pool != null && goodMidL - goodFrom + weakMidL - weakFrom > FORK_JOIN_THRESHOLD) { newWeakMidLTask = helperBAsync(goodFrom, goodMidL, weakFrom, weakMidL, obj, tempFrom).fork(); } newWeakUntil = helperB(goodMidR, goodUntil, weakMidR, newWeakUntil, obj, tempMid); int newWeakMidL = newWeakMidLTask != null ? newWeakMidLTask.join() : helperB(goodFrom, goodMidL, weakFrom, weakMidL, obj, tempFrom); splitMerge.mergeThree(indices, tempFrom, goodFrom, goodMidL, goodMidL, goodMidR, goodMidR, goodUntil); return splitMerge.mergeThree(indices, tempFrom, weakFrom, newWeakMidL, weakMidL, newWeakMidR, weakMidR, newWeakUntil); } } return sweepB(goodFrom, goodUntil, weakFrom, weakUntil, tempFrom); } } return weakUntil; } private void twoDimensionalCase(double[][] points, int[] ranks) { int maxRank = 1; int n = ranks.length; double[] firstPoint = points[indices[0]]; double lastX = firstPoint[0]; double lastY = firstPoint[1]; int lastRank = 0; // This is used here instead of temporary[0] to make it slightly faster. double minY = lastY; for (int i = 1; i < n; ++i) { int ii = indices[i]; double[] pp = points[ii]; double currX = pp[0]; double currY = pp[1]; if (currX == lastX && currY == lastY) { // Same point as the previous one. // The rank is the same as well. ranks[ii] = lastRank; } else if (currY < minY) { // Y smaller than the smallest Y previously seen. // The rank is thus zero. // ranks[ii] is already 0. minY = currY; lastRank = 0; } else { // At least the Y-smallest point dominates our point. int left, right; if (currY < lastY) { // We are better than the previous point in Y. // This means that we are at least that good. left = 0; right = lastRank; } else { // We are worse (or equal) than the previous point in Y. // This means that we are worse than this point. left = lastRank; right = maxRank; } // Running the binary search. while (right - left > 1) { int mid = (left + right) >>> 1; double midY = temporary[mid]; if (currY < midY) { right = mid; } else { left = mid; } } // "right" is now our rank. ranks[ii] = lastRank = right; temporary[right] = currY; if (right == maxRank && maxRank <= maximalMeaningfulRank) { ++maxRank; } } lastX = currX; lastY = currY; } } private boolean makesSenseRunInParallel(int nPoints, int dimension) { return nPoints > FORK_JOIN_THRESHOLD && dimension > 3; } private String getThreadDescription() { return allowedThreads == -1 ? "unlimited threads" : allowedThreads + " thread(s)"; } }
package dk.aau.rejsekortmobile; import org.androidannotations.annotations.Click; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.ViewById; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.widget.Button; @EActivity(R.layout.activity_main) public class MainActivity extends Activity { @ViewById Button checkInButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Click void checkInButtonClicked() { //Send check in message to Rejsekort server boolean checkIn = checkInUser(); if (checkIn){ checkInButton.setText("Checked in"); } } private static boolean checkInUser() { // TODO Send check in message to Rejsekort server return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
package com.battlelancer.seriesguide.util; import com.battlelancer.seriesguide.Constants; import com.battlelancer.seriesguide.R; import com.battlelancer.seriesguide.provider.SeriesContract.Shows; import com.battlelancer.seriesguide.service.NotificationService; import com.battlelancer.seriesguide.ui.SeriesGuidePreferences; import com.battlelancer.thetvdbapi.ImageCache; import com.jakewharton.trakt.ServiceManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.Cursor; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Environment; import android.preference.PreferenceManager; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DateFormatSymbols; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class Utils { private static final String TIMEZONE_ALWAYS_PST = "GMT-08:00"; private static final String TIMEZONE_US_ARIZONA = "America/Phoenix"; private static final String TIMEZONE_US_EASTERN = "America/New_York"; private static final String TIMEZONE_US_CENTRAL = "America/Chicago"; private static final String TIMEZONE_US_PACIFIC = "America/Los_Angeles"; private static final String TIMEZONE_US_MOUNTAIN = "America/Denver"; private static final int DEFAULT_BUFFER_SIZE = 8192; private static ServiceManager sServiceManagerWithAuthInstance; private static ServiceManager sServiceManagerInstance; public static final SimpleDateFormat thetvdbTimeFormatAMPM = new SimpleDateFormat("h:mm aa", Locale.US); public static final SimpleDateFormat thetvdbTimeFormatAMPMalt = new SimpleDateFormat("h:mmaa", Locale.US); public static final SimpleDateFormat thetvdbTimeFormatAMPMshort = new SimpleDateFormat("h aa", Locale.US); public static final SimpleDateFormat thetvdbTimeFormatNormal = new SimpleDateFormat("H:mm", Locale.US); /** * Parse a shows TVDb air time value to a ms value in Pacific Standard Time * (always without daylight saving). * * @param tvdbTimeString * @return */ public static long parseTimeToMilliseconds(String tvdbTimeString) { Date time = null; Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(TIMEZONE_ALWAYS_PST)); // try parsing with three different formats, most of the time the first // should match if (tvdbTimeString.length() != 0) { try { time = thetvdbTimeFormatAMPM.parse(tvdbTimeString); } catch (ParseException e) { try { time = thetvdbTimeFormatAMPMalt.parse(tvdbTimeString); } catch (ParseException e1) { try { time = thetvdbTimeFormatAMPMshort.parse(tvdbTimeString); } catch (ParseException e2) { try { time = thetvdbTimeFormatNormal.parse(tvdbTimeString); } catch (ParseException e3) { // string may be wrongly formatted time = null; } } } } } if (time != null) { Calendar timeCal = Calendar.getInstance(); timeCal.setTime(time); cal.set(Calendar.HOUR_OF_DAY, timeCal.get(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, timeCal.get(Calendar.MINUTE)); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTimeInMillis(); } else { return -1; } } /** * Parse a shows airtime ms value to an actual time. If given a TVDb day * string the day will get determined, too, all respecting user settings * like time zone and time offset. * * @param milliseconds * @param dayofweek * @param context * @return */ public static String[] parseMillisecondsToTime(long milliseconds, String dayofweek, Context context) { // return empty strings if time is missing if (context == null || milliseconds == -1) { return new String[] { "", "" }; } // set calendar time and day on always PST calendar // this is a workaround so we can convert the air day to a another time // zone without actually having a date final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(TIMEZONE_ALWAYS_PST)); final int year = cal.get(Calendar.YEAR); final int month = cal.get(Calendar.MONTH); final int day = cal.get(Calendar.DAY_OF_MONTH); cal.setTimeInMillis(milliseconds); // set the date back to today cal.set(year, month, day); // determine the shows common air day (Mo through Sun or daily) int dayIndex = -1; if (dayofweek != null) { dayIndex = getDayOfWeek(dayofweek); if (dayIndex > 0) { int today = cal.get(Calendar.DAY_OF_WEEK); // make sure we always assume a day which is today or later if (dayIndex - today < 0) { // we have a day before today cal.add(Calendar.DAY_OF_WEEK, (7 - today) + dayIndex); } else { // we have today or in the future cal.set(Calendar.DAY_OF_WEEK, dayIndex); } } } // convert time to local, including the day final Calendar localCal = Calendar.getInstance(); localCal.setTimeInMillis(cal.getTimeInMillis()); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); setOffsets(prefs, localCal, milliseconds); // create time string final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(context); final SimpleDateFormat dayFormat = new SimpleDateFormat("E"); final Date date = localCal.getTime(); timeFormat.setTimeZone(TimeZone.getDefault()); dayFormat.setTimeZone(TimeZone.getDefault()); String daystring = ""; if (dayIndex == 0) { daystring = context.getString(R.string.daily); } else if (dayIndex != -1) { daystring = dayFormat.format(date); } return new String[] { timeFormat.format(date), daystring }; } /** * Returns the Calendar constant (e.g. <code>Calendar.SUNDAY</code>) for a * given TVDb airday string (Monday through Sunday and Daily). If no match * is found -1 will be returned. * * @param TVDb day string * @return */ private static int getDayOfWeek(String day) { // catch Daily if (day.equalsIgnoreCase("Daily")) { return 0; } // catch Monday through Sunday DateFormatSymbols dfs = new DateFormatSymbols(Locale.US); String[] weekdays = dfs.getWeekdays(); for (int i = 1; i < weekdays.length; i++) { if (day.equalsIgnoreCase(weekdays[i])) { return i; } } // no match return -1; } /** * Return an array with absolute time [0], day [1] and relative time [2] of * the given millisecond time. Respects user offsets and 'Use my time zone' * setting. * * @param airtime * @param context * @return */ public static String[] formatToTimeAndDay(long airtime, Context context) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Calendar cal = getAirtimeCalendar(airtime, prefs); final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(context); final SimpleDateFormat dayFormat = new SimpleDateFormat("E"); Date airDate = cal.getTime(); String day = dayFormat.format(airDate); String absoluteTime = timeFormat.format(airDate); String relativeTime = DateUtils .getRelativeTimeSpanString(cal.getTimeInMillis(), System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL).toString(); return new String[] { absoluteTime, day, relativeTime }; } /** * Return date string of the given time, prefixed with the actual day of the * week (e.g. 'Mon, ') or 'today, ' if applicable. * * @param airtime * @param context * @return */ public static String formatToDate(long airtime, Context context) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Calendar cal = getAirtimeCalendar(airtime, prefs); TimeZone localTimeZone = cal.getTimeZone(); Date date = cal.getTime(); String timezone = localTimeZone.getDisplayName(localTimeZone.inDaylightTime(date), TimeZone.SHORT); String dateString = DateFormat.getDateFormat(context).format(date) + " " + timezone; // add today prefix if applicable if (DateUtils.isToday(cal.getTimeInMillis())) { dateString = context.getString(R.string.today) + ", " + dateString; } else { final SimpleDateFormat dayFormat = new SimpleDateFormat("E"); dateString = dayFormat.format(date) + ", " + dateString; } return dateString; } /** * Create a calendar set to the given airtime, time is adjusted according to * 'Use my time zone', 'Time Offset' settings and user time zone. * * @param airtime * @param prefs * @return */ public static Calendar getAirtimeCalendar(long airtime, final SharedPreferences prefs) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(airtime); setOffsets(prefs, cal, airtime); return cal; } /** * Add user set manual offset and auto-offset for US time zones. * * @param prefs * @param cal */ private static void setOffsets(SharedPreferences prefs, Calendar cal, long airtime) { boolean pacificInDaylight = TimeZone.getTimeZone(TIMEZONE_US_PACIFIC).inDaylightTime( new Date(airtime)); // get user-set hour offset int offset = Integer.valueOf(prefs.getString(SeriesGuidePreferences.KEY_OFFSET, "0")); TimeZone userTimeZone = TimeZone.getDefault(); if (userTimeZone.getID().equals(TIMEZONE_US_MOUNTAIN)) { offset -= 1; } else if (userTimeZone.getID().equals(TIMEZONE_US_CENTRAL)) { // for US Central subtract one hour more // shows always air an hour earlier offset -= 3; } else if (userTimeZone.getID().equals(TIMEZONE_US_EASTERN)) { offset -= 3; } else if (userTimeZone.getID().equals(TIMEZONE_US_ARIZONA)) { // Arizona has no daylight saving, correct for that // airtime might not be correct, yet, but the best we can do for now if (!pacificInDaylight) { offset -= 1; } } // we store all time values in GMT+08:00 (always Pacific Standard Time) // correct that if Pacific is in daylight savings if (pacificInDaylight) { offset -= 1; } if (offset != 0) { cal.add(Calendar.HOUR_OF_DAY, offset); } } /** * To correctly display and calculate upcoming episodes we need to modify * the current time to be later/earlier. Also respecting user-set offsets. * * @param prefs * @return */ public static long getFakeCurrentTime(SharedPreferences prefs) { return convertToFakeTime(System.currentTimeMillis(), prefs, true); } /** * Modify a time to be earlier/later respecting user-set offsets and * automatic offsets based on time zone. * * @param prefs * @param isCurrentTime * @return */ public static long convertToFakeTime(long time, SharedPreferences prefs, boolean isCurrentTime) { boolean pacificInDaylight = TimeZone.getTimeZone(TIMEZONE_US_PACIFIC).inDaylightTime( new Date(time)); int offset = Integer.valueOf(prefs.getString(SeriesGuidePreferences.KEY_OFFSET, "0")); TimeZone userTimeZone = TimeZone.getDefault(); if (userTimeZone.getID().equals(TIMEZONE_US_MOUNTAIN)) { // Mountain Time offset -= 1; } else if (userTimeZone.getID().equals(TIMEZONE_US_CENTRAL)) { // for US Central subtract one hour more // shows always air an hour earlier offset -= 3; } else if (userTimeZone.getID().equals(TIMEZONE_US_EASTERN)) { // Eastern Time offset -= 3; } else if (userTimeZone.getID().equals(TIMEZONE_US_ARIZONA)) { // Arizona has no daylight saving, correct for that if (!pacificInDaylight) { offset -= 1; } } if (pacificInDaylight) { offset -= 1; } if (offset != 0) { if (isCurrentTime) { // invert offset if we modify the current time time -= (offset * DateUtils.HOUR_IN_MILLIS); } else { // add offset if we modify an episodes air time time += (offset * DateUtils.HOUR_IN_MILLIS); } } return time; } public static long buildEpisodeAirtime(String tvdbDateString, long airtime) { TimeZone pacific = TimeZone.getTimeZone(TIMEZONE_ALWAYS_PST); SimpleDateFormat tvdbDateFormat = Constants.theTVDBDateFormat; tvdbDateFormat.setTimeZone(pacific); try { Date day = tvdbDateFormat.parse(tvdbDateString); Calendar dayCal = Calendar.getInstance(pacific); dayCal.setTime(day); // set an airtime if we have one (may not be the case for ended // shows) if (airtime != -1) { Calendar timeCal = Calendar.getInstance(pacific); timeCal.setTimeInMillis(airtime); dayCal.set(Calendar.HOUR_OF_DAY, timeCal.get(Calendar.HOUR_OF_DAY)); dayCal.set(Calendar.MINUTE, timeCal.get(Calendar.MINUTE)); dayCal.set(Calendar.SECOND, 0); dayCal.set(Calendar.MILLISECOND, 0); } long episodeAirtime = dayCal.getTimeInMillis(); return episodeAirtime; } catch (ParseException e) { // we just return -1 then return -1; } } /** * Returns a string in format "1x01 title" or "S1E01 title" dependent on a * user preference. */ public static String getNextEpisodeString(SharedPreferences prefs, String season, String episode, String title) { season = getEpisodeNumber(prefs, season, episode); season += " " + title; return season; } /** * Returns the episode number formatted according to the users preference * (e.g. '1x01', 'S01E01', ...). */ public static String getEpisodeNumber(SharedPreferences prefs, String season, String episode) { String format = prefs.getString(SeriesGuidePreferences.KEY_NUMBERFORMAT, SeriesGuidePreferences.NUMBERFORMAT_DEFAULT); if (format.equals(SeriesGuidePreferences.NUMBERFORMAT_DEFAULT)) { // 1x01 format season += "x"; } else { // S01E01 format // make season number always two chars long if (season.length() == 1) { season = "0" + season; } if (format.equals(SeriesGuidePreferences.NUMBERFORMAT_ENGLISHLOWER)) season = "s" + season + "e"; else season = "S" + season + "E"; } // make episode number always two chars long if (episode.length() == 1) { season += "0"; } season += episode; return season; } /** * Splits the string and reassembles it, separating the items with commas. * The given object is returned with the new string. * * @param tvdbstring * @return */ public static String splitAndKitTVDBStrings(String tvdbstring) { String[] splitted = tvdbstring.split("\\|"); tvdbstring = ""; for (String item : splitted) { if (tvdbstring.length() != 0) { tvdbstring += ", "; } tvdbstring += item; } return tvdbstring; } /** * Get the currently set episode sorting from settings. * * @param context * @return a EpisodeSorting enum set to the current sorting */ public static Constants.EpisodeSorting getEpisodeSorting(Context context) { String[] epsortingData = context.getResources().getStringArray(R.array.epsortingData); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context .getApplicationContext()); String currentPref = prefs.getString("episodeSorting", epsortingData[1]); Constants.EpisodeSorting sorting; if (currentPref.equals(epsortingData[0])) { sorting = Constants.EpisodeSorting.LATEST_FIRST; } else if (currentPref.equals(epsortingData[1])) { sorting = Constants.EpisodeSorting.OLDEST_FIRST; } else if (currentPref.equals(epsortingData[2])) { sorting = Constants.EpisodeSorting.UNWATCHED_FIRST; } else if (currentPref.equals(epsortingData[3])) { sorting = Constants.EpisodeSorting.ALPHABETICAL_ASC; } else if (currentPref.equals(epsortingData[4])) { sorting = Constants.EpisodeSorting.ALPHABETICAL_DESC; } else if (currentPref.equals(epsortingData[5])) { sorting = Constants.EpisodeSorting.DVDLATEST_FIRST; } else { sorting = Constants.EpisodeSorting.DVDOLDEST_FIRST; } return sorting; } public static boolean isHoneycombOrHigher() { // Can use static final constants like HONEYCOMB, declared in later // versions // of the OS since they are inlined at compile time. This is guaranteed // behavior. return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; } public static boolean isFroyoOrHigher() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO; } public static boolean isExtStorageAvailable() { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } public static boolean isNetworkConnected(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetworkInfo != null) { return activeNetworkInfo.isConnected(); } return false; } public static boolean isWifiConnected(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifiNetworkInfo = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (wifiNetworkInfo != null) { return wifiNetworkInfo.isConnected(); } return false; } public static void copyFile(File src, File dst) throws IOException { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } public static int copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int count = 0; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } /** * Update the latest episode fields for all existing shows. */ public static void updateLatestEpisodes(Context context) { Thread t = new UpdateLatestEpisodeThread(context); t.start(); } /** * Update the latest episode field for a specific show. */ public static void updateLatestEpisode(Context context, String showId) { Thread t = new UpdateLatestEpisodeThread(context, showId); t.start(); } public static class UpdateLatestEpisodeThread extends Thread { private Context mContext; private String mShowId; public UpdateLatestEpisodeThread(Context context) { mContext = context; this.setName("UpdateLatestEpisode"); } public UpdateLatestEpisodeThread(Context context, String showId) { this(context); mShowId = showId; } public void run() { if (mShowId != null) { // update single show DBUtils.updateLatestEpisode(mContext, mShowId); } else { // update all shows final Cursor shows = mContext.getContentResolver().query(Shows.CONTENT_URI, new String[] { Shows._ID }, null, null, null); while (shows.moveToNext()) { String id = shows.getString(0); DBUtils.updateLatestEpisode(mContext, id); } shows.close(); } // Adapter gets notified by ContentProvider } } /** * Get the trakt-java ServiceManger with user credentials and our API key * set. * * @param context * @param refreshCredentials Set this flag to refresh the user credentials. * @return * @throws Exception When decrypting the password failed. */ public static synchronized ServiceManager getServiceManagerWithAuth(Context context, boolean refreshCredentials) throws Exception { if (sServiceManagerWithAuthInstance == null) { sServiceManagerWithAuthInstance = new ServiceManager(); sServiceManagerWithAuthInstance.setApiKey(context.getResources().getString( R.string.trakt_apikey)); // this made some problems, so sadly disabled for now // manager.setUseSsl(true); refreshCredentials = true; } if (refreshCredentials) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context .getApplicationContext()); final String username = prefs.getString(SeriesGuidePreferences.KEY_TRAKTUSER, ""); String password = prefs.getString(SeriesGuidePreferences.KEY_TRAKTPWD, ""); password = SimpleCrypto.decrypt(password, context); sServiceManagerWithAuthInstance.setAuthentication(username, password); } return sServiceManagerWithAuthInstance; } /** * Get a trakt-java ServiceManager with just our API key set. NO user auth * data. * * @param context * @return */ public static synchronized ServiceManager getServiceManager(Context context) { if (sServiceManagerInstance == null) { sServiceManagerInstance = new ServiceManager(); sServiceManagerInstance.setApiKey(context.getResources().getString( R.string.trakt_apikey)); // this made some problems, so sadly disabled for now // manager.setUseSsl(true); } return sServiceManagerInstance; } public static String getTraktUsername(Context context) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context .getApplicationContext()); return prefs.getString(SeriesGuidePreferences.KEY_TRAKTUSER, ""); } public static String getVersion(Context context) { String version; try { version = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_META_DATA).versionName; } catch (NameNotFoundException e) { version = "UnknownVersion"; } return version; } /** * Put the TVDb season string in, get a full 'Season X' or 'Special * Episodes' string out. * * @param context * @param season * @return */ public static String getSeasonString(Context context, String season) { if (season.equals("0") || season.length() == 0) { season = context.getString(R.string.specialseason); } else { season = context.getString(R.string.season) + " " + season; } return season; } /** * If {@code isBusy} is {@code true}, then the image is only loaded if it is * in memory. In every other case a place-holder is shown. * * @param poster * @param path * @param isBusy * @param context */ public static void setPosterBitmap(ImageView poster, String path, boolean isBusy, Context context) { Bitmap bitmap = null; if (path.length() != 0) { bitmap = ImageCache.getInstance(context).getThumb(path, isBusy); } if (bitmap != null) { poster.setImageBitmap(bitmap); poster.setTag(null); } else { // set placeholder poster.setImageResource(R.drawable.show_generic); // Non-null tag means the view still needs to load it's data poster.setTag(path); } } /** * Run the notification service to display and (re)schedule upcoming episode * alarms. * * @param context */ public static void runNotificationService(Context context) { Intent i = new Intent(context, NotificationService.class); context.startService(i); } public static String toSHA1(byte[] convertme) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return Utils.byteArrayToHexString(md.digest(convertme)); } public static String byteArrayToHexString(byte[] b) { String result = ""; for (int i = 0; i < b.length; i++) { result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1); } return result; } public enum SGChannel { STABLE("com.battlelancer.seriesguide"), BETA("com.battlelancer.seriesguide.beta"), X( "com.battlelancer.seriesguide.x"); String packageName; private SGChannel(String packageName) { this.packageName = packageName; } } public static SGChannel getChannel(Context context) { String thisPackageName = context.getApplicationContext().getPackageName(); if (thisPackageName.equals(SGChannel.BETA.packageName)) { return SGChannel.BETA; } if (thisPackageName.equals(SGChannel.X.packageName)) { return SGChannel.X; } return SGChannel.STABLE; } public static void setValueOrPlaceholder(View view, final String value) { TextView field = (TextView) view; if (value == null || value.length() == 0) { field.setText(R.string.episode_unkownairdate); } else { field.setText(value); } } }
package org.voovan.http.message.packet; import org.voovan.http.message.HttpStatic; import org.voovan.tools.FastThreadLocal; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class Header { private String contentType; private String contentLength; private String contentEncoding; private String transferEncoding; private Map<String, String> headers; private static FastThreadLocal<StringBuilder> THREAD_STRING_BUILDER = FastThreadLocal.withInitial(()->new StringBuilder(512)); private boolean isCache = false; public Header(){ headers = new HashMap<String,String>(32); } /** * Header Map * @return HTTP-Header Map */ public Map<String,String> getHeaders() { return headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; } public boolean isCache() { return isCache; } public void setCache(boolean cache) { isCache = cache; } /** * name Header * @param header header name * @return header name */ public String remove(String header){ return headers.remove(header); } /** * name Header * @param header header name * @return */ public boolean contain(String header){ switch (header) { case HttpStatic.CONTENT_TYPE_STRING : return contentType!=null; case HttpStatic.CONTENT_ENCODING_STRING : return contentEncoding!=null; case HttpStatic.CONTENT_LENGTH_STRING : return contentLength!=null; case HttpStatic.TRANSFER_ENCODING_STRING : return transferEncoding!=null; default : return headers.containsKey(header); } } /** * name Header * @param header header name * @return header */ public String get(String header){ switch (header) { case HttpStatic.CONTENT_TYPE_STRING : return contentType; case HttpStatic.CONTENT_ENCODING_STRING : return contentEncoding; case HttpStatic.CONTENT_LENGTH_STRING : return contentLength; case HttpStatic.TRANSFER_ENCODING_STRING : return transferEncoding; default : return headers.get(header); } } /** * Header * @param header header name * @param value header nam * @return header name */ public String put(String header,String value){ switch (header) { case HttpStatic.CONTENT_TYPE_STRING : this.contentType = value; break; case HttpStatic.CONTENT_ENCODING_STRING : this.contentEncoding = value; break; case HttpStatic.CONTENT_LENGTH_STRING : this.contentLength = value; break; case HttpStatic.TRANSFER_ENCODING_STRING : this.transferEncoding = value; break; default : headers.put(header,value); } return value; } /** * Header * @param valueMap Header Map */ public void putAll(Map<String, String> valueMap){ for(Entry<String, String> entry : valueMap.entrySet()) { headers.put(entry.getKey(), entry.getValue()); } } /** * Header * @return header */ public int size(){ return headers.size(); } public void clear(){ if(!isCache) { contentType = null; contentLength = null; contentEncoding = null; transferEncoding = null; headers.clear(); } } @Override public String toString(){ StringBuilder headerContent = THREAD_STRING_BUILDER.get(); headerContent.setLength(0); if(contentType!=null) { headerContent.append(HttpStatic.CONTENT_TYPE_STRING); headerContent.append(HttpStatic.HEADER_SPLITER_STRING); headerContent.append(contentType); headerContent.append(HttpStatic.LINE_MARK_STRING); } if(contentEncoding!=null) { headerContent.append(HttpStatic.CONTENT_ENCODING_STRING); headerContent.append(HttpStatic.HEADER_SPLITER_STRING); headerContent.append(contentEncoding); headerContent.append(HttpStatic.LINE_MARK_STRING); } if(contentLength!=null) { headerContent.append(HttpStatic.CONTENT_LENGTH_STRING); headerContent.append(HttpStatic.HEADER_SPLITER_STRING); headerContent.append(contentLength); headerContent.append(HttpStatic.LINE_MARK_STRING); } if(transferEncoding!=null) { headerContent.append(HttpStatic.TRANSFER_ENCODING_STRING); headerContent.append(HttpStatic.HEADER_SPLITER_STRING); headerContent.append(transferEncoding); headerContent.append(HttpStatic.LINE_MARK_STRING); } for(Entry<String,String> headerItemEntry : this.headers.entrySet()){ String key = headerItemEntry.getKey(); String value = headerItemEntry.getValue(); if(!key.isEmpty()){ headerContent.append(key); headerContent.append(HttpStatic.HEADER_SPLITER_STRING); headerContent.append(value); headerContent.append(HttpStatic.LINE_MARK_STRING); } } return headerContent.toString(); } }
package wraith.library.WindowUtil.GUI; import java.awt.Graphics2D; public class GuiPanel extends GuiContainer{ public void render(Graphics2D g){ GuiComponent c; for(int i = 0; i<components.size(); i++){ c=components.get(i); c.update(); g.drawImage(c.getPane(), c.x, c.y, c.width, c.height, null); } } public GuiPanel(GuiContainer parent, int bufferWidth, int bufferHeight){ super(parent, bufferWidth, bufferHeight); } }
package sfBugsNew; import edu.umd.cs.findbugs.annotations.Confidence; import edu.umd.cs.findbugs.annotations.ExpectWarning; import edu.umd.cs.findbugs.annotations.NoWarning; public class Bug1219 { interface A { } interface B { } interface C { } interface D { } static class CC implements C {} static class DC implements D {} A objectA; @NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM) @ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.LOW) public boolean compare(B objectB) { return (objectA == objectB); } @NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM) @ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.LOW) public boolean compare(C objectC) { return (objectA == objectC); } @ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM) public static boolean compare(C objectC, D objectD) { return (objectC == objectD); } }
package com.mapswithme.maps.location; import android.annotation.SuppressLint; import android.net.SSLCertificateSocketFactory; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import com.mapswithme.maps.BuildConfig; import com.mapswithme.util.StorageUtils; import com.mapswithme.util.Utils; import com.mapswithme.util.log.DebugLogger; import com.mapswithme.util.log.FileLogger; import com.mapswithme.util.log.Logger; import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; /** * Implements interface that will be used by the core for * sending/receiving the raw data trough platform socket interface. * <p> * The instance of this class is supposed to be created in JNI layer * and supposed to be used in the thread safe environment, i.e. thread safety * should be provided externally (by the client of this class). * <p> * <b>All public methods are blocking and shouldn't be called from the main thread.</b> */ class PlatformSocket { private final static int DEFAULT_TIMEOUT = 30 * 1000; @NonNull private final static Logger LOGGER = createLogger(); private static volatile long sSslConnectionCounter; @Nullable private Socket mSocket; @Nullable private String mHost; private int mPort; private int mTimeout = DEFAULT_TIMEOUT; PlatformSocket() { sSslConnectionCounter = 0; LOGGER.d("***********************************************************************************"); LOGGER.d("Platform socket is created by core, ssl connection counter is discarded."); LOGGER.d("Installation ID: ", Utils.getInstallationId()); LOGGER.d("App version: ", BuildConfig.VERSION_NAME); LOGGER.d("App version code: ", BuildConfig.VERSION_CODE); } @NonNull private static Logger createLogger() { if (BuildConfig.BUILD_TYPE.equals("beta")) { String externalDir = StorageUtils.getExternalFilesDir(); if (!TextUtils.isEmpty(externalDir)) return new FileLogger(externalDir + "/" + PlatformSocket.class.getSimpleName() + ".log"); } return new DebugLogger(PlatformSocket.class.getSimpleName()); } public boolean open(@NonNull String host, int port) { if (mSocket != null) { LOGGER.e("Socket is already opened. Seems that it wasn't closed."); return false; } if (!isPortAllowed(port)) { LOGGER.e("A wrong port number, it must be within (0-65535) range", port); return false; } mHost = host; mPort = port; Socket socket = createSocket(host, port, true); if (socket != null && socket.isConnected()) { setReadSocketTimeout(socket, mTimeout); mSocket = socket; } return mSocket != null; } private static boolean isPortAllowed(int port) { return port >= 0 && port <= 65535; } @Nullable private static Socket createSocket(@NonNull String host, int port, boolean ssl) { return ssl ? createSslSocket(host, port) : createRegularSocket(host, port); } @Nullable private static Socket createSslSocket(@NonNull String host, int port) { Socket socket = null; try { SocketFactory sf = getSocketFactory(); socket = sf.createSocket(host, port); sSslConnectionCounter++; LOGGER.d(" LOGGER.d(sSslConnectionCounter + " ssl connection is established."); } catch (IOException e) { LOGGER.e(e, "Failed to create the ssl socket, mHost = " + host + " mPort = " + port); } return socket; } @Nullable private static Socket createRegularSocket(@NonNull String host, int port) { Socket socket = null; try { socket = new Socket(host, port); LOGGER.d("Regular socket is created and tcp handshake is passed successfully"); } catch (IOException e) { LOGGER.e(e, "Failed to create the socket, mHost = " + host + " mPort = " + port); } return socket; } @SuppressLint("SSLCertificateSocketFactoryGetInsecure") @NonNull private static SocketFactory getSocketFactory() { // Trusting to any ssl certificate factory that will be used in // debug mode, for testing purposes only. if (BuildConfig.DEBUG) //TODO: implement the custom KeyStore to make the self-signed certificates work return SSLCertificateSocketFactory.getInsecure(0, null); return SSLSocketFactory.getDefault(); } public void close() { if (mSocket == null) { LOGGER.d("Socket is already closed or it wasn't opened yet\n"); return; } try { mSocket.close(); LOGGER.d("Socket has been closed: ", this + "\n"); } catch (IOException e) { LOGGER.e(e, "Failed to close socket: ", this + "\n"); } finally { mSocket = null; } } public boolean read(@NonNull byte[] data, int count) { if (!checkSocketAndArguments(data, count)) return false; LOGGER.d("Reading method is started, data.length = " + data.length + ", count = " + count); long startTime = SystemClock.elapsedRealtime(); int readBytes = 0; try { if (mSocket == null) throw new AssertionError("mSocket cannot be null"); InputStream in = mSocket.getInputStream(); while (readBytes != count && (SystemClock.elapsedRealtime() - startTime) < mTimeout) { try { LOGGER.d("Attempting to read " + count + " bytes from offset = " + readBytes); int read = in.read(data, readBytes, count - readBytes); if (read == -1) { LOGGER.d("All data is read from the stream, read bytes count = " + readBytes + "\n"); break; } if (read == 0) { LOGGER.e("0 bytes are obtained. It's considered as error\n"); break; } LOGGER.d("Read bytes count = " + read + "\n"); readBytes += read; } catch (SocketTimeoutException e) { long readingTime = SystemClock.elapsedRealtime() - startTime; LOGGER.e(e, "Socked timeout has occurred after " + readingTime + " (ms)\n "); if (readingTime > mTimeout) { LOGGER.e("Socket wrapper timeout has occurred, requested count = " + (count - readBytes) + ", readBytes = " + readBytes + "\n"); break; } } } } catch (IOException e) { LOGGER.e(e, "Failed to read data from socket: ", this, "\n"); } return count == readBytes; } public boolean write(@NonNull byte[] data, int count) { if (!checkSocketAndArguments(data, count)) return false; LOGGER.d("Writing method is started, data.length = " + data.length + ", count = " + count); long startTime = SystemClock.elapsedRealtime(); try { if (mSocket == null) throw new AssertionError("mSocket cannot be null"); OutputStream out = mSocket.getOutputStream(); out.write(data, 0, count); LOGGER.d(count + " bytes are written\n"); return true; } catch (SocketTimeoutException e) { long writingTime = SystemClock.elapsedRealtime() - startTime; LOGGER.e(e, "Socked timeout has occurred after " + writingTime + " (ms)\n"); } catch (IOException e) { LOGGER.e(e, "Failed to write data to socket: " + this + "\n"); } return false; } private boolean checkSocketAndArguments(@NonNull byte[] data, int count) { if (mSocket == null) { LOGGER.e("Socket must be opened before reading/writing\n"); return false; } if (data.length < 0 || count < 0 || count > data.length) { LOGGER.e("Illegal arguments, data.length = " + data.length + ", count = " + count + "\n"); return false; } return true; } public void setTimeout(int millis) { mTimeout = millis; LOGGER.d("Setting the socket wrapper timeout = " + millis + " ms\n"); } private void setReadSocketTimeout(@NonNull Socket socket, int millis) { try { socket.setSoTimeout(millis); } catch (SocketException e) { LOGGER.e(e, "Failed to set system socket timeout: " + millis + "ms, " + this + "\n"); } } @Override public String toString() { return "PlatformSocket{" + "mSocket=" + mSocket + ", mHost='" + mHost + '\'' + ", mPort=" + mPort + '}'; } }
package com.devendra.speechtimer; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Vector; import com.devendra.speechtimer.util.ReportData; import com.devendra.speechtimer.util.SpeakerEntry; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.SystemClock; import android.preference.PreferenceManager; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.res.Configuration; import android.content.res.Resources; import android.database.DataSetObserver; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.Chronometer; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements TextWatcher { static final int MAX_TIME_COUNT = 11; static final int STOPPED = 1; static final int PAUSED = 2; static final int RUNNING = 3; class SpecialTimerData { public int timerId; public int playPauseId; public int logId; public int stopId; public int timerState; public long lastPauseTime; public String elapsedTime; }; private HashMap<String, SpecialTimerData> helperMap = new HashMap<>(); OnSharedPreferenceChangeListener prefListener; class TimerEntryDeleteClickListner implements DialogInterface.OnClickListener { private int position = -1; TimerEntryDeleteClickListner(int pos) { position = pos; } @Override public void onClick(DialogInterface dialog, int which) { ListView lv = (ListView) findViewById(R.id.reportListView); ReportData rd = (ReportData)lv.getAdapter(); SpeakerEntry se = rd.getItem(position); rd.remove(se); rd.setChanged(); } } class TimerEntryEditClickListner implements DialogInterface.OnClickListener, TextWatcher{ private int position = -1; private String editedName; TimerEntryEditClickListner(int pos) { position = pos; editedName = ""; } @Override public void onClick(DialogInterface dialog, int which) { if (!editedName.isEmpty()) { ListView lv = (ListView) findViewById(R.id.reportListView); ReportData rd = (ReportData)lv.getAdapter(); SpeakerEntry se = rd.getItem(position); rd.remove(se); se.name = editedName; rd.insert(se, position); rd.setChanged(); } getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); } @Override public void afterTextChanged(Editable arg0) { editedName = arg0.toString(); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SetupActivity(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. // Set text of quick timer Toolbar myToolbar = findViewById(R.id.toolbar); myToolbar.setTitle("SpeechTimer"); myToolbar.setTitleTextColor(0xFFFFFFFF); setSupportActionBar(myToolbar); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setIcon(R.drawable.ic_launcher); if (helperMap.size() == 0) // If the helper map was not initialized in onRestoreInstanceState() (means no orientation change case) initHelperMap(); setTimerInitState(R.id.quicktimer,R.string.QuickTimer); setTimerInitState(R.id.wholemeeting,R.string.WholeMeeting); } private void initHelperMap() { helperMap.clear(); SpecialTimerData std = new SpecialTimerData(); std.timerId = R.id.quicktimer; std.logId = R.id.quickTimerLog; std.playPauseId = R.id.quickTimerPlay; std.stopId = R.id.quickTimerStop; std.timerState = STOPPED; std.lastPauseTime = 0; helperMap.put(getResources().getString(R.string.QuickTimer), std); SpecialTimerData std2 = new SpecialTimerData(); std2.timerId = R.id.wholemeeting; std2.logId = R.id.wholeMeetingLog; std2.playPauseId = R.id.wholeMeetingPlay; std2.stopId = R.id.wholeMeetingStop; std2.timerState = STOPPED; std2.lastPauseTime = 0; helperMap.put(getResources().getString(R.string.WholeMeeting), std2); } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); // Save UI state changes to the savedInstanceState. // This bundle will be passed to onCreate if the process is // killed and restarted. for (Map.Entry<String, SpecialTimerData> entry : helperMap.entrySet()) { SpecialTimerData std = entry.getValue(); savedInstanceState.putInt(entry.getKey() + "State", std.timerState); Chronometer qt = findViewById(std.timerId); if (std.timerState != STOPPED) savedInstanceState.putString(entry.getKey() + "Elapsed", qt.getText().toString()); } } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // Restore UI state from the savedInstanceState. // This bundle has also been passed to onCreate. initHelperMap(); for (Map.Entry<String, SpecialTimerData> entry : helperMap.entrySet()) { SpecialTimerData std = entry.getValue(); std.timerState = savedInstanceState.getInt(entry.getKey() + "State"); if (std.timerState != STOPPED) std.elapsedTime = savedInstanceState.getString(entry.getKey() + "Elapsed"); helperMap.put(entry.getKey(),std); } } @Override public void onBackPressed() { boolean updateModel = false; for (Map.Entry<String, SpecialTimerData> entry : helperMap.entrySet()) { updateModel = (updateModel || (entry.getValue().timerState != STOPPED)); } if (updateModel) updateModelAndFile("back", false); super.onBackPressed(); } private void SetupActivity() { PreferenceManager.setDefaultValues(this, R.xml.pref_general, false); registerLangChangeListner(); updateActivityLanguage(); setContentView(R.layout.activity_main); EditText t1 = (EditText)findViewById(R.id.editText2); t1.setGravity(Gravity.CENTER); t1.addTextChangedListener(this); // Empty report text TextView emptyReportText = new TextView(this); emptyReportText.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); emptyReportText.setText(getResources().getString(R.string.NoRecentSpeakers)); emptyReportText.setTextSize(30); ListView lv = (ListView) findViewById(R.id.reportListView); lv.setEmptyView(emptyReportText); RelativeLayout rl =(RelativeLayout) findViewById(R.id.reportLayout); rl.addView(emptyReportText); } private void registerLangChangeListner() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @SuppressLint("NewApi") public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (key.compareTo("language") == 0 ) { if (Build.VERSION.SDK_INT >= 11) { recreate(); } else { updateActivityLanguage(); OnRunTimeLangUpdate(); } } } }; sharedPreferences.registerOnSharedPreferenceChangeListener(prefListener); } private void updateActivityLanguage() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String languageToLoad = sharedPreferences.getString("language", "en"); // Setup language Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; Resources rApp = getBaseContext().getResources(); rApp.updateConfiguration(config, rApp.getDisplayMetrics()); getResources().updateConfiguration(config, getResources().getDisplayMetrics()); } private void OnRunTimeLangUpdate() { ((EditText) findViewById(R.id.editText1)).setHint(R.string.next_presenter); ((TextView) findViewById(R.id.toInSpeech)).setText(R.string.to); ((TextView) findViewById(R.id.minBeforSpeech)).setText(R.string.min); ((Button) findViewById(R.id.speech)).setText(R.string.speech); ((Button) findViewById(R.id.table_topic)).setText(R.string.table); ((Button) findViewById(R.id.evaluation)).setText(R.string.evaluation); TextView emptyView = (TextView) ((ListView) findViewById(R.id.reportListView)).getEmptyView(); emptyView.setText(R.string.NoRecentSpeakers); ((Button) findViewById(R.id.button1)).setText(R.string.DeleteAll); ((Chronometer) findViewById(R.id.quicktimer)).setText(R.string.QuickTimer); } private void initializeReport() { ReportData rd = new ReportData(this, R.layout.report_entry, R.id.colorsymbol); ListView lv = findViewById(R.id.reportListView); lv.setAdapter(rd); rd.setNotifyOnChange(true); rd.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { ListView lv = (ListView) findViewById(R.id.reportListView); Button b = (Button)findViewById(R.id.deletAll); if (lv.getAdapter().getCount() == 0) b.setVisibility(View.INVISIBLE); else b.setVisibility(View.VISIBLE); } @Override public void onInvalidated() { } }); Button b = (Button)findViewById(R.id.deletAll); if (lv.getAdapter().getCount() == 0) b.setVisibility(View.INVISIBLE); else b.setVisibility(View.VISIBLE); } @Override protected void onStart() { super.onStart(); EditText nameText = (EditText) findViewById(R.id.editText1); nameText.setText(""); initializeReport(); } @Override protected void onStop() { ListView lv = (ListView) findViewById(R.id.reportListView); ReportData rd = (ReportData)lv.getAdapter(); rd.commitChanges(this); super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onPrepareOptionsMenu (Menu menu) { super.onPrepareOptionsMenu(menu); menu.findItem(R.id.action_settings).setTitle(R.string.action_settings); menu.findItem(R.id.help).setTitle(R.string.helpVideo); return true; } private int getMinSpeechTime() { EditText nameField = (EditText) findViewById(R.id.editText2); String minTimeStr = nameField.getText().toString(); int minTimeInt = 0; if (minTimeStr.length() > 0) { minTimeInt = Integer.parseInt(minTimeStr); } return minTimeInt; } private void launchTimer(int minTime, int maxTime, int type) { //Inform the user the button2 has been clicked EditText nameField = (EditText) findViewById(R.id.editText1); Intent myIntent = new Intent(MainActivity.this, Timer.class); myIntent.putExtra("speech_type", type); myIntent.putExtra("name", nameField.getText().toString().replace(',', ' ')); myIntent.putExtra("min_time", minTime); myIntent.putExtra("max_time", maxTime); MainActivity.this.startActivity(myIntent); } private void setTimerInitState(int timerID, int labelID) { Chronometer timer = (Chronometer) findViewById(timerID); String label = getResources().getString(labelID); SpecialTimerData std = helperMap.get(label); if (std.timerState == STOPPED) { timer.setText(label); findViewById(std.logId).setVisibility(View.GONE); findViewById(std.playPauseId).setVisibility(View.GONE); findViewById(std.stopId).setVisibility(View.GONE); } else { String timeFields[] = std.elapsedTime.split(":"); timer.setBase(SystemClock.elapsedRealtime() - Integer.parseInt(timeFields[0])*60000 - Integer.parseInt(timeFields[1])*1000); timer.start(); } helperMap.put(label, std); } public void buttonOnClick(View v) { switch(v.getId()) { case R.id.speech: int minSpeechTime = getMinSpeechTime(); Button maxTimeButton = (Button) findViewById(R.id.buttonMaxTime); int maxSpeechTime = Integer.parseInt(maxTimeButton.getText().toString()); launchTimer(minSpeechTime, maxSpeechTime, R.id.speech); break; case R.id.table_topic: launchTimer(1, 2, R.id.table_topic); break; case R.id.evaluation: launchTimer(2, 3, R.id.evaluation); break; } } public void specialTimerOnClick(View v) { String tag = (String) v.getTag(); SpecialTimerData std = helperMap.get(tag); Chronometer timer = findViewById(std.timerId); ImageButton playPause = findViewById(std.playPauseId); if (std.timerState == STOPPED) { timer.setBase(SystemClock.elapsedRealtime()); timer.start(); playPause.setImageResource(R.drawable.ic_action_pause); playPause.setVisibility(View.VISIBLE); findViewById(std.logId).setVisibility(View.VISIBLE); findViewById(std.stopId).setVisibility(View.VISIBLE); std.timerState = RUNNING; std.lastPauseTime = 0; } else { playPauseSpecialTimer(v); } helperMap.put(tag, std); } public void logSpecialTimer(View v) { updateModelAndFile((String)v.getTag(), true); } public void stopSpecialTimer(View v) { String tag = (String) v.getTag(); SpecialTimerData std = helperMap.get(tag); Chronometer timer = findViewById(std.timerId); ImageButton playPause = findViewById(std.playPauseId); updateModelAndFile(tag, false); timer.stop(); timer.setText(tag); std.timerState = STOPPED; playPause.setVisibility(View.GONE); findViewById(std.logId).setVisibility(View.GONE); findViewById(std.stopId).setVisibility(View.GONE); } public void playPauseSpecialTimer(View v) { String tag = (String) v.getTag(); SpecialTimerData std = helperMap.get(tag); Chronometer timer = findViewById(std.timerId); ImageButton playPause = findViewById(std.playPauseId); if (std.timerState == RUNNING) { timer.stop(); std.timerState = PAUSED; std.lastPauseTime = SystemClock.elapsedRealtime(); playPause.setImageResource(R.drawable.ic_action_play); playPause.setVisibility(View.VISIBLE); findViewById(std.logId).setVisibility(View.VISIBLE); findViewById(std.stopId).setVisibility(View.VISIBLE); } else if (std.timerState == PAUSED) { timer.start(); std.timerState = RUNNING; long intervalOnPause = (SystemClock.elapsedRealtime() - std.lastPauseTime); timer.setBase( timer.getBase() + intervalOnPause ); playPause.setImageResource(R.drawable.ic_action_pause); playPause.setVisibility(View.VISIBLE); findViewById(std.logId).setVisibility(View.VISIBLE); findViewById(std.stopId).setVisibility(View.VISIBLE); } helperMap.put(tag, std); } public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.action_settings: Intent myIntent = new Intent(MainActivity.this, SettingsActivity.class); MainActivity.this.startActivity(myIntent); return true; case R.id.help: Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("http: startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub String s = arg0.toString(); int minNum = 0; if (s.length() > 0) minNum = Integer.parseInt(arg0.toString()); Button maxEdit = (Button)findViewById(R.id.buttonMaxTime); maxEdit.setText(Integer.toString(Math.min(minNum + 2, 99), 10)); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } public void maxButtonOnClick(View v) { CharSequence maxTime[] = new CharSequence[MAX_TIME_COUNT]; int minTimeInt = getMinSpeechTime(); for (int i=0; i < MAX_TIME_COUNT; i++) { maxTime[i] = Integer.toString(i + minTimeInt); } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select Maximum Time") .setItems(maxTime, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // The 'which' argument contains the index position // of the selected item int minTimeInt = getMinSpeechTime(); Button maxTimeButton = (Button) findViewById(R.id.buttonMaxTime); maxTimeButton.setText(Integer.toString(minTimeInt + which)); } }).show(); } public void deleteAllClick(View v) { // Ask user if he really want delete all records new AlertDialog.Builder(this) .setMessage(R.string.clearReportDlgTitle) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ListView lv = (ListView) findViewById(R.id.reportListView); ReportData rd = (ReportData)lv.getAdapter(); rd.clear(); rd.setChanged(); } }) .setNegativeButton(R.string.no, null) .show(); } public void reportEntryEditClick(View v) { ListView lv = (ListView) findViewById(R.id.reportListView); int pos = lv.getPositionForView((View)v.getParent()); // Ask user if he really want delete the item records TimerEntryEditClickListner nameEditorDlgListner = new TimerEntryEditClickListner(pos); // Set an EditText view to get user input final EditText input = new EditText(this); input.setId(R.id.nameEditText); input.addTextChangedListener(nameEditorDlgListner); input.setHint(R.string.enterName); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setView(input) .setPositiveButton("Ok", nameEditorDlgListner) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Canceled. getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); } }); final AlertDialog dialog = alert.create(); Configuration config = getResources().getConfiguration(); if (config.keyboard == Configuration.KEYBOARD_NOKEYS) { input.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } }); } dialog.show(); } public void reportEntryDeleteClick(View v) { ListView lv = (ListView) findViewById(R.id.reportListView); int pos = lv.getPositionForView((View)v.getParent()); // Ask user if he really want delete the item records new AlertDialog.Builder(this) .setMessage(R.string.removeEntryDlgTitle) .setPositiveButton(R.string.yes, new TimerEntryDeleteClickListner(pos)) .setNegativeButton(R.string.no, null) .show(); } private void updateModelAndFile(String tag, boolean log) { Vector<String> tags = new Vector<>(); if (tag == "back") { // Is it a call from Back button handler? String tag1 = getResources().getString(R.string.QuickTimer); SpecialTimerData std = helperMap.get(tag1); if (std.timerState != STOPPED) { tags.add(tag1); } String tag2 = getResources().getString(R.string.WholeMeeting); if (helperMap.get(tag2).timerState != STOPPED) { tags.add(tag2); } if(tags.size() == 0) { return; // No Special timer was running when back pressed } } else { tags.add(tag); } File file = new File(this.getFilesDir(), SpeakerEntry.REPORT_FILE); long l = file.lastModified(); Date now = new Date(); try { FileWriter fw = new FileWriter(file, file.exists() && (now.getTime() - l < SpeakerEntry.MAX_MEET_DURATION)) ; PrintWriter pw = new PrintWriter(fw); // Update report model ListView lv = (ListView) findViewById(R.id.reportListView); ReportData rd = (ReportData)lv.getAdapter(); for (String t: tags) { SpeakerEntry se = new SpeakerEntry(); se.name = (log?"Elapsed":""); se.type = t; SpecialTimerData std = helperMap.get(t); Chronometer contentView = findViewById(std.timerId); se.duration = contentView.getText().toString(); rd.add(se); pw.println(se.toFileLine()); } rd.setChanged(); // Modal changed pw.close(); fw.close(); } catch(Exception e) { // Ignore if file could not be write } } }
package com.loopbook.cuhk_loopbook; import java.util.Calendar; import android.app.AlarmManager; import android.app.PendingIntent; import android.os.SystemClock; import android.content.Intent; import android.widget.Toast; import android.content.Context; public class CheckSched { public static void scheduleNotification(Context context) { Intent notificationIntent = new Intent(context, DueChecker.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmMgr = (AlarmManager) (context.getSystemService(Context.ALARM_SERVICE)); Calendar calendar = Calendar.getInstance(); if (BuildInfo.DEBUG) { calendar.setTimeInMillis(System.currentTimeMillis() + 5000); alarmMgr.setInexactRepeating( AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent); } else { // Set the alarm to start at approximately ?:??. calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 15); calendar.set(Calendar.MINUTE, 36); alarmMgr.setInexactRepeating( AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_HALF_DAY, pendingIntent); } } }
package com.rey.material.demo; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.rey.material.app.DatePickerDialog; import com.rey.material.app.Dialog; import com.rey.material.app.DialogFragment; import com.rey.material.app.TimePickerDialog; import com.rey.material.widget.Button; import com.rey.material.widget.EditText; import com.rey.material.widget.FloatingActionButton; import com.rey.material.widget.Slider; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class SetRuleFragment extends Fragment implements View.OnClickListener{ private TextView startTimeText; private TextView endTimeText; private TextView tv_discrete; private TextView dateText; private Activity main; private MyDB myDB; private Rule rule; private static long ruleId; public static SetRuleFragment newInstance(){ ruleId = -1; SetRuleFragment fragment = new SetRuleFragment(); return fragment; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d("update", "ruleId when first created " + String.valueOf(ruleId)); View v = inflater.inflate(R.layout.fragment_setrule, container, false); Button bt_start_time_picker = (Button)v.findViewById(R.id.button_start_time_picker); Button bt_end_time_picker = (Button)v.findViewById(R.id.button_end_time_picker); Button bt_sumbit = (Button)v.findViewById(R.id.button_submit); Button bt_date_picker = (Button)v.findViewById(R.id.button_date_picker); Button bt_cancel = (Button)v.findViewById(R.id.button_cancel); if (ruleId == -1){ bt_cancel.setVisibility(View.GONE); } else{ bt_cancel.setVisibility(View.VISIBLE); } startTimeText = (TextView)v.findViewById(R.id.start_time_text); endTimeText = (TextView)v.findViewById(R.id.end_time_text); dateText = (TextView)v.findViewById(R.id.date_text); Date date = new Date(); startTimeText.setText(DateFormat.getTimeInstance(DateFormat.SHORT).format(date)); endTimeText.setText(DateFormat.getTimeInstance(DateFormat.SHORT).format(date)); dateText.setText(SimpleDateFormat.getDateInstance().format(date)); final EditText editText = (EditText)v.findViewById(R.id.textfield_with_label); main = this.getActivity(); myDB = MyDB.getInstance(container.getContext()); bt_start_time_picker.setOnClickListener(this); bt_end_time_picker.setOnClickListener(this); bt_date_picker.setOnClickListener(this); // set default rule values DateFormat timeFormat = new SimpleDateFormat("HH:mm"); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); rule = new Rule("Rule", dateFormat.format(date), timeFormat.format(date), timeFormat.format(date), "8"); if (ruleId == -1){ bt_sumbit.setText("submit"); bt_sumbit.setOnClickListener(new View.OnClickListener(){ public void onClick(View view){ // Log.d("submit", "editText" + editText.getText().toString()); // if (editText.getText().toString() != "") rule.setTitle(editText.getText().toString()); myDB.insert(rule); Log.d("submit", rule.getTitle()); Log.d("submit", rule.getDate()); Log.d("submit", rule.getStart_time()); Log.d("submit", rule.getEnd_time()); Log.d("submit", rule.getVolume()); Toast.makeText(main, "Rule Submitted", Toast.LENGTH_SHORT).show(); } }); } else{ bt_sumbit.setText("update"); final long passinId = ruleId; bt_sumbit.setOnClickListener(new View.OnClickListener(){ public void onClick(View view){ rule.setTitle(editText.getText().toString()); // myDB.updateB... } }); ruleId = -1; } Slider sl_discrete = (Slider)v.findViewById(R.id.volume_slider); tv_discrete = (TextView)v.findViewById(R.id.slider_volume_text); tv_discrete.setText(String.format("volume %d", sl_discrete.getValue())); sl_discrete.setOnPositionChangeListener(new Slider.OnPositionChangeListener() { @Override public void onPositionChanged(Slider view, float oldPos, float newPos, int oldValue, int newValue) { rule.setVolume(Integer.toString(newValue)); tv_discrete.setText(String.format("volume %d", newValue)); } }); return v; } @Override public void onPause() { super.onPause(); } @Override public void onResume() { super.onResume(); } @Override public void onClick(View v){ if (v instanceof FloatingActionButton){ FloatingActionButton bt = (FloatingActionButton)v; bt.setLineMorphingState((bt.getLineMorphingState() + 1) % 2, true); } Dialog.Builder builder = null; switch (v.getId()){ case R.id.button_start_time_picker: builder = new TimePickerDialog.Builder(6, 00){ @Override public void onPositiveActionClicked(DialogFragment fragment) { TimePickerDialog dialog = (TimePickerDialog)fragment.getDialog(); String message = dialog.getFormattedTime(DateFormat.getTimeInstance(DateFormat.SHORT)); rule.setStart_time(dialog.getHour() + ":" + dialog.getMinute()); //Toast.makeText(fragment.getDialog().getContext(), "Time is " + dialog.getFormattedTime(SimpleDateFormat.getTimeInstance()), Toast.LENGTH_SHORT).show(); startTimeText.setText(message); super.onPositiveActionClicked(fragment); } @Override public void onNegativeActionClicked(DialogFragment fragment) { Toast.makeText(fragment.getDialog().getContext(), "Cancelled" , Toast.LENGTH_SHORT).show(); super.onNegativeActionClicked(fragment); } }; builder.positiveAction("OK") .negativeAction("CANCEL"); break; case R.id.button_end_time_picker: builder = new TimePickerDialog.Builder(6, 00){ @Override public void onPositiveActionClicked(DialogFragment fragment) { TimePickerDialog dialog = (TimePickerDialog)fragment.getDialog(); String message = dialog.getFormattedTime(DateFormat.getTimeInstance(DateFormat.SHORT)); //Toast.makeText(fragment.getDialog().getContext(), "Time is " + dialog.getFormattedTime(SimpleDateFormat.getTimeInstance()), Toast.LENGTH_SHORT).show(); rule.setEnd_time(dialog.getHour() + ":" + dialog.getMinute()); endTimeText.setText(message); super.onPositiveActionClicked(fragment); } @Override public void onNegativeActionClicked(DialogFragment fragment) { Toast.makeText(fragment.getDialog().getContext(), "Cancelled" , Toast.LENGTH_SHORT).show(); super.onNegativeActionClicked(fragment); } }; builder.positiveAction("OK") .negativeAction("CANCEL"); break; case R.id.button_date_picker: builder = new DatePickerDialog.Builder(){ @Override public void onPositiveActionClicked(DialogFragment fragment) { DatePickerDialog dialog = (DatePickerDialog)fragment.getDialog(); String date = dialog.getFormattedDate(SimpleDateFormat.getDateInstance()); //Toast.makeText(fragment.getDialog().getContext(), "Date is " + date, Toast.LENGTH_SHORT).show(); dateText.setText(date); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); rule.setDate(dateFormat.format(dialog.getDate())); super.onPositiveActionClicked(fragment); } @Override public void onNegativeActionClicked(DialogFragment fragment) { Toast.makeText(fragment.getDialog().getContext(), "Cancelled" , Toast.LENGTH_SHORT).show(); super.onNegativeActionClicked(fragment); } }; builder.positiveAction("OK") .negativeAction("CANCEL"); break; } DialogFragment fragment = DialogFragment.newInstance(builder); fragment.show(getFragmentManager(), null); } public void setUpdateId(long id){ this.ruleId = id; Log.d("update", "set " + String.valueOf(this.ruleId)); } }
package com.samourai.sentinel; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.content.LocalBroadcastManager; import android.text.Editable; import android.text.TextWatcher; import android.view.Display; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; //import android.util.Log; import org.bitcoinj.core.Address; import org.bitcoinj.core.Coin; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.uri.BitcoinURI; import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.client.android.Contents; import com.google.zxing.client.android.encode.QRCodeEncoder; import com.samourai.sentinel.api.APIFactory; import com.samourai.sentinel.service.WebSocketService; import com.samourai.sentinel.util.AddressFactory; import com.samourai.sentinel.util.AppUtil; import com.samourai.sentinel.util.ExchangeRateFactory; import com.samourai.sentinel.util.MonetaryUtil; import com.samourai.sentinel.util.PrefsUtil; import com.samourai.sentinel.util.ReceiveLookAtUtil; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigInteger; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Set; //import com.google.bitcoin.core.Coin; public class ReceiveFragment extends Fragment { private static final String ARG_SECTION_NUMBER = "section_number"; private Locale locale = null; private static Display display = null; private static int imgWidth = 0; private ImageView ivQR = null; private TextView tvAddress = null; private LinearLayout addressLayout = null; private EditText edAmountBTC = null; private EditText edAmountFiat = null; private TextWatcher textWatcherBTC = null; private TextWatcher textWatcherFiat = null; private String defaultSeparator = null; private String strFiat = null; private double btc_fx = 286.0; private TextView tvFiatSymbol = null; private String addr = null; private boolean canRefresh = false; private Menu _menu = null; public static ReceiveFragment newInstance(int sectionNumber) { ReceiveFragment fragment = new ReceiveFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public static final String ACTION_INTENT = "com.samourai.sentinel.ReceiveFragment.REFRESH"; protected BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(ACTION_INTENT.equals(intent.getAction())) { Bundle extras = intent.getExtras(); if(extras != null && extras.containsKey("received_on")) { String in_addr = extras.getString("received_on"); if(in_addr.equals(addr)) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { getActivity().getFragmentManager().beginTransaction().remove(ReceiveFragment.this).commit(); } }); } } } } }; public ReceiveFragment() { ; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = null; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { rootView = inflater.inflate(R.layout.fragment_receive, container, false); } else { rootView = inflater.inflate(R.layout.fragment_receive_compat, container, false); } rootView.setFilterTouchesWhenObscured(true); rootView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { rootView.setBackgroundColor(getActivity().getResources().getColor(R.color.divider)); } locale = Locale.getDefault(); // getActivity().getActionBar().setTitle("My Bitcoin Address"); setHasOptionsMenu(true); getActivity().getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); display = (getActivity()).getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); imgWidth = size.x - 240; addr = getReceiveAddress(); addressLayout = (LinearLayout)rootView.findViewById(R.id.receive_address_layout); addressLayout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { new AlertDialog.Builder(getActivity()) .setTitle(R.string.app_name) .setMessage(R.string.receive_address_to_clipboard) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getActivity().getSystemService(android.content.Context.CLIPBOARD_SERVICE); android.content.ClipData clip = null; clip = android.content.ClipData.newPlainText("Receive address", addr); clipboard.setPrimaryClip(clip); Toast.makeText(getActivity(), R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show(); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); return false; } }); tvAddress = (TextView)rootView.findViewById(R.id.receive_address); ivQR = (ImageView)rootView.findViewById(R.id.qr); ivQR.setMaxWidth(imgWidth); ivQR.setOnTouchListener(new OnSwipeTouchListener(getActivity()) { @Override public void onSwipeLeft() { if(canRefresh) { addr = getReceiveAddress(); canRefresh = false; displayQRCode(); } } }); DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault()); DecimalFormatSymbols symbols=format.getDecimalFormatSymbols(); defaultSeparator = Character.toString(symbols.getDecimalSeparator()); strFiat = PrefsUtil.getInstance(getActivity()).getValue(PrefsUtil.CURRENT_FIAT, "USD"); btc_fx = ExchangeRateFactory.getInstance(getActivity()).getAvgPrice(strFiat); tvFiatSymbol = (TextView)rootView.findViewById(R.id.fiatSymbol); tvFiatSymbol.setText(getDisplayUnits() + "-" + strFiat); edAmountBTC = (EditText)rootView.findViewById(R.id.amountBTC); edAmountFiat = (EditText)rootView.findViewById(R.id.amountFiat); textWatcherBTC = new TextWatcher() { public void afterTextChanged(Editable s) { edAmountBTC.removeTextChangedListener(this); edAmountFiat.removeTextChangedListener(textWatcherFiat); int unit = PrefsUtil.getInstance(getActivity()).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); int max_len = 8; NumberFormat btcFormat = NumberFormat.getInstance(Locale.getDefault()); switch (unit) { case MonetaryUtil.MICRO_BTC: max_len = 2; break; case MonetaryUtil.MILLI_BTC: max_len = 4; break; default: max_len = 8; break; } btcFormat.setMaximumFractionDigits(max_len + 1); btcFormat.setMinimumFractionDigits(0); double d = 0.0; try { d = Double.parseDouble(s.toString()); String s1 = btcFormat.format(d); if (s1.indexOf(defaultSeparator) != -1) { String dec = s1.substring(s1.indexOf(defaultSeparator)); if (dec.length() > 0) { dec = dec.substring(1); if (dec.length() > max_len) { edAmountBTC.setText(s1.substring(0, s1.length() - 1)); edAmountBTC.setSelection(edAmountBTC.getText().length()); s = edAmountBTC.getEditableText(); } } } } catch (NumberFormatException nfe) { ; } switch (unit) { case MonetaryUtil.MICRO_BTC: d = d / 1000000.0; break; case MonetaryUtil.MILLI_BTC: d = d / 1000.0; break; default: break; } edAmountFiat.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(d * btc_fx)); edAmountFiat.setSelection(edAmountFiat.getText().length()); edAmountFiat.addTextChangedListener(textWatcherFiat); edAmountBTC.addTextChangedListener(this); displayQRCode(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { ; } public void onTextChanged(CharSequence s, int start, int before, int count) { ; } }; edAmountBTC.addTextChangedListener(textWatcherBTC); textWatcherFiat = new TextWatcher() { public void afterTextChanged(Editable s) { edAmountFiat.removeTextChangedListener(this); edAmountBTC.removeTextChangedListener(textWatcherBTC); int max_len = 2; NumberFormat fiatFormat = NumberFormat.getInstance(Locale.getDefault()); fiatFormat.setMaximumFractionDigits(max_len + 1); fiatFormat.setMinimumFractionDigits(0); double d = 0.0; try { d = Double.parseDouble(s.toString()); String s1 = fiatFormat.format(d); if(s1.indexOf(defaultSeparator) != -1) { String dec = s1.substring(s1.indexOf(defaultSeparator)); if(dec.length() > 0) { dec = dec.substring(1); if(dec.length() > max_len) { edAmountFiat.setText(s1.substring(0, s1.length() - 1)); edAmountFiat.setSelection(edAmountFiat.getText().length()); } } } } catch(NumberFormatException nfe) { ; } int unit = PrefsUtil.getInstance(getActivity()).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch (unit) { case MonetaryUtil.MICRO_BTC: d = d * 1000000.0; break; case MonetaryUtil.MILLI_BTC: d = d * 1000.0; break; default: break; } edAmountBTC.setText(MonetaryUtil.getInstance().getBTCFormat().format(d / btc_fx)); edAmountBTC.setSelection(edAmountBTC.getText().length()); edAmountBTC.addTextChangedListener(textWatcherBTC); edAmountFiat.addTextChangedListener(this); displayQRCode(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { ; } public void onTextChanged(CharSequence s, int start, int before, int count) { ; } }; edAmountFiat.addTextChangedListener(textWatcherFiat); IntentFilter filter = new IntentFilter(ACTION_INTENT); LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter); displayQRCode(); return rootView; } @Override public void onDestroy() { getActivity().getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver); super.onDestroy(); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); // menu.findItem(R.id.action_sweep).setVisible(false); menu.findItem(R.id.action_settings).setVisible(false); MenuItem itemShare = menu.findItem(R.id.action_share_receive).setVisible(true); itemShare.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { new AlertDialog.Builder(getActivity()) .setTitle(R.string.app_name) .setMessage(R.string.receive_address_to_share) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String strFileName = AppUtil.getInstance(getActivity()).getReceiveQRFilename(); File file = new File(strFileName); if(!file.exists()) { try { file.createNewFile(); } catch(Exception e) { Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } file.setReadable(true, false); FileOutputStream fos = null; try { fos = new FileOutputStream(file); } catch(FileNotFoundException fnfe) { ; } android.content.ClipboardManager clipboard = (android.content.ClipboardManager)getActivity().getSystemService(android.content.Context.CLIPBOARD_SERVICE); android.content.ClipData clip = null; clip = android.content.ClipData.newPlainText("Receive address", addr); clipboard.setPrimaryClip(clip); if(file != null && fos != null) { Bitmap bitmap = ((BitmapDrawable)ivQR.getDrawable()).getBitmap(); bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos); try { fos.close(); } catch(IOException ioe) { ; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/png"); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); startActivity(Intent.createChooser(intent, getActivity().getText(R.string.send_payment_code))); } } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); return false; } }); MenuItem itemRefresh = menu.findItem(R.id.action_refresh).setVisible(false); itemRefresh.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (canRefresh) { addr = getReceiveAddress(); canRefresh = false; displayQRCode(); } return false; } }); _menu = menu; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MainActivity2) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER)); } private void displayQRCode() { BigInteger bamount = null; try { double amount = NumberFormat.getInstance(locale).parse(edAmountBTC.getText().toString()).doubleValue(); int unit = PrefsUtil.getInstance(getActivity()).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch (unit) { case MonetaryUtil.MICRO_BTC: amount = amount / 1000000.0; break; case MonetaryUtil.MILLI_BTC: amount = amount / 1000.0; break; default: break; } long lamount = (long)(amount * 1e8); if(!bamount.equals(BigInteger.ZERO)) { ivQR.setImageBitmap(generateQRCode(BitcoinURI.convertToBitcoinURI(Address.fromBase58(MainNetParams.get(), addr), Coin.valueOf(lamount), null, null))); } else { ivQR.setImageBitmap(generateQRCode(addr)); } } catch(NumberFormatException nfe) { ivQR.setImageBitmap(generateQRCode(addr)); } catch(ParseException pe) { ivQR.setImageBitmap(generateQRCode(addr)); } tvAddress.setText(addr); checkPrevUse(); ReceiveLookAtUtil.getInstance().add(addr); new Thread(new Runnable() { @Override public void run() { if(AppUtil.getInstance(getActivity().getApplicationContext()).isServiceRunning(WebSocketService.class)) { getActivity().stopService(new Intent(getActivity().getApplicationContext(), WebSocketService.class)); } getActivity().startService(new Intent(getActivity().getApplicationContext(), WebSocketService.class)); } }).start(); } private Bitmap generateQRCode(String uri) { Bitmap bitmap = null; QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(uri, null, Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), imgWidth); try { bitmap = qrCodeEncoder.encodeAsBitmap(); } catch (WriterException e) { e.printStackTrace(); } return bitmap; } private void checkPrevUse() { final Set<String> xpubKeys = SamouraiSentinel.getInstance(getActivity()).getXPUBs().keySet(); final Set<String> legacyKeys = SamouraiSentinel.getInstance(getActivity()).getLegacy().keySet(); final List<String> xpubList = new ArrayList<String>(); xpubList.addAll(xpubKeys); xpubList.addAll(legacyKeys); if(!xpubList.get(SamouraiSentinel.getInstance(getActivity()).getCurrentSelectedAccount() - 1).startsWith("xpub")) { return; } final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { try { final JSONObject jsonObject = APIFactory.getInstance(getActivity()).getAddressInfo(addr); handler.post(new Runnable() { @Override public void run() { try { if(jsonObject != null) { if(jsonObject.has("n_tx") && (jsonObject.getLong("n_tx") > 0)) { Toast.makeText(getActivity(), R.string.address_used_previously, Toast.LENGTH_SHORT).show(); canRefresh = true; _menu.findItem(R.id.action_refresh).setVisible(true); } else { canRefresh = false; _menu.findItem(R.id.action_refresh).setVisible(false); } } } catch (Exception e) { e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } public String getDisplayUnits() { return (String) MonetaryUtil.getInstance().getBTCUnits()[PrefsUtil.getInstance(getActivity()).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC)]; } private String getReceiveAddress() { final Set<String> xpubKeys = SamouraiSentinel.getInstance(getActivity()).getXPUBs().keySet(); final Set<String> legacyKeys = SamouraiSentinel.getInstance(getActivity()).getLegacy().keySet(); final List<String> xpubList = new ArrayList<String>(); xpubList.addAll(xpubKeys); xpubList.addAll(legacyKeys); String addr = null; if(xpubList.get(SamouraiSentinel.getInstance(getActivity()).getCurrentSelectedAccount() - 1).startsWith("xpub")) { String xpub = xpubList.get(SamouraiSentinel.getInstance(getActivity()).getCurrentSelectedAccount() - 1); int account = AddressFactory.getInstance(getActivity()).xpub2account().get(xpub); addr = AddressFactory.getInstance(getActivity()).get(AddressFactory.RECEIVE_CHAIN, account); } else { addr = xpubList.get(SamouraiSentinel.getInstance(getActivity()).getCurrentSelectedAccount() - 1); } return addr; } }
package com.sinyuk.yuk.ui.feeds; import android.app.Activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import com.bumptech.glide.Glide; import com.f2prateek.rx.preferences.RxSharedPreferences; import com.sinyuk.yuk.AppModule; import com.sinyuk.yuk.R; import com.sinyuk.yuk.api.DribbleApi; import com.sinyuk.yuk.data.shot.DaggerShotRepositoryComponent; import com.sinyuk.yuk.data.shot.Shot; import com.sinyuk.yuk.data.shot.ShotRepository; import com.sinyuk.yuk.ui.BaseFragment; import com.sinyuk.yuk.utils.BetterViewAnimator; import com.sinyuk.yuk.utils.PrefsUtils; import com.sinyuk.yuk.utils.lists.ListItemMarginDecoration; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import fr.castorflex.android.smoothprogressbar.SmoothProgressBar; import rx.functions.Action1; import timber.log.Timber; public class FeedsFragment extends BaseFragment { @Inject ShotRepository shotRepository; @Inject RxSharedPreferences mSharedPreferences; @BindView(R.id.loading_layout) RelativeLayout mLoadingLayout; @BindView(R.id.layout_list) RelativeLayout mListLayout; @BindView(R.id.recycler_view) RecyclerView mRecyclerView; @BindView(R.id.progress_bar) SmoothProgressBar mSmoothProgressBar; @BindView(R.id.layout_error) RelativeLayout mLayoutError; @BindView(R.id.layout_empty) RelativeLayout mLayoutEmpty; @BindView(R.id.view_animator) BetterViewAnimator mViewAnimator; private FeedsAdapter mAdapter; private ArrayList<Shot> mShotList = new ArrayList<>(); private int mPage; public FeedsFragment() { // need a default constructor } @Override protected void beforeInflate() { Timber.tag("FeedsFragment"); } @Override public void onAttach(Activity activity) { super.onAttach(activity); DaggerShotRepositoryComponent.builder() .appModule(new AppModule(activity.getApplication())) .build().inject(this); } @Override protected int getRootViewId() { return R.layout.feed_list_fragment; } @Override protected void finishInflate() { initRecyclerView(); mRecyclerView.postDelayed(() -> loadFeeds(DribbleApi.ANIMATED, 1), 0); } private void initRecyclerView() { mAdapter = new FeedsAdapter(mContext, Glide.with(this), mShotList); mRecyclerView.setAdapter(mAdapter); mRecyclerView.addItemDecoration(new ListItemMarginDecoration(2, R.dimen.content_space_8, true, mContext)); final LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false); mRecyclerView.setLayoutManager(layoutManager); mSharedPreferences.getBoolean(PrefsUtils.auto_play_gif, false) .asObservable() .subscribe(autoPlayGif -> { mAdapter.setAutoPlayGif(autoPlayGif); }); mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onChanged() { mViewAnimator.setDisplayedChildId(mAdapter.getItemCount() == 0 ? R.id.layout_empty : R.id.layout_list); /*swipeRefreshView.setRefreshing(false);*/ } }); } // @Subscribe(threadMode = ThreadMode.MAIN) public void setFilterType(String type) { mPage = 1; loadFeeds(type, mPage); } private void loadFeeds(String type, int page) { shotRepository.getShots(type, page) .subscribe(new Action1<List<Shot>>() { @Override public void call(List<Shot> shots) { if (page == 1 && !mShotList.isEmpty()) { mShotList.clear(); } mShotList.addAll(shots); mAdapter.notifyDataSetChanged(); } }); } }
package com.ternaryop.photoshelf.util.log; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class Log { private static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US); public static void error(Throwable t, File destFile, String... msg) { String date = DATE_TIME_FORMAT.format(new Date()); try (FileOutputStream fos = new FileOutputStream(destFile, true)) { PrintStream ps = new PrintStream(fos); if (msg != null) { for (String m : msg) { ps.println(date + " - " + m); } } t.printStackTrace(ps); ps.flush(); ps.close(); } catch (Exception fosEx) { fosEx.printStackTrace(); } } }
package com.zhao.album; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Message; import android.support.v4.util.LruCache; import android.util.Log; import android.view.WindowManager; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class AlbumBitmapCacheHelper { private volatile static AlbumBitmapCacheHelper instance = null; private LruCache<String, Bitmap> cache; /** * path */ private ArrayList<String> currentShowString; // private ContentResolver cr; private AlbumBitmapCacheHelper() { final int memory = (int) (Runtime.getRuntime().maxMemory() / 1024 / 4); cache = new LruCache<String, Bitmap>(memory) { @Override protected int sizeOf(String key, Bitmap value) { //bitmap return value.getRowBytes() * value.getHeight() / 1024; } }; currentShowString = new ArrayList<String>(); // cr = AppContext.getInstance().getContentResolver(); } public void releaseAllSizeCache(){ cache.evictAll(); cache.resize(1); } public void releaseHalfSizeCache() { cache.resize((int) (Runtime.getRuntime().maxMemory() / 1024 / 8)); } public void resizeCache() { cache.resize((int) (Runtime.getRuntime().maxMemory() / 1024 / 4)); } public void clearCache() { cache.evictAll(); cache = null; instance = null; } public static AlbumBitmapCacheHelper getInstance() { if (instance == null) { synchronized (AlbumBitmapCacheHelper.class) { if (instance == null) { instance = new AlbumBitmapCacheHelper(); } } } return instance; } /** * pathbitmap * * @param path * @param width 0 * @param height 0 * @param callback bitmap * @param objects */ public Bitmap getBitmap(final String path, int width, int height, final ILoadImageCallback callback, Object... objects){ Bitmap bitmap = getBitmapFromCache(path, width, height); if (bitmap != null) { Log.e("zhao", "get bitmap from cache"); } else { decodeBitmapFromPath(path, width, height, callback, objects); } return bitmap; } //try another size to get better display ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 5, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); // ExecutorService tpe = Executors.newFixedThreadPool(1); /** * pathbitmap */ private void decodeBitmapFromPath(final String path, final int width, final int height, final ILoadImageCallback callback, final Object... objects) throws OutOfMemoryError { final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { callback.onLoadImageCallBack((Bitmap) msg.obj, path, objects); } }; tpe.execute(new Runnable() { @Override public void run() { if (!currentShowString.contains(path)||cache==null) { return; } Bitmap bitmap = null; if (width == 0 || height == 0) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); options.inSampleSize = computeScale(options, ((WindowManager) (AppContext.getInstance().getSystemService(Context.WINDOW_SERVICE))).getDefaultDisplay().getWidth(), ((WindowManager) (AppContext.getInstance().getSystemService(Context.WINDOW_SERVICE))).getDefaultDisplay().getWidth()); options.inJustDecodeBounds = false; try { bitmap = BitmapFactory.decodeFile(path, options); } catch (OutOfMemoryError e) { releaseAllSizeCache(); bitmap = BitmapFactory.decodeFile(path, options); } } else { //temp // samplesize,samplesize > 4, // temp String hash = CommonUtil.md5(path); File file = new File(CommonUtil.getDataPath()); if (!file.exists()) file.mkdirs(); String tempPath = CommonUtil.getDataPath() + hash + ".temp"; File picFile = new File(path); File tempFile = new File(tempPath); //,temp if (tempFile.exists() && (picFile.lastModified() <= tempFile.lastModified())) bitmap = BitmapFactory.decodeFile(tempPath); if (bitmap == null) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); options.inSampleSize = computeScale(options, width, height); options.inJustDecodeBounds = false; // if(objects.length != 0){ // long start = System.currentTimeMillis(); // bitmap = MediaStore.Images.Thumbnails.getThumbnail(cr, Long.parseLong(objects[0].toString()), // MediaStore.Video.Thumbnails.MINI_KIND, options); // }else{ bitmap = BitmapFactory.decodeFile(path, options); if (bitmap != null && cache!=null) { bitmap = centerSquareScaleBitmap(bitmap, ((bitmap.getWidth() > bitmap.getHeight()) ? bitmap.getHeight() : bitmap.getWidth())); } if (options.inSampleSize >= 4) { try { file = new File(tempPath); if (!file.exists()) file.createNewFile(); else { file.delete(); file.createNewFile(); } FileOutputStream fos = new FileOutputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); fos.write(baos.toByteArray()); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }else{ //tempcache if (bitmap != null && cache!=null) { bitmap = centerSquareScaleBitmap(bitmap, ((bitmap.getWidth() > bitmap.getHeight()) ? bitmap.getHeight() : bitmap.getWidth())); } } } if (bitmap != null && cache!=null) cache.put(path +"_"+ width +"_"+height, bitmap); Message msg = Message.obtain(); msg.obj = bitmap; handler.sendMessage(msg); } }); } /** * @param bitmap * @param edgeLength * @return */ public static Bitmap centerSquareScaleBitmap(Bitmap bitmap, int edgeLength) { if (null == bitmap || edgeLength <= 0) { return null; } Bitmap result = bitmap; int widthOrg = bitmap.getWidth(); int heightOrg = bitmap.getHeight(); int xTopLeft = (widthOrg - edgeLength) / 2; int yTopLeft = (heightOrg - edgeLength) / 2; if (xTopLeft == 0 && yTopLeft == 0) return result; try { result = Bitmap.createBitmap(bitmap, xTopLeft, yTopLeft, edgeLength, edgeLength); bitmap.recycle(); } catch (Exception e) { return null; } return result; } private int computeScale(BitmapFactory.Options options, int width, int height) { if (options == null) return 1; int widthScale = (int)((float) options.outWidth / (float) width); int heightScale = (int)((float) options.outHeight / (float) height); int scale = (widthScale > heightScale ? widthScale : heightScale); if (scale < 1) scale = 1; return scale; } /** * lrucachenull * * @param path ,key * @param width * @param height * @return value */ private Bitmap getBitmapFromCache(final String path, int width, int height) { return cache.get(path +"_"+ width +"_"+height); } /** * pathlist */ public void addPathToShowlist(String path) { currentShowString.add(path); } /** * listpath */ public void removePathFromShowlist(String path) { currentShowString.remove(path); } public interface ILoadImageCallback { void onLoadImageCallBack(Bitmap bitmap, String path, Object... objects); } /** * threads */ public void removeAllThreads() { currentShowString.clear(); for (Runnable runnable : tpe.getQueue()) { tpe.remove(runnable); } } }
package lt.vilnius.tvarkau; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.location.Address; import android.location.Geocoder; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.design.widget.TextInputLayout; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.support.v7.widget.Toolbar; import android.util.Base64; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.ui.PlacePicker; import com.google.android.gms.maps.model.LatLng; import com.google.firebase.crash.FirebaseCrash; import com.gun0912.tedpicker.Config; import com.gun0912.tedpicker.ImagePickerActivity; import com.viewpagerindicator.CirclePageIndicator; import org.greenrobot.eventbus.EventBus; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import autodagger.AutoComponent; import autodagger.AutoInjector; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnItemSelected; import icepick.State; import lt.vilnius.tvarkau.api.ApiMethod; import lt.vilnius.tvarkau.api.ApiRequest; import lt.vilnius.tvarkau.api.ApiResponse; import lt.vilnius.tvarkau.api.GetNewProblemParams; import lt.vilnius.tvarkau.api.LegacyApiModule; import lt.vilnius.tvarkau.api.LegacyApiService; import lt.vilnius.tvarkau.entity.Profile; import lt.vilnius.tvarkau.entity.ReportType; import lt.vilnius.tvarkau.events_listeners.NewProblemAddedEvent; import lt.vilnius.tvarkau.utils.GlobalConsts; import lt.vilnius.tvarkau.utils.PermissionUtils; import lt.vilnius.tvarkau.views.adapters.ProblemImagesPagerAdapter; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; import static android.Manifest.permission.CAMERA; import static android.Manifest.permission.READ_EXTERNAL_STORAGE; import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; import static lt.vilnius.tvarkau.ChooseReportTypeActivity.EXTRA_REPORT_TYPE; @AutoComponent(modules = {LegacyApiModule.class, AppModule.class, SharedPreferencesModule.class}) @AutoInjector @Singleton public class NewProblemActivity extends BaseActivity { @Inject LegacyApiService legacyApiService; @Inject SharedPreferences myProblemsPreferences; private static final int REQUEST_IMAGE_CAPTURE = 1; private static final int PERMISSION_REQUEST_CODE = 10; public static final int REQUEST_PLACE_PICKER = 11; public static final int REQUEST_PROFILE = 12; public static final int REQUEST_CHOOSE_REPORT_TYPE = 13; private static final String[] REQUIRED_PERMISSIONS = {WRITE_EXTERNAL_STORAGE, CAMERA, READ_EXTERNAL_STORAGE}; private static final String ANONYMOUS_USER_SESSION_IS = "null"; private static final String PROBLEM_PREFERENCE_KEY = "problem"; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.report_problem_location) EditText addProblemLocation; @BindView(R.id.problem_images_view_pager) ViewPager problemImagesViewPager; @BindView(R.id.problem_images_view_pager_indicator) CirclePageIndicator problemImagesViewPagerIndicator; @BindView(R.id.report_problem_type) EditText reportProblemType; @BindView(R.id.report_problem_privacy_mode) Spinner reportProblemPrivacyMode; @BindView(R.id.report_problem_description) EditText reportProblemDescription; @BindView(R.id.report_problem_take_photo) FloatingActionButton reportProblemTakePhoto; @BindView(R.id.report_problem_location_wrapper) TextInputLayout reportProblemLocationWrapper; @BindView(R.id.report_problem_description_wrapper) TextInputLayout reportProblemDescriptionWrapper; @BindView(R.id.report_problem_type_wrapper) TextInputLayout reportProblemTypeWrapper; @State File lastPhotoFile; @State LatLng locationCords; @State ArrayList<Uri> problemImagesURIs; @State Profile profile; @State ReportType reportType; String address; String[] photos; private Snackbar snackbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_problem); ButterKnife.bind(this); DaggerNewProblemActivityComponent .builder() .appModule(new AppModule(this.getApplication())) .sharedPreferencesModule(new SharedPreferencesModule()) .legacyApiModule(new LegacyApiModule()) .build() .inject(this); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close); initProblemImagesPager(); initPrivacyModeSpinner(); } private void initPrivacyModeSpinner() { ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.report_privacy_mode, R.layout.item_report_type_spinner); adapter.setDropDownViewResource(R.layout.item_report_type_spinner_dropdown); reportProblemPrivacyMode.setAdapter(adapter); } private void initProblemImagesPager() { problemImagesViewPager.setAdapter(new ProblemImagesPagerAdapter(this, null)); problemImagesViewPager.setOffscreenPageLimit(3); problemImagesViewPagerIndicator.setViewPager(problemImagesViewPager); problemImagesViewPagerIndicator.setVisibility(View.GONE); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.action_send: sendProblem(); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.new_problem_toolbar_menu, menu); return true; } public void sendProblem() { if (validateProblemInputs()) { ProgressDialog progressDialog = createProgressDialog(); progressDialog.show(); Observable<String[]> photoObservable; if (problemImagesURIs != null) { photos = new String[problemImagesURIs.size()]; photoObservable = Observable.from(problemImagesURIs) .map(uri -> Uri.fromFile(new File(uri.toString()))) .map(uri -> { Bitmap bitmap = null; try { bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 60, byteArrayOutputStream); byte[] byteArrayImage = byteArrayOutputStream.toByteArray(); return Base64.encodeToString(byteArrayImage, Base64.NO_WRAP); } catch (IOException e) { e.printStackTrace(); return null; } }) .toList() .map(photos -> { String[] photoArray = new String[photos.size()]; photos.toArray(photoArray); return photoArray; }); } else { photoObservable = Observable.just(null); } Action1<ApiResponse<Integer>> onSuccess = apiResponse -> { if (apiResponse.getResult() != null) { String newProblemId = apiResponse.getResult().toString(); myProblemsPreferences .edit() .putString(PROBLEM_PREFERENCE_KEY + newProblemId, newProblemId) .apply(); EventBus.getDefault().post(new NewProblemAddedEvent()); progressDialog.dismiss(); Toast.makeText(this, R.string.problem_successfully_sent, Toast.LENGTH_SHORT).show(); finish(); } }; Action1<Throwable> onError = throwable -> { throwable.printStackTrace(); progressDialog.dismiss(); Toast.makeText(getApplicationContext(), R.string.error_submitting_problem, Toast.LENGTH_SHORT).show(); }; photoObservable.flatMap(photos -> Observable.just( new GetNewProblemParams.Builder() .setSessionId(ANONYMOUS_USER_SESSION_IS) .setDescription(reportProblemDescription.getText().toString()) .setType(reportType.getName()) .setAddress(address) .setLatitude(locationCords.latitude) .setLongitude(locationCords.longitude) .setPhoto(photos) .setEmail(null) .setPhone(null) .setMessageDescription(null) .create()) ).map(params -> new ApiRequest<>(ApiMethod.NEW_PROBLEM, params)) .flatMap(request -> legacyApiService.postNewProblem(request)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( onSuccess, onError ); } } private ProgressDialog createProgressDialog() { ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setMessage(getString(R.string.sending_problem)); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); return progressDialog; } private boolean validateProblemInputs() { boolean addressIsValid = false; boolean descriptionIsValid = false; boolean problemTypeIsValid = false; if (address != null) { addressIsValid = true; reportProblemDescriptionWrapper.setError(null); } else { reportProblemLocationWrapper.setError(getText(R.string.error_problem_location_is_empty)); } if (reportProblemDescription.getText() != null && reportProblemDescription.getText().length() > 0) { descriptionIsValid = true; } else { reportProblemDescriptionWrapper.setError(getText(R.string.error_problem_description_is_empty)); } if (reportType != null) { problemTypeIsValid = true; } else { reportProblemTypeWrapper.setError(getText(R.string.error_problem_type_is_empty)); } return addressIsValid && descriptionIsValid && problemTypeIsValid; } public void takePhoto() { Config config = new Config(); config.setToolbarTitleRes(R.string.choose_photos_title); config.setCameraBtnImage(R.drawable.ic_photo_camera_white); ImagePickerActivity.setConfig(config); Intent intent = new Intent(this, ImagePickerActivity.class); Bundle bundle = ActivityOptionsCompat.makeScaleUpAnimation(reportProblemTakePhoto, 0, 0, reportProblemTakePhoto.getWidth(), reportProblemTakePhoto.getHeight()).toBundle(); if (problemImagesURIs != null) { intent.putParcelableArrayListExtra(ImagePickerActivity.EXTRA_IMAGE_URIS, problemImagesURIs); } ActivityCompat.startActivityForResult(this, intent, REQUEST_IMAGE_CAPTURE, bundle); } @OnClick(R.id.report_problem_take_photo) public void onTakePhotoClicked() { if (PermissionUtils.isAllPermissionsGranted(this, REQUIRED_PERMISSIONS)) { takePhoto(); } else { ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, PERMISSION_REQUEST_CODE); } } @OnClick(R.id.report_problem_type) public void onChooseProblemTypeClicked() { Intent intent = new Intent(this, ChooseReportTypeActivity.class); startActivityForResult(intent, REQUEST_CHOOSE_REPORT_TYPE); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case PERMISSION_REQUEST_CODE: if (PermissionUtils.isAllPermissionsGranted(this, REQUIRED_PERMISSIONS)) { takePhoto(); } else { Toast.makeText(this, R.string.error_need_camera_and_storage_permission, Toast.LENGTH_SHORT).show(); } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } private boolean isEditedByUser() { return reportProblemDescription.getText().length() > 0 || reportProblemPrivacyMode.getSelectedItemPosition() > 0 || reportType != null || locationCords != null || problemImagesURIs != null; } @Override public void onBackPressed() { if (isEditedByUser()) { new AlertDialog.Builder(this) .setMessage(getString(R.string.discard_changes_title)) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.discard_changes_positive, (dialog, whichButton) -> NewProblemActivity.super.onBackPressed()) .setNegativeButton(R.string.discard_changes_negative, null).show(); } else { super.onBackPressed(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { switch (requestCode) { case REQUEST_IMAGE_CAPTURE: problemImagesURIs = data.getParcelableArrayListExtra(ImagePickerActivity.EXTRA_IMAGE_URIS); Uri[] problemImagesURIsArr = problemImagesURIs.toArray(new Uri[problemImagesURIs.size()]); String[] photoArray = new String[problemImagesURIsArr.length]; for (int i = 0; i < problemImagesURIsArr.length; i++) { photoArray[i] = new File(problemImagesURIsArr[i].getPath()).toString(); } setPhotos(photoArray); break; case REQUEST_PLACE_PICKER: Place place = PlacePicker.getPlace(this, data); LatLng latLng = place.getLatLng(); Geocoder geocoder = new Geocoder(this); List<Address> addresses = null; try { addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); } catch (IOException e) { e.printStackTrace(); FirebaseCrash.report(e); } if (addresses != null && addresses.get(0).getLocality() != null) { String city = addresses.get(0).getLocality(); if (city.equalsIgnoreCase(GlobalConsts.CITY_VILNIUS)) { address = addresses.get(0).getAddressLine(0); reportProblemLocationWrapper.setError(null); addProblemLocation.setText(address); locationCords = latLng; if (snackbar != null && snackbar.isShown()) { snackbar.dismiss(); } } else { showIncorrectPlaceSnackbar(); } } else { showIncorrectPlaceSnackbar(); } break; case REQUEST_PROFILE: profile = Profile.returnProfile(this); break; case REQUEST_CHOOSE_REPORT_TYPE: if (data.hasExtra(EXTRA_REPORT_TYPE)) { reportType = data.getParcelableExtra(EXTRA_REPORT_TYPE); reportProblemTypeWrapper.setError(null); reportProblemType.setText(reportType.getName()); } break; } } else { switch (requestCode) { case REQUEST_PROFILE: reportProblemPrivacyMode.setSelection(0); break; } } } private void showIncorrectPlaceSnackbar() { View view = this.getCurrentFocus(); snackbar = Snackbar.make(view, R.string.error_location_incorrect, Snackbar.LENGTH_INDEFINITE); snackbar.setAction(R.string.choose_again, v -> showPlacePicker(view)) .setActionTextColor(ContextCompat.getColor(this, R.color.snackbar_action_text)) .show(); } private void setPhotos(String[] photoArray) { if (photoArray.length > 1) { problemImagesViewPagerIndicator.setVisibility(View.VISIBLE); } problemImagesViewPager.setAdapter(new ProblemImagesPagerAdapter<>(this, photoArray)); } @OnClick(R.id.report_problem_location) public void onProblemLocationClicked(View view) { showPlacePicker(view); } @OnItemSelected(R.id.report_problem_privacy_mode) public void onPrivacyModeSelected(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: profile = null; break; case 1: profile = Profile.returnProfile(this); if (profile == null) { Intent intent = new Intent(this, MyProfileActivity.class); startActivityForResult(intent, REQUEST_PROFILE); } break; } } @Override public boolean onSupportNavigateUp() { onBackPressed(); return false; } private void showPlacePicker(View view) { PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder(); try { Intent intent = builder.build(this); Bundle bundle = ActivityOptionsCompat.makeScaleUpAnimation(view, 0, 0, view.getWidth(), view.getHeight()).toBundle(); ActivityCompat.startActivityForResult(this, intent, REQUEST_PLACE_PICKER, bundle); } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) { e.printStackTrace(); Toast.makeText(this, R.string.check_google_play_services, Toast.LENGTH_LONG).show(); } } }
package net.ldvsoft.warofviruses; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.IOException; import java.util.List; import java.util.UUID; import static net.ldvsoft.warofviruses.GameLogic.BOARD_SIZE; import static net.ldvsoft.warofviruses.MenuActivity.OPPONENT_BOT; import static net.ldvsoft.warofviruses.MenuActivity.OPPONENT_LOCAL_PLAYER; import static net.ldvsoft.warofviruses.MenuActivity.OPPONENT_NETWORK_PLAYER; import static net.ldvsoft.warofviruses.MenuActivity.OPPONENT_TYPE; public class GameActivity extends GameActivityBase { private static Gson gson = new Gson(); private BroadcastReceiver tokenSentReceiver; private BroadcastReceiver gameLoadedFromServerReceiver; private Game game; private final HumanPlayer.OnGameStateChangedListener ON_GAME_STATE_CHANGED_LISTENER = new HumanPlayer.OnGameStateChangedListener() { @Override public void onGameStateChanged(final GameLogic gameLogic) { runOnUiThread(new Runnable() { @Override public void run() { redrawGame(gameLogic); } }); } }; private HumanPlayer humanPlayer = new HumanPlayer(HumanPlayer.USER_ANONYMOUS, GameLogic.PlayerFigure.CROSS, ON_GAME_STATE_CHANGED_LISTENER); private class OnExitActivityListener implements DialogInterface.OnClickListener { private boolean saveGame; public OnExitActivityListener(boolean saveGame) { this.saveGame = saveGame; } @Override public void onClick(DialogInterface dialog, int which) { if (!saveGame) game = null; GameActivity.super.onBackPressed(); } } @Override public void onBackPressed() { new AlertDialog.Builder(this) .setMessage("Do you want to save current game?") .setCancelable(false) .setPositiveButton("Yes", new OnExitActivityListener(true)) .setNegativeButton("No", new OnExitActivityListener(false)) .show(); } @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); game = new Game(); tokenSentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean sentToken = prefs.getBoolean(WoVPreferences.GCM_SENT_TOKEN_TO_SERVER, false); if (sentToken) { Toast.makeText(GameActivity.this, "YEEEEEEEY!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(GameActivity.this, "Oh no, Oh no, Oh no-no-no-no(", Toast.LENGTH_SHORT).show(); } } }; Intent intent = getIntent(); setCurrentGameListeners(); switch (intent.getIntExtra(OPPONENT_TYPE, -1)) { case OPPONENT_BOT: game.startNewGame(humanPlayer, new AIPlayer(GameLogic.PlayerFigure.ZERO)); initButtons(); break; case OPPONENT_LOCAL_PLAYER: game.startNewGame(humanPlayer, new HumanPlayer(humanPlayer.getUser(), GameLogic.PlayerFigure.ZERO)); initButtons(); break; case OPPONENT_NETWORK_PLAYER: game = null; break; default: Log.wtf("GameActivityBase", "Could not start new game: incorrect opponent type"); } findViewById(R.id.game_bar_replay).setVisibility(View.GONE); if (game != null) { redrawGame(game.getGameLogic()); } } @Override protected void onPause() { Log.d("GameActivityBase", "onPause"); if (game != null) { saveCurrentGame(); game.onStop(); } unregisterReceiver(gameLoadedFromServerReceiver); LocalBroadcastManager .getInstance(this) .unregisterReceiver(tokenSentReceiver); super.onPause(); } private class OnSkipTurnListener implements View.OnClickListener { @Override public void onClick(View v) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { if (!game.skipTurn(humanPlayer)) { return null; } return null; } }.execute(); } } private class OnGiveUpListener implements View.OnClickListener { @Override public void onClick(View v) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { game.giveUp(humanPlayer); return null; } }.execute(); } } private class OnBoardClickListener implements View.OnClickListener { private final int x, y; OnBoardClickListener(int x, int y) { this.x = x; this.y = y; } @Override public void onClick(View v) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { game.doTurn(humanPlayer, x, y); return null; } }.execute(); } } private void initButtons() { Button skipTurnButton = (Button) findViewById(R.id.game_button_passturn); skipTurnButton.setOnClickListener(new OnSkipTurnListener()); Button giveUpButton = (Button) findViewById(R.id.game_button_giveup); giveUpButton.setOnClickListener(new OnGiveUpListener()); for (int i = 0; i != BOARD_SIZE; i++) for (int j = 0; j != BOARD_SIZE; j++) { boardButtons[i][j].setOnClickListener(new OnBoardClickListener(i, j)); } } @Override protected void onStop() { super.onStop(); } protected void onResume() { super.onResume(); new StoredGameLoader().execute(); gameLoadedFromServerReceiver = new GameLoadedFromServerReceiver(); registerReceiver(gameLoadedFromServerReceiver, new IntentFilter(WoVPreferences.GAME_LOADED_FROM_SERVER_BROADCAST)); LocalBroadcastManager .getInstance(this) .registerReceiver(tokenSentReceiver, new IntentFilter(WoVPreferences.GCM_REGISTRATION_COMPLETE)); } private void setCurrentGameListeners() { game.setOnGameFinishedListener(new Game.OnGameFinishedListener() { @Override public void onGameFinished() { saveCurrentGame(); } }); } private void saveCurrentGame() { new AsyncTask<Game, Void, Void> (){ @Override protected Void doInBackground(Game... params) { for (Game game : params) { //actually, there is only one game DBOpenHelper.getInstance(GameActivity.this).addGame(game); } return null; } }.execute(game); } private final class StoredGameLoader extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { Game loadedGame = DBOpenHelper.getInstance(GameActivity.this).getActiveGame(); if (loadedGame == null) { Log.d("GameActivity", "FAIL: Null game loaded"); } else { Log.d("GameActivity", "OK: game loaded"); game = loadedGame; if (game.getCrossPlayer() instanceof HumanPlayer) { ((HumanPlayer) game.getCrossPlayer()).setOnGameStateChangedListener(ON_GAME_STATE_CHANGED_LISTENER); } else if (game.getZeroPlayer() instanceof HumanPlayer) { ((HumanPlayer) game.getZeroPlayer()).setOnGameStateChangedListener(ON_GAME_STATE_CHANGED_LISTENER); } //it's a dirty hack, don't know how to do better } return null; } @Override protected void onPostExecute(Void aVoid) { if (game != null) { onGameLoaded(game); } } } private class GameLoadedFromServerReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d("GameActivity", "networkLoadGame broadcast recieved!"); Bundle tmp = intent.getBundleExtra(WoVPreferences.GAME_BUNDLE); String data = tmp.getString(WoVProtocol.DATA); JsonObject jsonData = (JsonObject) new JsonParser().parse(data); User cross = gson.fromJson(jsonData.get(WoVProtocol.CROSS_USER), User.class); User zero = gson.fromJson(jsonData.get(WoVProtocol.ZERO_USER), User.class); DBOpenHelper.getInstance(GameActivity.this).addUser(cross); DBOpenHelper.getInstance(GameActivity.this).addUser(zero); GameLogic.PlayerFigure myFigure = gson.fromJson(jsonData.get(WoVProtocol.MY_FIGURE), GameLogic.PlayerFigure.class); Player playerCross, playerZero; switch (myFigure) { case CROSS: playerZero = new ClientNetworkPlayer(cross, GameLogic.PlayerFigure.ZERO, GameActivity.this); playerCross = humanPlayer = new HumanPlayer(zero, GameLogic.PlayerFigure.CROSS); break; case ZERO: playerCross = new ClientNetworkPlayer(cross, GameLogic.PlayerFigure.CROSS, GameActivity.this); playerZero = humanPlayer = new HumanPlayer(zero, GameLogic.PlayerFigure.ZERO); break; default: throw new IllegalArgumentException("Illegal myFigure value!"); } List<GameEvent> events = (WoVProtocol.getEventsFromIntArray(gson.fromJson(jsonData.get(WoVProtocol.TURN_ARRAY), int[].class))); humanPlayer.setOnGameStateChangedListener(ON_GAME_STATE_CHANGED_LISTENER); int crossType = myFigure == GameLogic.PlayerFigure.CROSS ? 0 : 2; int zeroType = 2 - crossType; //fixme remove magic constants game = Game.deserializeGame(gson.fromJson(jsonData.get(WoVProtocol.GAME_ID), int.class), playerCross, crossType, playerZero, zeroType, GameLogic.deserialize(events)); initButtons(); redrawGame(game.getGameLogic()); } } @Override protected void onStart() { super.onStart(); } private void onGameLoaded(Game game) { this.game = game; game.updateGameInfo(); setCurrentGameListeners(); initButtons(); redrawGame(game.getGameLogic()); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } if (id == R.id.test2) { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg; try { GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(GameActivity.this); Bundle data = new Bundle(); data.putString(WoVProtocol.ACTION, WoVProtocol.ACTION_PING); String id = UUID.randomUUID().toString(); gcm.send(getString(R.string.gcm_defaultSenderId) + "@gcm.googleapis.com", id, data); msg = "Sent message"; } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { if (msg == null) return; Toast.makeText(GameActivity.this, msg, Toast.LENGTH_SHORT).show(); } }.execute(null, null, null); return true; } return super.onOptionsItemSelected(item); } }
package org.wikipedia.history; import android.content.Context; import android.content.DialogInterface; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.view.ActionMode; import android.text.Editable; import android.text.TextWatcher; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import org.wikipedia.BackPressedHandler; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.database.CursorAdapterLoaderCallback; import org.wikipedia.database.contract.PageHistoryContract; import org.wikipedia.page.PageActivity; import org.wikipedia.views.ViewUtil; import java.text.DateFormat; import java.util.Date; import static org.wikipedia.Constants.HISTORY_FRAGMENT_LOADER_ID; import static org.wikipedia.util.DimenUtil.getContentTopOffsetPx; public class HistoryFragment extends Fragment implements BackPressedHandler { private ListView historyEntryList; private View historyEmptyContainer; private TextView historyEmptyTitle; private TextView historyEmptyMessage; private HistoryEntryAdapter adapter; private EditText entryFilter; private WikipediaApp app; private LoaderCallback callback; private ActionMode actionMode; private HistorySearchTextWatcher textWatcher = new HistorySearchTextWatcher(); private HistoryItemClickListener itemClickListener = new HistoryItemClickListener(); private HistoryItemLongClickListener itemLongClickListener = new HistoryItemLongClickListener(); private boolean firstRun = true; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); app = WikipediaApp.getInstance(); adapter = new HistoryEntryAdapter(getContext(), null, true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_history, container, false); rootView.setPadding(0, getContentTopOffsetPx(getActivity()), 0, 0); historyEntryList = (ListView) rootView.findViewById(R.id.history_entry_list); historyEmptyContainer = rootView.findViewById(R.id.history_empty_container); historyEmptyTitle = (TextView) rootView.findViewById(R.id.history_empty_title); historyEmptyMessage = (TextView) rootView.findViewById(R.id.history_empty_message); entryFilter = (EditText) rootView.findViewById(R.id.history_search_list); app.adjustDrawableToTheme(((ImageView) rootView.findViewById(R.id.history_empty_image)).getDrawable()); entryFilter.addTextChangedListener(textWatcher); historyEntryList.setAdapter(adapter); historyEntryList.setOnItemClickListener(itemClickListener); historyEntryList.setOnItemLongClickListener(itemLongClickListener); callback = new LoaderCallback(getContext(), adapter); getActivity().getSupportLoaderManager().initLoader(HISTORY_FRAGMENT_LOADER_ID, null, callback); return rootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); historyEntryList.setEmptyView(historyEmptyContainer); } @Override public void onDestroyView() { getActivity().getSupportLoaderManager().destroyLoader(HISTORY_FRAGMENT_LOADER_ID); entryFilter.removeTextChangedListener(textWatcher); historyEntryList.setOnItemClickListener(null); historyEntryList.setOnItemLongClickListener(null); historyEntryList.setAdapter(null); super.onDestroyView(); } @Override public boolean onBackPressed() { if (actionMode != null) { actionMode.finish(); return true; } return false; } private class HistoryEntryAdapter extends CursorAdapter { HistoryEntryAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); } @Override public View newView(Context context, Cursor cursor, ViewGroup viewGroup) { View view = getActivity().getLayoutInflater().inflate(R.layout.item_page_list_entry, viewGroup, false); view.setBackgroundResource(R.drawable.selectable_item_background); return view; } private String getDateString(Date date) { return DateFormat.getDateInstance().format(date); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView title = (TextView) view.findViewById(R.id.page_list_item_title); HistoryEntry entry = HistoryEntry.DATABASE_TABLE.fromCursor(cursor); title.setText(entry.getTitle().getDisplayText()); view.setTag(entry); ViewUtil.loadImageUrlInto((SimpleDraweeView) view.findViewById(R.id.page_list_item_image), PageHistoryContract.PageWithImage.IMAGE_NAME.val(cursor)); // Check the previous item, see if the times differ enough // If they do, display the section header. // Always do it this is the first item. String curTime, prevTime = ""; if (cursor.getPosition() != 0) { Cursor prevCursor = (Cursor) getItem(cursor.getPosition() - 1); HistoryEntry prevEntry = HistoryEntry.DATABASE_TABLE.fromCursor(prevCursor); prevTime = getDateString(prevEntry.getTimestamp()); } curTime = getDateString(entry.getTimestamp()); TextView sectionHeader = (TextView) view.findViewById(R.id.page_list_header_text); if (!curTime.equals(prevTime)) { sectionHeader.setText(curTime); sectionHeader.setVisibility(View.VISIBLE); } else { sectionHeader.setVisibility(View.GONE); } } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (!isMenuToBeSetUp()) { return; } inflater.inflate(R.menu.menu_history, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (!isMenuToBeSetUp()) { return; } boolean isHistoryAvailable = historyEntryList.getCount() > 0; menu.findItem(R.id.menu_clear_all_history) .setVisible(isHistoryAvailable) .setEnabled(isHistoryAvailable); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_clear_all_history: new AlertDialog.Builder(getActivity()) .setTitle(R.string.dialog_title_clear_history) .setMessage(R.string.dialog_message_clear_history) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Clear history! new DeleteAllHistoryTask(app).execute(); entryFilter.setVisibility(View.GONE); ((PageActivity) getActivity()).resetAfterClearHistory(); } }) .setNegativeButton(R.string.no, null).create().show(); return true; default: return super.onOptionsItemSelected(item); } } private class HistoryItemClickListener implements AdapterView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (actionMode == null) { HistoryEntry oldEntry = (HistoryEntry) view.getTag(); HistoryEntry newEntry = new HistoryEntry(oldEntry.getTitle(), HistoryEntry.SOURCE_HISTORY); ((PageActivity) getActivity()).loadPage(oldEntry.getTitle(), newEntry); } } } private boolean isMenuToBeSetUp() { return isAdded() && !((PageActivity)getActivity()).isSearching(); } private class HistoryItemLongClickListener implements AdapterView.OnItemLongClickListener { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (actionMode != null) { return false; } historyEntryList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); actionMode = ((AppCompatActivity)getActivity()).startSupportActionMode(new ActionMode.Callback() { private final String actionModeTag = "actionModeHistory"; @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(R.menu.menu_history_context, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { mode.setTag(actionModeTag); return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { if (item.getItemId() == R.id.menu_delete_selected_history) { SparseBooleanArray checkedItems = historyEntryList.getCheckedItemPositions(); for (int i = 0; i < checkedItems.size(); i++) { if (checkedItems.valueAt(i)) { app.getDatabaseClient(HistoryEntry.class).delete( HistoryEntry.DATABASE_TABLE.fromCursor((Cursor) adapter.getItem(checkedItems.keyAt(i))), PageHistoryContract.PageWithImage.SELECTION); } } if (checkedItems.size() == historyEntryList.getAdapter().getCount()) { entryFilter.setVisibility(View.GONE); } mode.finish(); return true; } else { throw new RuntimeException("Unknown context menu item clicked"); } } @Override public void onDestroyActionMode(ActionMode mode) { historyEntryList.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); actionMode = null; // Clear all selections historyEntryList.clearChoices(); historyEntryList.requestLayout(); // Required to immediately redraw unchecked states } }); historyEntryList.setItemChecked(position, true); return true; } } private class HistorySearchTextWatcher implements TextWatcher { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { // Do nothing } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { // Do nothing } @Override public void afterTextChanged(Editable editable) { getActivity().getSupportLoaderManager().restartLoader(HISTORY_FRAGMENT_LOADER_ID, null, callback); if (editable.length() == 0) { historyEmptyTitle.setText(R.string.history_empty_title); historyEmptyMessage.setVisibility(View.VISIBLE); } else { historyEmptyTitle.setText(getString(R.string.history_search_empty_message, editable.toString())); historyEmptyMessage.setVisibility(View.GONE); } } } private class LoaderCallback extends CursorAdapterLoaderCallback { LoaderCallback(@NonNull Context context, @NonNull CursorAdapter adapter) { super(context, adapter); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { String titleCol = PageHistoryContract.PageWithImage.TITLE.qualifiedName(); String selection = null; String[] selectionArgs = null; historyEmptyContainer.setVisibility(View.GONE); String searchStr = entryFilter.getText().toString(); if (!searchStr.isEmpty()) { searchStr = searchStr.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_"); selection = "UPPER(" + titleCol + ") LIKE UPPER(?) ESCAPE '\\'"; selectionArgs = new String[]{"%" + searchStr + "%"}; } Uri uri = PageHistoryContract.PageWithImage.URI; final String[] projection = null; String order = PageHistoryContract.PageWithImage.ORDER_MRU; return new CursorLoader(context(), uri, projection, selection, selectionArgs, order); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { super.onLoadFinished(cursorLoader, cursor); if (!isAdded()) { return; } // Hide search bar if history is empty, but not when a search turns up no results if (firstRun && cursor.getCount() == 0) { entryFilter.setVisibility(View.GONE); } firstRun = false; getActivity().supportInvalidateOptionsMenu(); } } }
package pe.edu.unitek.eventosapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button mi_boton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mi_boton = (Button) findViewById(R.id.button); mi_boton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } }
package org.commcare.android.adapters; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import net.sqlcipher.database.SQLiteDatabase; import org.commcare.android.models.AsyncNodeEntityFactory; import org.commcare.android.models.Entity; import org.commcare.android.models.NodeEntityFactory; import org.commcare.android.models.notifications.NotificationMessageFactory; import org.commcare.android.models.notifications.NotificationMessageFactory.StockMessages; import org.commcare.android.util.CachingAsyncImageLoader; import org.commcare.android.util.SessionUnavailableException; import org.commcare.android.util.StringUtils; import org.commcare.android.view.EntityView; import org.commcare.android.view.GridEntityView; import org.commcare.android.view.GridMediaView; import org.commcare.android.view.HorizontalMediaView; import org.commcare.dalvik.R; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.preferences.CommCarePreferences; import org.commcare.suite.model.Detail; import org.commcare.suite.model.DetailField; import org.javarosa.core.model.Constants; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.services.Logger; import org.javarosa.xpath.XPathTypeMismatchException; import org.javarosa.xpath.expr.XPathFuncExpr; import org.odk.collect.android.views.media.AudioController; import android.app.Activity; import android.database.DataSetObserver; import android.speech.tts.TextToSpeech; import android.util.Pair; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; /** * @author ctsims * @author wspride * * This adapter class handles displaying the cases for a CommCareODK user. * Depending on the <grid> block of the Detail this adapter is constructed with, cases might be * displayed as normal EntityViews or as AdvancedEntityViews */ public class EntityListAdapter implements ListAdapter { public static final int SPECIAL_ACTION = -2; private int actionPosition = -1; private boolean actionEnabled; private boolean mFuzzySearchEnabled = true; Activity context; Detail detail; List<DataSetObserver> observers; List<Entity<TreeReference>> full; List<Entity<TreeReference>> current; List<TreeReference> references; TextToSpeech tts; AudioController controller; private TreeReference selected; private boolean hasWarned; int currentSort[] = {}; boolean reverseSort = false; private NodeEntityFactory mNodeFactory; boolean mAsyncMode = false; private String[] currentSearchTerms; EntitySearcher mCurrentSortThread = null; Object mSyncLock = new Object(); public static int SCALE_FACTOR = 1; // How much we want to degrade the image quality to enable faster laoding. TODO: get cleverer private CachingAsyncImageLoader mImageLoader; // Asyncronous image loader, allows rows with images to scroll smoothly private boolean usesGridView = false; // false until we determine the Detail has at least one <grid> block private boolean inAwesomeMode = false; public EntityListAdapter(Activity activity, Detail detail, List<TreeReference> references, List<Entity<TreeReference>> full, int[] sort, TextToSpeech tts, AudioController controller, NodeEntityFactory factory) throws SessionUnavailableException { this.detail = detail; actionEnabled = detail.getCustomAction() != null; this.full = full; setCurrent(new ArrayList<Entity<TreeReference>>()); this.references = references; this.context = activity; this.observers = new ArrayList<DataSetObserver>(); mNodeFactory = factory; //TODO: I am a bad person and I should feel bad. This should get encapsulated //somewhere in the factory as a callback (IE: How to sort/or whether to or something) mAsyncMode= (factory instanceof AsyncNodeEntityFactory); //TODO: Maybe we can actually just replace by checking whether the node is ready? if(!mAsyncMode) { if(sort.length != 0) { sort(sort); } filterValues(""); } else { setCurrent(new ArrayList<Entity<TreeReference>>(full)); } this.tts = tts; this.controller = controller; if(android.os.Build.VERSION.SDK_INT >= 14){ mImageLoader = new CachingAsyncImageLoader(context, SCALE_FACTOR); } else{ mImageLoader = null; } if(detail.getCustomAction() != null) { } usesGridView = detail.usesGridView(); this.mFuzzySearchEnabled = CommCarePreferences.isFuzzySearchEnabled(); } /** * Set the current display set for this adapter * * @param arrayList */ private void setCurrent(List<Entity<TreeReference>> arrayList) { current = arrayList; if(actionEnabled) { actionPosition = current.size(); } } private void filterValues(String filterRaw) { this.filterValues(filterRaw, false); } private void filterValues(String filterRaw, boolean synchronous) { synchronized(mSyncLock) { if(mCurrentSortThread != null) { mCurrentSortThread.finish(); } String[] searchTerms = filterRaw.split("\\s+"); for(int i = 0 ; i < searchTerms.length ; ++i) { searchTerms[i] = StringUtils.normalize(searchTerms[i]); } mCurrentSortThread = new EntitySearcher(filterRaw, searchTerms); mCurrentSortThread.startThread(); //In certain circumstances we actually want to wait for that filter //to finish if(synchronous) { try { mCurrentSortThread.thread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } private class EntitySearcher { private String filterRaw; private String[] searchTerms; List<Entity<TreeReference>> matchList; //Ugh, annoying. ArrayList<Pair<Integer, Integer>> matchScores; private boolean cancelled = false; Thread thread; public EntitySearcher(String filterRaw, String[] searchTerms) { this.filterRaw = filterRaw; this.searchTerms = searchTerms; matchList = new ArrayList<Entity<TreeReference>>(); matchScores = new ArrayList<Pair<Integer, Integer>>(); } public void startThread() { thread = new Thread(new Runnable() { @Override public void run() { //Make sure that we have loaded the necessary cached data //before we attempt to search over it while(!mNodeFactory.isEntitySetReady()) { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } search(); } }); thread.start(); } public void finish() { this.cancelled = true; try { thread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void search() { Locale currentLocale = Locale.getDefault(); long startTime = System.currentTimeMillis(); //It's a bit sketchy here, because this DB lock will prevent //anything else from processing SQLiteDatabase db = CommCareApplication._().getUserDbHandle(); db.beginTransaction(); full: for(int index = 0 ; index < full.size() ; ++index) { //Every once and a while we should make sure we're not blocking anything with the database if(index % 500 == 0) { db.yieldIfContendedSafely(); } Entity<TreeReference> e = full.get(index); if(cancelled) { break; } if("".equals(filterRaw)) { matchList.add(e); continue; } boolean add = false; int score = 0; filter: for(String filter: searchTerms) { add = false; for(int i = 0 ; i < e.getNumFields(); ++i) { String field = e.getNormalizedField(i); if(field != "" && field.toLowerCase(currentLocale).contains(filter)) { add = true; continue filter; } else { // We possibly now want to test for edit distance for // fuzzy matching if (mFuzzySearchEnabled) { for (String fieldChunk : e.getSortFieldPieces(i)) { Pair<Boolean, Integer> match = StringUtils.fuzzyMatch(fieldChunk, filter); if (match.first) { add = true; score += match.second; continue filter; } } } } } if (!add) { break; } } if(add) { //matchList.add(e); matchScores.add(Pair.create(index, score)); continue full; } } if(mAsyncMode) { Collections.sort(matchScores, new Comparator<Pair<Integer, Integer>>() { @Override public int compare(Pair<Integer, Integer> lhs, Pair<Integer, Integer> rhs) { return lhs.second - rhs.second; } }); } for(Pair<Integer, Integer> match : matchScores) { matchList.add(full.get(match.first)); } db.setTransactionSuccessful(); db.endTransaction(); if(cancelled) { return; } long time = System.currentTimeMillis() - startTime; if(time > 1000) { Logger.log("cache", "Presumably finished caching new entities, time taken: " + time + "ms"); } context.runOnUiThread(new Runnable() { @Override public void run() { setCurrent(matchList); currentSearchTerms = searchTerms; update(); } }); } } private void sort(int[] fields) { //The reversing here is only relevant if there's only one sort field and we're on it sort(fields, (currentSort.length == 1 && currentSort[0] == fields[0]) ? !reverseSort : false); } private void sort(int[] fields, boolean reverse) { this.reverseSort = reverse; hasWarned = false; currentSort = fields; java.util.Collections.sort(full, new Comparator<Entity<TreeReference>>() { public int compare(Entity<TreeReference> object1, Entity<TreeReference> object2) { for(int i = 0 ; i < currentSort.length ; ++i) { boolean reverseLocal = (detail.getFields()[currentSort[i]].getSortDirection() == DetailField.DIRECTION_DESCENDING) ^ reverseSort; int cmp = (reverseLocal ? -1 : 1) * getCmp(object1, object2, currentSort[i]); if(cmp != 0 ) { return cmp;} } return 0; } private int getCmp(Entity<TreeReference> object1, Entity<TreeReference> object2, int index) { int sortType = detail.getFields()[index].getSortType(); String a1 = object1.getSortField(index); String a2 = object2.getSortField(index); // COMMCARE-161205: Problem with search functionality // If one of these is null, we need to get the field in the same index, not the field in SortType if(a1 == null) { a1 = object1.getFieldString(index); } if(a2 == null) { a2 = object2.getFieldString(index); } //TODO: We might want to make this behavior configurable (Blanks go first, blanks go last, etc); //For now, regardless of typing, blanks are always smaller than non-blanks if(a1.equals("")) { if(a2.equals("")) { return 0; } else { return -1; } } else if(a2.equals("")) { return 1; } Comparable c1 = applyType(sortType, a1); Comparable c2 = applyType(sortType, a2); if(c1 == null || c2 == null) { //Don't do something smart here, just bail. return -1; } return c1.compareTo(c2); } private Comparable applyType(int sortType, String value) { try { if(sortType == Constants.DATATYPE_TEXT) { return value.toLowerCase(); } else if(sortType == Constants.DATATYPE_INTEGER) { //Double int compares just fine here and also //deals with NaN's appropriately double ret = XPathFuncExpr.toInt(value); if(Double.isNaN(ret)){ String[] stringArgs = new String[3]; stringArgs[2] = value; if(!hasWarned){ CommCareApplication._().reportNotificationMessage(NotificationMessageFactory.message(StockMessages.Bad_Case_Filter, stringArgs)); hasWarned = true; } } return ret; } else if(sortType == Constants.DATATYPE_DECIMAL) { double ret = XPathFuncExpr.toDouble(value); if(Double.isNaN(ret)){ String[] stringArgs = new String[3]; stringArgs[2] = value; if(!hasWarned){ CommCareApplication._().reportNotificationMessage(NotificationMessageFactory.message(StockMessages.Bad_Case_Filter, stringArgs)); hasWarned = true; } } return ret; } else { //Hrmmmm :/ Handle better? return value; } } catch(XPathTypeMismatchException e) { //So right now this will fail 100% silently, which is bad. return null; } } }); } /* (non-Javadoc) * @see android.widget.ListAdapter#areAllItemsEnabled() */ public boolean areAllItemsEnabled() { return true; } /* (non-Javadoc) * @see android.widget.ListAdapter#isEnabled(int) */ public boolean isEnabled(int position) { return true; } /* * Includes action, if enabled, as an item. * * (non-Javadoc) * @see android.widget.Adapter#getCount() */ public int getCount() { return getCount(false, false); } /* * Returns total number of items, ignoring any filter. */ public int getFullCount() { return getCount(false, true); } /* * Get number of items, with a parameter to decide whether or not action counts as an item. */ public int getCount(boolean ignoreAction, boolean fullCount) { //Always one extra element if the action is defined return (fullCount ? full.size() : current.size()) + (actionEnabled && !ignoreAction ? 1 : 0); } /* (non-Javadoc) * @see android.widget.Adapter#getItem(int) */ public TreeReference getItem(int position) { return current.get(position).getElement(); } /* (non-Javadoc) * @see android.widget.Adapter#getItemId(int) */ public long getItemId(int position) { if(actionEnabled) { if(position == actionPosition) { return SPECIAL_ACTION; } } return references.indexOf(current.get(position).getElement()); } /* (non-Javadoc) * @see android.widget.Adapter#getItemViewType(int) */ public int getItemViewType(int position) { if(actionEnabled) { if(position == actionPosition) { return 1; } } return 0; } public void setController(AudioController controller) { this.controller = controller; } /* (non-Javadoc) * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup) */ /* Note that position gives a unique "row" id, EXCEPT that the header row AND the first content row * are both assigned position 0 -- this is not an issue for current usage, but it could be in future */ public View getView(int position, View convertView, ViewGroup parent) { if(actionEnabled && position == actionPosition) { HorizontalMediaView tiav =(HorizontalMediaView)convertView; if(tiav == null) { tiav = new HorizontalMediaView(context); } tiav.setDisplay(detail.getCustomAction().getDisplay()); tiav.setBackgroundResource(R.drawable.list_bottom_tab); //We're gonna double pad this because we want to give it some visual distinction //and keep the icon more centered int padding = (int) context.getResources().getDimension(R.dimen.entity_padding); tiav.setPadding(padding, padding, padding, padding); return tiav; } Entity<TreeReference> entity = current.get(position); // if we use a <grid>, setup an AdvancedEntityView if(usesGridView){ GridEntityView emv =(GridEntityView)convertView; if(emv == null) { emv = new GridEntityView(context, detail, entity, currentSearchTerms, mImageLoader, controller, mFuzzySearchEnabled); } else{ emv.setSearchTerms(currentSearchTerms); emv.setViews(context, detail, entity); } return emv; } // if not, just use the normal row else{ EntityView emv =(EntityView)convertView; if (emv == null) { emv = new EntityView(context, detail, entity, tts, currentSearchTerms, controller, position, mFuzzySearchEnabled); } else { emv.setSearchTerms(currentSearchTerms); emv.refreshViewsForNewEntity(entity, entity.getElement().equals(selected), position); } return emv; } } /* (non-Javadoc) * @see android.widget.Adapter#getViewTypeCount() */ public int getViewTypeCount() { return actionEnabled? 2 : 1; } /* (non-Javadoc) * @see android.widget.Adapter#hasStableIds() */ public boolean hasStableIds() { return true; } /* (non-Javadoc) * @see android.widget.Adapter#isEmpty() */ public boolean isEmpty() { return getCount() > 0; } public void applyFilter(String s) { filterValues(s); } private void update() { for(DataSetObserver o : observers) { o.onChanged(); } } public void sortEntities(int[] keys) { sort(keys); } public int[] getCurrentSort() { return currentSort; } public boolean isCurrentSortReversed() { return reverseSort; } /* (non-Javadoc) * @see android.widget.Adapter#registerDataSetObserver(android.database.DataSetObserver) */ public void registerDataSetObserver(DataSetObserver observer) { this.observers.add(observer); } /* (non-Javadoc) * @see android.widget.Adapter#unregisterDataSetObserver(android.database.DataSetObserver) */ public void unregisterDataSetObserver(DataSetObserver observer) { this.observers.remove(observer); } public void notifyCurrentlyHighlighted(TreeReference chosen) { this.selected = chosen; update(); } public void setAwesomeMode(boolean awesome){ inAwesomeMode = awesome; } public int getPosition(TreeReference chosen) { for(int i = 0 ; i < current.size() ; ++i) { Entity<TreeReference> e = current.get(i); if(e.getElement().equals(chosen)) { return i; } } return -1; } /** * Signal that this adapter is dying. If we are doing any asynchronous work, * we need to stop doing so. */ public void signalKilled() { synchronized(mSyncLock) { if(mCurrentSortThread != null) { mCurrentSortThread.finish(); } } } }
package com.i906.mpt.internal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; /** * @author Noorzaini Ilhami */ @Module class OkHttpModule { @Provides @Singleton @Named("data") List<Interceptor> provideOkHttpInterceptors() { List<Interceptor> list = new ArrayList<>(); list.add(new HeaderInterceptor()); return list; } @Provides @Singleton @Named("network") List<Interceptor> provideOkHttpNetworkInterceptors() { return Collections.emptyList(); } }
package com.wemater.dao; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.hibernate.HibernateException; import com.wemater.exception.DataNotFoundException; import com.wemater.exception.DataNotInsertedException; import com.wemater.exception.EvaluateException; import com.wemater.util.SessionUtil; public class GenericDaoImpl<T,Id extends Serializable> implements GenericDao<T, Id> { private final SessionUtil sessionUtil; private Class<T> type; //inject sessionUtil object at the runtime to use the session and type of class at runtime public GenericDaoImpl(SessionUtil sessionUtil, Class<T> type) { this.sessionUtil = sessionUtil; this.type = type; } public SessionUtil getSessionUtil() throws InstantiationException { if (sessionUtil == null) throw new InstantiationException("SessionUtil has not been set on DAO before usage"); return sessionUtil; } @Override public long save(T entity) { Long id = null; try { sessionUtil.beginSessionWithTransaction(); id = (Long) sessionUtil.getSession().save(entity); sessionUtil.CommitCurrentTransaction(); } catch (RuntimeException e) { sessionUtil.rollBackCurrentTransaction(); throw new DataNotInsertedException("400","NaturalId already present"); } return id; } @Override public void update(T entity) { try { sessionUtil.beginSessionWithTransaction(); sessionUtil.getSession().update(entity); sessionUtil.CommitCurrentTransaction(); } catch (RuntimeException e) { sessionUtil.rollBackCurrentTransaction(); throw new EvaluateException(e); } } @SuppressWarnings("unchecked") @Override public List<T> findAll() { List<T> entityList = new ArrayList<T>(); try { sessionUtil.beginSessionWithTransaction(); entityList= sessionUtil.getSession().createQuery("from "+type.getSimpleName()) .list(); if(entityList.isEmpty()) throw new DataNotFoundException("404", "No "+type.getSimpleName()+"'s present "); sessionUtil.CommitCurrentTransaction(); } catch ( RuntimeException e) { sessionUtil.rollBackCurrentTransaction(); throw new EvaluateException(e); } return entityList; } @SuppressWarnings("unchecked") @Override public T find(Id id) { T entity = null; try { sessionUtil.beginSessionWithTransaction(); entity = (T) sessionUtil.getSession().get(type, id); if(entity == null) throw new DataNotFoundException("404", type.getSimpleName()+" not found"); sessionUtil.CommitCurrentTransaction(); } catch (RuntimeException e) { sessionUtil.rollBackCurrentTransaction(); System.out.println("inside the catch find by id"); throw new EvaluateException(e); } return entity; } @SuppressWarnings("unchecked") @Override public T find(String naturalId) { T entity = null; try { sessionUtil.beginSessionWithTransaction(); entity = (T) sessionUtil.getSession().bySimpleNaturalId(type).load(naturalId); if(entity == null) throw new DataNotFoundException("404", type.getSimpleName()+" not found"); sessionUtil.CommitCurrentTransaction(); } catch (RuntimeException e) { sessionUtil.rollBackCurrentTransaction(); System.out.println("inside the catch find natural id"); throw new EvaluateException(e); } return entity; } @Override public void delete(T entity) { try { sessionUtil.beginSessionWithTransaction(); sessionUtil.getSession().delete(entity); sessionUtil.CommitCurrentTransaction(); } catch (HibernateException e) { sessionUtil.rollBackCurrentTransaction(); throw new EvaluateException(e); } } /// write new here. use the HQl query and insert the parameter and type.getsimplename @Override public void deleteAll() { System.out.println("delete all wont work"); } }
package org.basex.server; import static org.junit.Assert.*; import java.io.*; import org.basex.*; import org.basex.core.cmd.*; import org.basex.util.*; import org.junit.*; public final class SemaphoreTest extends SandboxTest { /** Test file. */ private static final String FILE = "src/test/resources/factbook.zip"; /** Test queries. */ private static final String [] QUERIES = { "(db:open('" + NAME + "')//province)[position() < 10] ! (insert node <test/> into .)", "(1 to 100000)[. = 0]" }; /** Number of clients. */ private static final int CLIENTS = 50; /** Server reference. */ private BaseXServer server; /** Socket reference. */ private Session sess; /** * Starts the server. * @throws IOException exception */ @Before public void start() throws IOException { server = createServer(); sess = createClient(); sess.execute(new CreateDB(NAME, FILE)); } /** * Stops the server. * @throws Exception exception */ @After public void stop() throws Exception { sess.execute(new DropDB(NAME)); sess.close(); stopServer(server); } /** * Efficiency test. * @throws Exception exception */ @Test public void runClients() throws Exception { final Client[] cl = new Client[CLIENTS]; for(int i = 0; i < CLIENTS; ++i) cl[i] = new Client(i); for(final Client c : cl) c.start(); for(final Client c : cl) c.join(); for(final Client c : cl) c.session.close(); } /** Single client. */ static class Client extends Thread { /** Client session. */ ClientSession session; /** Query number. */ final int number; /** * Default constructor. * @param nr query number */ Client(final int nr) { number = nr; try { session = createClient(); } catch(final IOException ex) { fail(Util.message(ex)); } } @Override public void run() { try { session.query(QUERIES[number % QUERIES.length]).execute(); } catch(final IOException ex) { fail(Util.message(ex)); } } } }
package com.dianping.bee.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.site.lookup.ComponentTestCase; /** * @author <a href="mailto:yiming.liu@dianping.com">Yiming Liu</a> */ @RunWith(JUnit4.class) public class JDBCTest extends ComponentTestCase { @Test public void testConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { Connection conn = null; String url = "jdbc:mysql://127.0.0.1:2330/"; String dbName = "cat"; String driver = "com.mysql.jdbc.Driver"; String userName = "test"; String password = "test"; Class.forName(driver).newInstance(); DriverManager.setLoginTimeout(600); conn = DriverManager.getConnection(url + dbName, userName, password); Assert.assertNotNull(conn); Assert.assertFalse(conn.isClosed()); conn.close(); Assert.assertTrue(conn.isClosed()); } @Test public void testSingleQuery() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { String url = "jdbc:mysql://localhost:2330/"; String dbName = "cat"; String driver = "com.mysql.jdbc.Driver"; String userName = "test"; String password = "test"; Class.forName(driver).newInstance(); DriverManager.setLoginTimeout(600); Connection conn = DriverManager.getConnection(url + dbName, userName, password); Statement stmt = conn.createStatement(); Assert.assertNotNull(stmt); ResultSet rs = stmt.executeQuery("select type, sum(failures) from transaction where domain=? and starttime=?"); Assert.assertEquals(2, rs.getMetaData().getColumnCount()); Assert.assertNotNull(rs); rs.last(); Assert.assertTrue(rs.getRow() > 0); displayResultSet(rs); conn.close(); } @Test public void testMultiQueryInSameDatabase() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { String url = "jdbc:mysql://localhost:2330/"; String dbName = "cat"; String driver = "com.mysql.jdbc.Driver"; String userName = "test"; String password = "test"; Class.forName(driver).newInstance(); DriverManager.setLoginTimeout(600); Connection conn = DriverManager.getConnection(url + dbName, userName, password); Statement stmt1 = conn.createStatement(); Assert.assertNotNull(stmt1); ResultSet rs1 = stmt1.executeQuery("select type, sum(failures) from transaction where domain=? and starttime=?"); Assert.assertEquals(2, rs1.getMetaData().getColumnCount()); Assert.assertNotNull(rs1); rs1.last(); Assert.assertTrue(rs1.getRow() > 0); displayResultSet(rs1); Statement stmt2 = conn.createStatement(); Assert.assertNotNull(stmt2); ResultSet rs2 = stmt2.executeQuery("select type,sum(failures) from event"); Assert.assertEquals(2, rs2.getMetaData().getColumnCount()); Assert.assertNotNull(rs2); rs2.last(); Assert.assertTrue(rs2.getRow() > 0); displayResultSet(rs2); conn.close(); } @Test public void testMultiQueryInMultiDatabaese() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { String url = "jdbc:mysql://localhost:2330/"; String dbName = "cat"; String driver = "com.mysql.jdbc.Driver"; String userName = "test"; String password = "test"; Class.forName(driver).newInstance(); DriverManager.setLoginTimeout(600); Connection conn1 = DriverManager.getConnection(url + dbName, userName, password); Statement stmt1 = conn1.createStatement(); Assert.assertNotNull(stmt1); ResultSet rs1 = stmt1.executeQuery("select type, sum(failures) from transaction where domain=? and starttime=?"); Assert.assertEquals(2, rs1.getMetaData().getColumnCount()); Assert.assertNotNull(rs1); rs1.last(); Assert.assertTrue(rs1.getRow() > 0); displayResultSet(rs1); conn1.close(); dbName = "dog"; Connection conn2 = DriverManager.getConnection(url + dbName, userName, password); Statement stmt2 = conn2.createStatement(); Assert.assertNotNull(stmt2); ResultSet rs2 = stmt2.executeQuery("select type, sum(failures) from transaction where domain=? and starttime=?"); Assert.assertEquals(2, rs2.getMetaData().getColumnCount()); Assert.assertNotNull(rs2); rs2.last(); Assert.assertTrue(rs2.getRow() > 0); displayResultSet(rs2); conn2.close(); } private void displayResultSet(ResultSet rs) throws SQLException { ResultSetMetaData meta = rs.getMetaData(); int columns = meta.getColumnCount(); for (int column = 1; column <= columns; column++) { String columnName = meta.getColumnName(column); System.out.print(columnName + "\t"); } System.out.println(); rs.first(); while (rs.next()) { for (int column = 1; column <= columns; column++) { System.out.print(rs.getString(column) + "\t"); } System.out.println(); } } }
package brix.workspace; import java.util.List; import java.util.Map; public interface WorkspaceManager { public List<Workspace> getWorkspaces(); public List<Workspace> getWorkspacesFiltered(String workspaceName, Map<String, String> workspaceAttributes); public Workspace createWorkspace(); public Workspace getWorkspace(String workspaceId); public void deleteWorkspace(String workspaceId); }
package org.aktin.broker.xml.util; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class Util { public static String readContent(Reader reader) throws IOException{ StringBuilder builder = new StringBuilder(); int c = -1; char[] chars = new char[1024]; do{ c = reader.read(chars, 0, chars.length); //if we have valid chars, append them to end of string. if( c > 0 ){ builder.append(chars, 0, c); } }while(c>0); return builder.toString(); } public static Document parseDocument(Reader reader) throws IOException{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); try { return factory.newDocumentBuilder().parse(new InputSource(reader)); } catch (ParserConfigurationException | SAXException e) { throw new IOException(e); } } public static String formatHttpDate(Instant instant){ // TODO java 7 incompatible return DateTimeFormatter.RFC_1123_DATE_TIME.format(instant.atOffset(ZoneOffset.UTC)); } public static void writeDOM(Node node, OutputStream out, String encoding) throws TransformerException, UnsupportedEncodingException{ writeDOM(node, new OutputStreamWriter(out, encoding), encoding); } public static void writeDOM(Node node, Writer writer, String encoding) throws TransformerException{ TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, encoding); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(new DOMSource(node), new StreamResult(writer)); } }
package test; import com.healthmarketscience.jackcess.DatabaseBuilder; import java.io.*; import com.healthmarketscience.jackcess.*; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; public class Test { private static String[] cages; private static int fromCount; public static void main(String[] args) { fromCount = 0; boolean isDone = false; boolean hasDatabase = false; boolean hasFrom = false; String from = ""; String to = ""; String modify = ""; String fromYear = ""; String fromRange = ""; String[] toCages = new String[10]; String[] toRanges = new String[10]; int[] rangeStart = new int[10]; int[] rangeEnd = new int[10]; int[] capacities = new int[10]; int[] capacityCounter = new int[10]; String[] cagesAtCapacity = new String[10]; int[] cagesAtCapacityAmount = new int[10]; String[] cagesAtCapacityRange = new String[10]; int cagesAtCapacityCounter = 0; int toCounter = 0; DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); Date date = new Date(); String currentDate = dateFormat.format(date); ArrayList<Table> tables = new ArrayList<Table>(); ArrayList<String> totalTables = new ArrayList<String>(); try { initCages(); File file; Database db = null; Table table = null; Table unspecified = null; Table otherTable = null; while (!isDone) { String s = StartWindow.createAndShowGUI(hasDatabase, hasFrom); if (s.equals("add")) { capacityCounter = addEntry(tables, toCages, toRanges, capacities, capacityCounter, unspecified, otherTable, from); for (int i = 0; i < toCages.length; i++) { if (capacities[i] != 0 && capacities[i] == capacityCounter[i]) { cagesAtCapacity[cagesAtCapacityCounter] = toCages[i]; cagesAtCapacityAmount[cagesAtCapacityCounter] = capacities[i]; cagesAtCapacityRange[cagesAtCapacityCounter] = toRanges[i]; cagesAtCapacityCounter++; toCages[i] = null; toRanges[i] = null; rangeStart[i] = 0; rangeEnd[i] = 0; capacities[i] = 0; capacityCounter[i] = 0; tables.remove(i); toCages = stringShift(toCages); toRanges = stringShift(toRanges); rangeStart = intShift(rangeStart); rangeEnd = intShift(rangeEnd); capacities = intShift(capacities); capacityCounter = intShift(capacityCounter); toCounter } } } else if (s.equals("quit")) { isDone = true; } else if (s.equals("new")) { String temp = DatabasePanel.createAndShowGUI(); int index = temp.indexOf('_'); int index2 = temp.indexOf('_', index+1); if (index == 0 || index == temp.length() - 1) { } else { from = temp.substring(0, index); fromYear = temp.substring(index+1, index2); fromRange = temp.substring(index2+1); String name = "Cage" + from + "_Birth" + fromYear + "_" + currentDate; file = new File(name + ".accdb"); db = new DatabaseBuilder(file).setFileFormat(Database.FileFormat.V2000).create(); unspecified = new TableBuilder("Unspecified") .addColumn(new ColumnBuilder("ID", DataType.LONG).setAutoNumber(true)) .addColumn(new ColumnBuilder("Belly", DataType.TEXT)) .toTable(db); otherTable = new TableBuilder("Database") .addColumn(new ColumnBuilder("ID", DataType.LONG).setAutoNumber(true)) .addColumn(new ColumnBuilder("From", DataType.TEXT)) .addColumn(new ColumnBuilder("To", DataType.TEXT)) .addColumn(new ColumnBuilder("Belly", DataType.TEXT)) .toTable(db); hasFrom = true; } } else if (s.equals("to")) { to = GetTo.createAndShowGUI(); if (to.equals(":-:")) { } else { int index = to.indexOf(':'); int index2 = to.indexOf(':', index+1); String range = to.substring(index+1, index2); int index3 = range.indexOf('-'); boolean isRangeValid = true; int start = 0; int end = 0; if (isInteger(range.substring(0,index3))) { start = Integer.parseInt(range.substring(0,index3)); } else { isRangeValid = false; } if (isInteger(range.substring(index3+1))) { end = Integer.parseInt(range.substring(index3+1)); } else { isRangeValid = false; } if (isRangeValid) { for (int i = 0; i < toRanges.length; i++) { for (int j = start; j <= end; j++) { if (j == rangeStart[i] || j == rangeEnd[i]) { isRangeValid = false; } } if (rangeStart[i] == start && rangeEnd[i] == end) { isRangeValid = true; } } } String cage = to.substring(0,index); boolean isCageValid = false; for (int i = 1; i < cages.length; i++) { if (cages[i].equals(cage)) { isCageValid = true; } } String capacity = to.substring(index2+1); boolean isCapacityValid = isInteger(capacity) && (Integer.parseInt(capacity) > 0); boolean tableExists = false; for (int i = 0; i < toCages.length; i++) { if (cage.equals(toCages[i])) { tableExists = true; } } if (isRangeValid && isCageValid && isCapacityValid && !tableExists) { String temp; if (index == 1) { temp = "" + to.charAt(0); } else { temp = to.substring(0, index); } toCages[toCounter] = temp; toRanges[toCounter] = to.substring(index+1, index2); index = toRanges[toCounter].indexOf('-'); rangeStart[toCounter] = Integer.parseInt(toRanges[toCounter].substring(0,index)); rangeEnd[toCounter] = Integer.parseInt(toRanges[toCounter].substring(index+1)); capacities[toCounter] = Integer.parseInt(to.substring(index2+1)); toCounter++; table = new TableBuilder("To pen: " + temp) .addColumn(new ColumnBuilder("ID", DataType.LONG).setAutoNumber(true)) .addColumn(new ColumnBuilder("Belly", DataType.TEXT)) .toTable(db); totalTables.add(temp); tables.add(table); hasDatabase = true; } else { ErrorWindow.createAndShowGUI("Illegal input"); } } } else if (s.equals("modify")) { modify = ModifyTo.createAndShowGUI(toCages, toRanges, capacities); if (!modify.equals("-1")) { int i = Integer.parseInt(modify); toCages[i] = null; toRanges[i] = null; rangeStart[i] = 0; rangeEnd[i] = 0; capacities[i] = 0; capacityCounter[i] = 0; tables.remove(i); toCages = stringShift(toCages); toRanges = stringShift(toRanges); rangeStart = intShift(rangeStart); rangeEnd = intShift(rangeEnd); capacities = intShift(capacities); capacityCounter = intShift(capacityCounter); toCounter } } if (toCounter == 0) { hasDatabase = false; } else { hasDatabase = true; } } File log = new File("Cage" + from + "_Birth" + fromYear + "_" + currentDate + "_log.txt"); BufferedWriter writer = new BufferedWriter(new FileWriter(log)); writer.write("From Pen: " + from + "\r\n\tTotal: " + fromCount + "\r\n\tYear: " + fromYear + "\r\n\tSize: " + fromRange + "\r\n"); for (int i = 0; i < toCages.length; i++) { if (cagesAtCapacity[i] != null) { writer.write("\r\n\r\nTo Pen: " + cagesAtCapacity[i] + "\r\n\tTransferred: " + cagesAtCapacityAmount[i] + "\r\n\tCurrent Size: " + cagesAtCapacityRange[i]); } } for (int i = 0; i < toCages.length; i++) { if (toCages[i] != null) { writer.write("\r\n\r\nTo Pen: " + toCages[i] + "\r\n\tTransferred: " + capacityCounter[i] + "\r\n\tCurrent Size: " + toRanges[i]); } } int totalCount = 0; for (int i = 0; i < toCages.length; i++) { if (toCages[i] != null) { totalCount = totalCount + capacityCounter[i]; } } for (int i = 0; i < toCages.length; i++) { if (cagesAtCapacity[i] != null) { totalCount = totalCount + cagesAtCapacityAmount[i]; } } if (fromCount - totalCount != 0) { writer.write("\r\n\r\nUnspecified: " + (fromCount - totalCount)); } writer.close(); } catch (IOException e) { } } public static int[] addEntry(ArrayList<Table> tables, String[] toCages, String[] toRanges, int[] capacities, int[] capacityCounter, Table unspecified, Table otherTable, String from) { String to = ""; String belly; int[] rangeStart = new int[10]; int[] rangeEnd = new int[10]; for(int i = 0; i < toCages.length; i++) { if (toRanges[i] != null) { int index = toRanges[i].indexOf('-'); rangeStart[i] = Integer.parseInt(toRanges[i].substring(0,index)); rangeEnd[i] = Integer.parseInt(toRanges[i].substring(index+1)); } } do { belly = BellySize.createAndShowGUI(); if (belly.equals("done")) { } else { to = ""; int index = 0; boolean inRange = false; for (int i = 0; i < toCages.length; i++) { if (rangeStart[i] <= Integer.parseInt(belly) && Integer.parseInt(belly) <= rangeEnd[i]) { index = i; to = toCages[i]; capacityCounter[i]++; i = toCages.length; inRange = true; } } try { if (inRange) { tables.get(index).addRow(0, belly); } else { unspecified.addRow(0, belly); } otherTable.addRow(0, from, to, belly); fromCount++; } catch (IOException e) { } for (int i = 0; i < toCages.length; i++) { if (capacities[i] != 0 && capacityCounter[i] == capacities[i]) { belly = "done"; ErrorWindow.createAndShowGUI("Reached capacity on Cage " + toCages[i]); } } } } while (!belly.equals("done")); return capacityCounter; } public static boolean isInteger(String str) { if (str == null) { return false; } int length = str.length(); if (length == 0) { return false; } int i = 0; if (str.charAt(0) == '-') { if (length == 1) { return false; } i = 1; } for (; i < length; i++) { char c = str.charAt(i); if (c <= '/' || c >= ':') { return false; } } return true; } private static void initCages() { cages = new String[149]; for (int i = 1; i < 100; i++) { cages[i] = "" + i; } for (int i = 1; i < 17; i++) { cages[99 + i] = "" + i + "A"; } for (int i = 1; i < 34; i++) { cages[99 + 16 + i] = "" + i + "B"; } } public static boolean checkCage(String s) { boolean isGood = false; for (int i = 1; i < cages.length; i++) { if (s.equals(cages[i])) { isGood = true; } } return isGood; } public static String[] stringShift(String[] input) { int j = 0; int k = 0; String[] temp = new String[10]; while (j < 10) { if (input[j] != null) { temp[k] = input[j]; k++; } j++; } return temp; } public static int[] intShift(int[] input) { int j = 0; int k = 0; int[] temp = new int[10]; while (j < 10) { if (input[j] != 0) { temp[k] = input[j]; k++; } j++; } return temp; } }
package ru.stqa.pft.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import ru.stqa.pft.addressbook.model.CantactData; import java.util.concurrent.TimeUnit; public class ContactHelper extends HelperBase { public ContactHelper(WebDriver wd) { super(wd); } public void submitNewConract() { click(By.xpath("//div[@id='content']/form/input[21]")); } public void fillContactForm(CantactData cantactData) { type(By.name("firstname"), cantactData.getFirstname()); type(By.name("lastname"), cantactData.getLastname()); type(By.name("address"), cantactData.getAddress()); type(By.name("home"), cantactData.getPhone()); type(By.name("email"), cantactData.getEmail()); } public void initAddNew() { click(By.linkText("add new")); } public void selectContact() { click(By.name("selected[]")); } public void selectEditButton() { click(By.xpath("//table[@id='maintable']/tbody/tr[2]/td[8]/a/img")); } public void selectUpdateButton() { click(By.name("update")); } public void selectDeleteButton() { click(By.xpath(" //div[@id='content']/form[2]/div[2]/input")); } public void closeAlert() { wd.switchTo().alert().accept(); wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); } }
/** * ISOMsgPanel * Swing based GUI to ISOMsg * @author apr@cs.com.uy * @see uy.com.cs.jpos.iso.ISOMsg */ /* * $Log$ * Revision 1.2 1999/05/18 14:50:10 apr * Show ISOMsg fields in new frame * * Revision 1.1 1999/05/18 12:02:59 apr * Added GUI package * */ package uy.com.cs.jpos.iso.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; import java.util.*; import uy.com.cs.jpos.iso.*; /** * Called from ISOChannelPanel when you click on it's ISOMeter.<br> * It enable field and header visualization by means of visual * components such as JTable * * @see ISOChannelPanel * @see ISORequestListenerPanel */ public class ISOMsgPanel extends JPanel { ISOMsg m; Vector validFields; public ISOMsgPanel(ISOMsg m, boolean withDump) { super(); this.m = m; setLayout(new BorderLayout()); setBorder(BorderFactory.createRaisedBevelBorder()); setValidFields(); add(createISOMsgTable(), BorderLayout.CENTER); if (withDump) add(createISOMsgDumpPanel(), BorderLayout.SOUTH); } public ISOMsgPanel(ISOMsg m) { this(m, true); } private void setValidFields() { validFields = new Vector(); for (int i=0; i<=128; i++) if (m.hasField(i)) validFields.addElement(new Integer(i)); } private JComponent createISOMsgTable() { TableModel dataModel = new AbstractTableModel() { public int getColumnCount() { return 3; } public int getRowCount() { return validFields.size(); } public String getColumnName(int columnIndex) { switch (columnIndex) { case 0 : return " case 1 : return "Content"; case 2 : return "Description"; default: return ""; } } public Object getValueAt(int row, int col) { switch (col) { case 0 : return ((Integer)validFields.elementAt(row)); case 1 : try { int index = ((Integer)validFields.elementAt(row)).intValue(); Object obj = m.getValue(index); if (obj instanceof String) return obj.toString(); else if (obj instanceof byte[]) return ISOUtil.hexString((byte[]) obj); else if (obj instanceof ISOMsg) return "<ISOMsg>"; } catch (ISOException e) { e.printStackTrace(); } break; case 2 : int i=((Integer)validFields.elementAt(row)).intValue(); ISOPackager p = m.getPackager(); return p.getFieldDescription(m,i); } return "<???>"; } }; JTable table = new JTable(dataModel); table.getColumnModel().getColumn(0).setPreferredWidth(10); table.setPreferredScrollableViewportSize( new Dimension (500,table.getRowCount()*table.getRowHeight())); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); ListSelectionModel rowSM = table.getSelectionModel(); rowSM.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { ListSelectionModel lsm = (ListSelectionModel)e.getSource(); if (!lsm.isSelectionEmpty()) { int selectedRow = lsm.getMinSelectionIndex(); try { int index = ((Integer) validFields.elementAt(selectedRow)).intValue(); Object obj = m.getValue(index); if (obj instanceof ISOMsg) { ISOMsg sm = (ISOMsg) obj; JFrame f = new JFrame("ISOMsg field "+index); ISOMsgPanel p = new ISOMsgPanel(sm, false); f.getContentPane().add(p); f.pack(); f.show(); } } catch (ISOException ex) { ex.printStackTrace(); } } } }); JScrollPane scrollpane = new JScrollPane(table); return scrollpane; } JComponent createISOMsgDumpPanel() { JPanel p = new JPanel(); JTextArea t = new JTextArea(3,20); p.setLayout(new BorderLayout()); p.setBackground(Color.white); p.setBorder(BorderFactory.createLoweredBevelBorder()); p.add(new JLabel("Dump", SwingConstants.LEFT), BorderLayout.NORTH); t.setFont(new Font ("Helvetica", Font.PLAIN, 8)); t.setLineWrap(true); try { StringBuffer buf = new StringBuffer(); if (m.getHeader() != null) buf.append("--[Header]--\n" +ISOUtil.hexString(m.getHeader()) + "\n--[Msg]--\n"); byte[] b = m.pack(); buf.append (ISOUtil.hexString(b)); t.setText(buf.toString()); } catch (ISOException e) { t.setText(e.toString()); t.setForeground(Color.red); } p.add(t, BorderLayout.CENTER); return p; } }
package org.jpos.iso; import org.jpos.iso.header.BaseHeader; import org.jpos.iso.packager.XMLPackager; import org.jpos.util.Loggeable; import java.io.*; import java.lang.ref.WeakReference; import java.util.*; /** * implements <b>Composite</b> * whithin a <b>Composite pattern</b> * * @author apr@cs.com.uy * @version $Id$ * @see ISOComponent * @see ISOField */ public class ISOMsg extends ISOComponent implements Cloneable, Loggeable, Externalizable { protected Map fields; protected int maxField; protected ISOPackager packager; protected boolean dirty, maxFieldDirty; protected int direction; protected ISOHeader header; protected int fieldNumber = -1; public static final int INCOMING = 1; public static final int OUTGOING = 2; private static final long serialVersionUID = 4306251831901413975L; private WeakReference sourceRef; /** * Creates an ISOMsg */ public ISOMsg () { fields = new TreeMap(); maxField = -1; dirty = true; maxFieldDirty=true; direction = 0; header = null; } /** * Creates a nested ISOMsg */ public ISOMsg (int fieldNumber) { this(); setFieldNumber (fieldNumber); } /** * changes this Component field number<br> * Use with care, this method does not change * any reference held by a Composite. * @param fieldNumber new field number */ public void setFieldNumber (int fieldNumber) { this.fieldNumber = fieldNumber; } /** * Creates an ISOMsg with given mti * @param mti Msg's MTI */ public ISOMsg (String mti) { this(); try { setMTI (mti); } catch (ISOException e) { // should never happen } } /** * Sets the direction information related to this message * @param direction can be either ISOMsg.INCOMING or ISOMsg.OUTGOING */ public void setDirection(int direction) { this.direction = direction; } /** * Sets an optional message header image * @param b header image */ public void setHeader(byte[] b) { header = new BaseHeader (b); } public void setHeader (ISOHeader header) { this.header = header; } /** * get optional message header image * @return message header image (may be null) */ public byte[] getHeader() { return (header != null) ? header.pack() : null; } /** * Return this messages ISOHeader */ public ISOHeader getISOHeader() { return header; } /** * @return the direction (ISOMsg.INCOMING or ISOMsg.OUTGOING) * @see ISOChannel */ public int getDirection() { return direction; } /** * @return true if this message is an incoming message * @see ISOChannel */ public boolean isIncoming() { return direction == INCOMING; } /** * @return true if this message is an outgoing message * @see ISOChannel */ public boolean isOutgoing() { return direction == OUTGOING; } /** * @return the max field number associated with this message */ public int getMaxField() { if (maxFieldDirty) recalcMaxField(); return maxField; } private void recalcMaxField() { maxField = 0; Iterator iter = fields.keySet().iterator(); while (iter.hasNext()) { Object obj = iter.next(); if (obj instanceof Integer) maxField = Math.max (maxField, ((Integer)obj).intValue()); } maxFieldDirty = false; } /** * @param p - a peer packager */ public void setPackager (ISOPackager p) { packager = p; } /** * @return the peer packager */ public ISOPackager getPackager () { return packager; } /** * Set a field within this message * @param c - a component */ public void set (ISOComponent c) throws ISOException { if (c != null) { Integer i = (Integer) c.getKey(); fields.put (i, c); if (i.intValue() > maxField) { maxField = i.intValue(); } dirty = true; } } /** * Creates an ISOField associated with fldno within this ISOMsg * @param fldno field number * @param value field value */ public void set(int fldno, String value) throws ISOException { if (value != null) { if (!(packager instanceof ISOBasePackager)) { // No packager is available, we can't tell what the field // might be, so treat as a String! set(new ISOField(fldno, value)); } else { // This ISOMsg has a packager, so use it Object obj = ((ISOBasePackager) packager).getFieldPackager(fldno); if (obj instanceof ISOBinaryFieldPackager) { set(new ISOBinaryField(fldno, ISOUtil.hex2byte(value))); } else { set(new ISOField(fldno, value)); } } } else unset(fldno); } /** * Creates an ISOField associated with fldno within this ISOMsg * @param fpath dot-separated field path (i.e. 63.2) * @param value field value */ public void set (String fpath, String value) throws ISOException { StringTokenizer st = new StringTokenizer (fpath, "."); ISOMsg m = this; for (;;) { int fldno = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) { Object obj = m.getValue(fldno); if (obj instanceof ISOMsg) m = (ISOMsg) obj; else /* * we need to go deeper, however, if the value == null then * there is nothing to do (unset) at the lower levels, so break now and save some processing. */ if (value == null) { break; } else { // We have a value to set, so adding a level to hold it is sensible. m.set (m = new ISOMsg (fldno)); } } else { m.set (fldno, value); break; } } } /** * Creates an ISOField associated with fldno within this ISOMsg * @param fpath dot-separated field path (i.e. 63.2) * @param c component */ public void set (String fpath, ISOComponent c) throws ISOException { StringTokenizer st = new StringTokenizer (fpath, "."); ISOMsg m = this; for (;;) { int fldno = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) { Object obj = m.getValue(fldno); if (obj instanceof ISOMsg) m = (ISOMsg) obj; else /* * we need to go deeper, however, if the value == null then * there is nothing to do (unset) at the lower levels, so break now and save some processing. */ if (c == null) { break; } else { // We have a value to set, so adding a level to hold it is sensible. m.set (m = new ISOMsg (fldno)); } } else { m.set (c); break; } } } /** * Creates an ISOField associated with fldno within this ISOMsg * @param fpath dot-separated field path (i.e. 63.2) * @param value binary field value */ public void set (String fpath, byte[] value) throws ISOException { StringTokenizer st = new StringTokenizer (fpath, "."); ISOMsg m = this; for (;;) { int fldno = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) { Object obj = m.getValue(fldno); if (obj instanceof ISOMsg) m = (ISOMsg) obj; else m.set (m = new ISOMsg (fldno)); } else { m.set (fldno, value); break; } } } /** * Creates an ISOBinaryField associated with fldno within this ISOMsg * @param fldno field number * @param value field value */ public void set (int fldno, byte[] value) throws ISOException { if (value != null) set (new ISOBinaryField (fldno, value)); else unset (fldno); } /** * Unset a field if it exists, otherwise ignore. * @param fldno - the field number */ public void unset (int fldno) { if (fields.remove (fldno) != null) dirty = maxFieldDirty = true; } /** * Unsets several fields at once * @param flds - array of fields to be unset from this ISOMsg */ public void unset (int[] flds) { for (int i=0; i<flds.length; i++) unset (flds[i]); } /** * Unset a field referenced by a fpath if it exists, otherwise ignore. * @param fpath dot-separated field path (i.e. 63.2) * @throws ISOException */ public void unset (String fpath) throws ISOException { StringTokenizer st = new StringTokenizer (fpath, "."); ISOMsg m = this; ISOMsg lastm = m; int fldno = -1 ; int lastfldno ; for (;;) { lastfldno = fldno; fldno = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) { Object obj = m.getValue(fldno); if (obj instanceof ISOMsg) { lastm = m; m = (ISOMsg) obj; } else { // No real way of unset further subfield, exit. Perhaps should be ISOException? break; } } else { m.unset(fldno); if (m.hasFields() == false && (lastfldno != -1)) { lastm.unset(lastfldno); } break; } } } /** * In order to interchange <b>Composites</b> and <b>Leafs</b> we use * getComposite(). A <b>Composite component</b> returns itself and * a Leaf returns null. * * @return ISOComponent */ public ISOComponent getComposite() { return this; } /** * setup BitMap * @exception ISOException */ public void recalcBitMap () throws ISOException { if (!dirty) return; int mf = Math.min (getMaxField(), 192); BitSet bmap = new BitSet (((mf+62)>>6)<<6); for (int i=1; i<=mf; i++) if ((fields.get (i)) != null) bmap.set (i); set (new ISOBitMap (-1, bmap)); dirty = false; } /** * clone fields */ public Map getChildren() { return (Map) ((TreeMap)fields).clone(); } /** * pack the message with the current packager * @return the packed message * @exception ISOException */ public byte[] pack() throws ISOException { synchronized (this) { recalcBitMap(); return packager.pack(this); } } /** * unpack a message * @param b - raw message * @return consumed bytes * @exception ISOException */ public int unpack(byte[] b) throws ISOException { synchronized (this) { return packager.unpack(this, b); } } public void unpack (InputStream in) throws IOException, ISOException { synchronized (this) { packager.unpack(this, in); } } /** * dump the message to a PrintStream. The output is sorta * XML, intended to be easily parsed. * <br> * Each component is responsible for its own dump function, * ISOMsg just calls dump on every valid field. * @param p - print stream * @param indent - optional indent string */ public void dump (PrintStream p, String indent) { ISOComponent c; p.print (indent + "<" + XMLPackager.ISOMSG_TAG); switch (direction) { case INCOMING: p.print (" direction=\"incoming\""); break; case OUTGOING: p.print (" direction=\"outgoing\""); break; } if (fieldNumber != -1) p.print (" "+XMLPackager.ID_ATTR +"=\""+fieldNumber +"\""); p.println (">"); String newIndent = indent + " "; if (getPackager() != null) { p.println ( newIndent + "<!-- " + getPackager().getDescription() + " -->" ); } if (header instanceof Loggeable) ((Loggeable) header).dump (p, newIndent); for (int i=0; i<=maxField; i++) { if ((c = (ISOComponent) fields.get (i)) != null) c.dump (p, newIndent); // Uncomment to include bitmaps within logs // if (i == 0) { // if ((c = (ISOComponent) fields.get (new Integer (-1))) != null) // c.dump (p, newIndent); } p.println (indent + "</" + XMLPackager.ISOMSG_TAG+">"); } /** * get the component associated with the given field number * @param fldno the Field Number * @return the Component */ public ISOComponent getComponent(int fldno) { return (ISOComponent) fields.get(fldno); } /** * Return the object value associated with the given field number * @param fldno the Field Number * @return the field Object */ public Object getValue(int fldno) throws ISOException { ISOComponent c = getComponent(fldno); return c != null ? c.getValue() : null; } /** * Return the object value associated with the given field path * @param fpath field path * @return the field Object (may be null) */ public Object getValue (String fpath) throws ISOException { StringTokenizer st = new StringTokenizer (fpath, "."); ISOMsg m = this; Object obj; for (;;) { int fldno = Integer.parseInt(st.nextToken()); obj = m.getValue (fldno); if (st.hasMoreTokens()) { if (obj instanceof ISOMsg) { m = (ISOMsg) obj; } else throw new ISOException ("Invalid path '" + fpath + "'"); } else break; } return obj; } /** * get the component associated with the given field number * @param fpath field path * @return the Component */ public ISOComponent getComponent (String fpath) throws ISOException { StringTokenizer st = new StringTokenizer (fpath, "."); ISOMsg m = this; ISOComponent obj = null; for (;;) { int fldno = Integer.parseInt(st.nextToken()); obj = m.getComponent(fldno); if (st.hasMoreTokens()) { if (obj instanceof ISOMsg) { m = (ISOMsg) obj; } else break; // 'Quick' exit if hierachy is not present. } else break; } return obj; } /** * Return the String value associated with the given ISOField number * @param fldno the Field Number * @return field's String value */ public String getString (int fldno) { String s = null; if (hasField (fldno)) { try { Object obj = getValue(fldno); if (obj instanceof String) s = (String) obj; else if (obj instanceof byte[]) s = ISOUtil.hexString ((byte[]) obj); } catch (ISOException e) { // ignore ISOException - return null } } return s; } /** * Return the String value associated with the given field path * @param fpath field path * @return field's String value (may be null) */ public String getString (String fpath) { String s = null; try { Object obj = getValue(fpath); if (obj instanceof String) s = (String) obj; else if (obj instanceof byte[]) s = ISOUtil.hexString ((byte[]) obj); } catch (ISOException e) { // ignore ISOException - return null } return s; } /** * Return the byte[] value associated with the given ISOField number * @param fldno the Field Number * @return field's byte[] value */ public byte[] getBytes (int fldno) { byte[] b = null; if (hasField (fldno)) { try { Object obj = getValue(fldno); if (obj instanceof String) b = ((String) obj).getBytes("ISO8859_1"); else if (obj instanceof byte[]) b = ((byte[]) obj); } catch (ISOException ignored) { } catch (UnsupportedEncodingException ignored) {} } return b; } /** * Return the String value associated with the given field path * @param fpath field path * @return field's byte[] value (may be null) */ public byte[] getBytes (String fpath) { byte[] b = null; try { Object obj = getValue(fpath); if (obj instanceof String) b = ((String) obj).getBytes("ISO8859_1"); else if (obj instanceof byte[]) b = ((byte[]) obj); } catch (ISOException ignored) { } catch (UnsupportedEncodingException ignored) { } return b; } /** * Check if a given field is present * @param fldno the Field Number * @return boolean indicating the existence of the field */ public boolean hasField(int fldno) { return fields.get(fldno) != null; } /** * Check if all fields are present * @param fields an array of fields to check for presence * @return true if all fields are present */ public boolean hasFields (int[] fields) { for (int i=0; i<fields.length; i++) if (!hasField (fields[i])) return false; return true; } /** * Check if a field indicated by a fpath is present * @param fpath dot-separated field path (i.e. 63.2) */ public boolean hasField (String fpath) throws ISOException { StringTokenizer st = new StringTokenizer (fpath, "."); ISOMsg m = this; for (;;) { int fldno = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) { Object obj = m.getValue(fldno); if (obj instanceof ISOMsg) { m = (ISOMsg) obj; } else { // No real way of checking for further subfields, return false, perhaps should be ISOException? return false; } } else { return m.hasField(fldno); } } } /** * @return true if ISOMsg has at least one field */ public boolean hasFields () { return !fields.isEmpty(); } /** * Don't call setValue on an ISOMsg. You'll sure get * an ISOException. It's intended to be used on Leafs * @see ISOField * @see ISOException */ public void setValue(Object obj) throws ISOException { throw new ISOException ("setValue N/A in ISOMsg"); } public Object clone() { try { ISOMsg m = (ISOMsg) super.clone(); m.fields = (TreeMap) ((TreeMap) fields).clone(); if (header != null) m.header = (ISOHeader) header.clone(); Iterator iter = fields.keySet().iterator(); while (iter.hasNext()) { Integer k = (Integer) iter.next(); ISOComponent c = (ISOComponent) m.fields.get (k); if (c instanceof ISOMsg) m.fields.put (k, ((ISOMsg)c).clone()); } return m; } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** * Partially clone an ISOMsg * @param fields int array of fields to go * @return new ISOMsg instance */ public Object clone(int[] fields) { try { ISOMsg m = (ISOMsg) super.clone(); m.fields = new TreeMap(); for (int i=0; i<fields.length; i++) { if (hasField(fields[i])) { try { m.set (getComponent(fields[i])); } catch (ISOException e) { // it should never happen } } } return m; } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** * add all fields present on received parameter to this ISOMsg<br> * please note that received fields take precedence over * existing ones (simplifying card agent message creation * and template handling) * @param m ISOMsg to merge */ public void merge (ISOMsg m) { for (int i=0; i<=m.getMaxField(); i++) try { if (m.hasField(i)) set (m.getComponent(i)); } catch (ISOException e) { // should never happen } } /** * @return a string suitable for a log */ public String toString() { StringBuffer s = new StringBuffer(); if (isIncoming()) s.append("< else if (isOutgoing()) s.append(" else s.append(" "); s.append(getString(0)); if (hasField(11)) { s.append(' '); s.append(getString(11)); } if (hasField(41)) { s.append(' '); s.append(getString(41)); } return s.toString(); } public Object getKey() throws ISOException { if (fieldNumber != -1) return fieldNumber; throw new ISOException ("This is not a subField"); } public Object getValue() { return this; } /** * @return true on inner messages */ public boolean isInner() { return fieldNumber > -1; } /** * @param mti new MTI * @exception ISOException if message is inner message */ public void setMTI (String mti) throws ISOException { if (isInner()) throw new ISOException ("can't setMTI on inner message"); set (new ISOField (0, mti)); } /** * moves a field (renumber) * @param oldFieldNumber old field number * @param newFieldNumber new field number * @throws ISOException */ public void move (int oldFieldNumber, int newFieldNumber) throws ISOException { ISOComponent c = getComponent (oldFieldNumber); unset (oldFieldNumber); if (c != null) { c.setFieldNumber (newFieldNumber); set (c); } else unset (newFieldNumber); } /** * @return current MTI * @exception ISOException on inner message or MTI not set */ public String getMTI() throws ISOException { if (isInner()) throw new ISOException ("can't getMTI on inner message"); else if (!hasField(0)) throw new ISOException ("MTI not available"); return (String) getValue(0); } /** * @return true if message "seems to be" a request * @exception ISOException on MTI not set */ public boolean isRequest() throws ISOException { return Character.getNumericValue(getMTI().charAt (2))%2 == 0; } /** * @return true if message "seems not to be" a request * @exception ISOException on MTI not set */ public boolean isResponse() throws ISOException { return !isRequest(); } /** * @return true if message is Retransmission * @exception ISOException on MTI not set */ public boolean isRetransmission() throws ISOException { return getMTI().charAt(3) == '1'; } /** * sets an appropiate response MTI. * * i.e. 0100 becomes 0110<br> * i.e. 0201 becomes 0210<br> * i.e. 1201 becomes 1210<br> * @exception ISOException on MTI not set or it is not a request */ public void setResponseMTI() throws ISOException { if (!isRequest()) throw new ISOException ("not a request - can't set response MTI"); String mti = getMTI(); char c1 = mti.charAt(3); char c2 = '0'; switch (c1) { case '0' : case '1' : c2='0';break; case '2' : case '3' : c2='2';break; case '4' : case '5' : c2='4';break; } set (new ISOField (0, mti.substring(0,2) +(Character.getNumericValue(getMTI().charAt (2))+1) + c2 ) ); } /** * sets an appropiate retransmission MTI<br> * @exception ISOException on MTI not set or it is not a request */ public void setRetransmissionMTI() throws ISOException { if (!isRequest()) throw new ISOException ("not a request"); set (new ISOField (0, getMTI().substring(0,3) + "1")); } protected void writeHeader (ObjectOutput out) throws IOException { int len = header.getLength(); if (len > 0) { out.writeByte ('H'); out.writeShort (len); out.write (header.pack()); } } protected void readHeader (ObjectInput in) throws IOException, ClassNotFoundException { byte[] b = new byte[in.readShort()]; in.readFully (b); setHeader (b); } protected void writePackager(ObjectOutput out) throws IOException { out.writeByte('P'); String pclass = packager.getClass().getName(); byte[] b = pclass.getBytes(); out.writeShort(b.length); out.write(b); } protected void readPackager(ObjectInput in) throws IOException, ClassNotFoundException { byte[] b = new byte[in.readShort()]; in.readFully(b); try { Class mypClass = Class.forName(new String(b)); ISOPackager myp = (ISOPackager) mypClass.newInstance(); setPackager(myp); } catch (Exception e) { setPackager(null); } } protected void writeDirection (ObjectOutput out) throws IOException { out.writeByte ('D'); out.writeByte (direction); } protected void readDirection (ObjectInput in) throws IOException, ClassNotFoundException { direction = in.readByte(); } public void writeExternal (ObjectOutput out) throws IOException { out.writeByte (0); // reserved for future expansion (version id) out.writeShort (fieldNumber); if (header != null) writeHeader (out); if (packager != null) writePackager(out); if (direction > 0) writeDirection (out); // List keySet = new ArrayList (fields.keySet()); // Collections.sort (keySet); Iterator iter = fields.values().iterator(); while (iter.hasNext()) { ISOComponent c = (ISOComponent) iter.next(); if (c instanceof ISOMsg) { writeExternal (out, 'M', c); } else if (c instanceof ISOBinaryField) { writeExternal (out, 'B', c); } else if (c instanceof ISOAmount) { writeExternal (out, 'A', c); } else if (c instanceof ISOField) { writeExternal (out, 'F', c); } } out.writeByte ('E'); } public void readExternal (ObjectInput in) throws IOException, ClassNotFoundException { in.readByte(); // ignore version for now fieldNumber = in.readShort(); byte fieldType; ISOComponent c; try { while ((fieldType = in.readByte()) != 'E') { c = null; switch (fieldType) { case 'F': c = new ISOField (); break; case 'A': c = new ISOAmount (); break; case 'B': c = new ISOBinaryField (); break; case 'M': c = new ISOMsg (); break; case 'H': readHeader (in); break; case 'P': readPackager(in); break; case 'D': readDirection (in); break; default: throw new IOException ("malformed ISOMsg"); } if (c != null) { ((Externalizable)c).readExternal (in); set (c); } } } catch (ISOException e) { throw new IOException (e.getMessage()); } } /** * Let this ISOMsg object hold a weak reference to an ISOSource * (usually used to carry a reference to the incoming ISOChannel) * @param source an ISOSource */ public void setSource (ISOSource source) { this.sourceRef = new WeakReference (source); } /** * @return an ISOSource or null */ public ISOSource getSource () { return (sourceRef != null) ? (ISOSource) sourceRef.get () : null; } private void writeExternal (ObjectOutput out, char b, ISOComponent c) throws IOException { out.writeByte (b); ((Externalizable) c).writeExternal (out); } }