answer
stringlengths
17
10.2M
package org.mitre.synthea.export; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import org.mitre.synthea.engine.Generator; import org.mitre.synthea.helpers.Config; import org.mitre.synthea.helpers.Utilities; import org.mitre.synthea.world.agents.Payer; import org.mitre.synthea.world.agents.Provider; public class MetadataExporter { /** * Export metadata about the current run of Synthea. * Metadata includes various pieces of information about how the population was generated, * such as version, config settings, and runtime args. * @param generator Generator that was used to generate the population * @throws IOException if an error occurs writing to the output directory */ public static void exportMetadata(Generator generator) throws IOException { // use a linked hashmap in an attempt to preserve insertion order. // ie, most important things at the top/start Map<String, Object> metadata = new LinkedHashMap<>(); metadata.put("runID", generator.id); Generator.GeneratorOptions opts = generator.options; // - population seed long seed = opts.seed; metadata.put("seed", seed); // clinician seed long clinicianSeed = opts.clinicianSeed; metadata.put("clinicianSeed", clinicianSeed); // reference time is expected to be entered on the command line as YYYYMMDD // note that Y = "week year" and y = "year" per the formatting guidelines // and D = "day in year" and d = "day in month", so what we actually want is yyyyMMdd SimpleDateFormat yyyymmdd = new SimpleDateFormat("yyyyMMdd"); String referenceTime = yyyymmdd.format(new Date(generator.referenceTime)); metadata.put("referenceTime", referenceTime); // - git commit hash of the current running version String version = Utilities.SYNTHEA_VERSION; metadata.put("version", version); // - number of patients, providers, payers generated // (in case "csv append mode" is on, and someone wants to link patients <--> run. // I think just these 3 should be enough to identify which run a line from any csv belongs to) int patientCount = generator.totalGeneratedPopulation.get(); metadata.put("patientCount", patientCount); int providerCount = Provider.getProviderList().size(); metadata.put("providerCount", providerCount); int payerCount = Payer.getAllPayers().size(); metadata.put("payerCount", payerCount); // Java version, String javaVersion = System.getProperty("java.version"); // something like "12" or "1.8.0_201" metadata.put("javaVersion", javaVersion); // Actual Date/Time of execution. String runStartTime = ExportHelper.iso8601Timestamp(opts.runStartTime); metadata.put("runStartTime", runStartTime); // Run time long runTimeInSeconds = (System.currentTimeMillis() - opts.runStartTime) / 1000; metadata.put("runTimeInSeconds", runTimeInSeconds); // selected run settings String[] configSettings = { "exporter.years_of_history", }; for (String configSetting : configSettings) { metadata.put(configSetting, Config.get(configSetting)); } // note that nulls don't get exported, so if gender, age, city, etc, aren't specified // then they won't even be in the output file String gender = opts.gender; metadata.put("gender", gender); boolean ageSpecified = opts.ageSpecified; int minAge = opts.minAge; int maxAge = opts.maxAge; String age = ageSpecified ? minAge + "-" + maxAge : null; metadata.put("age", age); String city = opts.city; metadata.put("city", city); String state = opts.state; metadata.put("state", state); String modules = opts.enabledModules == null ? "*" : String.join(";", opts.enabledModules); metadata.put("modules", modules); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(metadata); StringBuilder filenameBuilder = new StringBuilder(); filenameBuilder.append(runStartTime); filenameBuilder.append('_'); // patient count above is the # actually generated. // put in the filename the number they requested int patientRequestCount = opts.population; filenameBuilder.append(patientRequestCount); filenameBuilder.append('_'); filenameBuilder.append(state); if (city != null) { filenameBuilder.append('_'); filenameBuilder.append(city); } filenameBuilder.append('_'); filenameBuilder.append(generator.id); // make sure everything is filename-safe, replace "non-word characters" with _ String filename = filenameBuilder.toString().replaceAll("\\W+", "_"); File outputDirectory = Exporter.getOutputFolder("metadata", null); outputDirectory.mkdirs(); Path outputFile = outputDirectory.toPath().resolve(filename + ".json"); Files.write(outputFile, Collections.singleton(json), StandardOpenOption.CREATE_NEW); } }
package nl.nn.adapterframework.jdbc; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.sql.Types; import java.util.Date; import javax.naming.NamingException; import javax.sql.DataSource; import nl.nn.adapterframework.core.HasPhysicalDestination; import nl.nn.adapterframework.core.INamedObject; import nl.nn.adapterframework.core.IXAEnabled; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.jdbc.dbms.DbmsSupportFactory; import nl.nn.adapterframework.jdbc.dbms.IDbmsSupport; import nl.nn.adapterframework.jdbc.dbms.IDbmsSupportFactory; import nl.nn.adapterframework.jms.JNDIBase; import nl.nn.adapterframework.parameters.Parameter; import nl.nn.adapterframework.parameters.ParameterValue; import nl.nn.adapterframework.parameters.ParameterValueList; import org.apache.commons.lang.StringUtils; /** * Provides functions for JDBC connections. * * N.B. Note on using XA transactions: * If transactions are used, make sure that the database user can access the table SYS.DBA_PENDING_TRANSACTIONS. * If not, transactions present when the server goes down cannot be properly recovered, resulting in exceptions like: * <pre> The error code was XAER_RMERR. The exception stack trace follows: javax.transaction.xa.XAException at oracle.jdbc.xa.OracleXAResource.recover(OracleXAResource.java:508) </pre> * * * * @version Id * @author Gerrit van Brakel * @since 4.1 */ public class JdbcFacade extends JNDIBase implements INamedObject, HasPhysicalDestination, IXAEnabled { private String name; private String username=null; private String password=null; private DataSource datasource = null; private String datasourceName = null; // private String datasourceNameXA = null; private boolean transacted = false; private boolean connectionsArePooled=true; private IDbmsSupportFactory dbmsSupportFactoryDefault=null; private IDbmsSupportFactory dbmsSupportFactory=null; private IDbmsSupport dbmsSupport=null; protected String getLogPrefix() { return "["+this.getClass().getName()+"] ["+getName()+"] "; } // /** // * Returns either {@link #getDatasourceName() datasourceName} or {@link #getDatasourceNameXA() datasourceNameXA}, // * depending on the value of {@link #isTransacted()}. // * If the right one is not specified, the other is used. // */ // public String getDataSourceNameToUse() throws JdbcException { // String result = isTransacted() ? getDatasourceNameXA() : getDatasourceName(); // if (StringUtils.isEmpty(result)) { // // try the alternative... // result = isTransacted() ? getDatasourceName() : getDatasourceNameXA(); // if (StringUtils.isEmpty(result)) { // throw new JdbcException(getLogPrefix()+"neither datasourceName nor datasourceNameXA are specified"); // log.warn(getLogPrefix()+"correct datasourceName attribute not specified, will use ["+result+"]"); // return result; public String getDataSourceNameToUse() throws JdbcException { String result = getDatasourceName(); if (StringUtils.isEmpty(result)) { throw new JdbcException(getLogPrefix()+"no datasourceName specified"); } return result; } protected DataSource getDatasource() throws JdbcException { // TODO: create bean jndiContextPrefix instead of doing multiple attempts if (datasource==null) { String dsName = getDataSourceNameToUse(); try { log.debug(getLogPrefix()+"looking up Datasource ["+dsName+"]"); datasource =(DataSource) getContext().lookup( dsName ); if (datasource==null) { throw new JdbcException("Could not find Datasource ["+dsName+"]"); } String dsinfo=getDatasourceInfo(); if (dsinfo==null) { dsinfo=datasource.toString(); } log.info(getLogPrefix()+"looked up Datasource ["+dsName+"]: ["+dsinfo+"]"); } catch (NamingException e) { try { String tomcatDsName="java:comp/env/"+dsName; log.debug(getLogPrefix()+"could not find ["+dsName+"], now trying ["+tomcatDsName+"]"); datasource =(DataSource) getContext().lookup( tomcatDsName ); log.debug(getLogPrefix()+"looked up Datasource ["+tomcatDsName+"]: ["+datasource+"]"); } catch (NamingException e2) { try { String jbossDsName="java:/"+dsName; log.debug(getLogPrefix()+"could not find ["+dsName+"], now trying ["+jbossDsName+"]"); datasource =(DataSource) getContext().lookup( jbossDsName ); log.debug(getLogPrefix()+"looked up Datasource ["+jbossDsName+"]: ["+datasource+"]"); } catch (NamingException e3) { throw new JdbcException(getLogPrefix()+"cannot find Datasource ["+dsName+"]", e); } } } } return datasource; } public String getDatasourceInfo() throws JdbcException { String dsinfo=null; Connection conn=null; try { conn=getConnection(); DatabaseMetaData md=conn.getMetaData(); String product=md.getDatabaseProductName(); String productVersion=md.getDatabaseProductVersion(); String driver=md.getDriverName(); String driverVersion=md.getDriverVersion(); String url=md.getURL(); String user=md.getUserName(); dsinfo ="user ["+user+"] url ["+url+"] product ["+product+"] version ["+productVersion+"] driver ["+driver+"] version ["+driverVersion+"]"; } catch (SQLException e) { log.warn("Exception determining databaseinfo",e); } finally { if (conn!=null) { try { conn.close(); } catch (SQLException e1) { log.warn("exception closing connection for metadata",e1); } } } return dsinfo; } public int getDatabaseType() { IDbmsSupport dbms=getDbmsSupport(); if (dbms==null) { return -1; } return dbms.getDatabaseType(); } public IDbmsSupportFactory getDbmsSupportFactoryDefault() { if (dbmsSupportFactoryDefault==null) { dbmsSupportFactoryDefault=new DbmsSupportFactory(); } return dbmsSupportFactoryDefault; } public void setDbmsSupportFactoryDefault(IDbmsSupportFactory dbmsSupportFactory) { this.dbmsSupportFactoryDefault=dbmsSupportFactory; } public IDbmsSupportFactory getDbmsSupportFactory() { if (dbmsSupportFactory==null) { dbmsSupportFactory=getDbmsSupportFactoryDefault(); } return dbmsSupportFactory; } public void setDbmsSupportFactory(IDbmsSupportFactory dbmsSupportFactory) { this.dbmsSupportFactory=dbmsSupportFactory; } public void setDbmsSupport(IDbmsSupport dbmsSupport) { this.dbmsSupport=dbmsSupport; } public IDbmsSupport getDbmsSupport() { if (dbmsSupport==null) { Connection conn=null; try { conn=getConnection(); } catch (Exception e) { throw new RuntimeException("Cannot obtain connection to determine dbmssupport", e); } try { setDbmsSupport(getDbmsSupportFactory().getDbmsSupport(conn)); //databaseType=DbmsUtil.getDatabaseType(conn); } finally { try { if (conn!=null) { conn.close(); } } catch (SQLException e1) { log.warn("exception closing connection for dbmssupport",e1); } } } return dbmsSupport; } /** * Obtains a connection to the datasource. */ // TODO: consider making this one protected. public Connection getConnection() throws JdbcException { try { if (StringUtils.isNotEmpty(getUsername())) { return getDatasource().getConnection(getUsername(),getPassword()); } else { return getDatasource().getConnection(); } } catch (SQLException e) { throw new JdbcException(getLogPrefix()+"cannot open connection on datasource ["+getDataSourceNameToUse()+"]", e); } } /** * Returns the name and location of the database that this objects operates on. * * @see nl.nn.adapterframework.core.HasPhysicalDestination#getPhysicalDestinationName() */ public String getPhysicalDestinationName() { String result="unknown"; try { Connection connection = getConnection(); DatabaseMetaData metadata = connection.getMetaData(); result = metadata.getURL(); String catalog=null; catalog=connection.getCatalog(); result += catalog!=null ? ("/"+catalog):""; connection.close(); } catch (Exception e) { log.warn(getLogPrefix()+"exception retrieving PhysicalDestinationName", e); } return result; } protected void applyParameters(PreparedStatement statement, ParameterValueList parameters) throws SQLException, SenderException { // statement.clearParameters(); /* // getParameterMetaData() is not supported on the WebSphere java.sql.PreparedStatement implementation. int senderParameterCount = parameters.size(); int statementParameterCount = statement.getParameterMetaData().getParameterCount(); if (statementParameterCount<senderParameterCount) { throw new SenderException(getLogPrefix()+"statement has more ["+statementParameterCount+"] parameters defined than sender ["+senderParameterCount+"]"); } */ for (int i=0; i< parameters.size(); i++) { ParameterValue pv = parameters.getParameterValue(i); String paramType = pv.getDefinition().getType(); Object value = pv.getValue(); // log.debug("applying parameter ["+(i+1)+","+parameters.getParameterValue(i).getDefinition().getName()+"], value["+parameterValue+"]"); if (Parameter.TYPE_DATE.equals(paramType)) { if (value==null) { statement.setNull(i+1, Types.DATE); } else { statement.setDate(i+1, new java.sql.Date(((Date)value).getTime())); } } else if (Parameter.TYPE_DATETIME.equals(paramType)) { if (value==null) { statement.setNull(i+1, Types.TIMESTAMP); } else { statement.setTimestamp(i+1, new Timestamp(((Date)value).getTime())); } } else if (Parameter.TYPE_TIMESTAMP.equals(paramType)) { if (value==null) { statement.setNull(i+1, Types.TIMESTAMP); } else { statement.setTimestamp(i+1, new Timestamp(((Date)value).getTime())); } } else if (Parameter.TYPE_TIME.equals(paramType)) { if (value==null) { statement.setNull(i+1, Types.TIME); } else { statement.setTime(i+1, new java.sql.Time(((Date)value).getTime())); } } else if (Parameter.TYPE_NUMBER.equals(paramType)) { statement.setDouble(i+1, ((Number)value).doubleValue()); } else { statement.setString(i+1, (String)value); } } } /** * Sets the name of the object. */ public void setName(String name) { this.name = name; } public String getName() { return name; } /** * Sets the JNDI name of datasource that is used when {@link #isTransacted()} returns <code>false</code> */ public void setDatasourceName(String datasourceName) { this.datasourceName = datasourceName; } public String getDatasourceName() { return datasourceName; } /** * Sets the JNDI name of datasource that is used when {@link #isTransacted()} returns <code>true</code> */ public void setDatasourceNameXA(String datasourceNameXA) { if (StringUtils.isNotEmpty(datasourceNameXA)) { throw new IllegalArgumentException(getLogPrefix()+"use of attribute 'datasourceNameXA' is no longer supported. The datasource can now only be specified using attribute 'datasourceName'"); } // this.datasourceNameXA = datasourceNameXA; } // public String getDatasourceNameXA() { // return datasourceNameXA; /** * Sets the user name that is used to open the database connection. * If a value is set, it will be used together with the (@link #setPassword(String) specified password} * to open the connection to the database. */ public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } /** * Sets the password that is used to open the database connection. * @see #setPassword(String) */ public void setPassword(String password) { this.password = password; } protected String getPassword() { return password; } /** * controls the use of transactions */ public void setTransacted(boolean transacted) { this.transacted = transacted; } public boolean isTransacted() { return transacted; } public boolean isConnectionsArePooled() { return connectionsArePooled || isTransacted(); } public void setConnectionsArePooled(boolean b) { connectionsArePooled = b; } }
package org.nanopub.extra.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; public class NanopubServerUtils { // Version numbers have the form MAJOR.MINOR (for example, 0.12 is a newer version than 0.9!) public static final String requiredProtocolVersion = "0.2"; public static final int requiredProtocolVersionValue = getVersionValue(requiredProtocolVersion); private static HttpClient httpClient; protected NanopubServerUtils() { throw new RuntimeException("no instances allowed"); } public static List<String> loadPeerList(String serverUrl) throws IOException { return loadList(serverUrl + "peers"); } public static List<String> loadPeerList(ServerInfo si) throws IOException { return loadPeerList(si.getPublicUrl()); } public static List<String> loadNanopubUriList(String serverUrl, int page) throws IOException { return loadList(serverUrl +"nanopubs?page=" + page); } public static List<String> loadNanopubUriList(ServerInfo si, int page) throws IOException { return loadNanopubUriList(si.getPublicUrl(), page); } public static List<String> loadList(String url) throws IOException { List<String> list = new ArrayList<String>(); HttpGet get = new HttpGet(url); get.setHeader("Content-Type", "text/plain"); BufferedReader r = null; try { if (httpClient == null) { RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000) .setConnectionRequestTimeout(100).setSocketTimeout(10000).build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setDefaultMaxPerRoute(10); connManager.setMaxTotal(1000); httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig) .setConnectionManager(connManager).build(); } HttpResponse resp = httpClient.execute(get); int code = resp.getStatusLine().getStatusCode(); if (code < 200 || code > 299) { throw new IOException("HTTP error: " + code + " " + resp.getStatusLine().getReasonPhrase()); } InputStream in = resp.getEntity().getContent(); r = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8"))); String line = null; while ((line = r.readLine()) != null) { list.add(line.trim()); } } finally { if (r != null) r.close(); } return list; } private static final List<String> bootstrapServerList = new ArrayList<>(); static { // Hard-coded server instances: bootstrapServerList.add("http://np.inn.ac/"); bootstrapServerList.add("http://nanopubs.semanticscience.org/"); bootstrapServerList.add("http://nanopubs.stanford.edu/nanopub-server/"); bootstrapServerList.add("http://rdf.disgenet.org/nanopub-server/"); bootstrapServerList.add("http://app.petapico.d2s.labs.vu.nl/nanopub-server/"); bootstrapServerList.add("http://app.tkuhn.eculture.labs.vu.nl/nanopub-server-1/"); bootstrapServerList.add("http://app.tkuhn.eculture.labs.vu.nl/nanopub-server-2/"); bootstrapServerList.add("http://app.tkuhn.eculture.labs.vu.nl/nanopub-server-3/"); bootstrapServerList.add("http://app.tkuhn.eculture.labs.vu.nl/nanopub-server-4/"); bootstrapServerList.add("http://nanopub.backend1.scify.org/nanopub-server/"); bootstrapServerList.add("http://nanopub.exynize.com/"); bootstrapServerList.add("http://sprout038.sprout.yale.edu/nanopub-server/"); bootstrapServerList.add("http://nanopubs.restdesc.org/"); } public static List<String> getBootstrapServerList() { return bootstrapServerList; } public static int getVersionValue(String versionString) { try { int major = Integer.parseInt(versionString.split("\\.")[0]); int minor = Integer.parseInt(versionString.split("\\.")[1]); return (major * 1000) + minor; } catch (Exception ex) { return 0; } } }
package org.objectstyle.japp.worker; import java.io.File; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.types.FileSet; import com.oracle.appbundler.AppBundlerTask; import com.oracle.appbundler.Option; /** * Packages OS X apps for Java 1.7+ using Oracle appbunder. */ class JAppMacWorker extends AbstractAntWorker { JAppMacWorker(JApp parent) { super(parent); } public void execute() { validateJavaVersion(); createDirectories(); bundle(); } private void validateJavaVersion() { // not using commons SystemUtils... They are replying on static enums // and will become obsolete eventually String classVersion = System.getProperty("java.class.version"); int dot = classVersion.indexOf('.'); classVersion = dot > 0 ? classVersion.substring(0, dot) : classVersion; int classVersionInt; try { classVersionInt = Integer.parseInt(classVersion); } catch (Exception e) { // hmm.. return; } if (classVersionInt < 51) { throw new BuildException("Minimal JDK requirement is 1.7. Got : " + System.getProperty("java.version")); } } void createDirectories() { File baseDir = parent.getDestDir(); if (!baseDir.isDirectory() && !baseDir.mkdirs()) { throw new BuildException("Can't create directory " + baseDir.getAbsolutePath()); } } void bundle() { String[] jvmOptions = parent.getJvmOptions() != null ? parent.getJvmOptions().split("\\s") : new String[0]; AppBundlerTask bundler = createTask(AppBundlerTask.class); // TODO: hardcoded keys that are nice to support... // bundler.setApplicationCategory("public.app-category.developer-tools"); bundler.setDisplayName(parent.getLongName()); bundler.setIcon(parent.getIcon()); bundler.setIdentifier(parent.getName()); bundler.setMainClassName(parent.getMainClass()); bundler.setName(parent.getName()); bundler.setOutputDirectory(parent.getDestDir()); bundler.setShortVersion(parent.getVersion()); for (String op : jvmOptions) { Option option = new Option(); option.setValue(op); bundler.addConfiguredOption(option); } for (FileSet fs : parent.getLibs()) { bundler.addConfiguredClassPath(fs); } bundler.execute(); } }
package org.nanopub.extra.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; public class NanopubServerUtils { // Version numbers have the form MAJOR.MINOR (for example, 0.12 is a newer version than 0.9!) public static final String requiredProtocolVersion = "0.2"; public static final int requiredProtocolVersionValue = getVersionValue(requiredProtocolVersion); private static HttpClient httpClient; protected NanopubServerUtils() { throw new RuntimeException("no instances allowed"); } public static List<String> loadPeerList(String serverUrl) throws IOException { return loadList(serverUrl + "peers"); } public static List<String> loadPeerList(ServerInfo si) throws IOException { return loadPeerList(si.getPublicUrl()); } public static List<String> loadNanopubUriList(String serverUrl, int page) throws IOException { return loadList(serverUrl +"nanopubs?page=" + page); } public static List<String> loadNanopubUriList(ServerInfo si, int page) throws IOException { return loadNanopubUriList(si.getPublicUrl(), page); } public static List<String> loadList(String url) throws IOException { List<String> list = new ArrayList<String>(); HttpGet get = new HttpGet(url); get.setHeader("Content-Type", "text/plain"); BufferedReader r = null; try { if (httpClient == null) { RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000) .setConnectionRequestTimeout(100).setSocketTimeout(10000).build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setDefaultMaxPerRoute(10); connManager.setMaxTotal(1000); httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig) .setConnectionManager(connManager).build(); } HttpResponse resp = httpClient.execute(get); int code = resp.getStatusLine().getStatusCode(); if (code < 200 || code > 299) { throw new IOException("HTTP error: " + code + " " + resp.getStatusLine().getReasonPhrase()); } InputStream in = resp.getEntity().getContent(); r = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8"))); String line = null; while ((line = r.readLine()) != null) { list.add(line.trim()); } } finally { if (r != null) r.close(); } return list; } private static final List<String> bootstrapServerList = new ArrayList<>(); static { // Hard-coded server instances: bootstrapServerList.add("http://np.inn.ac/"); bootstrapServerList.add("http://nanopubs.semanticscience.org/"); bootstrapServerList.add("http://nanopubs.stanford.edu/nanopub-server/"); } public static List<String> getBootstrapServerList() { return bootstrapServerList; } public static int getVersionValue(String versionString) { try { int major = Integer.parseInt(versionString.split("\\.")[0]); int minor = Integer.parseInt(versionString.split("\\.")[1]); return (major * 1000) + minor; } catch (Exception ex) { return 0; } } }
package org.opennars.inference; import org.opennars.control.DerivationContext; import org.opennars.entity.*; import org.opennars.io.Symbols; import org.opennars.language.*; import org.opennars.main.Parameters; import java.util.HashMap; import java.util.Map; import static org.opennars.inference.TruthFunctions.*; import static org.opennars.language.Terms.reduceComponents; /** * Compound term composition and decomposition rules, with two premises. * <p> * New compound terms are introduced only in forward inference, while * decompositional rules are also used in backward inference */ public final class CompositionalRules { /** * {<S ==> M>, <P ==> M>} |- {<(S|P) ==> M>, <(S&P) ==> M>, <(S-P) ==> * M>, * <(P-S) ==> M>} * * @param taskSentence The first premise * @param belief The second premise * @param index The location of the shared term * @param nal Reference to the memory */ static void composeCompound(final Statement taskContent, final Statement beliefContent, final int index, final DerivationContext nal) { if ((!nal.getCurrentTask().sentence.isJudgment()) || (taskContent.getClass() != beliefContent.getClass())) { return; } final Term componentT = taskContent.term[1 - index]; final Term componentB = beliefContent.term[1 - index]; final Term componentCommon = taskContent.term[index]; final int order1 = taskContent.getTemporalOrder(); final int order2 = beliefContent.getTemporalOrder(); final int order = TemporalRules.composeOrder(order1, order2); if (order == TemporalRules.ORDER_INVALID) { return; } if ((componentT instanceof CompoundTerm) && ((CompoundTerm) componentT).containsAllTermsOf(componentB)) { decomposeCompound((CompoundTerm) componentT, componentB, componentCommon, index, true, order, nal); return; } else if ((componentB instanceof CompoundTerm) && ((CompoundTerm) componentB).containsAllTermsOf(componentT)) { decomposeCompound((CompoundTerm) componentB, componentT, componentCommon, index, false, order, nal); return; } final TruthValue truthT = nal.getCurrentTask().sentence.truth; final TruthValue truthB = nal.getCurrentBelief().truth; final TruthValue truthOr = union(truthT, truthB); final TruthValue truthAnd = intersection(truthT, truthB); TruthValue truthDif = null; Term termOr = null; Term termAnd = null; Term termDif = null; if (index == 0) { if (taskContent instanceof Inheritance) { termOr = IntersectionInt.make(componentT, componentB); termAnd = IntersectionExt.make(componentT, componentB); if (truthB.isNegative()) { if (!truthT.isNegative()) { termDif = DifferenceExt.make(componentT, componentB); truthDif = intersection(truthT, negation(truthB)); } } else if (truthT.isNegative()) { termDif = DifferenceExt.make(componentB, componentT); truthDif = intersection(truthB, negation(truthT)); } } else if (taskContent instanceof Implication) { termOr = Disjunction.make(componentT, componentB); termAnd = Conjunction.make(componentT, componentB); } processComposed(taskContent, componentCommon, termOr, order, truthOr, nal); processComposed(taskContent, componentCommon, termAnd, order, truthAnd, nal); processComposed(taskContent, componentCommon, termDif, order, truthDif, nal); } else { // index == 1 if (taskContent instanceof Inheritance) { termOr = IntersectionExt.make(componentT, componentB); termAnd = IntersectionInt.make(componentT, componentB); if (truthB.isNegative()) { if (!truthT.isNegative()) { termDif = DifferenceInt.make(componentT, componentB); truthDif = intersection(truthT, negation(truthB)); } } else if (truthT.isNegative()) { termDif = DifferenceInt.make(componentB, componentT); truthDif = intersection(truthB, negation(truthT)); } } else if (taskContent instanceof Implication) { termOr = Conjunction.make(componentT, componentB); termAnd = Disjunction.make(componentT, componentB); } processComposed(taskContent, termOr, componentCommon, order, truthOr, nal); processComposed(taskContent, termAnd, componentCommon, order, truthAnd, nal); processComposed(taskContent, termDif, componentCommon, order, truthDif, nal); } } /** * Finish composing implication term * * @param premise1 Type of the contentInd * @param subject Subject of contentInd * @param predicate Predicate of contentInd * @param truth TruthValue of the contentInd * @param memory Reference to the memory */ private static void processComposed(final Statement statement, final Term subject, final Term predicate, final int order, final TruthValue truth, final DerivationContext nal) { if ((subject == null) || (predicate == null)) { return; } final Term content = Statement.make(statement, subject, predicate, order); if ((content == null) || statement == null || content.equals(statement) || content.equals(nal.getCurrentBelief().term)) { return; } final BudgetValue budget = BudgetFunctions.compoundForward(truth, content, nal); nal.doublePremiseTask(content, truth, budget, false, false); //(allow overlap) but not needed here, isn't detachment, this one would be even problematic from control perspective because its composition } /** * {<(S|P) ==> M>, <P ==> M>} |- <S ==> M> * * @param implication The implication term to be decomposed * @param componentCommon The part of the implication to be removed * @param term1 The other term in the contentInd * @param index The location of the shared term: 0 for subject, 1 for * predicate * @param compoundTask Whether the implication comes from the task * @param nal Reference to the memory */ private static void decomposeCompound(final CompoundTerm compound, final Term component, final Term term1, final int index, final boolean compoundTask, final int order, final DerivationContext nal) { if ((compound instanceof Statement) || (compound instanceof ImageExt) || (compound instanceof ImageInt)) { return; } Term term2 = reduceComponents(compound, component, nal.mem()); if (term2 == null) { return; } long delta = 0; while ((term2 instanceof Conjunction) && (((CompoundTerm) term2).term[0] instanceof Interval)) { final Interval interval = (Interval) ((CompoundTerm) term2).term[0]; delta += interval.time; term2 = ((CompoundTerm)term2).setComponent(0, null, nal.mem()); } final Task task = nal.getCurrentTask(); final Sentence sentence = task.sentence; final Sentence belief = nal.getCurrentBelief(); final Statement oldContent = (Statement) task.getTerm(); final TruthValue v1; final TruthValue v2; if (compoundTask) { v1 = sentence.truth; v2 = belief.truth; } else { v1 = belief.truth; v2 = sentence.truth; } TruthValue truth = null; final Term content; if (index == 0) { content = Statement.make(oldContent, term1, term2, order); if (content == null) { return; } if (oldContent instanceof Inheritance) { if (compound instanceof IntersectionExt) { truth = reduceConjunction(v1, v2); } else if (compound instanceof IntersectionInt) { truth = reduceDisjunction(v1, v2); } else if ((compound instanceof SetInt) && (component instanceof SetInt)) { truth = reduceConjunction(v1, v2); } else if ((compound instanceof SetExt) && (component instanceof SetExt)) { truth = reduceDisjunction(v1, v2); } else if (compound instanceof DifferenceExt) { if (compound.term[0].equals(component)) { truth = reduceDisjunction(v2, v1); } else { truth = reduceConjunctionNeg(v1, v2); } } } else if (oldContent instanceof Implication) { if (compound instanceof Conjunction) { truth = reduceConjunction(v1, v2); } else if (compound instanceof Disjunction) { truth = reduceDisjunction(v1, v2); } } } else { content = Statement.make(oldContent, term2, term1, order); if (content == null) { return; } if (oldContent instanceof Inheritance) { if (compound instanceof IntersectionInt) { truth = reduceConjunction(v1, v2); } else if (compound instanceof IntersectionExt) { truth = reduceDisjunction(v1, v2); } else if ((compound instanceof SetExt) && (component instanceof SetExt)) { truth = reduceConjunction(v1, v2); } else if ((compound instanceof SetInt) && (component instanceof SetInt)) { truth = reduceDisjunction(v1, v2); } else if (compound instanceof DifferenceInt) { if (compound.term[1].equals(component)) { truth = reduceDisjunction(v2, v1); } else { truth = reduceConjunctionNeg(v1, v2); } } } else if (oldContent instanceof Implication) { if (compound instanceof Disjunction) { truth = reduceConjunction(v1, v2); } else if (compound instanceof Conjunction) { truth = reduceDisjunction(v1, v2); } } } if (truth != null) { final BudgetValue budget = BudgetFunctions.compoundForward(truth, content, nal); if (delta != 0) { long baseTime = task.sentence.getOccurenceTime(); if (baseTime != Stamp.ETERNAL) { baseTime += delta; nal.getTheNewStamp().setOccurrenceTime(baseTime); } } nal.doublePremiseTask(content, truth, budget, false, true); //(allow overlap), a form of detachment } } /** * {(||, S, P), P} |- S {(&&, S, P), P} |- S * * @param implication The implication term to be decomposed * @param componentCommon The part of the implication to be removed * @param compoundTask Whether the implication comes from the task * @param nal Reference to the memory */ static void decomposeStatement(final CompoundTerm compound, final Term component, final boolean compoundTask, final int index, final DerivationContext nal) { final boolean isTemporalConjunction = (compound instanceof Conjunction) && !((Conjunction) compound).isSpatial; if (isTemporalConjunction && (compound.getTemporalOrder() == TemporalRules.ORDER_FORWARD) && (index != 0)) { return; } long occurrence_time = nal.getCurrentTask().sentence.getOccurenceTime(); if(isTemporalConjunction && (compound.getTemporalOrder() == TemporalRules.ORDER_FORWARD)) { if(!nal.getCurrentTask().sentence.isEternal() && compound.term[index + 1] instanceof Interval) { final long shift_occurrence = ((Interval)compound.term[index + 1]).time; occurrence_time = nal.getCurrentTask().sentence.getOccurenceTime() + shift_occurrence; } } final Task task = nal.getCurrentTask(); final Sentence taskSentence = task.sentence; final Sentence belief = nal.getCurrentBelief(); final Term content = reduceComponents(compound, component, nal.mem()); if (content == null) { return; } TruthValue truth = null; BudgetValue budget; if (taskSentence.isQuestion() || taskSentence.isQuest()) { budget = BudgetFunctions.compoundBackward(content, nal); nal.getTheNewStamp().setOccurrenceTime(occurrence_time); nal.doublePremiseTask(content, truth, budget, false, false); // special inference to answer conjunctive questions with query variables if (taskSentence.term.hasVarQuery()) { final Concept contentConcept = nal.mem().concept(content); if (contentConcept == null) { return; } final Sentence contentBelief = contentConcept.getBelief(nal, task); if (contentBelief == null) { return; } final Task contentTask = new Task(contentBelief, task.budget, false); nal.setCurrentTask(contentTask); final Term conj = Conjunction.make(component, content); truth = intersection(contentBelief.truth, belief.truth); budget = BudgetFunctions.compoundForward(truth, conj, nal); nal.getTheNewStamp().setOccurrenceTime(occurrence_time); nal.doublePremiseTask(conj, truth, budget, false, false); } } else { final TruthValue v1; final TruthValue v2; if (compoundTask) { v1 = taskSentence.truth; v2 = belief.truth; } else { v1 = belief.truth; v2 = taskSentence.truth; } if (compound instanceof Conjunction) { if (taskSentence.isGoal() && !compoundTask) { return; } } else if (compound instanceof Disjunction) { if (taskSentence.isGoal() && !compoundTask) { return; } } else { return; } if (compound instanceof Conjunction) { if (taskSentence.isGoal()) { truth = intersection(v1, v2); } else { // isJudgment truth = reduceConjunction(v1, v2); } } else if (compound instanceof Disjunction) { if (taskSentence.isGoal()) { truth = reduceConjunction(v2, v1); } else { // isJudgment truth = reduceDisjunction(v1, v2); } } budget = BudgetFunctions.compoundForward(truth, content, nal); } nal.getTheNewStamp().setOccurrenceTime(occurrence_time); nal.doublePremiseTask(content, truth, budget, false, false); } /** * Introduce a dependent variable in an outer-layer conjunction {<S --> P1>, * <S --> P2>} |- (&&, <#x --> P1>, <#x --> P2>) * * @param taskContent The first premise <M --> S> * @param beliefContent The second premise <M --> P> * @param index The location of the shared term: 0 for subject, 1 for * predicate * @param nal Reference to the memory */ public static void introVarOuter(final Statement taskContent, final Statement beliefContent, final int index, final DerivationContext nal) { if (!(taskContent instanceof Inheritance)) { return; } final Variable varInd1 = new Variable("$varInd1"); final Variable varInd2 = new Variable("$varInd2"); Term term11dependent=null, term12dependent=null, term21dependent=null, term22dependent=null; Term term11 = index == 0 ? varInd1 : taskContent.getSubject(); Term term21 = index == 0 ? varInd1 : beliefContent.getSubject(); Term term12 = index == 0 ? taskContent.getPredicate() : varInd1; Term term22 = index == 0 ? beliefContent.getPredicate() : varInd1; if (index == 0) { term12dependent=term12; term22dependent=term22; } else { term11dependent=term11; term21dependent=term21; } Term commonTerm = null; final Map<Term, Term> subs = new HashMap<>(); // comment to firstIsImage and secondIsSameImage: // Because if we have <{a} --> P> and <{a} --> C> // then we want to introduce (&&,<{#1} -- P>,<{#1} --> C>). // so we have to indeed check that // they are equal set types (not seeing [a] and {a} as same) // TODO< findCommonTermPredicate and findCommonSubject are actually symmetric to each other -> merge them with a enum > if (index == 0) { if (term12 instanceof ImageExt) { boolean firstIsImage = term22 instanceof ImageExt; boolean secondIsSameImage = true; commonTerm = findCommonTermPredicate(term12, term22, commonTerm, firstIsImage, secondIsSameImage); if (commonTerm != null) { subs.put(commonTerm, varInd2); term12 = ((CompoundTerm) term12).applySubstitute(subs); term22 = applySubstituteIfCompoundTerm(varInd2, term22, subs); } } if (commonTerm==null && term22 instanceof ImageExt) { boolean firstIsImage = term12 instanceof ImageExt; boolean secondIsSameImage = true; commonTerm = findCommonTermPredicate(term22, term12, commonTerm, firstIsImage, secondIsSameImage); if (commonTerm != null) { subs.put(commonTerm, varInd2); term22 = ((CompoundTerm) term22).applySubstitute(subs); term12 = applySubstituteIfCompoundTerm(varInd2, term12, subs); } } } else { if (term21 instanceof ImageInt) { boolean firstIsImage = true; boolean secondIsSameImage = term11 instanceof ImageInt; commonTerm = findCommonSubject(term11, term21, commonTerm, firstIsImage, secondIsSameImage); if (commonTerm != null) { subs.put(commonTerm, varInd2); term21 = ((CompoundTerm) term21).applySubstitute(subs); term11 = applySubstituteIfCompoundTerm(varInd2, term11, subs); } } if (commonTerm==null && term11 instanceof ImageInt) { boolean firstIsImage = true; boolean secondIsSameImage = term21 instanceof ImageInt; commonTerm = findCommonSubject(term21, term11, commonTerm, firstIsImage, secondIsSameImage); if (commonTerm != null) { subs.put(commonTerm, varInd2); term11 = ((CompoundTerm) term11).applySubstitute(subs); term21 = applySubstituteIfCompoundTerm(varInd2, term21, subs); } } } Statement state1 = Inheritance.make(term11, term12); Statement state2 = Inheritance.make(term21, term22); Term content = Implication.make(state1, state2); if (content == null) { return; } final TruthValue truthT = nal.getCurrentTask().sentence.truth; final TruthValue truthB = nal.getCurrentBelief().truth; if ((truthT == null) || (truthB == null)) { if(Parameters.DEBUG) { System.out.println("ERROR: Belief with null truth value. (introVarOuter)"); } return; } TruthValue truth = induction(truthT, truthB); BudgetValue budget = BudgetFunctions.compoundForward(truth, content, nal); nal.doublePremiseTask(content, truth, budget, false, false); content = Implication.make(state2, state1); truth = induction(truthB, truthT); budget = BudgetFunctions.compoundForward(truth, content, nal); nal.doublePremiseTask(content, truth, budget, false, false); content = Equivalence.make(state1, state2); truth = comparison(truthT, truthB); budget = BudgetFunctions.compoundForward(truth, content, nal); nal.doublePremiseTask(content, truth, budget, false, false); final Variable varDep = new Variable("#varDep"); if (index == 0) { state1 = Inheritance.make(varDep, term12dependent); state2 = Inheritance.make(varDep, term22dependent); } else { state1 = Inheritance.make(term11dependent, varDep); state2 = Inheritance.make(term21dependent, varDep); } if ((state1==null) || (state2 == null)) return; content = Conjunction.make(state1, state2); truth = intersection(truthT, truthB); budget = BudgetFunctions.compoundForward(truth, content, nal); nal.doublePremiseTask(content, truth, budget, false, false); } private static Term applySubstituteIfCompoundTerm(final Variable varInd2, final Term term22, Map<Term, Term> subs) { return term22 instanceof CompoundTerm ? ((CompoundTerm)term22).applySubstitute(subs) : varInd2; } private static Term findCommonSubject(final Term containedTest, Term tested, final Term commonTerm, final boolean firstIsImage, final boolean secondIsSameImage) { Term resultCommonTerm = commonTerm; if (tested.containsTermRecursively(containedTest)) { resultCommonTerm = containedTest; } if(secondIsSameImage && resultCommonTerm == null) { resultCommonTerm = retCommonTerm(containedTest, tested, firstIsImage); } return resultCommonTerm; } private static Term findCommonTermPredicate(Term tested, Term containedTest, Term commonTerm, boolean firstIsImage, boolean secondIsSameImage) { Term resultCommonTerm = commonTerm; if (tested.containsTermRecursively(containedTest)) { resultCommonTerm = containedTest; } if(secondIsSameImage && resultCommonTerm == null) { resultCommonTerm = retCommonTerm(tested, containedTest, firstIsImage); } return resultCommonTerm; } private static Term retCommonTerm(Term term12, Term term22, boolean firstIsImage) { Term commonTerm; commonTerm = ((Image) term12).getTheOtherComponent(); if(!(term22.containsTermRecursively(commonTerm))) { commonTerm=null; } if (firstIsImage && ((commonTerm == null) || !(term22).containsTermRecursively(commonTerm))) { commonTerm = ((Image) term22).getTheOtherComponent(); if ((commonTerm == null) || !(term12).containsTermRecursively(commonTerm)) { commonTerm = null; } } return commonTerm; } /** * {<M --> S>, <C ==> <M --> P>>} |- <(&&, <#x --> S>, C) ==> <#x --> P>> * {<M --> S>, (&&, C, <M --> P>)} |- (&&, C, <<#x --> S> ==> <#x --> P>>) * * @param taskContent The first premise directly used in internal induction, * <M --> S> * @param beliefContent The componentCommon to be used as a premise in * internal induction, <M --> P> * @param oldCompound The whole contentInd of the first premise, Implication * or Conjunction * @param nal Reference to the memory */ static boolean introVarInner(final Statement premise1, final Statement premise2, final CompoundTerm oldCompound, final DerivationContext nal) { final Task task = nal.getCurrentTask(); final Sentence taskSentence = task.sentence; if (!taskSentence.isJudgment() || (premise1.getClass() != premise2.getClass()) || oldCompound.containsTerm(premise1)) { return false; } final Term subject1 = premise1.getSubject(); final Term subject2 = premise2.getSubject(); final Term predicate1 = premise1.getPredicate(); final Term predicate2 = premise2.getPredicate(); final Term commonTerm1; final Term commonTerm2; if (subject1.equals(subject2)) { commonTerm1 = subject1; commonTerm2 = secondCommonTerm(predicate1, predicate2, 0); } else if (predicate1.equals(predicate2)) { commonTerm1 = predicate1; commonTerm2 = secondCommonTerm(subject1, subject2, 0); } else { return false; } final Sentence belief = nal.getCurrentBelief(); final Map<Term, Term> substitute = new HashMap<>(); boolean b1 = false, b2 = false; { final Variable varDep2 = new Variable("#varDep2"); Term content = Conjunction.make(premise1, oldCompound); if (!(content instanceof CompoundTerm)) return false; substitute.put(commonTerm1, varDep2); content = ((CompoundTerm)content).applySubstitute(substitute); final TruthValue truth = intersection(taskSentence.truth, belief.truth); final BudgetValue budget = BudgetFunctions.forward(truth, nal); b1 = (nal.doublePremiseTask(content, truth, budget, false, false))!=null; } substitute.clear(); { final Variable varInd1 = new Variable("$varInd1"); final Variable varInd2 = new Variable("$varInd2"); substitute.put(commonTerm1, varInd1); if (commonTerm2 != null) { substitute.put(commonTerm2, varInd2); } Term content = Implication.make(premise1, oldCompound); if ((content == null) || (!(content instanceof CompoundTerm))) { return false; } content = ((CompoundTerm)content).applySubstituteToCompound(substitute); final TruthValue truth; if (premise1.equals(taskSentence.term)) { truth = induction(belief.truth, taskSentence.truth); } else { truth = induction(taskSentence.truth, belief.truth); } final BudgetValue budget = BudgetFunctions.forward(truth, nal); b2 = nal.doublePremiseTask(content, truth, budget, false, false)!=null; } return b1 || b2; } /** * Introduce a second independent variable into two terms with a common * component * * @param term1 The first term * @param term2 The second term * @param index The index of the terms in their statement */ private static Term secondCommonTerm(final Term term1, final Term term2, final int index) { Term commonTerm = null; if (index == 0) { if ((term1 instanceof ImageExt) && (term2 instanceof ImageExt)) { commonTerm = ((ImageExt) term1).getTheOtherComponent(); if ((commonTerm == null) || !term2.containsTermRecursively(commonTerm)) { commonTerm = ((ImageExt) term2).getTheOtherComponent(); if ((commonTerm == null) || !term1.containsTermRecursively(commonTerm)) { commonTerm = null; } } } } else if ((term1 instanceof ImageInt) && (term2 instanceof ImageInt)) { commonTerm = ((ImageInt) term1).getTheOtherComponent(); if ((commonTerm == null) || !term2.containsTermRecursively(commonTerm)) { commonTerm = ((ImageInt) term2).getTheOtherComponent(); if ((commonTerm == null) || !term1.containsTermRecursively(commonTerm)) { commonTerm = null; } } } return commonTerm; } public static void eliminateVariableOfConditionAbductive(final int figure, final Sentence sentence, final Sentence belief, final DerivationContext nal) { Statement T1 = (Statement) sentence.term; Statement T2 = (Statement) belief.term; Term S1 = T2.getSubject(); Term S2 = T1.getSubject(); Term P1 = T2.getPredicate(); Term P2 = T1.getPredicate(); final Map<Term, Term> res1 = new HashMap<>(); final Map<Term, Term> res2 = new HashMap<>(); final Map<Term, Term> res3 = new HashMap<>(); final Map<Term, Term> res4 = new HashMap<>(); if (figure == 21) { res1.clear(); res2.clear(); Variables.findSubstitute(Symbols.VAR_INDEPENDENT, P1, S2, res1, res2); //this part is T1 = (Statement) T1.applySubstitute(res2); //independent, the rule works if it unifies if(T1==null) { return; } T2 = (Statement) T2.applySubstitute(res1); if(T2==null) { return; } //update the variables because T1 and T2 may have changed S1 = T2.getSubject(); P2 = T1.getPredicate(); eliminateVariableOfConditionAbductiveTryCrossUnification(sentence, belief, nal, S1, P2, res3, res4); } else if (figure == 12) { res1.clear(); res2.clear(); Variables.findSubstitute(Symbols.VAR_INDEPENDENT, S1, P2, res1, res2); //this part is T1 = (Statement) T1.applySubstitute(res2); //independent, the rule works if it unifies if(T1==null) { return; } T2 = (Statement) T2.applySubstitute(res1); if(T2==null) { return; } //update the variables because T1 and T2 may have changed S2 = T1.getSubject(); P1 = T2.getPredicate(); eliminateVariableOfConditionAbductiveTryCrossUnification(sentence, belief, nal, S2, P1, res3, res4); } else if (figure == 11) { res1.clear(); res2.clear(); Variables.findSubstitute(Symbols.VAR_INDEPENDENT, S1, S2, res1, res2); //this part is T1 = (Statement) T1.applySubstitute(res2); //independent, the rule works if it unifies if(T1==null) { return; } T2 = (Statement) T2.applySubstitute(res1); if(T2==null) { return; } P1 = T2.getPredicate(); P2 = T1.getPredicate(); //update the variables because T1 and T2 may have changed eliminateVariableOfConditionAbductiveTryCrossUnification(sentence, belief, nal, P1, P2, res3, res4); } else if (figure == 22) { res1.clear(); res2.clear(); Variables.findSubstitute(Symbols.VAR_INDEPENDENT, P1, P2, res1, res2); //this part is T1 = (Statement) T1.applySubstitute(res2); //independent, the rule works if it unifies if(T1==null) { return; } T2 = (Statement) T2.applySubstitute(res1); if(T2==null) { return; } //update the variables because T1 and T2 may have changed S1 = T2.getSubject(); S2 = T1.getSubject(); if (S1 instanceof Conjunction) { //try to unify S2 with a component for (final Term s1 : ((CompoundTerm) S1).term) { res3.clear(); res4.clear(); //here the dependent part matters, see example of Issue40 if (Variables.findSubstitute(Symbols.VAR_DEPENDENT, s1, S2, res3, res4)) { for (Term s2 : ((CompoundTerm) S1).term) { if (!(s2 instanceof CompoundTerm)) { continue; } s2 = ((CompoundTerm) s2).applySubstitute(res3); if(s2==null || s2.hasVarIndep()) { continue; } if (s2!=null && !s2.equals(s1) && (sentence.truth != null) && (belief.truth != null)) { final TruthValue truth = abduction(sentence.truth, belief.truth); final BudgetValue budget = BudgetFunctions.compoundForward(truth, s2, nal); nal.doublePremiseTask(s2, truth, budget, false, false); } } } } } if (S2 instanceof Conjunction) { //try to unify S1 with a component for (final Term s1 : ((CompoundTerm) S2).term) { res3.clear(); res4.clear(); //here the dependent part matters, see example of Issue40 if (Variables.findSubstitute(Symbols.VAR_DEPENDENT, s1, S1, res3, res4)) { for (Term s2 : ((CompoundTerm) S2).term) { if (!(s2 instanceof CompoundTerm)) { continue; } s2 = ((CompoundTerm) s2).applySubstitute(res3); if(s2==null || s2.hasVarIndep()) { continue; } if (s2!=null && !s2.equals(s1) && (sentence.truth != null) && (belief.truth != null)) { final TruthValue truth = abduction(sentence.truth, belief.truth); final BudgetValue budget = BudgetFunctions.compoundForward(truth, s2, nal); nal.doublePremiseTask(s2, truth, budget, false, false); } } } } } } } private static void eliminateVariableOfConditionAbductiveTryCrossUnification(Sentence sentence, Sentence belief, DerivationContext nal, Term s1, Term p2, Map<Term, Term> res3, Map<Term, Term> res4) { if (s1 instanceof Conjunction) { //try to unify P2 with a component eliminateVariableOfConditionAbductiveTryUnification1(sentence, belief, nal, p2, (CompoundTerm) s1, res3, res4); } if (p2 instanceof Conjunction) { //try to unify S1 with a component eliminateVariableOfConditionAbductiveTryUnification1(sentence, belief, nal, s1, (CompoundTerm) p2, res3, res4); } } private static void eliminateVariableOfConditionAbductiveTryUnification1(Sentence sentence, Sentence belief, DerivationContext nal, Term p1, CompoundTerm p2, Map<Term, Term> res3, Map<Term, Term> res4) { for (final Term s1 : p2.term) { res3.clear(); res4.clear(); //here the dependent part matters, see example of Issue40 if (Variables.findSubstitute(Symbols.VAR_DEPENDENT, s1, p1, res3, res4)) { eliminateVariableOfConditionAbductiveInner1(sentence, belief, nal, p2, res3, s1); } } } private static void eliminateVariableOfConditionAbductiveInner1(Sentence sentence, Sentence belief, DerivationContext nal, CompoundTerm s1, Map<Term, Term> res3, Term s12) { for (Term s2 : s1.term) { if (!(s2 instanceof CompoundTerm)) { continue; } s2 = ((CompoundTerm) s2).applySubstitute(res3); if(s2==null || s2.hasVarIndep()) { continue; } if (!s2.equals(s12) && (sentence.truth != null) && (belief.truth != null)) { final TruthValue truth = abduction(sentence.truth, belief.truth); final BudgetValue budget = BudgetFunctions.compoundForward(truth, s2, nal); nal.doublePremiseTask(s2, truth, budget, false, false); } } } static void IntroVarSameSubjectOrPredicate(final Sentence originalMainSentence, final Sentence subSentence, final Term component, final Term content, final int index, final DerivationContext nal) { final Term T1 = originalMainSentence.term; if (!(T1 instanceof CompoundTerm) || !(content instanceof CompoundTerm)) { return; } CompoundTerm T = (CompoundTerm) T1; CompoundTerm T2 = (CompoundTerm) content; if ((component instanceof Inheritance && content instanceof Inheritance) || (component instanceof Similarity && content instanceof Similarity)) { //CompoundTerm result = T; if (component.equals(content)) { return; //wouldnt make sense to create a conjunction here, would contain a statement twice } final Variable depIndVar1 = new Variable("#depIndVar1"); final Variable depIndVar2 = new Variable("#depIndVar2"); if (((Statement) component).getPredicate().equals(((Statement) content).getPredicate()) && !(((Statement) component).getPredicate() instanceof Variable)) { CompoundTerm zw = (CompoundTerm) T.term[index]; zw = (CompoundTerm) zw.setComponent(1, depIndVar1, nal.mem()); T2 = (CompoundTerm) T2.setComponent(1, depIndVar1, nal.mem()); final Conjunction res = (Conjunction) Conjunction.make(zw, T2); T = (CompoundTerm) T.setComponent(index, res, nal.mem()); } else if (((Statement) component).getSubject().equals(((Statement) content).getSubject()) && !(((Statement) component).getSubject() instanceof Variable)) { CompoundTerm zw = (CompoundTerm) T.term[index]; zw = (CompoundTerm) zw.setComponent(0, depIndVar2, nal.mem()); T2 = (CompoundTerm) T2.setComponent(0, depIndVar2, nal.mem()); final Conjunction res = (Conjunction) Conjunction.make(zw, T2); T = (CompoundTerm) T.setComponent(index, res, nal.mem()); } final TruthValue truth = induction(originalMainSentence.truth, subSentence.truth); final BudgetValue budget = BudgetFunctions.compoundForward(truth, T, nal); nal.doublePremiseTask(T, truth, budget, false, false); } } }
package org.owasp.dependencycheck.data.nvdcve; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.owasp.dependencycheck.data.cpe.Entry; import org.owasp.dependencycheck.data.cwe.CweDB; import org.owasp.dependencycheck.dependency.Reference; import org.owasp.dependencycheck.dependency.Vulnerability; import org.owasp.dependencycheck.dependency.VulnerableSoftware; import org.owasp.dependencycheck.utils.FileUtils; import org.owasp.dependencycheck.utils.Settings; /** * The database holding information about the NVD CVE data. * * @author Jeremy Long (jeremy.long@owasp.org) */ public class CveDB { //<editor-fold defaultstate="collapsed" desc="Constants to create, maintain, and retrieve data from the CVE Database"> /** * SQL Statement to create an index on the reference table. */ public static final String CREATE_INDEX_IDXREFERENCE = "CREATE INDEX IF NOT EXISTS idxReference ON reference(cveid)"; /** * SQL Statement to create an index on the software for finding CVE entries based on CPE data. */ public static final String CREATE_INDEX_IDXSOFTWARE = "CREATE INDEX IF NOT EXISTS idxSoftware ON software(product, vendor, version)"; /** * SQL Statement to create an index for retrieving software by CVEID. */ public static final String CREATE_INDEX_IDXSOFTWARECVE = "CREATE INDEX IF NOT EXISTS idxSoftwareCve ON software(cveid)"; /** * SQL Statement to create an index on the vulnerability table. */ public static final String CREATE_INDEX_IDXVULNERABILITY = "CREATE INDEX IF NOT EXISTS idxVulnerability ON vulnerability(cveid)"; /** * SQL Statement to create the reference table. */ public static final String CREATE_TABLE_REFERENCE = "CREATE TABLE IF NOT EXISTS reference (cveid CHAR(13), " + "name varchar(1000), url varchar(1000), source varchar(255))"; /** * SQL Statement to create the software table. */ public static final String CREATE_TABLE_SOFTWARE = "CREATE TABLE IF NOT EXISTS software (cveid CHAR(13), cpe varchar(500), " + "vendor varchar(255), product varchar(255), version varchar(50), previousVersion varchar(50))"; /** * SQL Statement to create the vulnerability table. */ public static final String CREATE_TABLE_VULNERABILITY = "CREATE TABLE IF NOT EXISTS vulnerability (cveid CHAR(13) PRIMARY KEY, " + "description varchar(8000), cwe varchar(10), cvssScore DECIMAL(3,1), cvssAccessVector varchar(20), " + "cvssAccessComplexity varchar(20), cvssAuthentication varchar(20), cvssConfidentialityImpact varchar(20), " + "cvssIntegrityImpact varchar(20), cvssAvailabilityImpact varchar(20))"; /** * SQL Statement to delete references by CVEID. */ public static final String DELETE_REFERENCE = "DELETE FROM reference WHERE cveid = ?"; /** * SQL Statement to delete software by CVEID. */ public static final String DELETE_SOFTWARE = "DELETE FROM software WHERE cveid = ?"; /** * SQL Statement to delete a vulnerability by CVEID. */ public static final String DELETE_VULNERABILITY = "DELETE FROM vulnerability WHERE cveid = ?"; /** * SQL Statement to insert a new reference. */ public static final String INSERT_REFERENCE = "INSERT INTO reference (cveid, name, url, source) VALUES (?, ?, ?, ?)"; /** * SQL Statement to insert a new software. */ public static final String INSERT_SOFTWARE = "INSERT INTO software (cveid, cpe, vendor, product, version, previousVersion) " + "VALUES (?, ?, ?, ?, ?, ?)"; /** * SQL Statement to insert a new vulnerability. */ public static final String INSERT_VULNERABILITY = "INSERT INTO vulnerability (cveid, description, cwe, cvssScore, cvssAccessVector, " + "cvssAccessComplexity, cvssAuthentication, cvssConfidentialityImpact, cvssIntegrityImpact, cvssAvailabilityImpact) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; /** * SQL Statement to find CVE entries based on CPE data. */ public static final String SELECT_CVE_FROM_SOFTWARE = "SELECT cveid FROM software WHERE Vendor = ? AND Product = ? AND " + "(version = '-' OR previousVersion IS NOT NULL OR version=?)"; /** * SQL Statement to select references by CVEID. */ public static final String SELECT_REFERENCE = "SELECT source, name, url FROM reference WHERE cveid = ?"; /** * SQL Statement to select software by CVEID. */ public static final String SELECT_SOFTWARE = "SELECT cpe, previousVersion FROM software WHERE cveid = ?"; /** * SQL Statement to select a vulnerability by CVEID. */ public static final String SELECT_VULNERABILITY = "SELECT cveid, description, cwe, cvssScore, cvssAccessVector, cvssAccessComplexity, " + "cvssAuthentication, cvssConfidentialityImpact, cvssIntegrityImpact, cvssAvailabilityImpact FROM vulnerability WHERE cveid = ?"; //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Collection of CallableStatements to work with the DB"> /** * delete reference - parameters (cveid). */ private CallableStatement deleteReferences; /** * delete software - parameters (cveid). */ private CallableStatement deleteSoftware; /** * delete vulnerability - parameters (cveid). */ private CallableStatement deleteVulnerabilities; /** * insert reference - parameters (cveid, name, url, source). */ private CallableStatement insertReference; /** * insert software - parameters (cveid, cpe, vendor, product, version, previousVersion). */ private CallableStatement insertSoftware; /** * insert vulnerability - parameters (cveid, description, cwe, cvssScore, cvssAccessVector, * cvssAccessComplexity, cvssAuthentication, cvssConfidentialityImpact, cvssIntegrityImpact, cvssAvailabilityImpact). */ private CallableStatement insertVulnerability; /** * select cve from software - parameters (vendor, product, version). */ private CallableStatement selectCveFromSoftware; /** * select vulnerability - parameters (cveid). */ private CallableStatement selectVulnerability; /** * select reference - parameters (cveid). */ private CallableStatement selectReferences; /** * select software - parameters (cveid). */ private CallableStatement selectSoftware; //</editor-fold> /** * Database connection */ private Connection conn; /** * Opens the database connection. If the database does not exist, it will * create a new one. * * @throws IOException thrown if there is an IO Exception * @throws SQLException thrown if there is a SQL Exception * @throws DatabaseException thrown if there is an error initializing a new database * @throws ClassNotFoundException thrown if the h2 database driver cannot be loaded */ @edu.umd.cs.findbugs.annotations.SuppressWarnings( value = "DMI_EMPTY_DB_PASSWORD", justification = "Yes, I know... Blank password.") public void open() throws IOException, SQLException, DatabaseException, ClassNotFoundException { final String fileName = CveDB.getDataDirectory().getCanonicalPath() + File.separator + "cve"; final File f = new File(fileName); final boolean createTables = !f.exists(); final String connStr = "jdbc:h2:file:" + fileName; Class.forName("org.h2.Driver"); conn = DriverManager.getConnection(connStr, "sa", ""); if (createTables) { createTables(); } buildStatements(); } /** * Cleans up the object and ensures that "close" has been called. * @throws Throwable thrown if there is a problem */ @Override protected void finalize() throws Throwable { close(); super.finalize(); //not necessary if extending Object. } /** * Closes the DB4O database. Close should be called on * this object when it is done being used. */ public void close() { if (conn != null) { try { conn.close(); } catch (SQLException ex) { Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex); } conn = null; } } /** * Retrieves the vulnerabilities associated with the specified CPE. * * @param cpeStr the CPE name * @return a list of Vulnerabilities * @throws DatabaseException thrown if there is an exception retrieving data */ public List<Vulnerability> getVulnerabilities(String cpeStr) throws DatabaseException { ResultSet rs = null; final Entry cpe = new Entry(); try { cpe.parseName(cpeStr); } catch (UnsupportedEncodingException ex) { Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex); } final List<Vulnerability> vulnerabilities = new ArrayList<Vulnerability>(); try { selectCveFromSoftware.setString(1, cpe.getVendor()); selectCveFromSoftware.setString(2, cpe.getProduct()); selectCveFromSoftware.setString(3, cpe.getVersion()); rs = selectCveFromSoftware.executeQuery(); while (rs.next()) { final Vulnerability v = getVulnerability(rs.getString("cveid")); vulnerabilities.add(v); } } catch (SQLException ex) { throw new DatabaseException("Exception retrieving vulnerability for " + cpeStr, ex); } finally { if (rs != null) { try { rs.close(); } catch (SQLException ex) { Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex); } } } return vulnerabilities; } /** * Gets a vulnerability for the provided CVE. * * @param cve the CVE to lookup * @return a vulnerability object * @throws DatabaseException if an exception occurs */ private Vulnerability getVulnerability(String cve) throws DatabaseException { ResultSet rsV = null; ResultSet rsR = null; ResultSet rsS = null; Vulnerability vuln = null; try { selectVulnerability.setString(1, cve); rsV = selectVulnerability.executeQuery(); if (rsV.next()) { vuln = new Vulnerability(); vuln.setName(cve); vuln.setDescription(rsV.getString(2)); String cwe = rsV.getString(3); if (cwe != null) { final String name = CweDB.getCweName(cwe); if (name != null) { cwe += " " + name; } } vuln.setCwe(cwe); vuln.setCvssScore(rsV.getFloat(4)); vuln.setCvssAccessVector(rsV.getString(5)); vuln.setCvssAccessComplexity(rsV.getString(6)); vuln.setCvssAuthentication(rsV.getString(7)); vuln.setCvssConfidentialityImpact(rsV.getString(8)); vuln.setCvssIntegrityImpact(rsV.getString(9)); vuln.setCvssAvailabilityImpact(rsV.getString(10)); selectReferences.setString(1, cve); rsR = selectReferences.executeQuery(); while (rsR.next()) { vuln.addReference(rsR.getString(1), rsR.getString(2), rsR.getString(3)); } selectSoftware.setString(1, cve); rsS = selectSoftware.executeQuery(); while (rsS.next()) { final String cpe = rsS.getString(1); final String prevVersion = rsS.getString(2); if (prevVersion == null) { vuln.addVulnerableSoftware(cpe); } else { vuln.addVulnerableSoftware(cpe, prevVersion); } } } } catch (SQLException ex) { throw new DatabaseException("Error retrieving " + cve, ex); } finally { if (rsV != null) { try { rsV.close(); } catch (SQLException ex) { Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex); } } if (rsR != null) { try { rsR.close(); } catch (SQLException ex) { Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex); } } if (rsS != null) { try { rsS.close(); } catch (SQLException ex) { Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex); } } } return vuln; } /** * Updates the vulnerability within the database. If the vulnerability does not * exist it will be added. * * @param vuln the vulnerability to add to the database * @throws DatabaseException is thrown if the database */ public void updateVulnerability(Vulnerability vuln) throws DatabaseException { try { // first delete any existing vulnerability info. deleteReferences.setString(1, vuln.getName()); deleteReferences.execute(); deleteSoftware.setString(1, vuln.getName()); deleteSoftware.execute(); deleteVulnerabilities.setString(1, vuln.getName()); deleteVulnerabilities.execute(); insertVulnerability.setString(1, vuln.getName()); insertVulnerability.setString(2, vuln.getDescription()); insertVulnerability.setString(3, vuln.getCwe()); insertVulnerability.setFloat(4, vuln.getCvssScore()); insertVulnerability.setString(5, vuln.getCvssAccessVector()); insertVulnerability.setString(6, vuln.getCvssAccessComplexity()); insertVulnerability.setString(7, vuln.getCvssAuthentication()); insertVulnerability.setString(8, vuln.getCvssConfidentialityImpact()); insertVulnerability.setString(9, vuln.getCvssIntegrityImpact()); insertVulnerability.setString(10, vuln.getCvssAvailabilityImpact()); insertVulnerability.execute(); insertReference.setString(1, vuln.getName()); for (Reference r : vuln.getReferences()) { insertReference.setString(2, r.getName()); insertReference.setString(3, r.getUrl()); insertReference.setString(4, r.getSource()); insertReference.execute(); } insertSoftware.setString(1, vuln.getName()); for (VulnerableSoftware s : vuln.getVulnerableSoftware()) { //cveid, cpe, vendor, product, version, previousVersion insertSoftware.setString(2, s.getName()); insertSoftware.setString(3, s.getVendor()); insertSoftware.setString(4, s.getProduct()); insertSoftware.setString(5, s.getVersion()); if (s.hasPreviousVersion()) { insertSoftware.setString(6, s.getPreviousVersion()); } else { insertSoftware.setNull(6, java.sql.Types.VARCHAR); } insertSoftware.execute(); } } catch (SQLException ex) { Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex); throw new DatabaseException("Error updating '" + vuln.getName() + "'", ex); } } /** * Retrieves the directory that the JAR file exists in so that * we can ensure we always use a common data directory. * * @return the data directory for this index. * @throws IOException is thrown if an IOException occurs of course... */ public static File getDataDirectory() throws IOException { final String fileName = Settings.getString(Settings.KEYS.CVE_INDEX); final File path = FileUtils.getDataDirectory(fileName, CveDB.class); if (!path.exists()) { if (!path.mkdirs()) { throw new IOException("Unable to create NVD CVE Data directory"); } } return path; } /** * Creates the database structure (tables and indexes) to store the CVE data * * @throws SQLException thrown if there is a sql exception * @throws DatabaseException thrown if there is a database exception */ protected void createTables() throws SQLException, DatabaseException { Statement statement = null; try { statement = conn.createStatement(); statement.execute(CREATE_TABLE_VULNERABILITY); statement.execute(CREATE_TABLE_REFERENCE); statement.execute(CREATE_TABLE_SOFTWARE); statement.execute(CREATE_INDEX_IDXSOFTWARE); statement.execute(CREATE_INDEX_IDXREFERENCE); statement.execute(CREATE_INDEX_IDXVULNERABILITY); statement.execute(CREATE_INDEX_IDXSOFTWARECVE); } finally { if (statement != null) { try { statement.close(); } catch (SQLException ex) { Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex); } } } } /** * Builds the CallableStatements used by the application. * @throws DatabaseException thrown if there is a database exception */ private void buildStatements() throws DatabaseException { try { deleteReferences = conn.prepareCall(DELETE_REFERENCE); deleteSoftware = conn.prepareCall(DELETE_SOFTWARE); deleteVulnerabilities = conn.prepareCall(DELETE_VULNERABILITY); insertReference = conn.prepareCall(INSERT_REFERENCE); insertSoftware = conn.prepareCall(INSERT_SOFTWARE); insertVulnerability = conn.prepareCall(INSERT_VULNERABILITY); selectCveFromSoftware = conn.prepareCall(SELECT_CVE_FROM_SOFTWARE); selectVulnerability = conn.prepareCall(SELECT_VULNERABILITY); selectReferences = conn.prepareCall(SELECT_REFERENCE); selectSoftware = conn.prepareCall(SELECT_SOFTWARE); } catch (SQLException ex) { throw new DatabaseException("Unable to prepare statements", ex); } } }
package org.pfaa.chemica.registration; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.pfaa.chemica.Chemica; import org.pfaa.chemica.item.MaterialStack; import org.pfaa.chemica.model.Aggregate; import org.pfaa.chemica.model.Aggregate.Aggregates; import org.pfaa.chemica.model.Compound.Compounds; import org.pfaa.chemica.model.Condition; import org.pfaa.chemica.model.Element; import org.pfaa.chemica.model.Mixture; import org.pfaa.chemica.model.MixtureComponent; import org.pfaa.chemica.model.State; import org.pfaa.chemica.processing.Form; import org.pfaa.chemica.processing.Form.Forms; import org.pfaa.chemica.util.ChanceStack; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import cpw.mods.fml.common.ObfuscationReflectionHelper; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.ShapedRecipes; import net.minecraft.item.crafting.ShapelessRecipes; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; public class RecipeUtils { public static ItemStack getPrimaryGrindingOutput(Mixture mixture) { List<MixtureComponent> comps = mixture.getComponents(); MixtureComponent input; if (comps.size() > 0) { input = comps.get(0); } else { input = new MixtureComponent(mixture, 1.0F); } return getGrindingOutputItemStack(input); } public static List<ChanceStack> getSecondaryGrindingOutputs(Mixture mixture, boolean excludeAggregates) { List<MixtureComponent> components = mixture.getComponents(); Iterable<MixtureComponent> secondaries = components.subList(components.size() > 0 ? 1 : 0, components.size()); if (excludeAggregates) { secondaries = Iterables.filter(secondaries, notAggregate); } return Lists.newArrayList(Iterables.transform(secondaries, mixtureComponentToGrindingOutput)); } public static ItemStack getGrindingOutputItemStack(MixtureComponent input) { Form form = Forms.DUST; if (input.material == Aggregates.SAND || input.material == Aggregates.GRAVEL) { form = Forms.PILE; } else if (input.weight < 1.0F) { form = Forms.TINY_DUST; } return OreDictUtils.lookupBest(form, input.material); } private static final float TINY_DUST_WEIGHT = 0.1F; private static Function<MixtureComponent,ChanceStack> mixtureComponentToGrindingOutput = new Function<MixtureComponent,ChanceStack>() { @Override public ChanceStack apply(MixtureComponent input) { return getGrindingOutput(input); } }; private static Predicate<MixtureComponent> notAggregate = new Predicate<MixtureComponent>() { public boolean apply(MixtureComponent obj) { return !(obj.material instanceof Aggregate); } }; public static ChanceStack getGrindingOutput(MixtureComponent input) { float weight = (float)input.weight; ItemStack itemStack = getGrindingOutputItemStack(input); if (weight < 1.0F) { int ntiny = (int)(weight / TINY_DUST_WEIGHT); if (ntiny > 0) { itemStack = itemStack.copy(); itemStack.stackSize = ntiny; weight = 1.0F; } else { weight = weight / TINY_DUST_WEIGHT; } } return new ChanceStack(itemStack, weight); } public static void oreDictifyRecipes(Map<ItemStack, String> replacements, ItemStack[] exclusions) { ItemStack[] replaceStacks = replacements.keySet().toArray(new ItemStack[0]); @SuppressWarnings("unchecked") List<IRecipe> recipes = CraftingManager.getInstance().getRecipeList(); List<IRecipe> recipesToRemove = new ArrayList<IRecipe>(); List<IRecipe> recipesToAdd = new ArrayList<IRecipe>(); // Search vanilla recipes for recipes to replace for(IRecipe recipe : recipes) { ItemStack output = recipe.getRecipeOutput(); if (output != null && hasItem(false, exclusions, output)) { //FMLLog.info("excluded recipe: %s", output.getItemName()); continue; } Object[] ingredients = getIngredients(recipe); if(hasItem(true, ingredients, replaceStacks)) { try { recipesToAdd.add(createOreRecipe(recipe, replacements)); recipesToRemove.add(recipe); } catch (Exception e) { Chemica.log.warn("Failed to ore dictify recipe for '" + output.getUnlocalizedName() + "'"); } } } recipes.removeAll(recipesToRemove); recipes.addAll(recipesToAdd); } private static Object[] getIngredients(IRecipe obj) { if (obj instanceof ShapedRecipes) { return ((ShapedRecipes) obj).recipeItems; } if (obj instanceof ShapelessRecipes) { return ((ShapelessRecipes) obj).recipeItems.toArray(); } if (obj instanceof ShapedOreRecipe) { return ((ShapedOreRecipe) obj).getInput(); } if (obj instanceof ShapelessOreRecipe) { return ((ShapelessOreRecipe) obj).getInput().toArray(); } return new Object[] { }; } private static boolean hasItem(boolean strict, Object[] recipe, ItemStack... ingredients) { for (Object recipeIngredient : recipe) { if (recipeIngredient instanceof ItemStack) { for (ItemStack ingredient : ingredients) { if (OreDictionary.itemMatches(ingredient, (ItemStack)recipeIngredient, strict)) { return true; } } } } return false; } private static <T extends IRecipe> T createOreRecipe(Class<T> klass, IRecipe recipe, Map<ItemStack, String> replacements) throws Exception { Constructor<T> constructor = klass.getDeclaredConstructor(recipe.getClass(), Map.class); constructor.setAccessible(true); T replacedRecipe = constructor.newInstance(recipe, replacements); return replacedRecipe; } private static IRecipe createOreRecipe(IRecipe recipe, Map<ItemStack, String> replacements) throws Exception { if (recipe instanceof ShapedRecipes) { return createOreRecipe(ShapedOreRecipe.class, recipe, replacements); } else if (recipe instanceof ShapelessRecipes) { return createOreRecipe(ShapelessOreRecipe.class, recipe, replacements); } else if (recipe instanceof ShapedOreRecipe) { return recreateOreRecipe((ShapedOreRecipe)recipe, replacements); } else if (recipe instanceof ShapelessOreRecipe) { return recreateOreRecipe((ShapelessOreRecipe)recipe, replacements); } throw new IllegalArgumentException("Unknown recipe type"); } private static IRecipe recreateOreRecipe(ShapelessOreRecipe recipe, Map<ItemStack, String> replacements) { Object[] ingredients = recipe.getInput().toArray(); replaceIngredients(ingredients, replacements); return new ShapelessOreRecipe(recipe.getRecipeOutput(), ingredients); } private static IRecipe recreateOreRecipe(ShapedOreRecipe recipe, Map<ItemStack, String> replacements) { Object[] ingredients = recipe.getInput().clone(); replaceIngredients(ingredients, replacements); return recreateOreRecipe(recipe, recipe.getRecipeOutput(), ingredients); } public static IRecipe recreateOreRecipe(ShapedOreRecipe template, ItemStack output, Object[] input) { int width = ObfuscationReflectionHelper.getPrivateValue(ShapedOreRecipe.class, template, "width"); int height = ObfuscationReflectionHelper.getPrivateValue(ShapedOreRecipe.class, template, "height"); for (int i = 0; i < input.length; i++) { if (input[i] instanceof String) { input[i] = OreDictionary.getOres((String) input[i]); } } ShapedOreRecipe recipe = new ShapedOreRecipe(output, 'x', Blocks.anvil); ObfuscationReflectionHelper.setPrivateValue(ShapedOreRecipe.class, recipe, input, "input"); /* field names repeated to dispatch to correct overload */ ObfuscationReflectionHelper.setPrivateValue(ShapedOreRecipe.class, recipe, width, "width", "width"); ObfuscationReflectionHelper.setPrivateValue(ShapedOreRecipe.class, recipe, height, "height", "height"); return recipe; } private static void replaceIngredients(Object[] ingredients, Map<ItemStack, String> replacements) { for (int i = 0; i < ingredients.length; i++) { if (ingredients[i] instanceof ItemStack) { ItemStack ingredient = (ItemStack)ingredients[i]; for(Entry<ItemStack, String> replace : replacements.entrySet()) { if(OreDictionary.itemMatches(replace.getKey(), ingredient, true)) { ingredients[i] = replace.getValue(); break; } } } } } }
package sc.yhy.servlet; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * servlet * * @author YHY * */ public abstract class BaseServlet extends HttpServlet { static final Logger logfile = Logger.getLogger(BaseServlet.class.getName()); private static final long serialVersionUID = 9074877621851516177L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.genery(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.genery(request, response); } private void genery(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); long start = 0l, end = 0l; start = System.currentTimeMillis(); try { this.before(request, response); this.doServlet(request, response); this.after(request, response); } catch (Exception e) { logfile.info(e.getMessage()); } finally { this.isCommitted(response); } end = System.currentTimeMillis(); System.out.println("=" + (end - start) + " ms"); } private void isCommitted(HttpServletResponse response) { // if (response.isCommitted()) { // System.out.println("isCommitted=true"); // return; // } else { // System.out.println("isCommitted=false"); // return; } protected void sendRedirect(HttpServletResponse response, String url) throws IOException { response.sendRedirect(url); } protected void dispatcherForward(HttpServletRequest request, HttpServletResponse response, String url) throws IOException, ServletException { RequestDispatcher rd = request.getRequestDispatcher(url); rd.forward(request, response); } protected String getRequestParamValue(HttpServletRequest request, String key) { return request.getParameter(key); } protected String[] getRequestParamValues(HttpServletRequest request, String key) { return request.getParameterValues(key); } protected abstract void before(HttpServletRequest request, HttpServletResponse response) throws Exception; protected abstract void doServlet(HttpServletRequest request, HttpServletResponse response) throws Exception; protected abstract void after(HttpServletRequest request, HttpServletResponse response) throws Exception; }
package org.sagebionetworks.web.client; import static org.sagebionetworks.web.client.ClientProperties.ALERT_CONTAINER_ID; import static org.sagebionetworks.web.client.ClientProperties.DEFAULT_PLACE_TOKEN; import static org.sagebionetworks.web.client.ClientProperties.ERROR_OBJ_REASON_KEY; import static org.sagebionetworks.web.client.ClientProperties.ESCAPE_CHARACTERS_SET; import static org.sagebionetworks.web.client.ClientProperties.FULL_ENTITY_TOP_MARGIN_PX; import static org.sagebionetworks.web.client.ClientProperties.GB; import static org.sagebionetworks.web.client.ClientProperties.IMAGE_CONTENT_TYPES_SET; import static org.sagebionetworks.web.client.ClientProperties.KB; import static org.sagebionetworks.web.client.ClientProperties.MB; import static org.sagebionetworks.web.client.ClientProperties.REGEX_CLEAN_ANNOTATION_KEY; import static org.sagebionetworks.web.client.ClientProperties.REGEX_CLEAN_ENTITY_NAME; import static org.sagebionetworks.web.client.ClientProperties.STYLE_DISPLAY_INLINE; import static org.sagebionetworks.web.client.ClientProperties.TB; import static org.sagebionetworks.web.client.ClientProperties.WHITE_SPACE; import static org.sagebionetworks.web.client.ClientProperties.WIKI_URL; 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.sagebionetworks.gwt.client.schema.adapter.DateUtils; import org.sagebionetworks.markdown.constants.WidgetConstants; import org.sagebionetworks.repo.model.AccessRequirement; import org.sagebionetworks.repo.model.Analysis; import org.sagebionetworks.repo.model.Annotations; import org.sagebionetworks.repo.model.Code; import org.sagebionetworks.repo.model.Data; import org.sagebionetworks.repo.model.Entity; import org.sagebionetworks.repo.model.EntityHeader; import org.sagebionetworks.repo.model.EntityPath; import org.sagebionetworks.repo.model.ExpressionData; import org.sagebionetworks.repo.model.FileEntity; import org.sagebionetworks.repo.model.Folder; import org.sagebionetworks.repo.model.GenotypeData; import org.sagebionetworks.repo.model.Link; import org.sagebionetworks.repo.model.Page; import org.sagebionetworks.repo.model.PhenotypeData; import org.sagebionetworks.repo.model.Project; import org.sagebionetworks.repo.model.RObject; import org.sagebionetworks.repo.model.Reference; import org.sagebionetworks.repo.model.Step; import org.sagebionetworks.repo.model.Study; import org.sagebionetworks.repo.model.Summary; import org.sagebionetworks.repo.model.UserGroupHeader; import org.sagebionetworks.repo.model.UserProfile; import org.sagebionetworks.repo.model.UserSessionData; import org.sagebionetworks.repo.model.Versionable; import org.sagebionetworks.repo.model.file.FileHandle; import org.sagebionetworks.repo.model.file.PreviewFileHandle; import org.sagebionetworks.repo.model.table.TableEntity; import org.sagebionetworks.schema.FORMAT; import org.sagebionetworks.schema.ObjectSchema; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.web.client.cookie.CookieProvider; import org.sagebionetworks.web.client.events.CancelEvent; import org.sagebionetworks.web.client.events.CancelHandler; import org.sagebionetworks.web.client.events.EntityUpdatedEvent; import org.sagebionetworks.web.client.events.EntityUpdatedHandler; import org.sagebionetworks.web.client.model.EntityBundle; import org.sagebionetworks.web.client.place.Down; import org.sagebionetworks.web.client.place.Help; import org.sagebionetworks.web.client.place.Home; import org.sagebionetworks.web.client.place.LoginPlace; import org.sagebionetworks.web.client.place.Search; import org.sagebionetworks.web.client.place.Synapse; import org.sagebionetworks.web.client.place.Team; import org.sagebionetworks.web.client.place.TeamSearch; import org.sagebionetworks.web.client.place.Wiki; import org.sagebionetworks.web.client.utils.Callback; import org.sagebionetworks.web.client.utils.CallbackP; import org.sagebionetworks.web.client.utils.TOOLTIP_POSITION; import org.sagebionetworks.web.client.widget.Alert; import org.sagebionetworks.web.client.widget.Alert.AlertType; import org.sagebionetworks.web.client.widget.FitImage; import org.sagebionetworks.web.client.widget.entity.JiraURLHelper; import org.sagebionetworks.web.client.widget.entity.WidgetSelectionState; import org.sagebionetworks.web.client.widget.entity.browse.EntityFinder; import org.sagebionetworks.web.client.widget.entity.dialog.ANNOTATION_TYPE; import org.sagebionetworks.web.client.widget.entity.download.Uploader; import org.sagebionetworks.web.client.widget.sharing.AccessControlListEditor; import org.sagebionetworks.web.client.widget.table.TableCellFileHandle; import org.sagebionetworks.web.shared.EntityType; import org.sagebionetworks.web.shared.EntityWrapper; import org.sagebionetworks.web.shared.NodeType; import org.sagebionetworks.web.shared.PublicPrincipalIds; import org.sagebionetworks.web.shared.WebConstants; import org.sagebionetworks.web.shared.WikiPageKey; import org.sagebionetworks.web.shared.exceptions.BadRequestException; import org.sagebionetworks.web.shared.exceptions.ForbiddenException; import org.sagebionetworks.web.shared.exceptions.NotFoundException; import org.sagebionetworks.web.shared.exceptions.ReadOnlyModeException; import org.sagebionetworks.web.shared.exceptions.RestServiceException; import org.sagebionetworks.web.shared.exceptions.SynapseDownException; import org.sagebionetworks.web.shared.exceptions.UnauthorizedException; import org.sagebionetworks.web.shared.exceptions.UnknownErrorException; import com.extjs.gxt.ui.client.Style.HorizontalAlignment; import com.extjs.gxt.ui.client.event.BaseEvent; import com.extjs.gxt.ui.client.event.ButtonEvent; import com.extjs.gxt.ui.client.event.Events; import com.extjs.gxt.ui.client.event.Listener; import com.extjs.gxt.ui.client.event.SelectionListener; import com.extjs.gxt.ui.client.widget.Component; import com.extjs.gxt.ui.client.widget.ContentPanel; import com.extjs.gxt.ui.client.widget.Dialog; import com.extjs.gxt.ui.client.widget.Html; import com.extjs.gxt.ui.client.widget.LayoutContainer; import com.extjs.gxt.ui.client.widget.Text; import com.extjs.gxt.ui.client.widget.Window; import com.extjs.gxt.ui.client.widget.button.Button; import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction; import com.extjs.gxt.ui.client.widget.form.SimpleComboBox; import com.extjs.gxt.ui.client.widget.layout.CenterLayout; import com.extjs.gxt.ui.client.widget.layout.FitData; import com.extjs.gxt.ui.client.widget.layout.FitLayout; import com.extjs.gxt.ui.client.widget.layout.MarginData; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.NodeList; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.DomEvent; import com.google.gwt.event.dom.client.MouseOutEvent; import com.google.gwt.event.dom.client.MouseOutHandler; import com.google.gwt.event.dom.client.MouseOverEvent; import com.google.gwt.event.dom.client.MouseOverHandler; import com.google.gwt.event.logical.shared.AttachEvent; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.json.client.JSONNumber; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONValue; import com.google.gwt.place.shared.Place; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.AbstractImagePrototype; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.FocusWidget; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.InlineHTML; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.Widget; public class DisplayUtils { private static Logger displayUtilsLogger = Logger.getLogger(DisplayUtils.class.getName()); public static PublicPrincipalIds publicPrincipalIds = null; public static enum MessagePopup { INFO, WARNING, QUESTION } public static final String[] ENTITY_TYPE_DISPLAY_ORDER = new String[] { Folder.class.getName(), Study.class.getName(), Data.class.getName(), Code.class.getName(), Link.class.getName(), Analysis.class.getName(), Step.class.getName(), RObject.class.getName(), PhenotypeData.class.getName(), ExpressionData.class.getName(), GenotypeData.class.getName() }; /** * Returns a properly aligned icon from an ImageResource * @param icon * @return */ public static String getIconHtml(ImageResource icon) { if(icon == null) return null; return "<span class=\"iconSpan\">" + AbstractImagePrototype.create(icon).getHTML() + "</span>"; } /** * Returns a properly aligned icon from an ImageResource * @param icon * @return */ public static String getIconThumbnailHtml(ImageResource icon) { if(icon == null) return null; return "<span class=\"thumbnail-image-container\">" + AbstractImagePrototype.create(icon).getHTML() + "</span>"; } /** * Returns a properly aligned name and description for a special user or group * @param name of user or group * @return */ public static String getUserNameDescriptionHtml(String name, String description) { return DisplayUtilsGWT.TEMPLATES.nameAndUsername(name, description).asString(); } /** * Returns html for a thumbnail image. * * @param url * @return */ public static String getThumbnailPicHtml(String url) { if(url == null) return null; return DisplayUtilsGWT.TEMPLATES.profilePicture(url).asString(); } /** * Converts all hrefs to gwt anchors, and handles the anchors by sending them to a new window. * @param panel */ public static void sendAllLinksToNewWindow(HTMLPanel panel){ NodeList<com.google.gwt.dom.client.Element> anchors = panel.getElement().getElementsByTagName("a"); for ( int i = 0 ; i < anchors.getLength() ; i++ ) { com.google.gwt.dom.client.Element a = anchors.getItem(i); JSONObject jsonValue = new JSONObject(a); JSONValue hrefJSONValue = jsonValue.get("href"); if (hrefJSONValue != null){ final String href = hrefJSONValue.toString().replaceAll("\"", ""); String innerText = a.getInnerText(); Anchor link = new Anchor(); link.setStylePrimaryName("link"); link.setText(innerText); link.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { com.google.gwt.user.client.Window.open(href, "_blank", ""); } }); panel.addAndReplaceElement(link, a); } } } /** * Add a row to the provided FlexTable. * * @param key * @param value * @param table */ public static void addRowToTable(int row, String key, String value, FlexTable table) { addRowToTable(row, key, value, "boldRight", table); table.setHTML(row, 1, value); } public static void addRowToTable(int row, String key, String value, String styleName, FlexTable table) { table.setHTML(row, 0, key); table.getCellFormatter().addStyleName(row, 0, styleName); table.setHTML(row, 1, value); } public static void addRowToTable(int row, String label, Anchor key, String value, String styleName, FlexTable table) { table.setHTML(row, 0, label); table.getCellFormatter().addStyleName(row, 0, styleName); table.setWidget(row, 1, key); table.setHTML(row, 2, value); } public static String getFriendlySize(double size, boolean abbreviatedUnits) { NumberFormat df = NumberFormat.getDecimalFormat(); if(size >= TB) { return df.format(size/TB) + (abbreviatedUnits?" TB":" Terabytes"); } if(size >= GB) { return df.format(size/GB) + (abbreviatedUnits?" GB":" Gigabytes"); } if(size >= MB) { return df.format(size/MB) + (abbreviatedUnits?" MB":" Megabytes"); } if(size >= KB) { return df.format(size/KB) + (abbreviatedUnits?" KB":" Kilobytes"); } return df.format(size) + " bytes"; } /** * Use an EntityWrapper instead and check for an exception there * @param obj * @throws RestServiceException */ @Deprecated public static void checkForErrors(JSONObject obj) throws RestServiceException { if(obj == null) return; if(obj.containsKey("error")) { JSONObject errorObj = obj.get("error").isObject(); if(errorObj.containsKey("statusCode")) { JSONNumber codeObj = errorObj.get("statusCode").isNumber(); if(codeObj != null) { int code = ((Double)codeObj.doubleValue()).intValue(); if(code == 401) { // UNAUTHORIZED throw new UnauthorizedException(); } else if(code == 403) { // FORBIDDEN throw new ForbiddenException(); } else if (code == 404) { // NOT FOUND throw new NotFoundException(); } else if (code == 400) { // Bad Request String message = ""; if(obj.containsKey(ERROR_OBJ_REASON_KEY)) { message = obj.get(ERROR_OBJ_REASON_KEY).isString().stringValue(); } throw new BadRequestException(message); } else { throw new UnknownErrorException("Unknown Service error. code: " + code); } } } } } public static String getFileNameFromExternalUrl(String path){ //grab the text between the last '/' and following '?' String fileName = ""; if (path != null) { int lastSlash = path.lastIndexOf("/"); if (lastSlash > -1) { int firstQuestionMark = path.indexOf("?", lastSlash); if (firstQuestionMark > -1) { fileName = path.substring(lastSlash+1, firstQuestionMark); } else { fileName = path.substring(lastSlash+1); } } } return fileName; } /** * Handles the exception. Returns true if the user has been alerted to the exception already * @param ex * @param placeChanger * @return true if the user has been prompted */ public static boolean handleServiceException(Throwable ex, GlobalApplicationState globalApplicationState, boolean isLoggedIn, SynapseView view) { //send exception to the javascript console if (displayUtilsLogger != null && ex != null) displayUtilsLogger.log(Level.SEVERE, ex.getMessage()); if(ex instanceof ReadOnlyModeException) { view.showErrorMessage(DisplayConstants.SYNAPSE_IN_READ_ONLY_MODE); return true; } else if(ex instanceof SynapseDownException) { globalApplicationState.getPlaceChanger().goTo(new Down(DEFAULT_PLACE_TOKEN)); return true; } else if(ex instanceof UnauthorizedException) { // send user to login page showInfo(DisplayConstants.SESSION_TIMEOUT, DisplayConstants.SESSION_HAS_TIMED_OUT); globalApplicationState.getPlaceChanger().goTo(new LoginPlace(LoginPlace.LOGIN_TOKEN)); return true; } else if(ex instanceof ForbiddenException) { if(!isLoggedIn) { view.showErrorMessage(DisplayConstants.ERROR_LOGIN_REQUIRED); globalApplicationState.getPlaceChanger().goTo(new LoginPlace(LoginPlace.LOGIN_TOKEN)); } else { view.showErrorMessage(DisplayConstants.ERROR_FAILURE_PRIVLEDGES); } return true; } else if(ex instanceof BadRequestException) { //exception handling on the backend now throws the reason into the exception message. Easy! showErrorMessage(ex, globalApplicationState.getJiraURLHelper(), isLoggedIn, ex.getMessage()); return true; } else if(ex instanceof NotFoundException) { view.showErrorMessage(DisplayConstants.ERROR_NOT_FOUND); globalApplicationState.getPlaceChanger().goTo(new Home(DEFAULT_PLACE_TOKEN)); return true; } // For other exceptions, allow the consumer to send a good message to the user return false; } public static boolean checkForRepoDown(Throwable caught, PlaceChanger placeChanger, SynapseView view) { if(caught instanceof ReadOnlyModeException) { view.showErrorMessage(DisplayConstants.SYNAPSE_IN_READ_ONLY_MODE); return true; } else if(caught instanceof SynapseDownException) { placeChanger.goTo(new Down(DEFAULT_PLACE_TOKEN)); return true; } return false; } /** * Handle JSONObjectAdapterException. This will occur when the client is pointing to an incompatible repo version. * @param ex * @param placeChanger */ public static boolean handleJSONAdapterException(JSONObjectAdapterException ex, PlaceChanger placeChanger, UserSessionData currentUser) { DisplayUtils.showInfoDialog("Incompatible Client Version", DisplayConstants.ERROR_INCOMPATIBLE_CLIENT_VERSION, null); placeChanger.goTo(new Home(DEFAULT_PLACE_TOKEN)); return true; } /* * Button Saving */ public static void changeButtonToSaving(Button button, SageImageBundle sageImageBundle) { button.setText(DisplayConstants.BUTTON_SAVING); button.setIcon(AbstractImagePrototype.create(sageImageBundle.loading16())); } /* * Button Saving */ public static void changeButtonToSaving(com.google.gwt.user.client.ui.Button button) { button.addStyleName("disabled"); button.setHTML(SafeHtmlUtils.fromSafeConstant(DisplayConstants.BUTTON_SAVING + "...")); } /** * Check if an Annotation key is valid with the repository service * @param key * @return */ public static boolean validateAnnotationKey(String key) { if(key.matches(REGEX_CLEAN_ANNOTATION_KEY)) { return true; } return false; } /** * Check if an Entity (Node) name is valid with the repository service * @param key * @return */ public static boolean validateEntityName(String key) { if(key.matches(REGEX_CLEAN_ENTITY_NAME)) { return true; } return false; } /** * Cleans any invalid name characters from a string * @param str * @return */ public static String getOffendingCharacterForEntityName(String key) { return getOffendingCharacter(key, REGEX_CLEAN_ENTITY_NAME); } /** * Cleans any invalid name characters from a string * @param str * @return */ public static String getOffendingCharacterForAnnotationKey(String key) { return getOffendingCharacter(key, REGEX_CLEAN_ANNOTATION_KEY); } /** * Returns a ContentPanel used to show a component is loading in the view * @param sageImageBundle * @return */ public static ContentPanel getLoadingWidget(SageImageBundle sageImageBundle) { ContentPanel cp = new ContentPanel(); cp.setHeaderVisible(false); cp.setCollapsible(true); cp.setLayout(new CenterLayout()); cp.add(new HTML(SafeHtmlUtils.fromSafeConstant(DisplayUtils.getIconHtml(sageImageBundle.loading31())))); return cp; } public static String getLoadingHtml(SageImageBundle sageImageBundle) { return getLoadingHtml(sageImageBundle, DisplayConstants.LOADING); } public static String getLoadingHtml(SageImageBundle sageImageBundle, String message) { return DisplayUtils.getIconHtml(sageImageBundle.loading16()) + " " + message + "..."; } /** * Shows an info message to the user in the "Global Alert area". * For more precise control over how the message appears, * use the {@link displayGlobalAlert(Alert)} method. * @param title * @param message */ public static void showInfo(String title, String message) { Alert alert = new Alert(title, message, false); alert.setAlertType(AlertType.Info); alert.setTimeout(4000); displayGlobalAlert(alert); } /** * Shows an warning message to the user in the "Global Alert area". * For more precise control over how the message appears, * use the {@link displayGlobalAlert(Alert)} method. * @param title * @param message */ public static void showError(String title, String message, Integer timeout) { Alert alert = new Alert(title, message, true); alert.setAlertType(AlertType.Error); if(timeout != null) { alert.setTimeout(timeout); } displayGlobalAlert(alert); } public static void showErrorMessage(String message) { showPopup("", message, MessagePopup.WARNING, 300, DisplayConstants.OK, null, null, null); } /** * @param t * @param jiraHelper * @param profile * @param friendlyErrorMessage * (optional) */ public static void showErrorMessage(final Throwable t, final JiraURLHelper jiraHelper, boolean isLoggedIn, String friendlyErrorMessage) { if (!isLoggedIn) { showErrorMessage(t.getMessage()); return; } final Dialog d = new Dialog(); d.addStyleName("padding-5"); final String errorMessage = friendlyErrorMessage == null ? t.getMessage() : friendlyErrorMessage; HTML errorContent = new HTML( getIcon("glyphicon-exclamation-sign margin-right-10 font-size-22 alert-danger") + errorMessage); FlowPanel dialogContent = new FlowPanel(); dialogContent.addStyleName("margin-10"); dialogContent.add(errorContent); // create text area for steps FlowPanel formGroup = new FlowPanel(); formGroup.addStyleName("form-group margin-top-10"); formGroup.add(new HTML("<label>Describe the problem (optional)</label>")); final TextArea textArea = new TextArea(); textArea.addStyleName("form-control"); textArea.getElement().setAttribute("placeholder","Steps to reproduce the error"); textArea.getElement().setAttribute("rows", "4"); formGroup.add(textArea); dialogContent.add(formGroup); d.add(dialogContent); d.setAutoHeight(true); d.setHideOnButtonClick(true); d.setWidth(400); d.setPlain(true); d.setModal(true); d.setLayout(new FitLayout()); d.setButtonAlign(HorizontalAlignment.RIGHT); d.setHeading("Synapse Error"); d.yesText = DisplayConstants.SEND_BUG_REPORT; d.noText = DisplayConstants.DO_NOT_SEND_BUG_REPORT; d.setButtons(Dialog.YESNO); com.extjs.gxt.ui.client.widget.button.Button yesButton = d.getButtonById(Dialog.YES); yesButton.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { jiraHelper.createIssueOnBackend(textArea.getValue(), t, errorMessage, new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { showInfo("Report sent", "Thank you!"); } @Override public void onFailure(Throwable caught) { // failure to create issue! DisplayUtils.showErrorMessage(DisplayConstants.ERROR_GENERIC_NOTIFY+"\n" + caught.getMessage() +"\n\n" + textArea.getValue()); } }); } }); d.show(); } public static void showInfoDialog( String title, String message, Callback okCallback ) { showPopup(title, message, MessagePopup.INFO, 300, DisplayConstants.OK, okCallback, null, null); } public static void showConfirmDialog( String title, String message, Callback yesCallback, Callback noCallback ) { showPopup(title, message, MessagePopup.QUESTION, 300, DisplayConstants.YES, yesCallback, DisplayConstants.NO, noCallback); } public static void showConfirmDialog( String title, String message, Callback yesCallback ) { showConfirmDialog(title, message, yesCallback, new Callback() { @Override public void invoke() { //do nothing when No is clicked } }); } public static void showOkCancelMessage( String title, String message, MessagePopup iconStyle, int minWidth, Callback okCallback, Callback cancelCallback) { showPopup(title, message, iconStyle, minWidth, DisplayConstants.OK, okCallback, DisplayConstants.BUTTON_CANCEL, cancelCallback); } public static void showPopup(String title, String message, DisplayUtils.MessagePopup iconStyle, int minWidth, String primaryButtonText, final Callback primaryButtonCallback, String secondaryButtonText, final Callback secondaryButtonCallback) { final Window dialog = new Window(); dialog.setMaximizable(false); dialog.setSize(minWidth, 100); dialog.setPlain(true); dialog.setModal(true); dialog.setAutoHeight(true); dialog.setResizable(false); dialog.setClosable(false); //do not include x button in upper right String iconHtml = ""; if (MessagePopup.INFO.equals(iconStyle)) iconHtml = getIcon("glyphicon-info-sign font-size-22 margin-top-10 margin-left-10"); else if (MessagePopup.WARNING.equals(iconStyle)) iconHtml = getIcon("glyphicon-exclamation-sign font-size-22 margin-top-10 margin-left-10"); else if (MessagePopup.QUESTION.equals(iconStyle)) iconHtml = getIcon("glyphicon-question-sign font-size-22 margin-top-10 margin-left-10"); HorizontalPanel content = new HorizontalPanel(); if (iconHtml.length() > 0) content.add(new HTML(iconHtml)); HTMLPanel messagePanel = new HTMLPanel("h6", SafeHtmlUtils.htmlEscape(message)); messagePanel.addStyleName("margin-top-10 margin-left-10 margin-bottom-20"); messagePanel.setWidth((minWidth-75) + "px"); content.add(messagePanel); content.setWidth("100%"); content.addStyleName("whiteBackground padding-5"); dialog.add(content); dialog.setHeading(title); FlowPanel buttonPanel = new FlowPanel(); buttonPanel.setHeight("50px"); buttonPanel.addStyleName("whiteBackground"); boolean isSecondaryButton = secondaryButtonText != null; com.google.gwt.user.client.ui.Button continueButton = DisplayUtils .createButton(primaryButtonText, ButtonType.PRIMARY); continueButton.addStyleName("right margin-right-10 margin-bottom-10"); continueButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { dialog.hide(); if (primaryButtonCallback != null) primaryButtonCallback.invoke(); } }); buttonPanel.add(continueButton); if (isSecondaryButton) { com.google.gwt.user.client.ui.Button cancelButton = DisplayUtils .createButton(secondaryButtonText); cancelButton.addStyleName("right margin-bottom-10 margin-right-10"); cancelButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { dialog.hide(); if (secondaryButtonCallback != null) secondaryButtonCallback.invoke(); } }); buttonPanel.add(cancelButton); } dialog.add(buttonPanel); dialog.show(); center(dialog); } public static void center(Window window) { int left = (com.google.gwt.user.client.Window.getClientWidth() - window.getOffsetWidth()) / 2; int top = (com.google.gwt.user.client.Window.getClientHeight() - window.getOffsetHeight()) / 2; window.setPosition(left, top); com.google.gwt.user.client.Window.scrollTo(0, 0); } public static String getPrimaryEmail(UserProfile userProfile) { List<String> emailAddresses = userProfile.getEmails(); if (emailAddresses == null || emailAddresses.isEmpty()) throw new IllegalStateException("UserProfile email list is empty"); return emailAddresses.get(0); } public static String getDisplayName(UserProfile profile) { return getDisplayName(profile.getFirstName(), profile.getLastName(), profile.getUserName()); } public static String getDisplayName(UserGroupHeader header) { return DisplayUtils.getDisplayName(header.getFirstName(), header.getLastName(), header.getUserName()); } public static String getDisplayName(String firstName, String lastName, String userName) { StringBuilder sb = new StringBuilder(); boolean hasDisplayName = false; if (firstName != null && firstName.length() > 0) { sb.append(firstName.trim()); hasDisplayName = true; } if (lastName != null && lastName.length() > 0) { sb.append(" "); sb.append(lastName.trim()); hasDisplayName = true; } sb.append(getUserName(userName, hasDisplayName)); return sb.toString(); } public static boolean isTemporaryUsername(String username){ if(username == null) throw new IllegalArgumentException("UserName cannot be null"); return username.startsWith(WebConstants.TEMPORARY_USERNAME_PREFIX); } public static String getUserName(String userName, boolean inParens) { StringBuilder sb = new StringBuilder(); if (userName != null && !isTemporaryUsername(userName)) { //if the name is filled in, then put the username in parens if (inParens) sb.append(" ("); sb.append(userName); if (inParens) sb.append(")"); } return sb.toString(); } /** * Returns the NodeType for this entity class. * TODO : This should be removed when we move to using the Synapse Java Client * @param entity * @return */ public static NodeType getNodeTypeForEntity(Entity entity) { // DATASET, LAYER, PROJECT, EULA, AGREEMENT, ENTITY, ANALYSIS, STEP if(entity instanceof org.sagebionetworks.repo.model.Study) { return NodeType.STUDY; } else if(entity instanceof org.sagebionetworks.repo.model.Data) { return NodeType.DATA; } else if(entity instanceof org.sagebionetworks.repo.model.Project) { return NodeType.PROJECT; } else if(entity instanceof org.sagebionetworks.repo.model.Analysis) { return NodeType.ANALYSIS; } else if(entity instanceof org.sagebionetworks.repo.model.Step) { return NodeType.STEP; } else if(entity instanceof org.sagebionetworks.repo.model.Code) { return NodeType.CODE; } else if(entity instanceof org.sagebionetworks.repo.model.Link) { return NodeType.LINK; } return null; } public static String getEntityTypeDisplay(ObjectSchema schema) { String title = schema.getTitle(); if(title == null){ title = "<Title missing for Entity: "+schema.getId()+">"; } return title; } public static String getMarkdownWidgetWarningHtml(String warningText) { return getWarningHtml(DisplayConstants.MARKDOWN_WIDGET_WARNING, warningText); } public static String getMarkdownAPITableWarningHtml(String warningText) { return getWarningHtml(DisplayConstants.MARKDOWN_API_TABLE_WARNING, warningText); } public static String getWarningHtml(String title, String warningText) { return getAlertHtml(title, warningText, BootstrapAlertType.WARNING); } public static String getAlertHtml(String title, String text, BootstrapAlertType type) { return "<div class=\"alert alert-"+type.toString().toLowerCase()+"\"><span class=\"boldText\">"+ title + "</span> " + text + "</div>"; } public static String getAlertHtmlSpan(String title, String text, BootstrapAlertType type) { return "<span class=\"alert alert-"+type.toString().toLowerCase()+"\"><span class=\"boldText\">"+ title + "</span> " + text + "</span>"; } public static String getBadgeHtml(String i) { return "<span class=\"badge\">"+i+"</span>"; } public static String uppercaseFirstLetter(String display) { return display.substring(0, 1).toUpperCase() + display.substring(1); } /** * YYYY-MM-DD HH:mm:ss * @param toFormat * @return */ public static String converDataToPrettyString(Date toFormat) { if(toFormat == null) throw new IllegalArgumentException("Date cannot be null"); return DateUtils.convertDateToString(FORMAT.DATE_TIME, toFormat).replaceAll("T", " "); } /** * Converts a date to just a date. * @return yyyy-MM-dd * @return */ public static String converDateaToSimpleString(Date toFormat) { if(toFormat == null) throw new IllegalArgumentException("Date cannot be null"); return DateUtils.convertDateToString(FORMAT.DATE, toFormat); } public static String getSynapseWikiHistoryToken(String ownerId, String objectType, String wikiPageId) { Wiki place = new Wiki(ownerId, objectType, wikiPageId); return "#!" + getWikiPlaceString(Wiki.class) + ":" + place.toToken(); } public static String getTeamHistoryToken(String teamId) { Team place = new Team(teamId); return "#!" + getTeamPlaceString(Team.class) + ":" + place.toToken(); } public static String getTeamSearchHistoryToken(String searchTerm) { TeamSearch place = new TeamSearch(searchTerm); return "#!" + getTeamSearchPlaceString(TeamSearch.class) + ":" + place.toToken(); } public static String getTeamSearchHistoryToken(String searchTerm, Integer start) { TeamSearch place = new TeamSearch(searchTerm, start); return "#!" + getTeamSearchPlaceString(TeamSearch.class) + ":" + place.toToken(); } public static String getLoginPlaceHistoryToken(String token) { LoginPlace place = new LoginPlace(token); return "#!" + getLoginPlaceString(LoginPlace.class) + ":" + place.toToken(); } public static String getHelpPlaceHistoryToken(String token) { Help place = new Help(token); return "#!" + getHelpPlaceString(Help.class) + ":" + place.toToken(); } public static String getSearchHistoryToken(String searchQuery) { Search place = new Search(searchQuery); return "#!" + getSearchPlaceString(Search.class) + ":" + place.toToken(); } public static String getSearchHistoryToken(String searchQuery, Long start) { Search place = new Search(searchQuery, start); return "#!" + getSearchPlaceString(Search.class) + ":" + place.toToken(); } public static String getSynapseHistoryToken(String entityId) { return "#" + getSynapseHistoryTokenNoHash(entityId, null); } public static String getSynapseHistoryTokenNoHash(String entityId) { return getSynapseHistoryTokenNoHash(entityId, null); } public static String getSynapseHistoryToken(String entityId, Long versionNumber) { return "#" + getSynapseHistoryTokenNoHash(entityId, versionNumber); } public static String getSynapseHistoryTokenNoHash(String entityId, Long versionNumber) { return getSynapseHistoryTokenNoHash(entityId, versionNumber, null); } public static String getSynapseHistoryTokenNoHash(String entityId, Long versionNumber, Synapse.EntityArea area) { return getSynapseHistoryTokenNoHash(entityId, versionNumber, area, null); } public static String getSynapseHistoryTokenNoHash(String entityId, Long versionNumber, Synapse.EntityArea area, String areaToken) { Synapse place = new Synapse(entityId, versionNumber, area, areaToken); return "!"+ getPlaceString(Synapse.class) + ":" + place.toToken(); } /** * Stub the string removing the last partial word * @param str * @param length * @return */ public static String stubStr(String str, int length) { if(str == null) { return ""; } if(str.length() > length) { String sub = str.substring(0, length); str = sub.replaceFirst(" \\w+$", "") + ".."; // clean off partial last word } return str; } /** * Stub the string with partial word at end left in * @param contents * @param maxLength * @return */ public static String stubStrPartialWord(String contents, int maxLength) { String stub = contents; if(contents != null && contents.length() > maxLength) { stub = contents.substring(0, maxLength-3); stub += " .."; } return stub; } /* * Private methods */ private static String getPlaceString(Class<Synapse> place) { return getPlaceString(place.getName()); } private static String getWikiPlaceString(Class<Wiki> place) { return getPlaceString(place.getName()); } public static LayoutContainer wrap(Widget widget) { LayoutContainer lc = new LayoutContainer(); lc.addStyleName("col-md-12"); lc.add(widget); return lc; } public static SimplePanel wrapInDiv(Widget widget) { SimplePanel lc = new SimplePanel(); lc.setWidget(widget); return lc; } private static String getTeamPlaceString(Class<Team> place) { return getPlaceString(place.getName()); } private static String getTeamSearchPlaceString(Class<TeamSearch> place) { return getPlaceString(place.getName()); } private static String getLoginPlaceString(Class<LoginPlace> place) { return getPlaceString(place.getName()); } private static String getHelpPlaceString(Class<Help> place) { return getPlaceString(place.getName()); } private static String getSearchPlaceString(Class<Search> place) { return getPlaceString(place.getName()); } private static String getPlaceString(String fullPlaceName) { fullPlaceName = fullPlaceName.replaceAll(".+\\.", ""); return fullPlaceName; } /** * Returns the offending character given a regex string * @param key * @param regex * @return */ private static String getOffendingCharacter(String key, String regex) { String suffix = key.replaceFirst(regex, ""); if(suffix != null && suffix.length() > 0) { return suffix.substring(0,1); } return null; } public static String createEntityLink(String id, String version, String display) { return "<a href=\"" + DisplayUtils.getSynapseHistoryToken(id) + "\">" + display + "</a>"; } public static enum IconSize { PX16, PX24 }; public static ImageResource getSynapseIconForEntityType(EntityType type, IconSize iconSize, IconsImageBundle iconsImageBundle) { String className = type == null ? null : type.getClassName(); return getSynapseIconForEntityClassName(className, iconSize, iconsImageBundle); } public static ImageResource getSynapseIconForEntity(Entity entity, IconSize iconSize, IconsImageBundle iconsImageBundle) { String className = entity == null ? null : entity.getClass().getName(); return getSynapseIconForEntityClassName(className, iconSize, iconsImageBundle); } /** * Create a loading window. * * @param sageImageBundle * @param message * @return */ public static Window createLoadingWindow(SageImageBundle sageImageBundle, String message) { Window window = new Window(); window.setModal(true); window.setHeight(114); window.setWidth(221); window.setBorders(false); SafeHtmlBuilder shb = new SafeHtmlBuilder(); shb.appendHtmlConstant(DisplayUtils.getIconHtml(sageImageBundle.loading31())); shb.appendEscaped(message); window.add(new Html(shb.toSafeHtml().asString()), new MarginData(20, 0, 0, 45)); window.setBodyStyleName("whiteBackground"); return window; } /** * Create a loading panel with a centered spinner. * * @param sageImageBundle * @param width * @param height * @return */ public static Widget createFullWidthLoadingPanel(SageImageBundle sageImageBundle) { return createFullWidthLoadingPanel(sageImageBundle, " Loading..."); } /** * Create a loading panel with a centered spinner. * * @param sageImageBundle * @param width * @param height * @return */ public static Widget createFullWidthLoadingPanel(SageImageBundle sageImageBundle, String message) { Widget w = new HTML(SafeHtmlUtils.fromSafeConstant( DisplayUtils.getIconHtml(sageImageBundle.loading31()) +" "+ message)); LayoutContainer panel = new LayoutContainer(); panel.add(w, new MarginData(FULL_ENTITY_TOP_MARGIN_PX, 0, FULL_ENTITY_TOP_MARGIN_PX, 0)); panel.addStyleName("center"); return panel; } public static ImageResource getSynapseIconForEntityClassName(String className, IconSize iconSize, IconsImageBundle iconsImageBundle) { ImageResource icon = null; if(Link.class.getName().equals(className)) { icon = iconsImageBundle.synapseLink16(); } else if(Analysis.class.getName().equals(className)) { // Analysis if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseAnalysis16(); else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseAnalysis24(); } else if(Code.class.getName().equals(className)) { // Code if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseFile16(); else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseFile24(); } else if(Data.class.getName().equals(className) || ExpressionData.class.getName().equals(className) || GenotypeData.class.getName().equals(className) || PhenotypeData.class.getName().equals(className)) { // Data if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseFile16(); else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseFile24(); } else if(Folder.class.getName().equals(className)) { // Folder if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseFolder16(); else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseFolder24(); } else if(FileEntity.class.getName().equals(className)) { // File if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseFile16(); else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseFile24(); } else if(Project.class.getName().equals(className)) { // Project if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseProject16(); else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseProject24(); } else if(RObject.class.getName().equals(className)) { // RObject if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseRObject16(); else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseRObject24(); } else if(Summary.class.getName().equals(className)) { // Summary if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseSummary16(); else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseSummary24(); } else if(Step.class.getName().equals(className)) { // Step if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseStep16(); else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseStep24(); } else if(Study.class.getName().equals(className)) { // Study if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseFolder16(); else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseFolder24(); } else if(Page.class.getName().equals(className)) { // Page if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapsePage16(); else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapsePage24(); } else if(TableEntity.class.getName().equals(className)) { // TableEntity if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseData16(); else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseData24(); } else { // default to Model if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseModel16(); else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseModel24(); } return icon; } /** * Maps mime types to icons. */ private static Map<String, String> attachmentMap = new HashMap<String, String>(); public static String UNKNOWN_ICON = "220"; public static String DEFAULT_PDF_ICON = "222"; public static String DEFAULT_IMAGE_ICON = "242"; public static String DEFAULT_TEXT_ICON = "224"; public static String DEFAULT_COMPRESSED_ICON = "226"; static{ attachmentMap.put("pdf", DEFAULT_PDF_ICON); attachmentMap.put("txt", DEFAULT_TEXT_ICON); attachmentMap.put("doc", DEFAULT_TEXT_ICON); attachmentMap.put("doc", DEFAULT_TEXT_ICON); attachmentMap.put("docx", DEFAULT_TEXT_ICON); attachmentMap.put("docx", DEFAULT_TEXT_ICON); attachmentMap.put("zip", DEFAULT_COMPRESSED_ICON); attachmentMap.put("tar", DEFAULT_COMPRESSED_ICON); attachmentMap.put("gz", DEFAULT_COMPRESSED_ICON); attachmentMap.put("rar", DEFAULT_COMPRESSED_ICON); attachmentMap.put("png", DEFAULT_IMAGE_ICON); attachmentMap.put("gif", DEFAULT_IMAGE_ICON); attachmentMap.put("jpg", DEFAULT_IMAGE_ICON); attachmentMap.put("jpeg", DEFAULT_IMAGE_ICON); attachmentMap.put("bmp", DEFAULT_IMAGE_ICON); attachmentMap.put("wbmp", DEFAULT_IMAGE_ICON); } /** * Get the icon to be used with a given file type. */ public static String getAttachmentIcon(String fileName){ if(fileName == null) return UNKNOWN_ICON; String mimeType = getMimeType(fileName); if(mimeType == null) return UNKNOWN_ICON; String icon = attachmentMap.get(mimeType.toLowerCase()); if(icon == null) return UNKNOWN_ICON; return icon; } /** * Get the mime type from a file name. * @param fileName * @return */ public static String getMimeType(String fileName){ if(fileName == null) return null; int index = fileName.lastIndexOf('.'); if(index < 0) return null; if(index+1 >= fileName.length()) return null; return fileName.substring(index+1, fileName.length()); } /** * Replace all white space * @param string * @return */ public static String replaceWhiteSpace(String string){ if(string == null) return null; string = string.replaceAll(" ", WHITE_SPACE); return string; } /** * Create the url to an attachment image. * @param baseURl * @param entityId * @param tokenId * @param fileName * @return */ public static String createAttachmentUrl(String baseURl, String entityId, String tokenId, String fileName){ return createAttachmentUrl(baseURl, entityId, tokenId, fileName, WebConstants.ENTITY_PARAM_KEY); } /** * Create the url to a profile attachment image. * @param baseURl * @param userId * @param tokenId * @param fileName * @return */ public static String createUserProfileAttachmentUrl(String baseURl, String userId, String tokenId, String fileName){ return createAttachmentUrl(baseURl, userId, tokenId, fileName, WebConstants.USER_PROFILE_PARAM_KEY); } public static String createUserProfilePicUrl(String baseURl, String userId){ return createAttachmentUrl(baseURl, userId, "", null, WebConstants.USER_PROFILE_PARAM_KEY); } /** * Create the url to an attachment image. * @param baseURl * @param id * @param tokenId * @param fileName * @return */ public static String createAttachmentUrl(String baseURl, String id, String tokenId, String fileName, String paramKey){ StringBuilder builder = new StringBuilder(); builder.append(baseURl); builder.append("?"+paramKey+"="); builder.append(id); builder.append("&"+WebConstants.TOKEN_ID_PARAM_KEY+"="); builder.append(tokenId); builder.append("&"+WebConstants.WAIT_FOR_URL+"=true"); //and do not cache builder.append(getParamForNoCaching()); return builder.toString(); } /** * Does this entity have attachmet previews? * @param entity * @return */ public static boolean hasChildrenOrPreview(EntityBundle bundle){ if(bundle == null) return true; if(bundle.getEntity() == null) return true; Boolean hasChildern = bundle.getHasChildren(); if(hasChildern == null) return true; return hasChildern; } public static ArrayList<EntityType> orderForDisplay(List<EntityType> children) { ArrayList<EntityType> ordered = new ArrayList<EntityType>(); if(children != null) { // fill map Map<String,EntityType> classToTypeMap = new HashMap<String, EntityType>(); for(EntityType child : children) { classToTypeMap.put(child.getClassName(), child); } // add child tabs in order for(String className : DisplayUtils.ENTITY_TYPE_DISPLAY_ORDER) { if(classToTypeMap.containsKey(className)) { EntityType child = classToTypeMap.get(className); classToTypeMap.remove(className); ordered.add(child); } } // add any remaining tabs that weren't covered by the display order for(String className : classToTypeMap.keySet()) { EntityType child = classToTypeMap.get(className); ordered.add(child); } } return ordered; } public static PopupPanel addToolTip(Widget widget, String message) { PopupPanel popup = addToolTip(widget); popup.setWidget(new HTML(message)); return popup; } /** * Creates and attaches a simple tooltip to a GWT widget * * Customization of content and style are made by the caller method * * @param widget: the widget to attach the popup/tooltip to * @return the new popup/tooltip that can be customized */ public static PopupPanel addToolTip(final Widget widget) { return addToolTip(widget, false, false); } /** * Provides a more flexible configuration of a tooltip's behavior * * Customization of content and style are made by the caller method * * Note: if keepOpen is set to true and autoHide is set to false, the caller * should provide an alternative way to closing/hiding the tooltip * * @param widget: the widget to attach to * @param keepToolTipOpen: whether the tooltip should remain open when the curser leaves the widget but * moves onto the tooltip * @param autoHide: whether the tooltip should close when the curser clicks outside of it * @return the new tooltip */ public static PopupPanel addToolTip(final Widget widget, boolean keepToolTipOpen, boolean autoHide) { final PopupPanel popup = createToolTip(autoHide); widget.addDomHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { popup.setPopupPositionAndShow(new PopupPanel.PositionCallback() { public void setPosition(int offsetWidth, int offsetHeight) { popup.showRelativeTo(widget); } }); } }, MouseOverEvent.getType()); //If the tooltip is to remain open, we do not "hide" it when the curser moves out of the widget if(keepToolTipOpen) { popup.addDomHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { popup.setPopupPositionAndShow(new PopupPanel.PositionCallback() { public void setPosition(int offsetWidth, int offsetHeight) { popup.showRelativeTo(widget); } }); } }, MouseOverEvent.getType()); } else { widget.addDomHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { popup.hide(); } }, MouseOutEvent.getType()); } return popup; } private static PopupPanel createToolTip(boolean autoHide) { final PopupPanel popup = new PopupPanel(autoHide); popup.setGlassEnabled(false); popup.addStyleName("topLevelZIndex"); return popup; } public static PopupPanel addToolTip(final Component widget, String message) { final PopupPanel popup = new PopupPanel(true); popup.setWidget(new HTML(message)); popup.setGlassEnabled(false); popup.addStyleName("topLevelZIndex"); widget.addListener(Events.OnMouseOver, new Listener<BaseEvent>() { @Override public void handleEvent(BaseEvent be) { popup.setPopupPositionAndShow(new PopupPanel.PositionCallback() { public void setPosition(int offsetWidth, int offsetHeight) { popup.showRelativeTo(widget); } }); } }); widget.addListener(Events.OnMouseOut, new Listener<BaseEvent>() { @Override public void handleEvent(BaseEvent be) { popup.hide(); } }); return popup; } /** * A list of tags that core attributes like 'title' cannot be applied to. * This prevents them from having methods like addToolTip applied to them */ public static final String[] CORE_ATTR_INVALID_ELEMENTS = {"base", "head", "html", "meta", "param", "script", "style", "title"}; /** * A counter variable for assigning unqiue id's to tool-tippified elements */ private static int tooltipCount= 0; private static int popoverCount= 0; /** * Adds a twitter bootstrap tooltip to the given widget using the standard Synapse configuration * * CAUTION - If not used with a non-block level element like * an anchor, img, or span the results will probably not be * quite what you want. Read the twitter bootstrap documentation * for the options that you can specify in optionsMap * * @param util the JSNIUtils class (or mock) * @param widget the widget to attach the tooltip to * @param tooltipText text to display * @param pos where to position the tooltip relative to the widget */ public static void addTooltip(final SynapseJSNIUtils util, Widget widget, String tooltipText, TOOLTIP_POSITION pos){ Map<String, String> optionsMap = new HashMap<String, String>(); optionsMap.put("title", tooltipText); optionsMap.put("data-placement", pos.toString().toLowerCase()); optionsMap.put("data-animation", "false"); optionsMap.put("data-html", "true"); addTooltip(util, widget, optionsMap); } private static void addTooltip(final SynapseJSNIUtils util, Widget widget, Map<String, String> optionsMap) { final Element el = widget.getElement(); String id = isNullOrEmpty(el.getId()) ? "sbn-tooltip-"+(tooltipCount++) : el.getId(); el.setId(id); optionsMap.put("id", id); optionsMap.put("rel", "tooltip"); if (el.getNodeType() == 1 && !isPresent(el.getNodeName(), CORE_ATTR_INVALID_ELEMENTS)) { // If nodeName is a tag and not in the INVALID_ELEMENTS list then apply the appropriate transformation applyAttributes(el, optionsMap); widget.addAttachHandler( new AttachEvent.Handler() { @Override public void onAttachOrDetach(AttachEvent event) { if (event.isAttached()) { util.bindBootstrapTooltip(el.getId()); } else { util.hideBootstrapTooltip(el.getId()); } } }); } } public static void addClickPopover(final SynapseJSNIUtils util, Widget widget, String title, String content, TOOLTIP_POSITION pos) { Map<String, String> optionsMap = new HashMap<String, String>(); optionsMap.put("data-html", "true"); optionsMap.put("data-animation", "true"); optionsMap.put("title", title); optionsMap.put("data-placement", pos.toString().toLowerCase()); optionsMap.put("trigger", "click"); addPopover(util, widget, content, optionsMap); } public static void addHoverPopover(final SynapseJSNIUtils util, Widget widget, String title, String content, TOOLTIP_POSITION pos) { Map<String, String> optionsMap = new HashMap<String, String>(); optionsMap.put("data-html", "true"); optionsMap.put("data-animation", "true"); optionsMap.put("title", title); optionsMap.put("data-placement", pos.toString().toLowerCase()); optionsMap.put("data-trigger", "hover"); addPopover(util, widget, content, optionsMap); } /** * Adds a popover to a target widget * * Same warnings apply as to {@link #addTooltip(SynapseJSNIUtils, Widget, String) addTooltip} */ public static void addPopover(final SynapseJSNIUtils util, Widget widget, String content, Map<String, String> optionsMap) { final Element el = widget.getElement(); el.setAttribute("data-content", content); String id = isNullOrEmpty(el.getId()) ? "sbn-popover-"+(popoverCount++) : el.getId(); optionsMap.put("id", id); optionsMap.put("rel", "popover"); if (el.getNodeType() == 1 && !isPresent(el.getNodeName(), CORE_ATTR_INVALID_ELEMENTS)) { // If nodeName is a tag and not in the INVALID_ELEMENTS list then apply the appropriate transformation applyAttributes(el, optionsMap); widget.addAttachHandler( new AttachEvent.Handler() { @Override public void onAttachOrDetach(AttachEvent event) { if (event.isAttached()) { util.bindBootstrapPopover(el.getId()); } } }); } } public static void applyAttributes(final Element el, Map<String, String> optionsMap) { for (Entry<String, String> option : optionsMap.entrySet()) { DOM.setElementAttribute(el, option.getKey(), option.getValue()); } } /* * Private methods */ private static boolean isNullOrEmpty(final String string) { return string == null || string.isEmpty(); } private static boolean isPresent(String needle, String[] haystack) { for (String el : haystack) { if (needle.equalsIgnoreCase(el)) { return true; } } return false; } /** * The preferred method for creating new global alerts. For a * default 'info' type alert, you can also use {@link showInfo(String, String)} * @param alert */ public static void displayGlobalAlert(Alert alert) { Element container = DOM.getElementById(ALERT_CONTAINER_ID); DOM.insertChild(container, alert.getElement(), 0); } public static String getVersionDisplay(Versionable versionable) { String version = ""; if(versionable == null || versionable.getVersionNumber() == null) return version; if(versionable.getVersionLabel() != null && !versionable.getVersionNumber().toString().equals(versionable.getVersionLabel())) { version = versionable.getVersionLabel() + " (" + versionable.getVersionNumber() + ")"; } else { version = versionable.getVersionNumber().toString(); } return version; } public static native JavaScriptObject newWindow(String url, String name, String features)/*-{ try { var window = $wnd.open(url, name, features); return window; }catch(err) { return null; } }-*/; public static native void setWindowTarget(JavaScriptObject window, String target)/*-{ window.location = target; }-*/; /** * links in the wiki pages that reference other wiki pages don't include the domain. this method adds the domain. * @param html * @return */ public static String fixWikiLinks(String html) { //adjust all wiki links so that they include the wiki domain return html.replaceAll("=\"/wiki", "=\""+WIKI_URL); } public static String fixEmbeddedYouTube(String html){ int startYouTubeLinkIndex = html.indexOf("www.youtube.com/embed"); while (startYouTubeLinkIndex > -1){ int endYoutubeLinkIndex = html.indexOf("<", startYouTubeLinkIndex); StringBuilder sb = new StringBuilder(); sb.append(html.substring(0, startYouTubeLinkIndex)); sb.append("<iframe width=\"300\" height=\"169\" src=\"https://" + html.substring(startYouTubeLinkIndex, endYoutubeLinkIndex) + "\" frameborder=\"0\" allowfullscreen=\"true\"></iframe>"); int t = sb.length(); sb.append(html.substring(endYoutubeLinkIndex)); html = sb.toString(); //search after t (for the next embed) startYouTubeLinkIndex = html.indexOf("www.youtube.com/embed", t); } return html; } public static String getYouTubeVideoUrl(String videoId) { return "http: } public static String getYouTubeVideoId(String videoUrl) { String videoId = null; //parse out the video id from the url int start = videoUrl.indexOf("v="); if (start > -1) { int end = videoUrl.indexOf("&", start); if (end == -1) end = videoUrl.length(); videoId = videoUrl.substring(start + "v=".length(), end); } if (videoId == null || videoId.trim().length() == 0) { throw new IllegalArgumentException("Could not determine the video ID from the given URL."); } return videoId; } public static Anchor createIconLink(AbstractImagePrototype icon, ClickHandler clickHandler) { Anchor anchor = new Anchor(); anchor.setHTML(icon.getHTML()); anchor.addClickHandler(clickHandler); return anchor; } public static String getVersionDisplay(Reference ref) { if (ref == null) return null; return getVersionDisplay(ref.getTargetId(), ref.getTargetVersionNumber()); } public static String getVersionDisplay(String id, Long versionNumber) { String version = id; if(versionNumber != null) { version += " (#" + versionNumber + ")"; } return version; } public static SafeHtml get404Html() { return SafeHtmlUtils .fromSafeConstant("<div class=\"margin-left-15 margin-top-15 padding-bottom-15\" style=\"height: 150px;\"><p class=\"error left colored\">404</p><h1>" + DisplayConstants.PAGE_NOT_FOUND + "</h1>" + "<p>" + DisplayConstants.PAGE_NOT_FOUND_DESC + "</p></div>"); } public static String getWidgetMD(String attachmentName) { if (attachmentName == null) return null; StringBuilder sb = new StringBuilder(); sb.append(WidgetConstants.WIDGET_START_MARKDOWN); sb.append(attachmentName); sb.append("}"); return sb.toString(); } public static SafeHtml get403Html() { return SafeHtmlUtils .fromSafeConstant("<div class=\"margin-left-15 margin-top-15 padding-bottom-15\" style=\"height: 150px;\"><p class=\"error left colored\">403</p><h1>" + DisplayConstants.FORBIDDEN + "</h1>" + "<p>" + DisplayConstants.UNAUTHORIZED_DESC + "</p></div>"); } /** * 'Upload File' button for an entity * @param entity * @param entityType */ public static Widget getUploadButton(final EntityBundle entityBundle, EntityType entityType, final Uploader uploader, IconsImageBundle iconsImageBundle, EntityUpdatedHandler handler) { com.google.gwt.user.client.ui.Button uploadButton = DisplayUtils.createIconButton(DisplayConstants.TEXT_UPLOAD_FILE_OR_LINK, ButtonType.DEFAULT, "glyphicon-arrow-up"); return configureUploadWidget(uploadButton, uploader, iconsImageBundle, null, entityBundle, handler, entityType, DisplayConstants.TEXT_UPLOAD_FILE_OR_LINK); } /** * 'Upload File' button something other than an entity (for example the team icon) */ public static Widget getUploadButton(final CallbackP<String> fileHandleIdCallback, final Uploader uploader, IconsImageBundle iconsImageBundle, String buttonText, ButtonType buttonType) { com.google.gwt.user.client.ui.Button uploadButton = DisplayUtils.createIconButton(buttonText, buttonType, null); return configureUploadWidget(uploadButton, uploader, iconsImageBundle, fileHandleIdCallback, null, null, null, buttonText); } /** * 'Upload File' button * @param entity * @param entityType */ private static Widget configureUploadWidget(final FocusWidget uploadButton, final Uploader uploader, IconsImageBundle iconsImageBundle, final CallbackP<String> fileHandleIdCallback, final EntityBundle entityBundle, EntityUpdatedHandler handler, EntityType entityType, final String buttonText) { final Window window = new Window(); uploader.clearHandlers(); // add user defined handler if (handler != null) uploader.addPersistSuccessHandler(handler); // add handlers for closing the window uploader.addPersistSuccessHandler(new EntityUpdatedHandler() { @Override public void onPersistSuccess(EntityUpdatedEvent event) { window.hide(); } }); uploader.addCancelHandler(new CancelHandler() { @Override public void onCancel(CancelEvent event) { window.hide(); } }); uploadButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { window.removeAll(); window.setPlain(true); window.setModal(true); window.setHeading(buttonText); window.setLayout(new FitLayout()); List<AccessRequirement> ars = null; Entity entity = null; boolean isEntity = true; if (entityBundle != null) { //is entity ars = entityBundle.getAccessRequirements(); entity = entityBundle.getEntity(); } else { //is something else that just wants a file handle id isEntity = false; } window.add(uploader.asWidget(entity, null,ars, fileHandleIdCallback,isEntity), new MarginData(5)); window.show(); window.setSize(uploader.getDisplayWidth(), uploader.getDisplayHeight()); } }); return uploadButton; } /** * Provides same functionality as java.util.Pattern.quote(). * @param pattern * @return */ public static String quotePattern(String pattern) { StringBuilder output = new StringBuilder(); for (int i = 0; i < pattern.length(); i++) { if (ESCAPE_CHARACTERS_SET.contains(pattern.charAt(i))) output.append("\\"); output.append(pattern.charAt(i)); } return output.toString(); } public static void updateTextArea(TextArea textArea, String newValue) { textArea.setValue(newValue); DomEvent.fireNativeEvent(Document.get().createChangeEvent(), textArea); } public static boolean isInTestWebsite(CookieProvider cookies) { return isInCookies(DisplayUtils.SYNAPSE_TEST_WEBSITE_COOKIE_KEY, cookies); } public static void setTestWebsite(boolean testWebsite, CookieProvider cookies) { setInCookies(testWebsite, DisplayUtils.SYNAPSE_TEST_WEBSITE_COOKIE_KEY, cookies); } public static final String SYNAPSE_TEST_WEBSITE_COOKIE_KEY = "SynapseTestWebsite"; public static boolean isInCookies(String cookieKey, CookieProvider cookies) { return cookies.getCookie(cookieKey) != null; } public static void setInCookies(boolean value, String cookieKey, CookieProvider cookies) { if (value && !isInCookies(cookieKey, cookies)) { //set the cookie cookies.setCookie(cookieKey, "true"); } else{ cookies.removeCookie(cookieKey); } } /** * Create the URL to a version of a wiki's attachments. * @param baseFileHandleUrl * @param wikiKey * @param fileName * @param preview * @param wikiVersion * @return */ public static String createVersionOfWikiAttachmentUrl(String baseFileHandleUrl, WikiPageKey wikiKey, String fileName, boolean preview, Long wikiVersion) { String attachmentUrl = createWikiAttachmentUrl(baseFileHandleUrl, wikiKey, fileName, preview); return attachmentUrl + "&" + WebConstants.WIKI_VERSION_PARAM_KEY + "=" + wikiVersion.toString(); } /** * Create the url to a wiki filehandle. * @param baseURl * @param id * @param tokenId * @param fileName * @return */ public static String createWikiAttachmentUrl(String baseFileHandleUrl, WikiPageKey wikiKey, String fileName, boolean preview){ //direct approach not working. have the filehandleservlet redirect us to the temporary wiki attachment url instead // String attachmentPathName = preview ? "attachmentpreview" : "attachment"; // return repoServicesUrl // +"/" +wikiKey.getOwnerObjectType().toLowerCase() // +"/"+ wikiKey.getOwnerObjectId() // +"/wiki/" // +wikiKey.getWikiPageId() // +"/"+ attachmentPathName+"?fileName="+URL.encodePathSegment(fileName); String wikiIdParam = wikiKey.getWikiPageId() == null ? "" : "&" + WebConstants.WIKI_ID_PARAM_KEY + "=" + wikiKey.getWikiPageId(); return baseFileHandleUrl + "?" + WebConstants.WIKI_OWNER_ID_PARAM_KEY + "=" + wikiKey.getOwnerObjectId() + "&" + WebConstants.WIKI_OWNER_TYPE_PARAM_KEY + "=" + wikiKey.getOwnerObjectType() + "&"+ WebConstants.WIKI_FILENAME_PARAM_KEY + "=" + fileName + "&" + WebConstants.FILE_HANDLE_PREVIEW_PARAM_KEY + "=" + Boolean.toString(preview) + wikiIdParam; } public static String createFileEntityUrl(String baseFileHandleUrl, String entityId, Long versionNumber, boolean preview){ return createFileEntityUrl(baseFileHandleUrl, entityId, versionNumber, preview, false); } public static String getParamForNoCaching() { return WebConstants.NOCACHE_PARAM + new Date().getTime(); } /** * Create a url that points to the FileHandleServlet. * WARNING: A GET request to this url will cause the file contents to be downloaded on the Servlet and sent back in the response. * USE TO REQUEST SMALL FILES ONLY and CACHE THE RESULTS * @param baseURl * @param encodedRedirectUrl * @return */ public static String createRedirectUrl(String baseFileHandleUrl, String encodedRedirectUrl){ return baseFileHandleUrl + "?" + WebConstants.PROXY_PARAM_KEY + "=" + Boolean.TRUE +"&" + WebConstants.REDIRECT_URL_KEY + "=" + encodedRedirectUrl; } /** * Create the url to a FileEntity filehandle. * @param baseURl * @param entityid * @return */ public static String createFileEntityUrl(String baseFileHandleUrl, String entityId, Long versionNumber, boolean preview, boolean proxy){ String versionParam = versionNumber == null ? "" : "&" + WebConstants.ENTITY_VERSION_PARAM_KEY + "=" + versionNumber.toString(); return baseFileHandleUrl + "?" + WebConstants.ENTITY_PARAM_KEY + "=" + entityId + "&" + WebConstants.FILE_HANDLE_PREVIEW_PARAM_KEY + "=" + Boolean.toString(preview) + "&" + WebConstants.PROXY_PARAM_KEY + "=" + Boolean.toString(proxy) + versionParam; } /** * Create the url to a Table cell file handle. * @param baseFileHandleUrl * @param details * @param preview * @param proxy * @return */ public static String createTableCellFileEntityUrl(String baseFileHandleUrl, TableCellFileHandle details, boolean preview, boolean proxy){ return baseFileHandleUrl + "?" + WebConstants.ENTITY_PARAM_KEY + "=" + details.getTableId() + "&" + WebConstants.TABLE_COLUMN_ID + "=" + details.getColumnId() + "&" + WebConstants.TABLE_ROW_ID + "=" + details.getRowId() + "&" + WebConstants.TABLE_ROW_VERSION_NUMBER + "=" + details.getVersionNumber() + "&" + WebConstants.FILE_HANDLE_PREVIEW_PARAM_KEY + "=" + Boolean.toString(preview) + "&" + WebConstants.PROXY_PARAM_KEY + "=" + Boolean.toString(proxy); } /** * Create the url to a Team icon filehandle. * @param baseURl * @param teamId * @return */ public static String createTeamIconUrl(String baseFileHandleUrl, String teamId){ return baseFileHandleUrl + "?" + WebConstants.TEAM_PARAM_KEY + "=" + teamId; } public static String createEntityVersionString(Reference ref) { return createEntityVersionString(ref.getTargetId(), ref.getTargetVersionNumber()); } public static String createEntityVersionString(String id, Long version) { if(version != null) return id+WebConstants.ENTITY_VERSION_STRING+version; else return id; } public static Reference parseEntityVersionString(String entityVersion) { String[] parts = entityVersion.split(WebConstants.ENTITY_VERSION_STRING); Reference ref = null; if(parts.length > 0) { ref = new Reference(); ref.setTargetId(parts[0]); if(parts.length > 1) { try { ref.setTargetVersionNumber(Long.parseLong(parts[1])); } catch(NumberFormatException e) {} } } return ref; } public static boolean isWikiSupportedType(Entity entity) { return (entity instanceof FileEntity || entity instanceof Folder || entity instanceof Project || entity instanceof TableEntity); } public static boolean isRecognizedImageContentType(String contentType) { String lowerContentType = contentType.toLowerCase(); return IMAGE_CONTENT_TYPES_SET.contains(lowerContentType); } public static boolean isTextType(String contentType) { return contentType.toLowerCase().startsWith("text/"); } public static boolean isCSV(String contentType) { return contentType != null && contentType.toLowerCase().startsWith("text/csv"); } public static boolean isTAB(String contentType) { return contentType != null && contentType.toLowerCase().startsWith(WebConstants.TEXT_TAB_SEPARATED_VALUES); } /** * Return a preview filehandle associated with this bundle (or null if unavailable) * @param bundle * @return */ public static PreviewFileHandle getPreviewFileHandle(EntityBundle bundle) { PreviewFileHandle fileHandle = null; if (bundle.getFileHandles() != null) { for (FileHandle fh : bundle.getFileHandles()) { if (fh instanceof PreviewFileHandle) { fileHandle = (PreviewFileHandle) fh; break; } } } return fileHandle; } /** * Return the filehandle associated with this bundle (or null if unavailable) * @param bundle * @return */ public static FileHandle getFileHandle(EntityBundle bundle) { FileHandle fileHandle = null; if (bundle.getFileHandles() != null) { FileEntity entity = (FileEntity)bundle.getEntity(); String targetId = entity.getDataFileHandleId(); for (FileHandle fh : bundle.getFileHandles()) { if (fh.getId().equals(targetId)) { fileHandle = fh; break; } } } return fileHandle; } public interface SelectedHandler<T> { public void onSelected(T selected); } public static void configureAndShowEntityFinderWindow(final EntityFinder entityFinder, final Window window, final SelectedHandler<Reference> handler) { window.setPlain(true); window.setModal(true); window.setHeading(DisplayConstants.FIND_ENTITIES); window.setLayout(new FitLayout()); window.add(entityFinder.asWidget(), new FitData(4)); window.addButton(new Button(DisplayConstants.SELECT, new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { Reference selected = entityFinder.getSelectedEntity(); handler.onSelected(selected); } })); window.addButton(new Button(DisplayConstants.BUTTON_CANCEL, new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { window.hide(); } })); window.setButtonAlign(HorizontalAlignment.RIGHT); window.show(); window.setSize(entityFinder.getViewWidth(), entityFinder.getViewHeight()); entityFinder.refresh(); } public static void loadTableSorters(final HTMLPanel panel, SynapseJSNIUtils synapseJSNIUtils) { String id = WidgetConstants.MARKDOWN_TABLE_ID_PREFIX; int i = 0; Element table = panel.getElementById(id + i); while (table != null) { synapseJSNIUtils.tablesorter(id+i); i++; table = panel.getElementById(id + i); } } public static Widget getShareSettingsDisplay(boolean isPublic, SynapseJSNIUtils synapseJSNIUtils) { final SimplePanel lc = new SimplePanel(); lc.addStyleName(STYLE_DISPLAY_INLINE); String styleName = isPublic ? "public-acl-image" : "private-acl-image"; String description = isPublic ? DisplayConstants.PUBLIC_ACL_ENTITY_PAGE : DisplayConstants.PRIVATE_ACL_ENTITY_PAGE; String tooltip = isPublic ? DisplayConstants.PUBLIC_ACL_DESCRIPTION : DisplayConstants.PRIVATE_ACL_DESCRIPTION; SafeHtmlBuilder shb = new SafeHtmlBuilder(); shb.appendHtmlConstant("<div class=\"" + styleName+ "\" style=\"display:inline; position:absolute\"></div>"); shb.appendHtmlConstant("<span style=\"margin-left: 20px;\">"+description+"</span>"); //form the html HTMLPanel htmlPanel = new HTMLPanel(shb.toSafeHtml()); htmlPanel.addStyleName("inline-block"); DisplayUtils.addTooltip(synapseJSNIUtils, htmlPanel, tooltip, TOOLTIP_POSITION.BOTTOM); lc.add(htmlPanel); return lc; } public static Long getVersion(Entity entity) { Long version = null; if (entity != null && entity instanceof Versionable) version = ((Versionable) entity).getVersionNumber(); return version; } public static void updateWidgetSelectionState(WidgetSelectionState state, String text, int cursorPos) { state.setWidgetSelected(false); state.setWidgetStartIndex(-1); state.setWidgetEndIndex(-1); state.setInnerWidgetText(null); if (cursorPos > -1) { //move back until I find a whitespace or the beginning int startWord = cursorPos-1; while(startWord > -1 && !Character.isSpace(text.charAt(startWord))) { startWord } startWord++; String possibleWidget = text.substring(startWord); if (possibleWidget.startsWith(WidgetConstants.WIDGET_START_MARKDOWN)) { //find the end int endWord = cursorPos; while(endWord < text.length() && !WidgetConstants.WIDGET_END_MARKDOWN.equals(String.valueOf(text.charAt(endWord)))) { endWord++; } //invalid widget specification if we went all the way to the end of the markdown if (endWord < text.length()) { //it's a widget //parse the type and descriptor endWord++; possibleWidget = text.substring(startWord, endWord); //set editable state.setWidgetSelected(true); state.setInnerWidgetText(possibleWidget.substring(WidgetConstants.WIDGET_START_MARKDOWN.length(), possibleWidget.length() - WidgetConstants.WIDGET_END_MARKDOWN.length())); state.setWidgetStartIndex(startWord); state.setWidgetEndIndex(endWord); } } } } /** * Surround the selectedText with the given markdown. Or, if the selected text is already surrounded by the markdown, then remove it. * @param text * @param markdown * @param startPos * @param selectionLength * @return */ public static String surroundText(String text, String startTag, String endTag, boolean isMultiline, int startPos, int selectionLength) throws IllegalArgumentException { if (text != null && selectionLength > -1 && startPos >= 0 && startPos <= text.length() && isDefined(startTag)) { if (endTag == null) endTag = ""; int startTagLength = startTag.length(); int endTagLength = endTag.length(); int eolPos = text.indexOf('\n', startPos); if (eolPos < 0) eolPos = text.length(); int endPos = startPos + selectionLength; if (eolPos < endPos && !isMultiline) throw new IllegalArgumentException(DisplayConstants.SINGLE_LINE_COMMAND_MESSAGE); String selectedText = text.substring(startPos, endPos); //check to see if this text is already surrounded by the markdown. int beforeSelectedTextPos = startPos - startTagLength; int afterSelectedTextPos = endPos + endTagLength; if (beforeSelectedTextPos > -1 && afterSelectedTextPos <= text.length()) { if (startTag.equals(text.substring(beforeSelectedTextPos, startPos)) && endTag.equals(text.substring(endPos, afterSelectedTextPos))) { //strip off markdown instead return text.substring(0, beforeSelectedTextPos) + selectedText + text.substring(afterSelectedTextPos); } } return text.substring(0, startPos) + startTag + selectedText + endTag + text.substring(endPos); } throw new IllegalArgumentException(DisplayConstants.INVALID_SELECTION); } public static boolean isDefined(String testString) { return testString != null && testString.trim().length() > 0; } public static void addAnnotation(Annotations annos, String name, ANNOTATION_TYPE type) { // Add a new annotation if(ANNOTATION_TYPE.STRING == type){ annos.addAnnotation(name, ""); }else if(ANNOTATION_TYPE.DOUBLE == type){ annos.addAnnotation(name, 0.0); }else if(ANNOTATION_TYPE.LONG == type){ annos.addAnnotation(name, 0l); }else if(ANNOTATION_TYPE.DATE == type){ annos.addAnnotation(name, new Date()); }else{ throw new IllegalArgumentException("Unknown type: "+type); } } public static void surroundWidgetWithParens(Panel container, Widget widget) { Text paren = new Text("("); paren.addStyleName("inline-block margin-left-5"); container.add(paren); widget.addStyleName("inline-block"); container.add(widget); paren = new Text(")"); paren.addStyleName("inline-block margin-right-10"); container.add(paren); } public static void showSharingDialog(final AccessControlListEditor accessControlListEditor, boolean canChangePermission, final Callback callback) { final Dialog window = new Dialog(); // configure layout int windowHeight = canChangePermission ? 552 : 282; window.setSize(560, windowHeight); window.setPlain(true); window.setModal(true); window.setHeading(DisplayConstants.TITLE_SHARING_PANEL); window.setLayout(new FitLayout()); window.add(accessControlListEditor.asWidget(), new FitData(4)); // configure buttons if (canChangePermission) { window.okText = "Save"; window.cancelText = "Cancel"; window.setButtons(Dialog.OKCANCEL); } else { window.cancelText = "Close"; window.setButtons(Dialog.CANCEL); } window.setButtonAlign(HorizontalAlignment.RIGHT); window.setHideOnButtonClick(false); window.setResizable(true); if (canChangePermission) { // "Apply" button // TODO: Disable the "Apply" button if ACLEditor has no unsaved changes Button applyButton = window.getButtonById(Dialog.OK); applyButton.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { // confirm close action if there are unsaved changes if (accessControlListEditor.hasUnsavedChanges()) { accessControlListEditor.pushChangesToSynapse(false, new AsyncCallback<EntityWrapper>() { @Override public void onSuccess(EntityWrapper result) { callback.invoke(); } @Override public void onFailure(Throwable caught) { //failure notification is handled by the acl editor view. } }); } window.hide(); } }); } // "Close" button Button closeButton = window.getButtonById(Dialog.CANCEL); closeButton.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { window.hide(); } }); window.show(); } public static LayoutContainer createRowContainer() { LayoutContainer row; row = new LayoutContainer(); row.setStyleName("row"); return row; } public static enum ButtonType { DEFAULT, PRIMARY, SUCCESS, INFO, WARNING, DANGER, LINK } public static enum BootstrapAlertType { SUCCESS, INFO, WARNING, DANGER } public static com.google.gwt.user.client.ui.Button createButton(String title) { return createIconButton(title, ButtonType.DEFAULT, null); } public static com.google.gwt.user.client.ui.Button createButton(String title, ButtonType type) { return createIconButton(title, type, null); } public static com.google.gwt.user.client.ui.Button createIconButton(String title, ButtonType type, String iconClass) { com.google.gwt.user.client.ui.Button btn = new com.google.gwt.user.client.ui.Button(); relabelIconButton(btn, title, iconClass); btn.removeStyleName("gwt-Button"); btn.addStyleName("btn btn-" + type.toString().toLowerCase()); return btn; } public static void relabelIconButton(com.google.gwt.user.client.ui.Button btn, String title, String iconClass) { String style = iconClass == null ? "" : " class=\"glyphicon " + iconClass+ "\"" ; btn.setHTML(SafeHtmlUtils.fromSafeConstant("<span" + style +"></span> " + title)); } public static String getIcon(String iconClass) { return "<span class=\"glyphicon " + iconClass + "\"></span>"; } public static String getFontelloIcon(String iconClass) { return "<span class=\"icon-" + iconClass + "\"></span>"; } public static EntityHeader getProjectHeader(EntityPath entityPath) { if(entityPath == null) return null; for(EntityHeader eh : entityPath.getPath()) { if(Project.class.getName().equals(eh.getType())) { return eh; } } return null; } public static FlowPanel getMediaObject(String heading, String description, ClickHandler clickHandler, String pictureUri, boolean defaultPictureSinglePerson, int headingLevel) { FlowPanel panel = new FlowPanel(); panel.addStyleName("media"); String linkStyle = ""; if (clickHandler != null) linkStyle = "link"; HTML headingHtml = new HTML("<h"+headingLevel+" class=\"media-heading "+linkStyle+"\">" + SafeHtmlUtils.htmlEscape(heading) + "</h"+headingLevel+">"); if (clickHandler != null) headingHtml.addClickHandler(clickHandler); if (pictureUri != null) { FitImage profilePicture = new FitImage(pictureUri, 64, 64); profilePicture.addStyleName("pull-left media-object imageButton"); if (clickHandler != null) profilePicture.addClickHandler(clickHandler); panel.add(profilePicture); } else { //display default picture String iconClass = defaultPictureSinglePerson ? "user" : "users"; HTML profilePicture = new HTML(DisplayUtils.getFontelloIcon(iconClass + " font-size-58 padding-2 imageButton userProfileImage lightGreyText margin-0-imp-before")); profilePicture.addStyleName("pull-left media-object displayInline "); if (clickHandler != null) profilePicture.addClickHandler(clickHandler); panel.add(profilePicture); } FlowPanel mediaBodyPanel = new FlowPanel(); mediaBodyPanel.addStyleName("media-body"); mediaBodyPanel.add(headingHtml); if (description != null) mediaBodyPanel.add(new HTML(SafeHtmlUtils.htmlEscape(description))); panel.add(mediaBodyPanel); return panel; } public static SimpleComboBox<String> createSimpleComboBox(List<String> values, String defaultValue){ final SimpleComboBox<String> cb = new SimpleComboBox<String>(); cb.add(values); cb.setSimpleValue(defaultValue); cb.setTypeAhead(false); cb.setEditable(false); cb.setForceSelection(true); cb.setTriggerAction(TriggerAction.ALL); return cb; } public static HTML getNewLabel(boolean superScript) { final HTML label = new HTML(DisplayConstants.NEW); label.addStyleName("label label-info margin-left-5"); if(superScript) label.addStyleName("tabLabel"); Timer t = new Timer() { @Override public void run() { label.setVisible(false); } }; t.schedule(30000); // hide after 30 seconds return label; } public static void setPlaceholder(Widget w, String placeholder) { w.getElement().setAttribute("placeholder", placeholder); } public static InlineHTML createFormHelpText(String text) { InlineHTML label = new InlineHTML(text); label.addStyleName("help-block"); return label; } public static String getShareMessage(String displayName, String entityId, String hostUrl) { return displayName + DisplayConstants.SHARED_ON_SYNAPSE + ":\n"+hostUrl+"#!Synapse:"+entityId+"\n\n"+DisplayConstants.TURN_OFF_NOTIFICATIONS+hostUrl+"#!Settings:0"; //alternatively, could use the gwt I18n Messages class client side } public static void getPublicPrincipalIds(UserAccountServiceAsync userAccountService, final AsyncCallback<PublicPrincipalIds> callback){ if (publicPrincipalIds == null) { userAccountService.getPublicAndAuthenticatedGroupPrincipalIds(new AsyncCallback<PublicPrincipalIds>() { @Override public void onSuccess(PublicPrincipalIds result) { publicPrincipalIds = result; callback.onSuccess(result); } @Override public void onFailure(Throwable caught) { callback.onFailure(caught); } }); } else callback.onSuccess(publicPrincipalIds); } public static String getPreviewSuffix(Boolean isPreview) { return isPreview ? WidgetConstants.DIV_ID_PREVIEW_SUFFIX : ""; } public static void hide(UIObject uiObject) { uiObject.addStyleName("hide"); } public static void show(UIObject uiObject) { uiObject.removeStyleName("hide"); } public static void hide(com.google.gwt.dom.client.Element uiObject) { uiObject.addClassName("hide"); } public static void show(com.google.gwt.dom.client.Element uiObject) { uiObject.removeClassName("hide"); } public static void showFormError(DivElement parentElement, DivElement messageElement) { parentElement.addClassName("has-error"); DisplayUtils.show(messageElement); } public static void hideFormError(DivElement parentElement, DivElement messageElement) { parentElement.removeClassName("has-error"); DisplayUtils.hide(messageElement); } public static String getInfoHtml(String safeHtmlMessage) { return "<div class=\"alert alert-info\">"+safeHtmlMessage+"</div>"; } public static String getTableRowViewAreaToken(String id) { return "row/" + id; } public static String getTableRowViewAreaToken(String id, String version) { String str = "row/" + id; if (version != null) str += "/rowversion/" + version; return str; } public static void goToLastPlace(GlobalApplicationState globalApplicationState) { Place forwardPlace = globalApplicationState.getLastPlace(); if(forwardPlace == null) { forwardPlace = new Home(ClientProperties.DEFAULT_PLACE_TOKEN); } globalApplicationState.getPlaceChanger().goTo(forwardPlace); } }
package org.spongepowered.api.data; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.spongepowered.api.data.DataQuery.of; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.lang3.ArrayUtils; import org.spongepowered.api.CatalogType; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.key.Key; import org.spongepowered.api.data.persistence.DataSerializer; import org.spongepowered.api.data.value.BaseValue; import org.spongepowered.api.util.Coerce; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; /** * Default implementation of a {@link DataView} being used in memory. */ public class MemoryDataView implements DataView { protected final Map<String, Object> map = Maps.newLinkedHashMap(); private final DataContainer container; private final DataView parent; private final DataQuery path; protected MemoryDataView() { checkState(this instanceof DataContainer, "Cannot construct a root MemoryDataView without a container!"); this.path = of(); this.parent = this; this.container = (DataContainer) this; } protected MemoryDataView(DataView parent, DataQuery path) { checkArgument(path.getParts().size() >= 1, "Path must have at least one part"); this.parent = parent; this.container = parent.getContainer(); this.path = parent.getCurrentPath().then(path); } @Override public DataContainer getContainer() { return this.container; } @Override public DataQuery getCurrentPath() { return this.path; } @Override public String getName() { List<String> parts = this.path.getParts(); return parts.isEmpty() ? "" : parts.get(parts.size() - 1); } @Override public Optional<DataView> getParent() { return Optional.ofNullable(this.parent); } @Override public Set<DataQuery> getKeys(boolean deep) { ImmutableSet.Builder<DataQuery> builder = ImmutableSet.builder(); for (Map.Entry<String, Object> entry : this.map.entrySet()) { builder.add(of(entry.getKey())); } if (deep) { for (Map.Entry<String, Object> entry : this.map.entrySet()) { if (entry.getValue() instanceof DataView) { for (DataQuery query : ((DataView) entry.getValue()).getKeys(true)) { builder.add(of(entry.getKey()).then(query)); } } } } return builder.build(); } @Override public Map<DataQuery, Object> getValues(boolean deep) { ImmutableMap.Builder<DataQuery, Object> builder = ImmutableMap.builder(); for (DataQuery query : getKeys(deep)) { Object value = get(query).get(); if (value instanceof DataView) { builder.put(query, ((DataView) value).getValues(deep)); } else { builder.put(query, get(query).get()); } } return builder.build(); } @Override public final boolean contains(DataQuery path) { checkNotNull(path, "path"); List<DataQuery> queryParts = path.getQueryParts(); if (queryParts.size() == 1) { String key = queryParts.get(0).getParts().get(0); return this.map.containsKey(key); } else { DataQuery subQuery = queryParts.get(0); Optional<DataView> subViewOptional = this.getUnsafeView(subQuery); if (!subViewOptional.isPresent()) { return false; } List<String> subParts = Lists.newArrayListWithCapacity(queryParts.size() - 1); for (int i = 1; i < queryParts.size(); i++) { subParts.add(queryParts.get(i).asString(".")); } return subViewOptional.get().contains(of(subParts)); } } @Override public boolean contains(DataQuery path, DataQuery... paths) { checkNotNull(path, "DataQuery cannot be null!"); checkNotNull(paths, "DataQuery varargs cannot be null!"); if (paths.length == 0) { return contains(path); } List<DataQuery> queries = new ArrayList<>(); queries.add(path); for (DataQuery query : paths) { queries.add(checkNotNull(query, "No null queries!")); } for (DataQuery query : queries) { if (!contains(query)) { return false; } } return true; } @Override public Optional<Object> get(DataQuery path) { checkNotNull(path, "path"); List<DataQuery> queryParts = path.getQueryParts(); int sz = queryParts.size(); if (sz == 0) { return Optional.<Object>of(this); } if (sz == 1) { String key = queryParts.get(0).getParts().get(0); if (this.map.containsKey(key)) { final Object object = this.map.get(key); if (object.getClass().isArray()) { if (object instanceof byte[]) { return Optional.<Object>of(ArrayUtils.clone((byte[]) object)); } else if (object instanceof short[]) { return Optional.<Object>of(ArrayUtils.clone((short[]) object)); } else if (object instanceof int[]) { return Optional.<Object>of(ArrayUtils.clone((int[]) object)); } else if (object instanceof long[]) { return Optional.<Object>of(ArrayUtils.clone((long[]) object)); } else if (object instanceof float[]) { return Optional.<Object>of(ArrayUtils.clone((float[]) object)); } else if (object instanceof double[]) { return Optional.<Object>of(ArrayUtils.clone((double[]) object)); } else if (object instanceof boolean[]) { return Optional.<Object>of(ArrayUtils.clone((boolean[]) object)); } else { return Optional.<Object>of(ArrayUtils.clone((Object[]) object)); } } return Optional.of(this.map.get(key)); } else { return Optional.empty(); } } DataQuery subQuery = queryParts.get(0); Optional<DataView> subViewOptional = this.getUnsafeView(subQuery); DataView subView; if (!subViewOptional.isPresent()) { return Optional.empty(); } else { subView = subViewOptional.get(); } List<String> subParts = Lists.newArrayListWithCapacity(queryParts.size() - 1); for (int i = 1; i < queryParts.size(); i++) { subParts.add(queryParts.get(i).asString(".")); } return subView.get(of(subParts)); } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public DataView set(DataQuery path, Object value) { checkNotNull(path, "path"); checkNotNull(value, "value"); checkState(this.container != null); @Nullable DataManager manager; try { manager = Sponge.getDataManager(); } catch (Exception e) { manager = null; } if (value instanceof DataView) { checkArgument(value != this, "Cannot set a DataView to itself."); copyDataView(path, (DataView) value); }else if (value instanceof DataSerializable) { DataContainer valueContainer = ((DataSerializable) value).toContainer(); checkArgument(!(valueContainer).equals(this), "Cannot insert self-referencing DataSerializable"); copyDataView(path, valueContainer); } else if (value instanceof CatalogType) { return set(path, ((CatalogType) value).getId()); } else if (manager != null && manager.getSerializer(value.getClass()).isPresent()) { DataSerializer serializer = manager.getSerializer(value.getClass()).get(); final DataContainer container = serializer.serialize(value); checkArgument(!container.equals(this), "Cannot insert self-referencing Objects!"); copyDataView(path, container); } else { List<String> parts = path.getParts(); if (parts.size() > 1) { String subKey = parts.get(0); DataQuery subQuery = of(subKey); Optional<DataView> subViewOptional = this.getUnsafeView(subQuery); DataView subView; if (!subViewOptional.isPresent()) { this.createView(subQuery); subView = (DataView) this.map.get(subKey); } else { subView = subViewOptional.get(); } List<String> subParts = Lists.newArrayListWithCapacity(parts.size() - 1); for (int i = 1; i < parts.size(); i++) { subParts.add(parts.get(i)); } subView.set(of(subParts), value); } else { if (value instanceof Collection) { setCollection(parts.get(0), (Collection) value); } else if (value instanceof Map) { setMap(parts.get(0), (Map) value); } else if (value.getClass().isArray()) { if (value instanceof byte[]) { this.map.put(parts.get(0), ArrayUtils.clone((byte[]) value)); } else if (value instanceof short[]) { this.map.put(parts.get(0), ArrayUtils.clone((short[]) value)); } else if (value instanceof int[]) { this.map.put(parts.get(0), ArrayUtils.clone((int[]) value)); } else if (value instanceof long[]) { this.map.put(parts.get(0), ArrayUtils.clone((long[]) value)); } else if (value instanceof float[]) { this.map.put(parts.get(0), ArrayUtils.clone((float[]) value)); } else if (value instanceof double[]) { this.map.put(parts.get(0), ArrayUtils.clone((double[]) value)); } else if (value instanceof boolean[]) { this.map.put(parts.get(0), ArrayUtils.clone((boolean[]) value)); } else { this.map.put(parts.get(0), ArrayUtils.clone((Object[]) value)); } } else { this.map.put(parts.get(0), value); } } } return this; } @Override public <E> DataView set(Key<? extends BaseValue<E>> key, E value) { return set(checkNotNull(key, "Key was null!").getQuery(), value); } @SuppressWarnings({"unchecked", "rawtypes"}) private void setCollection(String key, Collection<?> value) { ImmutableList.Builder<Object> builder = ImmutableList.builder(); @Nullable DataManager manager; try { manager = Sponge.getDataManager(); } catch (Exception e) { manager = null; } for (Object object : value) { if (object instanceof DataSerializable) { builder.add(((DataSerializable) object).toContainer()); } else if (object instanceof DataView) { MemoryDataView view = new MemoryDataContainer(); DataView internalView = (DataView) object; for (Map.Entry<DataQuery, Object> entry : internalView.getValues(false).entrySet()) { view.set(entry.getKey(), entry.getValue()); } builder.add(view); } else if (object instanceof Map) { builder.add(ensureSerialization((Map) object)); } else if (object instanceof Collection) { builder.add(ensureSerialization((Collection) object)); } else { if (manager != null) { final Optional<? extends DataSerializer<?>> serializerOptional = manager.getSerializer(object.getClass()); if (serializerOptional.isPresent()) { DataSerializer serializer = serializerOptional.get(); final DataContainer container = serializer.serialize(value); checkArgument(!container.equals(this), "Cannot insert self-referencing Objects!"); copyDataView(this.path, container); } else { builder.add(object); } } else { builder.add(object); } } } this.map.put(key, builder.build()); } @SuppressWarnings("rawtypes") private ImmutableList<Object> ensureSerialization(Collection<?> collection) { ImmutableList.Builder<Object> objectBuilder = ImmutableList.builder(); collection.forEach(element -> { if (element instanceof Collection) { objectBuilder.add(ensureSerialization((Collection) element)); } else if (element instanceof DataSerializable) { objectBuilder.add(((DataSerializable) element).toContainer()); } else { objectBuilder.add(element); } }); return objectBuilder.build(); } @SuppressWarnings("rawtypes") private ImmutableMap<?, ?> ensureSerialization(Map<?, ?> map) { ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder(); map.entrySet().forEach(entry -> { if (entry.getValue() instanceof Map) { builder.put(entry.getKey(), ensureSerialization((Map) entry.getValue())); } else if (entry.getValue() instanceof DataSerializable) { builder.put(entry.getKey(), ((DataSerializable) entry.getValue()).toContainer()); } else if (entry.getValue() instanceof Collection) { builder.put(entry.getKey(), ensureSerialization((Collection) entry.getValue())); } else { builder.put(entry.getKey(), entry.getValue()); } }); return builder.build(); } private void setMap(String key, Map<?, ?> value) { DataView view = createView(of(key)); for (Map.Entry<?, ?> entry : value.entrySet()) { view.set(of(entry.getKey().toString()), entry.getValue()); } } private void copyDataView(DataQuery path, DataView value) { Collection<DataQuery> valueKeys = value.getKeys(true); for (DataQuery oldKey : valueKeys) { set(path.then(oldKey), value.get(oldKey).get()); } } @Override public DataView remove(DataQuery path) { checkNotNull(path, "path"); List<String> parts = path.getParts(); if (parts.size() > 1) { String subKey = parts.get(0); DataQuery subQuery = of(subKey); Optional<DataView> subViewOptional = this.getUnsafeView(subQuery); DataView subView; if (!subViewOptional.isPresent()) { return this; } else { subView = subViewOptional.get(); } List<String> subParts = Lists.newArrayListWithCapacity(parts.size() - 1); for (int i = 1; i < parts.size(); i++) { subParts.add(parts.get(i)); } subView.remove(of(subParts)); } else { this.map.remove(parts.get(0)); } return this; } @Override public DataView createView(DataQuery path) { checkNotNull(path, "path"); List<DataQuery> queryParts = path.getQueryParts(); int sz = queryParts.size(); checkArgument(sz != 0, "The size of the query must be at least 1"); if (sz == 1) { DataQuery key = queryParts.get(0); DataView result = new MemoryDataView(this, key); this.map.put(key.getParts().get(0), result); return result; } else { List<String> subParts = Lists .newArrayListWithCapacity(queryParts.size() - 1); for (int i = 1; i < sz; i++) { subParts.add(queryParts.get(i).asString('.')); } DataQuery subQuery = of(subParts); DataView subView = (DataView) this.map.get(queryParts.get(0).asString('.')); if (subView == null) { subView = new MemoryDataView(this.parent, queryParts.get(0)); this.map.put(queryParts.get(0).asString('.'), subView); } return subView.createView(subQuery); } } @Override @SuppressWarnings("rawtypes") public DataView createView(DataQuery path, Map<?, ?> map) { checkNotNull(path, "path"); DataView section = createView(path); for (Map.Entry<?, ?> entry : map.entrySet()) { if (entry.getValue() instanceof Map) { section.createView(of('.', entry.getKey().toString()), (Map<?, ?>) entry.getValue()); } else { section.set(of('.', entry.getKey().toString()), entry.getValue()); } } return section; } @Override public Optional<DataView> getView(DataQuery path) { return get(path).filter(obj -> obj instanceof DataView).map(obj -> (DataView) obj); } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public Optional<? extends Map<?, ?>> getMap(DataQuery path) { Optional<Object> val = get(path); if (val.isPresent()) { if (val.get() instanceof DataView) { ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder(); for (Map.Entry<DataQuery, Object> entry : ((DataView) val.get()).getValues(false).entrySet()) { builder.put(entry.getKey().asString('.'), ensureMappingOf(entry.getValue())); } return Optional.of(builder.build()); } else if (val.get() instanceof Map) { return Optional.of((Map<?, ?>) ensureMappingOf(val.get())); } } return Optional.empty(); } private Object ensureMappingOf(Object object) { if (object instanceof DataView) { final ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder(); for (Map.Entry<DataQuery, Object> entry : ((DataView) object).getValues(false).entrySet()) { builder.put(entry.getKey().asString('.'), ensureMappingOf(entry.getValue())); } return builder.build(); } else if (object instanceof Map) { final ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder(); for (Map.Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) { builder.put(entry.getKey().toString(), ensureMappingOf(entry.getValue())); } return builder.build(); } else if (object instanceof Collection) { final ImmutableList.Builder<Object> builder = ImmutableList.builder(); for (Object entry : (Collection) object) { builder.add(ensureMappingOf(entry)); } return builder.build(); } else { return object; } } private Optional<DataView> getUnsafeView(DataQuery path) { return get(path).filter(obj -> obj instanceof DataView).map(obj -> (DataView) obj); } @Override public Optional<Boolean> getBoolean(DataQuery path) { return get(path).flatMap(Coerce::asBoolean); } @Override public Optional<Byte> getByte(DataQuery path) { return get(path).flatMap(Coerce::asByte); } @Override public Optional<Short> getShort(DataQuery path) { return get(path).flatMap(Coerce::asShort); } @Override public Optional<Integer> getInt(DataQuery path) { return get(path).flatMap(Coerce::asInteger); } @Override public Optional<Long> getLong(DataQuery path) { return get(path).flatMap(Coerce::asLong); } @Override public Optional<Float> getFloat(DataQuery path) { return get(path).flatMap(Coerce::asFloat); } @Override public Optional<Double> getDouble(DataQuery path) { return get(path).flatMap(Coerce::asDouble); } @Override public Optional<String> getString(DataQuery path) { return get(path).flatMap(Coerce::asString); } @Override public Optional<List<?>> getList(DataQuery path) { Optional<Object> val = get(path); if (val.isPresent()) { if (val.get() instanceof List<?>) { return Optional.<List<?>>of(Lists.newArrayList((List<?>) val.get())); } if (val.get() instanceof Object[]) { return Optional.<List<?>>of(Lists.newArrayList((Object[]) val.get())); } } return Optional.empty(); } @Override public Optional<List<String>> getStringList(DataQuery path) { return getUnsafeList(path).map(list -> list.stream() .map(Coerce::asString) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()) ); } private Optional<List<?>> getUnsafeList(DataQuery path) { return get(path) .filter(obj -> obj instanceof List<?> || obj instanceof Object[]) .map(obj -> { if (obj instanceof List<?>) { return (List<?>) obj; } else { return Arrays.asList((Object[]) obj); } } ); } @Override public Optional<List<Character>> getCharacterList(DataQuery path) { return getUnsafeList(path).map(list -> list.stream() .map(Coerce::asChar) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()) ); } @Override public Optional<List<Boolean>> getBooleanList(DataQuery path) { return getUnsafeList(path).map(list -> list.stream() .map(Coerce::asBoolean) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()) ); } @Override public Optional<List<Byte>> getByteList(DataQuery path) { return getUnsafeList(path).map(list -> list.stream() .map(Coerce::asByte) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()) ); } @Override public Optional<List<Short>> getShortList(DataQuery path) { return getUnsafeList(path).map(list -> list.stream() .map(Coerce::asShort) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()) ); } @Override public Optional<List<Integer>> getIntegerList(DataQuery path) { return getUnsafeList(path).map(list -> list.stream() .map(Coerce::asInteger) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()) ); } @Override public Optional<List<Long>> getLongList(DataQuery path) { return getUnsafeList(path).map(list -> list.stream() .map(Coerce::asLong) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()) ); } @Override public Optional<List<Float>> getFloatList(DataQuery path) { return getUnsafeList(path).map(list -> list.stream() .map(Coerce::asFloat) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()) ); } @Override public Optional<List<Double>> getDoubleList(DataQuery path) { return getUnsafeList(path).map(list -> list.stream() .map(Coerce::asDouble) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()) ); } @Override public Optional<List<Map<?, ?>>> getMapList(DataQuery path) { return getUnsafeList(path).map(list -> list.stream() .filter(obj -> obj instanceof Map<?, ?>) .map(obj -> (Map<?, ?>) obj) .collect(Collectors.toList()) ); } @Override public Optional<List<DataView>> getViewList(DataQuery path) { return getUnsafeList(path).map(list -> list.stream() .filter(obj -> obj instanceof DataView) .map(obj -> (DataView) obj) .collect(Collectors.toList()) ); } @SuppressWarnings("unchecked") @Override public <T extends DataSerializable> Optional<T> getSerializable(DataQuery path, Class<T> clazz) { checkNotNull(path, "path"); checkNotNull(clazz, "clazz"); if (clazz.isAssignableFrom(CatalogType.class)) { final Optional<T> catalog = (Optional<T>) getCatalogType(path, ((Class<? extends CatalogType>) clazz)); if (catalog.isPresent()) { return catalog; } } return getUnsafeView(path).flatMap(view -> Sponge.getDataManager().getBuilder(clazz) .flatMap(builder -> builder.build(view)) ); } @SuppressWarnings("unchecked") @Override public <T extends DataSerializable> Optional<List<T>> getSerializableList(DataQuery path, Class<T> clazz) { checkNotNull(path, "path"); checkNotNull(clazz, "clazz"); return Stream.<Supplier<Optional<List<T>>>>of( () -> { if (clazz.isAssignableFrom(CatalogType.class)) { return (Optional<List<T>>) (Optional<?>) getCatalogTypeList(path, (Class<? extends CatalogType>) clazz); } return Optional.empty(); }, () -> getViewList(path).flatMap(list -> Sponge.getDataManager().getBuilder(clazz).map(builder -> list.stream() .map(builder::build) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()) ) ) ) .map(Supplier::get) .filter(Optional::isPresent) .map(Optional::get) .findFirst(); } @Override public <T extends CatalogType> Optional<T> getCatalogType(DataQuery path, Class<T> catalogType) { checkNotNull(path, "path"); checkNotNull(catalogType, "dummy type"); return getString(path).flatMap(string -> Sponge.getRegistry().getType(catalogType, string)); } @Override public <T extends CatalogType> Optional<List<T>> getCatalogTypeList(DataQuery path, Class<T> catalogType) { checkNotNull(path, "path"); checkNotNull(catalogType, "catalogType"); return getStringList(path).map(list -> list.stream() .map(string -> Sponge.getRegistry().getType(catalogType, string)) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()) ); } @Override public <T> Optional<T> getObject(DataQuery path, Class<T> objectClass) { return getView(path).flatMap(view -> Sponge.getDataManager().getSerializer(objectClass) .flatMap(serializer -> serializer.deserialize(view)) ); } @Override public <T> Optional<List<T>> getObjectList(DataQuery path, Class<T> objectClass) { return getViewList(path).flatMap(viewList -> Sponge.getDataManager().getSerializer(objectClass).map(serializer -> viewList.stream() .map(serializer::deserialize) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()) ) ); } @Override public DataContainer copy() { final DataContainer container = new MemoryDataContainer(); getKeys(false).stream() .forEach(query -> get(query).ifPresent(obj -> container.set(query, obj) ) ); return container; } @Override public int hashCode() { return Objects.hashCode(this.map, this.path); } @Override public boolean equals(@Nullable Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final MemoryDataView other = (MemoryDataView) obj; return Objects.equal(this.map.entrySet(), other.map.entrySet()) && Objects.equal(this.path, other.path); } @Override public String toString() { final Objects.ToStringHelper helper = Objects.toStringHelper(this); if (!this.path.toString().isEmpty()) { helper.add("path", this.path); } return helper.add("map", this.map).toString(); } }
package lispy; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class Compiler { public static String jsNamespace = "lispy"; public static String prelude(String namespace) { StringBuilder builder = new StringBuilder(); builder.append(jsNamespace + "={"); builder.append("'=' : function(a,b){ return a == b; },"); builder.append("'+' : function(a,b){ return a + b; },"); builder.append("'-' : function(a,b){ return a - b; },"); builder.append("'*' : function(a,b){ return a * b; },"); builder.append("'/' : function(a,b){ return a / b; },"); builder.append("'<' : function(a,b){ return (a < b); },"); builder.append("'<=': function(a,b){ return (a <= b); },"); builder.append("'>=': function(a,b){ return (a >= b); },"); builder.append("'>' : function(a,b){ return (a > b); },"); // TODO add the rest of the built-in functions builder.append("'display': function(s){ if (console){ console.log(s); }; return null; }"); builder.append("};"); return builder.toString(); }; public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java lispy.Compiler path/to/file.scm\nOutputs 'file.js' in the current directory."); return; } String sourceFile = args[0]; String namespace = sourceFile.substring(0, sourceFile.lastIndexOf(".")); if (namespace.contains("/")) { namespace = namespace.substring(1 + namespace.lastIndexOf("/")); } Compiler.jsNamespace = namespace; String targetFile = String.format("%s.js", namespace); System.out.println(String.format("Output: %s", targetFile)); BufferedReader reader = new BufferedReader(new FileReader(sourceFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, false)); writer.write(prelude(namespace) + "\n"); String line; Environment env = Environment.getGlobalEnvironment(); while ((line = reader.readLine()) != null) { String output = Eval.emit(line, env); writer.write(output + "\n"); } reader.close(); writer.flush(); writer.close(); } }
package org.spongepowered.common.network; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.network.INetHandler; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.Packet; import net.minecraft.network.play.client.CPacketClientSettings; import net.minecraft.network.play.client.CPacketClientStatus; import net.minecraft.network.play.client.CPacketPlayer; import org.spongepowered.api.Sponge; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.common.event.tracking.IPhaseState; import org.spongepowered.common.event.tracking.PhaseContext; import org.spongepowered.common.event.tracking.phase.TrackingPhases; import org.spongepowered.common.event.tracking.phase.packet.PacketContext; import org.spongepowered.common.event.tracking.phase.packet.PacketPhase; import org.spongepowered.common.interfaces.entity.player.IMixinEntityPlayerMP; import org.spongepowered.common.item.inventory.util.ItemStackUtil; public class PacketUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static void onProcessPacket(Packet packetIn, INetHandler netHandler) { if (netHandler instanceof NetHandlerPlayServer) { try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { EntityPlayerMP packetPlayer = ((NetHandlerPlayServer) netHandler).player; frame.pushCause(packetPlayer); if (creativeExploitCheck(packetIn, packetPlayer)) { return; } // Don't process movement capture logic if player hasn't moved boolean ignoreMovementCapture = false; if (packetIn instanceof CPacketPlayer) { CPacketPlayer movingPacket = ((CPacketPlayer) packetIn); if (movingPacket instanceof CPacketPlayer.Rotation) { ignoreMovementCapture = true; } else if (packetPlayer.posX == movingPacket.x && packetPlayer.posY == movingPacket.y && packetPlayer.posZ == movingPacket.z) { ignoreMovementCapture = true; } } if (ignoreMovementCapture || (packetIn instanceof CPacketClientSettings)) { packetIn.processPacket(netHandler); } else { final ItemStackSnapshot cursor = ItemStackUtil.snapshotOf(packetPlayer.inventory.getItemStack()); IPhaseState<? extends PacketContext<?>> packetState = TrackingPhases.PACKET.getStateForPacket(packetIn); // At the very least make an unknown packet state case. final PacketContext<?> context = packetState.createPhaseContext(); if (!TrackingPhases.PACKET.isPacketInvalid(packetIn, packetPlayer, packetState)) { context .source(packetPlayer) .packetPlayer(packetPlayer) .packet(packetIn) .cursor(cursor); TrackingPhases.PACKET.populateContext(packetIn, packetPlayer, packetState, context); context.owner((Player) packetPlayer); context.notifier((Player) packetPlayer); } try (PhaseContext<?> packetContext = context) { packetContext.buildAndSwitch(); packetIn.processPacket(netHandler); } if (packetIn instanceof CPacketClientStatus) { // update the reference of player packetPlayer = ((NetHandlerPlayServer) netHandler).player; } ((IMixinEntityPlayerMP) packetPlayer).setPacketItem(ItemStack.EMPTY); } } } else { // client packetIn.processPacket(netHandler); } } // Overridden by MixinPacketUtil for exploit check private static boolean creativeExploitCheck(Packet<?> packetIn, EntityPlayerMP playerMP) { return false; } }
package org.trancecode.parallel; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import java.util.Iterator; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; /** * Parallel equivalent of {@link Iterables}. * * @author Herve Quiroz */ public final class ParallelIterables { /** * @see Iterables#transform(Iterable, Function) */ public static <F, T> Iterable<T> transform(final Iterable<F> fromIterable, final Function<? super F, ? extends T> function, final ExecutorService executor) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return ParallelIterators.transform(fromIterable.iterator(), function, executor); } }; } /** * @see Iterables#filter(Iterable, Predicate) */ public static <T> Iterable<T> filter(final Iterable<T> unfiltered, final Predicate<? super T> predicate, final ExecutorService executorService) { // TODO return Iterables.filter(unfiltered, predicate); } public static <T> Iterable<T> get(final Iterable<Future<T>> futures) { final Function<Future<T>, T> function = ParallelFunctions.get(); return Iterables.transform(futures, function); } private ParallelIterables() { // No instantiation } }
package org.zalando.nakadi.service; import com.google.common.collect.ImmutableSet; import org.everit.json.schema.Schema; import org.everit.json.schema.SchemaException; import org.everit.json.schema.loader.SchemaLoader; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.zalando.nakadi.domain.EventCategory; import org.zalando.nakadi.domain.EventType; import org.zalando.nakadi.domain.EventTypeStatistics; import org.zalando.nakadi.domain.Subscription; import org.zalando.nakadi.enrichment.Enrichment; import org.zalando.nakadi.exceptions.DuplicatedEventTypeNameException; import org.zalando.nakadi.exceptions.InternalNakadiException; import org.zalando.nakadi.exceptions.InvalidEventTypeException; import org.zalando.nakadi.exceptions.NakadiException; import org.zalando.nakadi.exceptions.NoSuchEventTypeException; import org.zalando.nakadi.exceptions.NoSuchPartitionStrategyException; import org.zalando.nakadi.exceptions.TopicCreationException; import org.zalando.nakadi.exceptions.TopicDeletionException; import org.zalando.nakadi.partitioning.PartitionResolver; import org.zalando.nakadi.repository.EventTypeRepository; import org.zalando.nakadi.repository.TopicRepository; import org.zalando.nakadi.repository.db.SubscriptionDbRepository; import org.zalando.nakadi.security.Client; import org.zalando.nakadi.util.FeatureToggleService; import org.zalando.nakadi.util.UUIDGenerator; import org.zalando.nakadi.validation.SchemaCompatibilityChecker; import org.zalando.nakadi.validation.SchemaIncompatibility; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import static org.zalando.nakadi.util.FeatureToggleService.Feature.CHECK_PARTITIONS_KEYS; @Component public class EventTypeService { private static final Logger LOG = LoggerFactory.getLogger(EventTypeService.class); private final EventTypeRepository eventTypeRepository; private final TopicRepository topicRepository; private final PartitionResolver partitionResolver; private final Enrichment enrichment; private final UUIDGenerator uuidGenerator; private final FeatureToggleService featureToggleService; private final SubscriptionDbRepository subscriptionRepository; private final SchemaCompatibilityChecker schemaCompatibilityChecker; @Autowired public EventTypeService(final EventTypeRepository eventTypeRepository, final TopicRepository topicRepository, final PartitionResolver partitionResolver, final Enrichment enrichment, final UUIDGenerator uuidGenerator, final FeatureToggleService featureToggleService, final SubscriptionDbRepository subscriptionRepository, final SchemaCompatibilityChecker schemaCompatibilityChecker) { this.eventTypeRepository = eventTypeRepository; this.topicRepository = topicRepository; this.partitionResolver = partitionResolver; this.enrichment = enrichment; this.uuidGenerator = uuidGenerator; this.featureToggleService = featureToggleService; this.subscriptionRepository = subscriptionRepository; this.schemaCompatibilityChecker = schemaCompatibilityChecker; } public List<EventType> list() { return eventTypeRepository.list(); } public Result<Void> create(final EventType eventType) { try { assignTopic(eventType); validateSchema(eventType); enrichment.validate(eventType); partitionResolver.validate(eventType); eventTypeRepository.saveEventType(eventType); topicRepository.createTopic(eventType); return Result.ok(); } catch (final InvalidEventTypeException | NoSuchPartitionStrategyException | DuplicatedEventTypeNameException e) { LOG.debug("Failed to create EventType.", e); return Result.problem(e.asProblem()); } catch (final TopicCreationException e) { LOG.error("Problem creating kafka topic. Rolling back event type database registration.", e); try { eventTypeRepository.removeEventType(eventType.getTopic()); } catch (final NakadiException e1) { return Result.problem(e.asProblem()); } return Result.problem(e.asProblem()); } catch (final NakadiException e) { LOG.error("Error creating event type " + eventType, e); return Result.problem(e.asProblem()); } } public Result<Void> delete(final String eventTypeName, final Client client) { try { final Optional<EventType> eventType = eventTypeRepository.findByNameO(eventTypeName); if (!eventType.isPresent()) { return Result.notFound("EventType \"" + eventTypeName + "\" does not exist."); } if (!client.idMatches(eventType.get().getOwningApplication())) { return Result.forbidden("You don't have access to this event type"); } final List<Subscription> subscriptions = subscriptionRepository.listSubscriptions( ImmutableSet.of(eventTypeName), Optional.empty(), 0, 1); if (!subscriptions.isEmpty()) { return Result.conflict("Not possible to remove event-type as it has subscriptions"); } eventTypeRepository.removeEventType(eventTypeName); topicRepository.deleteTopic(eventType.get().getTopic()); return Result.ok(); } catch (final TopicDeletionException e) { LOG.error("Problem deleting kafka topic " + eventTypeName, e); return Result.problem(e.asProblem()); } catch (final NakadiException e) { LOG.error("Error deleting event type " + eventTypeName, e); return Result.problem(e.asProblem()); } } public Result<Void> update(final String eventTypeName, final EventType eventType, final Client client) { try { final EventType original = eventTypeRepository.findByName(eventTypeName); if (!client.idMatches(original.getOwningApplication())) { return Result.forbidden("You don't have access to this event type"); } validateUpdate(eventTypeName, eventType); enrichment.validate(eventType); partitionResolver.validate(eventType); eventTypeRepository.update(eventType); return Result.ok(); } catch (final InvalidEventTypeException e) { return Result.problem(e.asProblem()); } catch (final NoSuchEventTypeException e) { LOG.debug("Could not find EventType: {}", eventTypeName); return Result.problem(e.asProblem()); } catch (final NakadiException e) { LOG.error("Unable to update event type", e); return Result.problem(e.asProblem()); } } public Result<EventType> get(final String eventTypeName) { try { final EventType eventType = eventTypeRepository.findByName(eventTypeName); return Result.ok(eventType); } catch (final NoSuchEventTypeException e) { LOG.debug("Could not find EventType: {}", eventTypeName); return Result.problem(e.asProblem()); } catch (final InternalNakadiException e) { LOG.error("Problem loading event type " + eventTypeName, e); return Result.problem(e.asProblem()); } } private void validateUpdate(final String name, final EventType eventType) throws NoSuchEventTypeException, InternalNakadiException, InvalidEventTypeException, NoSuchPartitionStrategyException { final EventType existingEventType = eventTypeRepository.findByName(name); validateName(name, eventType); validatePartitionKeys(Optional.empty(), eventType); validateSchemaChange(eventType, existingEventType); eventType.setDefaultStatistic( validateStatisticsUpdate(existingEventType.getDefaultStatistic(), eventType.getDefaultStatistic())); } private EventTypeStatistics validateStatisticsUpdate(final EventTypeStatistics existing, final EventTypeStatistics newStatistics) throws InvalidEventTypeException { if (existing != null && newStatistics == null) { return existing; } if (!Objects.equals(existing, newStatistics)) { throw new InvalidEventTypeException("default statistics must not be changed"); } return newStatistics; } private void validateName(final String name, final EventType eventType) throws InvalidEventTypeException { if (!eventType.getName().equals(name)) { throw new InvalidEventTypeException("path does not match resource name"); } } private void validateSchemaChange(final EventType eventType, final EventType existingEventType) throws InvalidEventTypeException { if (!existingEventType.getSchema().equals(eventType.getSchema())) { throw new InvalidEventTypeException("schema must not be changed"); } } private void validateSchema(final EventType eventType) throws InvalidEventTypeException { try { final JSONObject schemaAsJson = new JSONObject(eventType.getSchema().getSchema()); final Schema schema = SchemaLoader.load(schemaAsJson); if (eventType.getCategory() == EventCategory.BUSINESS && schema.definesProperty("#/metadata")) { throw new InvalidEventTypeException("\"metadata\" property is reserved"); } validatePartitionKeys(Optional.of(schema), eventType); validateJsonSchemaConstraints(schema); } catch (final JSONException e) { throw new InvalidEventTypeException("schema must be a valid json"); } catch (final SchemaException e) { throw new InvalidEventTypeException("schema must be a valid json-schema"); } } private void validateJsonSchemaConstraints(final Schema schema) throws InvalidEventTypeException { final List<SchemaIncompatibility> incompatibilities = schemaCompatibilityChecker.checkConstraints(schema); if (!incompatibilities.isEmpty()) { final String errorMessage = incompatibilities.stream().map(Object::toString) .collect(Collectors.joining(", ")); throw new InvalidEventTypeException("Invalid schema: " + errorMessage); } } private void validatePartitionKeys(final Optional<Schema> schemaO, final EventType eventType) throws InvalidEventTypeException, JSONException, SchemaException { if (!featureToggleService.isFeatureEnabled(CHECK_PARTITIONS_KEYS)) { return; } final Schema schema = schemaO.orElseGet(() -> { final JSONObject schemaAsJson = new JSONObject(eventType.getSchema().getSchema()); return SchemaLoader.load(schemaAsJson); }); final List<String> absentFields = eventType.getPartitionKeyFields().stream() .filter(field -> !schema.definesProperty(convertToJSONPointer(field))) .collect(Collectors.toList()); if (!absentFields.isEmpty()) { throw new InvalidEventTypeException("partition_key_fields " + absentFields + " absent in schema"); } } private void assignTopic(final EventType eventType) { eventType.setTopic(uuidGenerator.randomUUID().toString()); } private String convertToJSONPointer(final String value) { return value.replaceAll("\\.", "/"); } }
package org.yaml.snakeyaml.resolver; import java.util.regex.Pattern; final class ResolverTuple { private final String tag; private final Pattern regexp; public ResolverTuple(String tag, Pattern regexp) { this.tag = tag; this.regexp = regexp; } public String getTag() { return tag; } public Pattern getRegexp() { return regexp; } @Override public String toString() { return "Tuple tag=" + tag + " regexp=" + regexp; } }
package com.exedio.cope.util; import java.io.File; import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import com.exedio.cope.Cope; import com.exedio.cope.Model; public class ServletUtil { private static final String PARAMETER_MODEL = "model"; public static final ConnectToken getConnectedModel(final Servlet servlet) throws ServletException { final ServletConfig config = servlet.getServletConfig(); return getConnectedModel( config.getInitParameter(PARAMETER_MODEL), "servlet", config.getServletName(), servlet, config.getServletContext()); } public static final ConnectToken getConnectedModel(final Filter filter, final FilterConfig config) throws ServletException { return getConnectedModel( config.getInitParameter(PARAMETER_MODEL), "filter", config.getFilterName(), filter, config.getServletContext()); } private static final ConnectToken getConnectedModel( final String initParam, final String kind, final String name, final Object nameObject, final ServletContext context) throws ServletException { final String description = kind + ' ' + '"' + name + '"' + ' ' + '(' + nameObject.getClass().getName() + '@' + System.identityHashCode(nameObject) + ')'; final String modelName; final String modelNameSource; if(initParam==null) { final String contextParam = context.getInitParameter(PARAMETER_MODEL); if(contextParam==null) throw new ServletException(description + ": neither init-param nor context-param '"+PARAMETER_MODEL+"' set"); modelName = contextParam; modelNameSource = "context-param"; } else { modelName = initParam; modelNameSource = "init-param"; } final Model result; try { result = Cope.getModel(modelName); } catch(IllegalArgumentException e) { throw new ServletException(description + ", " + modelNameSource + ' ' + PARAMETER_MODEL + ':' + ' ' + e.getMessage(), e); } return connect(result, context, description); } /** * Connects the model using the properties from * the file <tt>cope.properties</tt> * in the directory <tt>WEB-INF</tt> * of the web application. * @see Model#connect(com.exedio.cope.ConnectProperties) * @see ConnectToken#issue(Model,com.exedio.cope.ConnectProperties,String) */ public static final ConnectToken connect(final Model model, final ServletContext context, final String name) { return ConnectToken.issue(model, new com.exedio.cope.ConnectProperties( new File(context.getRealPath("WEB-INF/cope.properties")), getPropertyContext(context)), name); } public static final Properties.Context getPropertyContext(final ServletContext context) { return new Properties.Context(){ public String get(final String key) { return context.getInitParameter(key); } @Override public String toString() { return "javax.servlet.ServletContext.getInitParameter of '" + context.getServletContextName() + '\''; } }; } /** * @deprecated Use {@link #getConnectedModel(Servlet)} instead */ @Deprecated public static final ConnectToken getModel(final Servlet servlet) throws ServletException { return getConnectedModel(servlet); } /** * @deprecated Use {@link #getConnectedModel(Filter,FilterConfig)} instead */ @Deprecated public static final ConnectToken getModel(final Filter filter, final FilterConfig config) throws ServletException { return getConnectedModel(filter, config); } /** * @deprecated Renamed to {@link #connect(Model, ServletContext, String)}. */ @Deprecated public static final ConnectToken initialize(final Model model, final ServletContext context, final String name) { return connect(model, context, name); } }
package pointGroups.geometry.symmetries; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import pointGroups.geometry.Point4D; import pointGroups.geometry.Quaternion; import pointGroups.geometry.Symmetry; public class TxTSymmetry implements Symmetry<Point4D, TxTSymmetry> { /** * The singleton instance of the IxI's symmetry class. */ private final static TxTSymmetry sym = new TxTSymmetry(true); private final List<Rotation4D> gen = new ArrayList<Rotation4D>(); private final static String filename = "tXt.sym"; private static Collection<Rotation4D> group; protected TxTSymmetry(final boolean readFile) { if (readFile) { try { group = GeneratorCreator.readSymmetryGroup(filename); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO: ungly!!!!1111 } else { gen.add(new Rotation4D(Quaternion.I, Quaternion.ONE)); gen.add(new Rotation4D(GeneratorCreator.qw, Quaternion.ONE)); gen.add(new Rotation4D(Quaternion.ONE, Quaternion.I)); gen.add(new Rotation4D(Quaternion.ONE, GeneratorCreator.qw)); group = GeneratorCreator.generateSymmetryGroup4D(gen); } } public enum Subgroups implements Subgroup<TxTSymmetry> { Full("Full [IxI] symmetry"); private final String name; Subgroups(final String name) { this.name = name; } @Override public String getName() { return this.name; } @Override public int order() { return sym.order(this); } } public static TxTSymmetry getSym() { return sym; } @Override public Collection<Point4D> images(final Point4D p, final Subgroup<TxTSymmetry> s) { return calculateImages(new Quaternion(p.re, p.i, p.j, p.k)); } @Override public Collection<Point4D> images(final Point4D p, final String s) { return images(p, Subgroups.valueOf(s)); } @Override public Collection<Subgroup<TxTSymmetry>> getSubgroups() { Collection<Subgroup<TxTSymmetry>> c = new LinkedList<>(); c.add(Subgroups.Full); return c; } @Override public int order(final pointGroups.geometry.Symmetry.Subgroup<TxTSymmetry> s) { return 576; } @Override public String getName() { return "[T x T]"; } @Override public Class<Point4D> getType() { return Point4D.class; } @Override public Subgroup<TxTSymmetry> getSubgroupByName(final String subgroup) { return Subgroups.valueOf(subgroup); } @Override public Point4D getNormalPoint() { return new Point4D(0.2, 0.3, 0.4, 0.5); // just anything } private Collection<Point4D> calculateImages(final Quaternion q) { Collection<Point4D> rotatedPointcollection = new ArrayList<>(); for (Rotation4D r : group) { rotatedPointcollection.add(r.rotate(q).asPoint4D()); } return rotatedPointcollection; } }
package permafrost.tundra.tn.profile; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.wm.app.b2b.server.ServiceException; import com.wm.app.tn.profile.Profile; import com.wm.app.tn.profile.ProfileStore; import com.wm.app.tn.profile.ProfileSummary; import com.wm.data.IData; import permafrost.tundra.data.CopyOnWriteIDataMap; import permafrost.tundra.data.IDataHelper; /** * A local in-memory cache of Trading Networks partner cache, to improve performance of Trading Networks * processes, and to avoid thread-synchronization bottlenecks in the Trading Networks partner profile * implementation. */ public class ProfileCache { /** * Initialization on demand holder idiom. */ private static class Holder { /** * The singleton instance of the class. */ private static final ProfileCache INSTANCE = new ProfileCache(); } /** * Disallow instantiation of this class; */ private ProfileCache() {} /** * Returns the singleton instance of this class. * * @return The singleton instance of this class. */ public static ProfileCache getInstance() { return Holder.INSTANCE; } /** * The local in-memory cache of Trading Networks partner profiles. */ protected ConcurrentMap<String, IData> cache = new ConcurrentHashMap<String, IData>(); /** * Refreshes all Trading Networks partner profiles stored in the cache from the Trading Networks database. * * @throws ServiceException If a database error occurs. */ public void refresh() throws ServiceException { for (String id : cache.keySet()) { get(id, true); } } /** * Removes all Trading Networks partner profiles from the cache. */ public void clear() { cache.clear(); } /** * Seeds the cache with all partner profiles from the Trading Networks database. * * @throws ServiceException If an error occurs. */ public void seed() throws ServiceException { seed(false); } /** * Seeds the cache with all partner profiles from the Trading Networks database. * * @param refresh If true, all profiles will be refreshed from the Trading Networks database, otherwise * profiles already cached will remain unrefreshed. * @throws ServiceException If an error occurs. */ public void seed(boolean refresh) throws ServiceException { List summaries = ProfileStore.getProfileSummaryList(false, false); if (summaries != null) { for (Object object : summaries) { if (object instanceof ProfileSummary) { ProfileSummary profile = (ProfileSummary)object; get(new ProfileID(profile.getProfileID()), refresh); } } } } /** * Returns a list of all the cached Trading Networks partner profiles. * * @return The list of all cached Trading Networks partner profiles. * @throws ServiceException If a database error occurs. */ public IData[] list() throws ServiceException { return list(false); } /** * Returns a list of all the cached Trading Networks partner profiles, optionally seeded from the Trading Networks * database. * * @param seed If true, the local cache will first be seeded with all Trading Networks partner profiles * from the Trading Networks database. * @return The list of all cached Trading Networks partner profiles. * @throws ServiceException If a database error occurs. */ public IData[] list(boolean seed) throws ServiceException { return list(seed, false); } /** * Returns a list of all the cached Trading Networks partner profiles, optionally seeded from the Trading Networks * database. * * @param seed If true, the local cache will first be seeded with all Trading Networks partner profiles * from the Trading Networks database. * @param refresh If true, all profiles will be refreshed from the Trading Networks database, otherwise * profiles already cached will remain unrefreshed. * @return The list of all cached Trading Networks partner profiles. * @throws ServiceException If a database error occurs. */ public IData[] list(boolean seed, boolean refresh) throws ServiceException { if (seed) seed(refresh); List<IData> output = new ArrayList<IData>(cache.size()); for (IData profile : cache.values()) { output.add(IDataHelper.duplicate(profile)); } return output.toArray(new IData[output.size()]); } /** * Returns the Trading Networks partner profile associated with the given internal ID from the cache if cached, or * from the Trading Networks database if not cached (at which time it will be lazily cached). * * @param id The internal ID associated with the partner profile to be returned. * @return The partner profile associated with the given internal ID. * @throws ServiceException If a database error occurs. */ public IData get(String id) throws ServiceException { return get(id, false); } /** * Returns the Trading Networks partner profile associated with the given internal ID from the cache if cached, or * from the Trading Networks database if not cached or if a refresh is requested (at which time it will be lazily * cached). * * @param id The internal ID associated with the partner profile to be returned. * @param refresh If true, the partner profile is first reloaded from the Trading Networks database before * being returned. * @return The partner profile associated with the given internal ID. * @throws ServiceException If a database error occurs. */ public IData get(String id, boolean refresh) throws ServiceException { if (id == null) return null; IData output = null; if (!refresh) output = cache.get(id); if (refresh || output == null) { Profile profile = ProfileHelper.get(id); if (profile != null) { // make the cached profile a read only IData document output = ProfileHelper.toIData(profile); // cache the profile against the internal ID cache.put(id, output); } } return CopyOnWriteIDataMap.of(output); } /** * Returns the Trading Networks partner profile associated with the given external ID from the cache if cached, or * from the Trading Networks database if not cached (at which time it will be lazily cached). * * @param id The external ID associated with the profile to be returned. * @param type The type of external ID specified. * @return The profile associated with the given external ID, or null if no profile exists with the * given external ID. * @throws ServiceException If a database error occurs. */ public IData get(String id, String type) throws ServiceException { return get(id, type, false); } /** * Returns the Trading Networks partner profile associated with the given external ID from the cache if cached, or * from the Trading Networks database if not cached or if a refresh is requested (at which time it will be lazily * cached). * * @param id The external ID associated with the profile to be returned. * @param type The type of external ID specified. * @param refresh If true, the partner profile is first reloaded from the Trading Networks database before * being returned. * @return The profile associated with the given external ID, or null if no profile exists with the * given external ID. * @throws ServiceException If a database error occurs. */ public IData get(String id, String type, boolean refresh) throws ServiceException { return get(new ProfileID(id, type), refresh); } /** * Returns the Trading Networks partner profile associated with the given ID from the cache if cached, or * from the Trading Networks database if not cached (at which time it will be lazily cached). * * @param id The ID associated with the profile to be returned. * @return The profile associated with the given ID, or null if no profile exists with the given ID. * @throws ServiceException If a database error occurs. */ public IData get(ProfileID id) throws ServiceException { return get(id, false); } /** * Returns the Trading Networks partner profile associated with the given ID from the cache if cached, or * from the Trading Networks database if not cached or if a refresh is requested (at which time it will be lazily * cached). * * @param id The ID associated with the profile to be returned. * @param refresh If true, the profile is first reloaded from the Trading Networks database before being * returned. * @return The profile associated with the given ID, or null if no profile exists with the given ID. * @throws ServiceException If a database error occurs. */ public IData get(ProfileID id, boolean refresh) throws ServiceException { if (id == null) return null; IData output = null; id = id.toInternalID(); if (id != null) { output = get(id.getValue(), refresh); } return output; } /** * Returns the Trading Networks My Enterprise profile from the cache if cached, or from the Trading Networks * database if not cached (at which time it will be lazily cached). * * @return The Trading Networks My Enterprise profile. * @throws ServiceException If a database error occurs. */ public IData self() throws ServiceException { return self(false); } /** * Returns the Trading Networks My Enterprise profile from the cache if cached, or from the Trading Networks * database if not cached or if a refresh is requested (at which time it will be lazily cached). * * @param refresh If true, the profile is first reloaded from the Trading Networks database before being * returned. * @return The Trading Networks My Enterprise profile. * @throws ServiceException If a database error occurs. */ public IData self(boolean refresh) throws ServiceException { IData output = null; String id = ProfileStore.getMyID(); if (id != null) { output = get(new ProfileID(id), refresh); } return output; } }
package romelo333.notenoughwands.Items; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumChatFormatting; import net.minecraft.world.World; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import net.minecraftforge.common.util.ForgeDirection; import romelo333.notenoughwands.Config; import romelo333.notenoughwands.varia.Tools; import java.util.HashMap; import java.util.List; import java.util.Map; public class MovingWand extends GenericWand { private float maxHardness = 50; private Map<String,Double> blacklisted = new HashMap<String, Double>(); public MovingWand() { setup("MovingWand", "movingWand").xpUsage(3).availability(AVAILABILITY_NORMAL).loot(5); } @Override public void initConfig(Configuration cfg) { super.initConfig(cfg); maxHardness = (float) cfg.get(Config.CATEGORY_WANDS, getUnlocalizedName() + "_maxHardness", maxHardness, "Max hardness this block can move.)").getDouble(); ConfigCategory category = cfg.getCategory(Config.CATEGORY_MOVINGBLACKLIST); if (category.isEmpty()) { // Initialize with defaults blacklist(cfg, "tile.shieldBlock"); blacklist(cfg, "tile.shieldBlock2"); blacklist(cfg, "tile.shieldBlock3"); blacklist(cfg, "tile.solidShieldBlock"); blacklist(cfg, "tile.invisibleShieldBlock"); setCost(cfg, "tile.mobSpawner", 5.0); setCost(cfg, "tile.blockAiry", 20.0); } else { for (Map.Entry<String, Property> entry : category.entrySet()) { blacklisted.put(entry.getKey(), entry.getValue().getDouble()); } } } private void blacklist(Configuration cfg, String name) { setCost(cfg, name, -1.0); } private void setCost(Configuration cfg, String name, double cost) { cfg.get(Config.CATEGORY_MOVINGBLACKLIST, name, cost); blacklisted.put(name, cost); } @Override public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean b) { super.addInformation(stack, player, list, b); NBTTagCompound compound = stack.getTagCompound(); if (!hasBlock(compound)) { list.add(EnumChatFormatting.RED + "Wand is empty."); } else { int id = compound.getInteger("block"); Block block = (Block) Block.blockRegistry.getObjectById(id); int meta = compound.getInteger("meta"); String name = Tools.getBlockName(block, meta); list.add(EnumChatFormatting.GREEN + "Block: " + name); } list.add("Right click to take a block."); list.add("Right click again on block to place it down."); } private boolean hasBlock(NBTTagCompound compound) { return compound != null && compound.hasKey("block"); } @Override public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float sx, float sy, float sz) { if (!world.isRemote) { NBTTagCompound compound = stack.getTagCompound(); if (hasBlock(compound)) { place(stack, player, world, x, y, z, side); } else { pickup(stack, player, world, x, y, z); } } return true; } private void place(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side) { int xx = x + ForgeDirection.getOrientation(side).offsetX; int yy = y + ForgeDirection.getOrientation(side).offsetY; int zz = z + ForgeDirection.getOrientation(side).offsetZ; NBTTagCompound tagCompound = stack.getTagCompound(); int id = tagCompound.getInteger("block"); Block block = (Block) Block.blockRegistry.getObjectById(id); int meta = tagCompound.getInteger("meta"); world.setBlock(xx, yy, zz, block, meta, 3); world.setBlockMetadataWithNotify(xx, yy, zz, meta, 3); if (tagCompound.hasKey("tedata")) { NBTTagCompound tc = (NBTTagCompound) tagCompound.getTag("tedata"); TileEntity tileEntity = world.getTileEntity(xx, yy, zz); if (tileEntity != null) { tc.setInteger("x", xx); tc.setInteger("y", yy); tc.setInteger("z", zz); tileEntity.readFromNBT(tc); tileEntity.markDirty(); world.markBlockForUpdate(xx, yy, zz); } } tagCompound.removeTag("block"); tagCompound.removeTag("tedata"); tagCompound.removeTag("meta"); stack.setTagCompound(tagCompound); } private void pickup(ItemStack stack, EntityPlayer player, World world, int x, int y, int z) { Block block = world.getBlock(x, y, z); int meta = world.getBlockMetadata(x, y, z); float hardness = block.getBlockHardness(world, x, y, z); if (hardness > maxHardness){ Tools.error(player, "This block is to hard to take."); return; } if (!block.canEntityDestroy(world, x, y, z, player)){ Tools.error(player, "You are not allowed to take this block"); return; } double cost = 1.0f; String unlocName = block.getUnlocalizedName(); if (blacklisted.containsKey(unlocName)) { cost = blacklisted.get(unlocName); } if (cost <= 0.001f) { Tools.error(player, "It is illegal to take this block"); return; } if (!checkUsage(stack, player, (float) cost)) { return; } NBTTagCompound tagCompound = Tools.getTagCompound(stack); String name = Tools.getBlockName(block, meta); if (name == null) { Tools.error(player, "You cannot select this block!"); } else { int id = Block.blockRegistry.getIDForObject(block); tagCompound.setInteger("block", id); tagCompound.setInteger("meta", meta); TileEntity tileEntity = world.getTileEntity(x, y, z); if (tileEntity != null) { NBTTagCompound tc = new NBTTagCompound(); tileEntity.writeToNBT(tc); world.removeTileEntity(x, y, z); tc.removeTag("x"); tc.removeTag("y"); tc.removeTag("z"); tagCompound.setTag("tedata", tc); } world.setBlockToAir(x, y, z); Tools.notify(player, "You took: " + name); registerUsage(stack, player, (float) cost); } } @Override protected void setupCraftingInt(Item wandcore) { GameRegistry.addRecipe(new ItemStack(this), "re ", "ew ", " w", 'r', Items.redstone, 'e', Items.ender_pearl, 'w', wandcore); } }
package ru.parallel.octotron.http.operations; import ru.parallel.octotron.core.attributes.SensorAttribute; import ru.parallel.octotron.core.attributes.Value; import ru.parallel.octotron.core.collections.ModelList; import ru.parallel.octotron.core.model.ModelEntity; import ru.parallel.octotron.core.primitive.exception.ExceptionModelFail; import ru.parallel.octotron.core.primitive.exception.ExceptionParseError; import ru.parallel.octotron.core.primitive.exception.ExceptionSystemError; import ru.parallel.octotron.exec.ExecutionController; import ru.parallel.octotron.http.operations.impl.ModelOperation; import ru.parallel.utils.format.ErrorString; import ru.parallel.utils.format.TextString; import ru.parallel.utils.format.TypedString; import java.util.Map; public class Modify { /** * adds a single import value to import queue<br> * */ public static class import_op extends ModelOperation { public import_op() {super("import", false);} @Override public TypedString Execute(ExecutionController controller, Map<String, String> params , boolean verbose, ModelList<? extends ModelEntity, ?> entities) throws ExceptionParseError { Utils.StrictParams(params, "name", "value"); String name = params.get("name"); String value_str = params.get("value"); Value value = Value.ValueFromStr(value_str); ModelEntity target = entities.Only(); if(target.GetSensor(name) == null) return new ErrorString("sensor does not exist: " + name); controller.Import(target, name, value); return new TextString("added to import queue"); } } /** * adds a single import value to unchecked import queue<br> * */ public static class unchecked_import extends ModelOperation { public unchecked_import() {super("unchecked_import", false);} @Override public TypedString Execute(ExecutionController controller, Map<String, String> params , boolean verbose, ModelList<? extends ModelEntity, ?> entities) throws ExceptionParseError { Utils.StrictParams(params, "name", "value"); String name = params.get("name"); String value_str = params.get("value"); Value value = Value.ValueFromStr(value_str); ModelEntity target = entities.Only(); if(target.GetSensor(name) == null) { try { controller.UnknownImport(target, name, value); } catch (ExceptionSystemError e) { throw new ExceptionModelFail(e); } return new TextString("attribute not found, but registered, import skipped"); } controller.Import(target, name, value); return new TextString("added to unchecked import queue"); } } /** * set invalid state to all given entities<br> * */ public static class set_valid extends ModelOperation { public set_valid() {super("set_valid", true);} @Override public TypedString Execute(ExecutionController controller, Map<String, String> params , boolean verbose, ModelList<? extends ModelEntity, ?> entities) throws ExceptionParseError { Utils.StrictParams(params, "name"); String name = params.get("name"); for(ModelEntity entity : entities) { SensorAttribute sensor = entity.GetSensor(name); sensor.SetValid(); controller.StateChange(sensor); } return new TextString("set the attribute to valid for " + entities.size() + " entities"); } } /** * set invalid state to all given entities<br> * */ public static class set_invalid extends ModelOperation { public set_invalid() {super("set_invalid", true);} @Override public TypedString Execute(ExecutionController controller, Map<String, String> params , boolean verbose, ModelList<? extends ModelEntity, ?> entities) throws ExceptionParseError { Utils.StrictParams(params, "name"); String name = params.get("name"); for(ModelEntity entity : entities) { SensorAttribute sensor = entity.GetSensor(name); sensor.SetInvalid(); controller.StateChange(sensor); } return new TextString("set the attribute to invalid for " + entities.size() + " entities"); } } /** * adds the marker to the all given entities<br> * */ public static class suppress extends ModelOperation { public suppress() {super("suppress", true);} @Override public TypedString Execute(ExecutionController controller, Map<String, String> params , boolean verbose, ModelList<? extends ModelEntity, ?> entities) throws ExceptionParseError { Utils.RequiredParams(params, "template_id"); Utils.AllParams(params, "template_id", "description"); String template_id_str = params.get("template_id"); long template_id = Value.ValueFromStr(template_id_str).GetLong(); String description = params.get("description"); if(description == null) description = ""; String res = ""; for(ModelEntity entity : entities) { long AID = controller.GetContext().model_service .SetSuppress(entity, template_id, true, description); if(AID != -1) { res += "suppressed reaction: " + AID + " with template: " + template_id + System.lineSeparator(); } else { res += "reaction with template: " + template_id + " not found on object: " + entity.GetID() + System.lineSeparator(); } } return new TextString(res); } } /** * adds the marker to the all given entities<br> * */ public static class unsuppress extends ModelOperation { public unsuppress() {super("unsuppress", true);} @Override public TypedString Execute(ExecutionController controller, Map<String, String> params , boolean verbose, ModelList<? extends ModelEntity, ?> entities) throws ExceptionParseError { Utils.RequiredParams(params, "template_id"); Utils.AllParams(params, "template_id"); String template_id_str = params.get("template_id"); long template_id = Value.ValueFromStr(template_id_str).GetLong(); String res = ""; for(ModelEntity entity : entities) { long AID = controller.GetContext().model_service .SetSuppress(entity, template_id, false, ""); if(AID != -1) { res += "unsuppressed reaction: " + AID + " with template: " + template_id + System.lineSeparator(); } else { res += "reaction with template: " + template_id + " not found on object: " + entity.GetID() + System.lineSeparator(); } } return new TextString(res); } } }
package ru.r2cloud.satellite.decoder; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.List; import java.util.zip.GZIPInputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.r2cloud.jradio.BeaconOutputStream; import ru.r2cloud.jradio.DopplerValueSource; import ru.r2cloud.jradio.aausat4.AAUSAT4; import ru.r2cloud.jradio.aausat4.AAUSAT4Beacon; import ru.r2cloud.jradio.blocks.ClockRecoveryMM; import ru.r2cloud.jradio.blocks.CorrelateAccessCodeTag; import ru.r2cloud.jradio.blocks.Firdes; import ru.r2cloud.jradio.blocks.FixedLengthTagger; import ru.r2cloud.jradio.blocks.FloatToChar; import ru.r2cloud.jradio.blocks.FrequencyXlatingFIRFilter; import ru.r2cloud.jradio.blocks.LowPassFilter; import ru.r2cloud.jradio.blocks.Multiply; import ru.r2cloud.jradio.blocks.MultiplyConst; import ru.r2cloud.jradio.blocks.QuadratureDemodulation; import ru.r2cloud.jradio.blocks.Rail; import ru.r2cloud.jradio.blocks.TaggedStreamToPdu; import ru.r2cloud.jradio.blocks.Window; import ru.r2cloud.jradio.detection.GmskFrequencyCorrection; import ru.r2cloud.jradio.detection.PeakDetection; import ru.r2cloud.jradio.detection.PeakInterval; import ru.r2cloud.jradio.detection.PeakValueSource; import ru.r2cloud.jradio.sink.WavFileSink; import ru.r2cloud.jradio.source.RtlSdr; import ru.r2cloud.jradio.source.SigSource; import ru.r2cloud.jradio.source.WavFileSource; import ru.r2cloud.jradio.source.Waveform; import ru.r2cloud.model.ObservationRequest; import ru.r2cloud.model.ObservationResult; import ru.r2cloud.satellite.Predict; import ru.r2cloud.util.Configuration; import ru.r2cloud.util.Util; public class Aausat4Decoder implements Decoder { private static final Logger LOG = LoggerFactory.getLogger(Aausat4Decoder.class); private final Configuration config; private final Predict predict; public Aausat4Decoder(Configuration config, Predict predict) { this.config = config; this.predict = predict; } @Override public ObservationResult decode(File rawIq, ObservationRequest req) { ObservationResult result = new ObservationResult(); result.setIqPath(rawIq); long numberOfDecodedPackets = 0; File binFile = new File(config.getTempDirectory(), "aausat4-" + req.getId() + ".bin"); File tempFile = new File(config.getTempDirectory(), "aausat4-" + req.getId() + ".temp"); WavFileSink tempWav = null; BufferedOutputStream fos = null; try { // 1 stage. correct doppler & remove DC offset Long totalSamples = Util.readTotalSamples(rawIq); if (totalSamples == null) { return result; } RtlSdr sdr = new RtlSdr(new GZIPInputStream(new FileInputStream(rawIq)), req.getInputSampleRate(), totalSamples); float[] taps = Firdes.lowPass(1.0, sdr.getContext().getSampleRate(), 6400, 1000, Window.WIN_HAMMING, 6.76); FrequencyXlatingFIRFilter xlating = new FrequencyXlatingFIRFilter(sdr, taps, req.getInputSampleRate() / req.getOutputSampleRate(), req.getSatelliteFrequency() - req.getActualFrequency()); SigSource source2 = new SigSource(Waveform.COMPLEX, (long) xlating.getContext().getSampleRate(), new DopplerValueSource(xlating.getContext().getSampleRate(), req.getSatelliteFrequency(), 1000L, req.getStartTimeMillis()) { @Override public long getDopplerFrequency(long satelliteFrequency, long currentTimeMillis) { return predict.getDownlinkFreq(satelliteFrequency, currentTimeMillis, req.getOrigin()); } }, 1.0); Multiply mul = new Multiply(xlating, source2); tempWav = new WavFileSink(mul, 16); fos = new BufferedOutputStream(new FileOutputStream(tempFile)); tempWav.process(fos); } catch (Exception e) { LOG.error("unable to correct doppler: " + rawIq.getAbsolutePath(), e); return result; } finally { Util.closeQuietly(tempWav); Util.closeQuietly(fos); } // 2 stage. detect peaks List<PeakInterval> peaks; WavFileSource source = null; try { source = new WavFileSource(new BufferedInputStream(new FileInputStream(tempFile))); PeakDetection detection = new PeakDetection(10, -80.0f, 3); peaks = detection.process(source); } catch (Exception e) { LOG.error("unable to detect peaks: " + tempFile.getAbsolutePath(), e); return result; } finally { Util.closeQuietly(source); } if (peaks.isEmpty()) { return result; } // 3 stage. correct peaks and decode AAUSAT4 input = null; BeaconOutputStream aos = null; try { source = new WavFileSource(new BufferedInputStream(new FileInputStream(tempFile))); SigSource source2 = new SigSource(Waveform.COMPLEX, (long) source.getContext().getSampleRate(), new PeakValueSource(peaks, new GmskFrequencyCorrection(2400, 10)), 1.0f); Multiply mul = new Multiply(source, source2); QuadratureDemodulation qd = new QuadratureDemodulation(mul, 0.4f); LowPassFilter lpf = new LowPassFilter(qd, 1.0, 1500.0f, 100, Window.WIN_HAMMING, 6.76); MultiplyConst mc = new MultiplyConst(lpf, 1.0f); ClockRecoveryMM clockRecovery = new ClockRecoveryMM(mc, mc.getContext().getSampleRate() / 2400, (float) (0.25 * 0.175 * 0.175), 0.005f, 0.175f, 0.005f); Rail rail = new Rail(clockRecovery, -1.0f, 1.0f); FloatToChar f2char = new FloatToChar(rail, 127.0f); CorrelateAccessCodeTag correlateTag = new CorrelateAccessCodeTag(f2char, 10, "010011110101101000110100010000110101010101000010", true); input = new AAUSAT4(new TaggedStreamToPdu(new FixedLengthTagger(correlateTag, AAUSAT4.VITERBI_TAIL_SIZE + 8))); // 8 for fsm aos = new BeaconOutputStream(new FileOutputStream(binFile)); while (input.hasNext()) { AAUSAT4Beacon next = input.next(); next.setBeginMillis(req.getStartTimeMillis() + (long) ((next.getBeginSample() * 1000) / source.getContext().getSampleRate())); aos.write(next); numberOfDecodedPackets++; } } catch (Exception e) { LOG.error("unable to process: " + rawIq.getAbsolutePath(), e); return result; } finally { Util.closeQuietly(input); Util.closeQuietly(aos); if (!tempFile.delete()) { LOG.error("unable to delete temp file: {}", tempFile.getAbsolutePath()); } } result.setNumberOfDecodedPackets(numberOfDecodedPackets); if (numberOfDecodedPackets <= 0) { if (binFile.exists() && !binFile.delete()) { LOG.error("unable to delete temp file: {}", binFile.getAbsolutePath()); } } else { result.setDataPath(binFile); } return result; } }
package ru.r2cloud.satellite; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonObject; import ru.r2cloud.FilenameComparator; import ru.r2cloud.model.ObservationFull; import ru.r2cloud.model.ObservationRequest; import ru.r2cloud.model.ObservationResult; import ru.r2cloud.util.Configuration; import ru.r2cloud.util.Util; public class ObservationResultDao { private static final Logger LOG = LoggerFactory.getLogger(ObservationResultDao.class); private final File basepath; private final Integer maxCount; public ObservationResultDao(Configuration config) { this.basepath = Util.initDirectory(config.getProperty("satellites.basepath.location")); this.maxCount = config.getInteger("scheduler.data.retention.count"); } public List<ObservationFull> findAllBySatelliteId(String satelliteId) { File dataRoot = new File(basepath, satelliteId + File.separator + "data"); if (!dataRoot.exists()) { return Collections.emptyList(); } File[] observations = dataRoot.listFiles(); Arrays.sort(observations, FilenameComparator.INSTANCE_DESC); List<ObservationFull> result = new ArrayList<ObservationFull>(observations.length); for (File curDirectory : observations) { ObservationFull cur = find(satelliteId, curDirectory); // some directories might be corrupted if (cur == null) { continue; } result.add(cur); } return result; } public ObservationFull find(String satelliteId, String observationId) { File baseDirectory = new File(basepath, satelliteId + File.separator + "data" + File.separator + observationId); if (!baseDirectory.exists()) { return null; } return find(satelliteId, baseDirectory); } private static ObservationFull find(String satelliteId, File curDirectory) { File dest = new File(curDirectory, "meta.json"); if (!dest.exists()) { return null; } ObservationFull full; try (BufferedReader r = new BufferedReader(new FileReader(dest))) { JsonObject meta = Json.parse(r).asObject(); full = ObservationFull.fromJson(meta); } catch (Exception e) { LOG.error("unable to load meta", e); return null; } ObservationResult result = full.getResult(); File a = new File(curDirectory, "a.jpg"); if (a.exists()) { result.setaPath(a); result.setaURL("/api/v1/admin/static/satellites/" + satelliteId + "/data/" + full.getReq().getId() + "/a.jpg"); } File data = new File(curDirectory, "data.bin"); if (data.exists()) { result.setDataPath(data); result.setDataURL("/api/v1/admin/static/satellites/" + satelliteId + "/data/" + full.getReq().getId() + "/data.bin"); } File wav = new File(curDirectory, "output.wav"); if (wav.exists()) { result.setWavPath(wav); } File spectogram = new File(curDirectory, "spectogram.png"); if (spectogram.exists()) { result.setSpectogramPath(spectogram); result.setSpectogramURL("/api/v1/admin/static/satellites/" + satelliteId + "/data/" + full.getReq().getId() + "/spectogram.png"); } return full; } public File saveImage(String satelliteId, String observationId, File a) { File dest = new File(getObservationBasepath(satelliteId, observationId), "a.jpg"); if (dest.exists()) { LOG.info("unable to save. dest already exist: {}", dest.getAbsolutePath()); return null; } if (!a.renameTo(dest)) { return null; } return dest; } public File saveData(String satelliteId, String observationId, File a) { File dest = new File(getObservationBasepath(satelliteId, observationId), "data.bin"); if (dest.exists()) { LOG.info("unable to save. dest already exist: {}", dest.getAbsolutePath()); return null; } if (!a.renameTo(dest)) { return null; } return dest; } public boolean saveSpectogram(String satelliteId, String observationId, File a) { File dest = new File(getObservationBasepath(satelliteId, observationId), "spectogram.png"); if (dest.exists()) { LOG.info("unable to save. dest already exist: {}", dest.getAbsolutePath()); return false; } return a.renameTo(dest); } public File insert(ObservationRequest observation, File wavPath) { File[] dataDirs = new File(basepath, observation.getSatelliteId() + File.separator + "data").listFiles(); if (dataDirs != null && dataDirs.length > maxCount) { Arrays.sort(dataDirs, FilenameComparator.INSTANCE_ASC); for (int i = 0; i < (dataDirs.length - maxCount); i++) { Util.deleteDirectory(dataDirs[i]); } } File observationBasePath = getObservationBasepath(observation); if (!observationBasePath.exists() && !observationBasePath.mkdirs()) { LOG.info("unable to create parent dir: {}", observationBasePath.getAbsolutePath()); return null; } ObservationFull full = new ObservationFull(observation); if (!update(full)) { return null; } return insertIQData(observation, wavPath); } private File insertIQData(ObservationRequest observation, File wavPath) { File dest = new File(getObservationBasepath(observation), "output.wav"); if (!dest.getParentFile().exists() && !dest.getParentFile().mkdirs()) { LOG.info("unable to create parent dir: {}", dest.getParentFile().getAbsolutePath()); return null; } if (dest.exists()) { LOG.info("unable to save. dest already exist: {}", dest.getAbsolutePath()); return null; } if (!wavPath.renameTo(dest)) { return null; } return dest; } public boolean update(ObservationFull cur) { JsonObject meta = cur.toJson(); File dest = new File(getObservationBasepath(cur.getReq()), "meta.json"); try (BufferedWriter w = new BufferedWriter(new FileWriter(dest))) { w.append(meta.toString()); return true; } catch (IOException e) { LOG.error("unable to write meta", e); return false; } } private File getObservationBasepath(ObservationRequest observation) { return getObservationBasepath(observation.getSatelliteId(), observation.getId()); } private File getObservationBasepath(String satelliteId, String observationId) { return new File(basepath, satelliteId + File.separator + "data" + File.separator + observationId); } }
package seedu.taskmanager.model.task; import static seedu.taskmanager.logic.commands.SortCommand.SORT_KEYWORD_ENDDATE; import static seedu.taskmanager.logic.commands.SortCommand.SORT_KEYWORD_STARTDATE; import java.util.Comparator; import java.util.Iterator; import java.util.List; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import seedu.taskmanager.commons.core.UnmodifiableObservableList; import seedu.taskmanager.commons.exceptions.DuplicateDataException; import seedu.taskmanager.commons.util.CollectionUtil; /** * A list of tasks that enforces uniqueness between its elements and does not * allow nulls. * * Supports a minimal set of list operations. * * @see Task#equals(Object) * @see CollectionUtil#elementsAreUnique(Collection) */ public class UniqueTaskList implements Iterable<Task> { private final ObservableList<Task> internalList = FXCollections.observableArrayList(); // @@author A0131278H /** * Returns the internalList of tasks */ public ObservableList<Task> getInternalList() { return internalList; } // @@author /** * Returns true if the list contains an equivalent task as the given * argument. */ public boolean contains(ReadOnlyTask toCheck) { assert toCheck != null; return internalList.contains(toCheck); } /** * Adds a task to the list. * * @throws DuplicateTaskException * if the task to add is a duplicate of an existing task in the * list. */ public void add(Task toAdd) throws DuplicateTaskException { assert toAdd != null; if (contains(toAdd)) { throw new DuplicateTaskException(); } internalList.add(toAdd); } /** * Updates the task in the list at position {@code index} with * {@code editedTask}. * * @throws DuplicateTaskException * if updating the task's details causes the task to be * equivalent to another existing task in the list. * @throws IndexOutOfBoundsException * if {@code index} < 0 or >= the size of the list. */ public void updateTask(int index, ReadOnlyTask editedTask) throws DuplicateTaskException { assert editedTask != null; Task taskToUpdate = internalList.get(index); if (!taskToUpdate.equals(editedTask) && internalList.contains(editedTask)) { throw new DuplicateTaskException(); } taskToUpdate.resetData(editedTask); // TODO: The code below is just a workaround to notify observers of the // updated task. // The right way is to implement observable properties in the Task // class. // Then, TaskCard should then bind its text labels to those observable // properties. internalList.set(index, taskToUpdate); } /** * Removes the equivalent task from the list. * * @throws TaskNotFoundException * if no such task could be found in the list. */ public boolean remove(ReadOnlyTask toRemove) throws TaskNotFoundException { assert toRemove != null; final boolean taskFoundAndDeleted = internalList.remove(toRemove); if (!taskFoundAndDeleted) { throw new TaskNotFoundException(); } return taskFoundAndDeleted; } public void setTasks(UniqueTaskList replacement) { this.internalList.setAll(replacement.internalList); } public void setTasks(List<? extends ReadOnlyTask> tasks) throws DuplicateTaskException { final UniqueTaskList replacement = new UniqueTaskList(); for (final ReadOnlyTask task : tasks) { replacement.add(new Task(task)); } setTasks(replacement); } public UnmodifiableObservableList<Task> asObservableList() { return new UnmodifiableObservableList<>(internalList); } @Override public Iterator<Task> iterator() { return internalList.iterator(); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof UniqueTaskList // instanceof handles nulls && this.internalList.equals(((UniqueTaskList) other).internalList)); } @Override public int hashCode() { return internalList.hashCode(); } /** * Signals that an operation would have violated the 'no duplicates' * property of the list. */ public static class DuplicateTaskException extends DuplicateDataException { protected DuplicateTaskException() { super("Operation would result in duplicate tasks"); } } /** * Signals that an operation targeting a specified task in the list would * fail because there is no such matching task in the list. */ public static class TaskNotFoundException extends Exception { } // @@author A0131278H /** * Sorts task list based on keywords (StartDate or EndDate). Tasks without start StartDate or * EndDate are ranked higher. */ public void sortByDate(String keyword) { if (keyword.equals(SORT_KEYWORD_STARTDATE)) { internalList.sort(new Comparator<Task>() { @Override public int compare(Task t1, Task t2) { if (t1.getStartDate().isPresent() && t2.getStartDate().isPresent()) { return t1.getStartDate().get().compareTo(t2.getStartDate().get()); } // @@author A0140032E if (t2.getStartDate().isPresent()) { return -1; } else { return 1; } // @@author A0131278H } }); } else if (keyword.equals(SORT_KEYWORD_ENDDATE)) { internalList.sort(new Comparator<Task>() { @Override public int compare(Task t1, Task t2) { if (t1.getEndDate().isPresent() && t2.getEndDate().isPresent()) { return t1.getEndDate().get().compareTo(t2.getEndDate().get()); } // @@author A0140032E if (t2.getEndDate().isPresent()) { return -1; } else { return 1; } // @@author A0131278H } }); } else { return; // Error message will be thrown by SortCommand } } }
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.logic.commands.AddEventCommand; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.IncorrectCommand; public class AddEventParser { private static final Pattern ARG_PATTERN = Pattern.compile("\\s*\"(?<quotedArg>[^\"]+)\"\\s*|\\s*(?<unquotedArg>[^\\s]+)\\s*"); private final Command incorrectCommand = new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddEventCommand.MESSAGE_USAGE)); private final LocalDateTime referenceDateTime; public AddEventParser() { this(null); } public AddEventParser(LocalDateTime referenceDateTime) { this.referenceDateTime = referenceDateTime; } public Command parse(String str) { final ParseResult args; try { args = parseArguments(str); } catch (IllegalValueException e) { return incorrectCommand; } // There must be at least one of { startDate, startTime }, and at least one of { endDate, endTime }. if ((args.startDate == null && args.startTime == null) || (args.endDate == null && args.endTime == null)) { return incorrectCommand; } final DateTimeParser parser = referenceDateTime != null ? new DateTimeParser(referenceDateTime) : new DateTimeParser(); try { final LocalDate startDate = args.startDate != null ? parser.parseDate(args.startDate) : parser.getReferenceDateTime().toLocalDate(); final LocalTime startTime = args.startTime != null ? parser.parseTime(args.startTime) : LocalTime.of(0, 0); final LocalDate endDate = args.endDate != null ? parser.parseDate(args.endDate) : startDate; final LocalTime endTime = args.endTime != null ? parser.parseTime(args.endTime) : LocalTime.of(23, 59); return new AddEventCommand(args.name, LocalDateTime.of(startDate, startTime), LocalDateTime.of(endDate, endTime)); } catch (IllegalValueException e) { return new IncorrectCommand(e.getMessage()); } } private static class ParseResult { String name; String startDate; String startTime; String endDate; String endTime; } private static ParseResult parseArguments(String str) throws IllegalValueException { final ParseResult result = new ParseResult(); final ArrayList<String> args = splitArgs(str); // name if (args.isEmpty()) { throw new IllegalValueException("expected name"); } result.name = args.remove(0); // startDate (optional) if (args.isEmpty()) { return result; } if (isDate(args.get(0))) { result.startDate = args.remove(0); } // startTime (optional) if (args.isEmpty()) { return result; } if (isTime(args.get(0))) { result.startTime = args.remove(0); } // Check Keyword "to" if (args.isEmpty()) { throw new IllegalValueException("expected ending time or ending date"); } if (isKeywordTo(args.get(0))) { args.remove(0); } else { throw new IllegalValueException("expected keyword \"to\""); } // endDate (optional) if (args.isEmpty()) { return result; } if (isDate(args.get(0))) { result.endDate = args.remove(0); } // endTime (optional) if (args.isEmpty()) { return result; } if (isTime(args.get(0))) { result.endTime = args.remove(0); } if (!args.isEmpty()) { throw new IllegalValueException("too many arguments"); } return result; } private static ArrayList<String> splitArgs(String str) { final Matcher matcher = ARG_PATTERN.matcher(str); final ArrayList<String> args = new ArrayList<>(); int start = 0; while (matcher.find(start)) { args.add(matcher.group("quotedArg") != null ? matcher.group("quotedArg") : matcher.group("unquotedArg")); start = matcher.end(); } return args; } private static boolean isDate(String str) { final DateTimeParser parser = new DateTimeParser(); try { parser.parseDate(str); return true; } catch (IllegalValueException e) { return false; } } private static boolean isTime(String str) { final DateTimeParser parser = new DateTimeParser(); try { parser.parseTime(str); return true; } catch (IllegalValueException e) { return false; } } private static boolean isKeywordTo(String str) { return str.equals("to"); } }
package team.unstudio.udpl.bungeecord; import com.google.common.collect.Iterables; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.messaging.Messenger; import org.bukkit.plugin.messaging.PluginMessageListener; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.BiFunction; import java.util.function.Consumer; public class BungeeChannel { /** * the registered bungee channels */ private static WeakHashMap<Plugin, BungeeChannel> registeredInstances = new WeakHashMap<>(); /** * the plugin message listener */ private final PluginMessageListener messageListener; /** * the user of this bungee channel */ private final Plugin plugin; private final Map<String, Queue<CompletableFuture<?>>> callbackMap = new HashMap<>(); private Map<String, ForwardConsumer> forwardListeners; private ForwardConsumer globalForwardListener; /** * Get or create new BungeeChannelApi instance */ public synchronized static BungeeChannel of(Plugin plugin) { return registeredInstances.compute(plugin, (k, v) -> { if (v == null) v = new BungeeChannel(plugin); return v; }); } private BungeeChannel(Plugin plugin) { this.plugin = plugin; // Prevent dev's from registering multiple channel listeners synchronized (registeredInstances) { registeredInstances.compute(plugin, (k, oldInstance) -> { if (oldInstance != null) oldInstance.unregister(); return this; }); } this.messageListener = this::onPluginMessageReceived; Messenger messenger = Bukkit.getServer().getMessenger(); messenger.registerOutgoingPluginChannel(plugin, "BungeeCord"); messenger.registerIncomingPluginChannel(plugin, "BungeeCord", messageListener); registerForwardListener("Teleport", this::teleportReceived); } /** * Unregister message channels. */ public void unregister() { Messenger messenger = Bukkit.getServer().getMessenger(); messenger.unregisterIncomingPluginChannel(plugin, "BungeeCord", messageListener); messenger.unregisterOutgoingPluginChannel(plugin); callbackMap.clear(); } private BiFunction<String, Queue<CompletableFuture<?>>, Queue<CompletableFuture<?>>> computeQueueValue(CompletableFuture<?> queueValue) { return (key, value) -> { if (value == null) value = new ArrayDeque<>(); value.add(queueValue); return value; }; } private String cachedServer; public String getCachedServer() { if (cachedServer == null) { cachedServer = getServer().join(); } return cachedServer; } /** * get the first player of now server */ public static Player getFirstPlayer() { // If you are running old bukkit versions, you need to change this to // Player ret = Bukkit.getOnlinePlayers()[0]; Player ret = Iterables.getFirst(Bukkit.getOnlinePlayers(), null); if (ret == null) { throw new IllegalArgumentException("Bungee Messaging Api requires at least one player online."); } return ret; } public void forwardToPlayer(String playerName, String channelName, Consumer<ByteArrayDataOutput> dataWriter) { Player player = getFirstPlayer(); ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("ForwardToPlayer"); output.writeUTF(playerName); output.writeUTF(channelName); ByteArrayDataOutput data = ByteStreams.newDataOutput(); dataWriter.accept(data); byte[] dataArray = data.toByteArray(); output.writeShort(dataArray.length); output.write(dataArray); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); } public void forward(String server, String channelName, Consumer<ByteArrayDataOutput> dataWriter) { Player player = getFirstPlayer(); ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("Forward"); output.writeUTF(server); output.writeUTF(channelName); ByteArrayDataOutput data = ByteStreams.newDataOutput(); dataWriter.accept(data); byte[] dataArray = data.toByteArray(); output.writeShort(dataArray.length); output.write(dataArray); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); } /** * set global forward listener. if has old one, it will be replaced * * @param globalListener new listener */ public void registerForwardListener(ForwardConsumer globalListener) { this.globalForwardListener = globalListener; } /** * add new listener listening targetChannel * * @param targetChannel your sub channel */ public void registerForwardListener(String targetChannel, ForwardConsumer listener) { if (forwardListeners == null) { forwardListeners = new HashMap<>(); } synchronized (forwardListeners) { forwardListeners.put(targetChannel, listener); } } /** * on receiving */ private void onPluginMessageReceived(String channel, Player player, byte[] message) { if (!channel.equalsIgnoreCase("BungeeCord")) return; ByteArrayDataInput input = ByteStreams.newDataInput(message); String subchannel = input.readUTF(); synchronized (callbackMap) { // check if arg-required message if (subchannel.equals("PlayerCount") || subchannel.equals("PlayerList") || subchannel.equals("UUIDOther") || subchannel.equals("ServerIP")) { // read the server/player name String identifier = input.readUTF(); // get the callback and poll the future CompletableFuture<?> callback = callbackMap.get(subchannel + "-" + identifier).poll(); if (callback == null) return; try { if (subchannel.equals("PlayerCount")) ((CompletableFuture<Integer>) callback).complete(Integer.valueOf(input.readInt())); else if (subchannel.equals("PlayerList")) ((CompletableFuture<List<String>>) callback).complete(Arrays.asList(input.readUTF().split(", "))); else if (subchannel.equals("UUIDOther")) ((CompletableFuture<String>) callback).complete(input.readUTF()); else if (subchannel.equals("ServerIP")) { String ip = input.readUTF(); int port = input.readUnsignedShort(); ((CompletableFuture<InetSocketAddress>) callback).complete(new InetSocketAddress(ip, port)); } } catch (Exception ex) { callback.completeExceptionally(ex); } // break next return; } // check forward message Queue<CompletableFuture<?>> callbacks = callbackMap.get(subchannel); if (callbacks == null) { String forwardSubchannel = input.readUTF(); short dataLength = input.readShort(); byte[] data = new byte[dataLength]; input.readFully(data); // accepting global forward listener if (globalForwardListener != null) globalForwardListener.accept(subchannel, player, data); if (forwardListeners == null) return; synchronized (forwardListeners) { ForwardConsumer listener = forwardListeners.get(forwardSubchannel); if (listener != null) { listener.accept(forwardSubchannel, player, data); } } return; } CompletableFuture<?> callback = callbacks.poll(); if (callback == null) return; try { switch (subchannel) { case "GetServers": ((CompletableFuture<List<String>>) callback).complete(Arrays.asList(input.readUTF().split(", "))); break; case "GetServer": ((CompletableFuture<String>) callback).complete(input.readUTF()); case "UUID": ((CompletableFuture<String>) callback).complete(input.readUTF()); break; case "IP": { String ip = input.readUTF(); int port = input.readInt(); ((CompletableFuture<InetSocketAddress>) callback).complete(new InetSocketAddress(ip, port)); break; } } } catch (Exception ex) { callback.completeExceptionally(ex); } } } public CompletableFuture<Integer> getPlayerCount(String serverName) { Player player = getFirstPlayer(); CompletableFuture<Integer> future = new CompletableFuture<>(); synchronized (callbackMap) { callbackMap.compute("PlayerCount-" + serverName, this.computeQueueValue(future)); } ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("PlayerCount"); output.writeUTF(serverName); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); return future; } public CompletableFuture<List<String>> getPlayerList(String serverName) { Player player = getFirstPlayer(); CompletableFuture<List<String>> future = new CompletableFuture<>(); synchronized (callbackMap) { callbackMap.compute("PlayerList-" + serverName, this.computeQueueValue(future)); } ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("PlayerList"); output.writeUTF(serverName); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); return future; } public CompletableFuture<List<String>> getServers() { Player player = getFirstPlayer(); CompletableFuture<List<String>> future = new CompletableFuture<>(); synchronized (callbackMap) { callbackMap.compute("GetServers", this.computeQueueValue(future)); } ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("GetServers"); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); return future; } /** * Connects a player to said subserver. * * @param player the player you want to teleport. * @param serverName the name of server to connect to, as defined in BungeeCord config.yml. */ public void connect(Player player, String serverName) { ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("Connect"); output.writeUTF(serverName); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); } public void connectOther(String playerName, String server) { Player player = getFirstPlayer(); ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("ConnectOther"); output.writeUTF(playerName); output.writeUTF(server); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); } /** * Get the (real) IP of a player. * * @param player The player you wish to get the IP of. * @return A {@link CompletableFuture} that, when completed, will return the (real) IP of {@code player}. */ public CompletableFuture<InetSocketAddress> getIp(Player player) { CompletableFuture<InetSocketAddress> future = new CompletableFuture<>(); synchronized (callbackMap) { callbackMap.compute("IP", this.computeQueueValue(future)); } ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("IP"); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); return future; } public void sendMessage(String playerName, String message) { Player player = getFirstPlayer(); ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("Message"); output.writeUTF(playerName); output.writeUTF(message); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); } public CompletableFuture<String> getServer() { Player player = getFirstPlayer(); CompletableFuture<String> future = new CompletableFuture<>(); synchronized (callbackMap) { callbackMap.compute("GetServer", this.computeQueueValue(future)); } ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("GetServer"); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); return future; } /** * Request the UUID of this player. * * @param player The player whose UUID you requested. * @return A {@link CompletableFuture} that, when completed, will return the UUID of {@code player}. */ public CompletableFuture<String> getUUID(Player player) { CompletableFuture<String> future = new CompletableFuture<>(); synchronized (callbackMap) { callbackMap.compute("UUID", this.computeQueueValue(future)); } ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("UUID"); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); return future; } public CompletableFuture<String> getUUID(String playerName) { Player player = getFirstPlayer(); CompletableFuture<String> future = new CompletableFuture<>(); synchronized (callbackMap) { callbackMap.compute("UUIDOther-" + playerName, this.computeQueueValue(future)); } ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("UUIDOther"); output.writeUTF(playerName); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); return future; } public CompletableFuture<InetSocketAddress> getServerIp(String serverName) { Player player = getFirstPlayer(); CompletableFuture<InetSocketAddress> future = new CompletableFuture<>(); synchronized (callbackMap) { callbackMap.compute("ServerIP-" + serverName, this.computeQueueValue(future)); } ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("ServerIP"); output.writeUTF(serverName); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); return future; } public void kickPlayer(String playerName, String kickMessage) { Player player = getFirstPlayer(); CompletableFuture<InetSocketAddress> future = new CompletableFuture<>(); synchronized (callbackMap) { callbackMap.compute("KickPlayer", this.computeQueueValue(future)); } ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeUTF("KickPlayer"); output.writeUTF(playerName); output.writeUTF(kickMessage); player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray()); } public void teleport(Player player, ServerLocation serverLocation) { // teleport to this server //TODO: Unsupport this. throw new UnsupportedOperationException(); // if (serverLocation.getServer().equals(getCachedServer())) { // player.teleport(serverLocation.toLocation()); // return; // connect(player, serverLocation.getServer()); // forward(serverLocation.getServer(), "Teleport", data -> { // data.writeUTF(player.getName()); // data.writeUTF(serverLocation.toString()); } /** * while teleport forward received */ private void teleportReceived(String channel, Player player, byte[] data){ ByteArrayDataInput dataInput = ByteStreams.newDataInput(data); String playerName = dataInput.readUTF(); ServerLocation serverLocation = ServerLocation.deserialize(dataInput.readUTF()); Player targetPlayer = Bukkit.getPlayer(playerName); if(targetPlayer==null||!targetPlayer.isOnline()) return; targetPlayer.teleport(serverLocation.toLocation()); } }
package seedu.taskboss.logic.commands; import seedu.taskboss.commons.core.EventsCenter; import seedu.taskboss.commons.core.Messages; import seedu.taskboss.commons.core.UnmodifiableObservableList; import seedu.taskboss.commons.events.ui.JumpToListRequestEvent; import seedu.taskboss.logic.commands.exceptions.CommandException; import seedu.taskboss.model.task.ReadOnlyTask; /** * Selects a task identified using it's last displayed index from TaskBoss. */ public class ViewCommand extends Command { public final int targetIndex; public static final String COMMAND_WORD = "view"; public static final String COMMAND_WORD_SHORT = "v"; public static final String MESSAGE_USAGE = COMMAND_WORD + "/" + COMMAND_WORD_SHORT + ": Selects the task identified by the index number used in the last task listing.\n" + "Parameters: INDEX (must be a positive integer)\n" + "Example: " + COMMAND_WORD + " 1" + " || " + COMMAND_WORD_SHORT + " 1"; public static final String MESSAGE_SELECT_TASK_SUCCESS = "Selected Task: %1$s"; public ViewCommand(int targetIndex) { this.targetIndex = targetIndex; } @Override public CommandResult execute() throws CommandException { UnmodifiableObservableList<ReadOnlyTask> lastShownList = model.getFilteredTaskList(); if (lastShownList.size() < targetIndex) { throw new CommandException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } EventsCenter.getInstance().post(new JumpToListRequestEvent(targetIndex - 1)); return new CommandResult(String.format(MESSAGE_SELECT_TASK_SUCCESS, targetIndex)); } }
package seedu.unburden.logic.commands; import java.util.List; import java.util.NoSuchElementException; import seedu.unburden.commons.exceptions.IllegalValueException; import seedu.unburden.model.tag.UniqueTagList.DuplicateTagException; import seedu.unburden.model.task.ReadOnlyTask; import seedu.unburden.model.task.Task; /** * Redo an undo action. * @@author A0139714B */ public class RedoCommand extends Command { public static final String COMMAND_WORD = "redo"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": redo the most recent undo command. \n " + "Example: " + COMMAND_WORD; public static final String MESSAGE_SUCCESS = "Redo success!"; public static final String MESSAGE_EMPTY_STACK = "No recent undo commands can be found."; public CommandResult execute() throws DuplicateTagException, IllegalValueException { try { assert model != null; model.loadFromUndoHistory(); overdueOrNot(); return new CommandResult(MESSAGE_SUCCESS); } catch (NoSuchElementException ee) { return new CommandResult(MESSAGE_EMPTY_STACK); } } //This method checks the entire list to check for overdue tasks private void overdueOrNot() throws IllegalValueException, DuplicateTagException { List<ReadOnlyTask> currentTaskList= model.getListOfTask().getTaskList(); for(ReadOnlyTask task : currentTaskList){ if(((Task) task).checkOverDue()){ ((Task) task).setOverdue(); } else{ ((Task) task).setNotOverdue(); } } } }
package control.forms.tabs; import java.awt.Rectangle; import java.awt.image.BufferedImage; import view.forms.Page; import model.settings.Status; import model.settings.ViewSettings; import control.ControlPaint; import control.interfaces.MoveEvent; import control.interfaces.TabbedListener; /** * Controller class for Tabs. Deals with the opening and the closing * of the entire tab pane (not opening another tab). * * * @author Julius Huelsmann * @version %I%, %U% * */ public class CTabs implements TabbedListener { /** * Instance of the main controller. */ private ControlPaint cp; /** * Constructor: saves the instance of the main controller * class which offers accessibility to other * controller, model and view classes. * * @param _cp instance of the main controller class which * is saved */ public CTabs(final ControlPaint _cp) { this.cp = _cp; } public final void closeListener() { double timetoclose0 = System.currentTimeMillis(); Page page = cp.getView().getPage(); //set new bounds in settings ViewSettings.setView_bounds_page( new Rectangle(ViewSettings.getView_bounds_page())); //re-initialize the image with the correct size cp.getControlPic().setBi_background(new BufferedImage( ViewSettings.getView_bounds_page().getSize().width, ViewSettings.getView_bounds_page().getSize().height, BufferedImage.TYPE_INT_ARGB)); cp.getControlPic().setBi(new BufferedImage( ViewSettings.getView_bounds_page().getSize().width, ViewSettings.getView_bounds_page().getSize().height, BufferedImage.TYPE_INT_ARGB)); cp.setBi_preprint(new BufferedImage( ViewSettings.getView_bounds_page().getSize().width, ViewSettings.getView_bounds_page().getSize().height, BufferedImage.TYPE_INT_ARGB)); //apply new size in view //takes some time and repaints the image. //TODO: better algorithm for opening. //save the previously displayed image (out of BufferedImage) //and write it into the new (greater one). Afterwards (re)paint //the sub image that is new. page.setSize( (int) ViewSettings.getView_bounds_page().getWidth(), (int) ViewSettings.getView_bounds_page().getHeight()); //time used ca. 0.8 sec // output double timetoclose1 = System.currentTimeMillis(); final int divisorToSeconds = 100; System.out.println(getClass() + "time passed" + (timetoclose1 - timetoclose0) / divisorToSeconds); //check whether location is okay. final int d = (int) (ViewSettings.getView_bounds_page().getHeight() / Status.getImageShowSize().height * Status.getImageSize().height - page.getJlbl_painting().getLocation().getY() - Status.getImageSize().height); if (d > 0) { page.getJlbl_painting().setLocation( (int) page.getJlbl_painting().getLocation().getX(), (int) page.getJlbl_painting().getLocation().getY() + d); } } /** * {@inheritDoc} */ public final void moveListener(final MoveEvent _event) { Page page = cp.getView().getPage(); page.setLocation( _event.getPnt_bottomLocation()); } /** * {@inheritDoc} */ public final void openListener() { Page page = cp.getView().getPage(); //set new bounds in settings ViewSettings.setView_bounds_page( new Rectangle(ViewSettings.getView_bounds_page_open())); //re-initialize the image with the correct size cp.getControlPic().setBi_background(new BufferedImage( ViewSettings.getView_bounds_page().getSize().width, ViewSettings.getView_bounds_page().getSize().height, BufferedImage.TYPE_INT_ARGB)); cp.getControlPic().setBi(new BufferedImage( ViewSettings.getView_bounds_page().getSize().width, ViewSettings.getView_bounds_page().getSize().height, BufferedImage.TYPE_INT_ARGB)); cp.setBi_preprint(new BufferedImage( ViewSettings.getView_bounds_page().getSize().width, ViewSettings.getView_bounds_page().getSize().height, BufferedImage.TYPE_INT_ARGB)); //apply new size in view //takes some time and repaints the image. //TODO: better algorithm for opening. //save the previously displayed image (out of BufferedImage) //and write the necessary stuff it into the new (smaller one) page.setSize( (int) ViewSettings.getView_bounds_page().getWidth(), (int) ViewSettings.getView_bounds_page().getHeight()); } }
package main; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import data.Rating; import database.RatingDB; public class Processor { private RatingDB db; public Processor() { db = new RatingDB("jdbc:mysql://ratewhatever.cloudapp.net/ratewhatever", "user", "1whatever"); } public void process(ClientSocket client, String str) throws IOException { String[] pairs = str.split("&"); Map<String, String> map = new HashMap<>(); for (int i = 0; i < pairs.length; i++) { String pair = pairs[i]; String[] tmp = pair.split("="); String key = decode(tmp[0]); String value = decode(tmp[1]); map.put(key, value); System.out.println("**" + key + " : " + value + "**"); } switching(client, map); } private void switching(ClientSocket client, Map<String, String> map) throws IOException { String action = map.get("action"); if (action == null) { // Something bad happened! return; } if (action.equals("new")) { addNewRating(client, map); } else if (action.equals("search")) { searchLocation(client, map); } else if (action.equals("reply")) { addReply(client, map); } } private void addReply(ClientSocket client, Map<String, String> map) { int ratingID = Integer.parseInt(map.get("ratingID")); String reply = map.get("reply"); // respond to client JSONBuilder jb = new JSONBuilder(); jb.addValue("action", "reply"); if (db.addNewReply(ratingID, reply)) { jb.addValue("status", "success"); } else { jb.addValue("status", "failed"); } client.sendToClient(jb.toString()); client.stopClient(); } private void searchLocation(ClientSocket client, Map<String, String> map) { String location = map.get("location"); List<Rating> ratingsList = db.getRatings(location); // respond to client JSONBuilder jb = new JSONBuilder(); jb.addValue("action", "search"); String[] ratings = new String[ratingsList.size()]; for (int i = 0; i < ratings.length; i++) { ratings[i] = ratingsList.get(i).toString(); } jb.addArray("list", ratings); client.sendToClient(jb.toString()); client.stopClient(); } private void addNewRating(ClientSocket client, Map<String, String> map) { String username = map.get("username"); String location = map.get("location"); int numStars = Integer.parseInt(map.get("numStars")); String description = map.get("description"); // respond to client JSONBuilder jb = new JSONBuilder(); jb.addValue("action", "new"); if (db.addNewRating(username, location, numStars, description)) { jb.addValue("status", "success"); client.sendToClient(jb.toString()); } else { // Database error! jb.addValue("status", "failed"); client.sendToClient(jb.toString()); } // Close connection client.stopClient(); } private String decode(String str) { char[] chars = str.toCharArray(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < chars.length; i++) { if (chars[i] == '+') { sb.append(' '); } else if (chars[i] == '%') { if (i + 2 >= chars.length) { // Something bad happened! return ""; } char ch = (char)Integer.parseInt(new String(chars, i + 1, 2), 16); sb.append(ch); i += 2; } else { sb.append(chars[i]); } } return sb.toString(); } }
package org.cornutum.tcases; import org.cornutum.tcases.generator.*; import org.cornutum.tcases.generator.io.*; import org.cornutum.tcases.io.*; import org.apache.commons.collections4.IteratorUtils; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Iterator; import java.util.Random; public class Reducer { public static class Options { /** * Creates a new Options object. */ public Options() { setSamples( 10); setResampleFactor( 0.0); } /** * Creates a new Options object. */ public Options( String[] args) { this(); int i; // Handle options for( i = 0; i < args.length && args[i].charAt(0) == '-'; i = handleOption( args, i)); // Handle additional arguments. handleArgs( args, i); } /** * Handles the i'th option and return the index of the next argument. */ protected int handleOption( String[] args, int i) { String arg = args[i]; if( arg.equals( "-f")) { i++; if( i >= args.length) { throwUsageException(); } setFunction( args[i]); } else if( arg.equals( "-g")) { i++; if( i >= args.length) { throwUsageException(); } setGenDef( new File( args[i])); } else if( arg.equals( "-r")) { i++; if( i >= args.length) { throwUsageException(); } try { setResampleFactor( Double.parseDouble( args[i])); } catch( Exception e) { throwUsageException( "Invalid resample factor", e); } } else if( arg.equals( "-s")) { i++; if( i >= args.length) { throwUsageException(); } try { int samples = Integer.parseInt( args[i]); if( samples <= 0) { throw new IllegalArgumentException( "Sample count must be greater than 0"); } setSamples( samples); } catch( Exception e) { throwUsageException( "Invalid sample count", e); } } else if( arg.equals( "-t")) { i++; if( i >= args.length) { throwUsageException(); } setTestDef( new File( args[i])); } else { throwUsageException(); } return i + 1; } /** * Handles the non-option arguments i, i+1, ... */ protected void handleArgs( String[] args, int i) { int nargs = args.length - i; if( nargs != 1) { throwUsageException(); } setInputDef( new File( args[i])); } /** * Throws a RuntimeException reporting a command line error. */ protected void throwUsageException() { throwUsageException( null, null); } /** * Throws a RuntimeException reporting a command line error. */ protected void throwUsageException( String detail) { throwUsageException( detail, null); } /** * Throws a RuntimeException reporting a command line error. */ protected void throwUsageException( String detail, Exception cause) { if( detail != null) { cause = new RuntimeException( detail, cause); } throw new RuntimeException ( "Usage: " + Reducer.class.getSimpleName() + " [-f function]" + " [-g genDef]" + " [-r resampleFactor]" + " [-s sampleCount]" + " [-t testDef]" + " inputDef", cause); } /** * Changes the initial number of samples. */ public void setSamples( int samples) { samples_ = samples; } /** * Returns the initial number of samples. */ public int getSamples() { return samples_; } /** * Changes the function for which tests cases are reduced. */ public void setFunction( String function) { function_ = function; } /** * Returns the function for which tests cases are reduced. */ public String getFunction() { return function_; } /** * Changes the base test definition file. */ public void setTestDef( File testDef) { testDef_ = testDef; } /** * Returns the base test definition file. */ public File getTestDef() { return testDef_; } /** * Changes the generator definition file. */ public void setGenDef( File genDef) { genDef_ = genDef; } /** * Returns the generator definition file. */ public File getGenDef() { return genDef_; } /** * Changes the input definition file */ public void setInputDef( File inputDef) { inputDef_ = inputDef; } /** * Returns the input definition file */ public File getInputDef() { return inputDef_; } /** * Changes the resample factor. * The <CODE>resampleFactor</CODE> determines the number of samples in the next round of reducing. * Depending on the <CODE>resampleFactor</CODE>, the next round may use more or fewer samples. * <P/> * If the previous round called for <CODE>N</CODE> samples and produced a reduction, then the number of samples for the * next round will be <CODE>N * ( 1 + resampleFactor)</CODE>. To increase sample count with each round, define * <CODE>resampleFactor</CODE> &gt; 0. To decrease sample count with each round, define -1 &lt; * <CODE>resampleFactor</CODE> &lt; 0. */ public void setResampleFactor( double resampleFactor) { resampleFactor_ = resampleFactor; } /** * Returns the {@link setResampleFactor resample factor}. */ public double getResampleFactor() { return resampleFactor_; } public String toString() { StringBuilder builder = new StringBuilder(); if( getFunction() != null) { builder.append( " -f ").append( getFunction()); } if( getGenDef() != null) { builder.append( " -g ").append( getGenDef().getPath()); } builder.append( " -r ").append( getResampleFactor()); builder.append( " -s ").append( getSamples()); if( getTestDef() != null) { builder.append( " -t ").append( getTestDef().getPath()); } return builder.toString(); } private File inputDef_; private String function_; private File testDef_; private File genDef_; private double resampleFactor_; private int samples_; } /** * Creates a new Reducer object. */ public Reducer() { } /** * For a {@link SystemInputDef system input definition}, updates the associated {@link GeneratorSet test case generators} * to reduce the number of generated test cases, using the given {@link Options command line options}. * <P/> * @see Reducer#run */ public static void main( String[] args) { int exitCode = 0; try { Reducer reducer = new Reducer(); reducer.run( new Options( args)); } catch( Exception e) { exitCode = 1; e.printStackTrace( System.err); } finally { System.exit( exitCode); } } /** * For a {@link SystemInputDef system input definition}, updates the associated {@link GeneratorSet test case generators} * to reduce the number of generated test cases, using the given {@link Options command line options}. * <P/> * The reducing process operates as a sequence of "rounds". Each round consists of a series of test case generations executions * called "samples". Each sample uses a new random seed to generate test cases for a specified function in * an attempt to find a seed that produces the fewest test cases. * <P/> * If all samples in a round complete without reducing the current minimum test case count, the reducing process * terminates. Otherwise, as soon as a new minimum is reached, a new round begins. The number of samples in each * subsequent round is determined using the {@link Options#setResampleFactor "resample factor"}. * <P/> * At the end of the reducing process, the {@link Options#setGenDef generator definition file} for the given * {@link Options#setInputDef system input definition} is updated with the random seed value that produces the minimum test case count. */ public void run( Options options) throws Exception { // Identify the system input definition file. File inputDefOption = options.getInputDef(); File inputDefFile; if( !(inputDefFile = inputDefOption).exists() && !(inputDefFile = new File( inputDefOption.getPath() + "-Input.xml")).exists() && !(inputDefFile = new File( inputDefOption.getPath() + ".xml")).exists()) { throw new RuntimeException( "Can't locate input file for path=" + inputDefOption); } File inputDir = inputDefFile.getParentFile(); // Read the system input definition. SystemInputDef inputDef = null; InputStream inputStream = null; try { logger_.info( "Reading system input definition={}", inputDefFile); if( inputDefFile != null) { inputStream = new FileInputStream( inputDefFile); } SystemInputDocReader reader = new SystemInputDocReader( inputStream); inputDef = reader.getSystemInputDef(); } catch( Exception e) { throw new RuntimeException( "Can't read input definition file=" + inputDefFile, e); } finally { IOUtils.closeQuietly( inputStream); } // Identify base test definition file. File baseDefFile = options.getTestDef(); if( baseDefFile != null && !baseDefFile.isAbsolute()) { // For relative path, read base test definitions from input directory. baseDefFile = new File( inputDir, baseDefFile.getPath()); } SystemTestDef baseDef = null; if( baseDefFile != null && baseDefFile.exists()) { // Read the previous base test definitions. InputStream testStream = null; try { logger_.info( "Reading base test definition={}", baseDefFile); testStream = new FileInputStream( baseDefFile); SystemTestDocReader reader = new SystemTestDocReader( testStream); baseDef = reader.getSystemTestDef(); } catch( Exception e) { throw new RuntimeException( "Can't read test definition file=" + baseDefFile, e); } finally { IOUtils.closeQuietly( testStream); } } // Identify the generator definition file. File genDefFile = options.getGenDef(); if( genDefFile == null) { genDefFile = new File( inputDir, Tcases.getProjectName( inputDefFile) + "-Generators.xml"); } else if( !genDefFile.isAbsolute()) { genDefFile = new File( inputDir, genDefFile.getPath()); } // Previous generator definitions exist? IGeneratorSet genDef = null; if( genDefFile.exists()) { // Yes, read generator definitions. InputStream genStream = null; try { logger_.info( "Reading generator definition={}", genDefFile); genStream = new FileInputStream( genDefFile); GeneratorSetDocReader reader = new GeneratorSetDocReader( genStream); genDef = reader.getGeneratorSet(); } catch( Exception e) { throw new RuntimeException( "Can't read generator definition file=" + genDefFile, e); } finally { IOUtils.closeQuietly( genStream); } } else { // No, use default TupleGenerator. GeneratorSet genSet = new GeneratorSet(); genSet.addGenerator( GeneratorSet.ALL, new TupleGenerator()); genDef = genSet; } // Identify generators to reduce. String function = options.getFunction(); ITestCaseGenerator functionGenerator = genDef.getGenerator( function); FunctionInputDef[] functionInputDefs; if( function == null) { functionInputDefs = IteratorUtils.toArray( inputDef.getFunctionInputDefs(), FunctionInputDef.class); } else if( inputDef.getFunctionInputDef( function) == null) { throw new RuntimeException( "Function=" + function + " is not defined"); } else if( functionGenerator == null || functionGenerator.equals( genDef.getGenerator( null))) { throw new RuntimeException( "No generator defined for function=" + function); } else { functionInputDefs = new FunctionInputDef[]{ inputDef.getFunctionInputDef( function) }; } // Find a seed that generates minimum test cases for the specified function(s). int initialCount = getTestCaseCount( baseDef, genDef, functionInputDefs); int samples; int round; int minCount; long minSeed; boolean reducing; Random random; for( samples = options.getSamples(), round = 1, minCount = initialCount, minSeed = 0L, reducing = true, random = new Random(); samples > 0 && reducing; samples = (int) Math.floor( samples * ( 1 + options.getResampleFactor())), round++) { // Perform next round of samples. int roundCount; long roundSeed; int i; for( i = 0, roundCount = 0, roundSeed = 0; i < samples && (roundCount = getTestCaseCount ( baseDef, genDef, functionInputDefs, (roundSeed = (long) (random.nextDouble() * Long.MAX_VALUE)))) >= minCount; i++); reducing = i < samples; if( reducing) { logger_.info( "Round {}: after {} samples, reached {} test cases", new Object[]{ round, i+1, roundCount}); minCount = roundCount; minSeed = roundSeed; } else { logger_.info( "Round {}: after {} samples, terminating", round, samples); } } if( minCount < initialCount) { // Write updates to generator definitions. setRandomSeed( genDef, functionInputDefs, minSeed); GeneratorSetDocWriter genWriter = null; try { logger_.info( "Updating generator definition={}", genDefFile); genWriter = new GeneratorSetDocWriter( new FileOutputStream( genDefFile)); genWriter.write( genDef); } catch( Exception e) { throw new RuntimeException( "Can't write generator definition file=" + genDefFile, e); } finally { if( genWriter != null) { genWriter.close(); } } } } /** * Returns the total number of test cases generated for the given functions. */ private int getTestCaseCount( SystemTestDef baseDef, IGeneratorSet genDef, FunctionInputDef[] functionInputDefs) { int testCaseCount = 0; for( int i = 0; i < functionInputDefs.length; i++) { FunctionInputDef functionInputDef = functionInputDefs[i]; FunctionTestDef functionBase = baseDef==null? null : baseDef.getFunctionTestDef( functionInputDef.getName()); TupleGenerator functionGen = (TupleGenerator) genDef.getGenerator( functionInputDef.getName()); FunctionTestDef functionTestDef = functionGen.getTests( functionInputDef, functionBase); for( Iterator<TestCase> testCases = functionTestDef.getTestCases(); testCases.hasNext(); testCaseCount++, testCases.next()); } return testCaseCount; } /** * Returns the total number of test cases generated for the given functions. */ private int getTestCaseCount( SystemTestDef baseDef, IGeneratorSet genDef, FunctionInputDef[] functionInputDefs, long seed) { setRandomSeed( genDef, functionInputDefs, seed); return getTestCaseCount( baseDef, genDef, functionInputDefs); } /** * Returns the total number of test cases generated for the given functions. */ private void setRandomSeed( IGeneratorSet genDef, FunctionInputDef[] functionInputDefs, long seed) { for( int i = 0; i < functionInputDefs.length; i++) { FunctionInputDef functionInputDef = functionInputDefs[i]; TupleGenerator functionGen = (TupleGenerator) genDef.getGenerator( functionInputDef.getName()); functionGen.setRandomSeed( seed); } } private static final Logger logger_ = LoggerFactory.getLogger( Reducer.class); }
package uk.ac.ox.oucs.vle.mvc; import javax.servlet.http.HttpServletRequest; import org.springframework.web.util.UrlPathHelper; public class PathInfoHelper extends UrlPathHelper { /** * Sakai wrapper around request returns pathInfo of null * which breaks spring mvc */ @Override public String getLookupPathForRequest(HttpServletRequest request) { String lookup = request.getPathInfo(); if (lookup == null) lookup = "/"; return lookup; } }
package com.google.firebase.quickstart; import com.google.auth.oauth2.GoogleCredentials; import com.google.common.collect.ImmutableMap; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.auth.ExportedUserRecord; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; import com.google.firebase.auth.FirebaseToken; import com.google.firebase.auth.ListUsersPage; import com.google.firebase.auth.UserRecord; import com.google.firebase.auth.UserRecord.CreateRequest; import com.google.firebase.auth.UserRecord.UpdateRequest; import com.google.firebase.database.*; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; public class AuthSnippets { public static void getUserById(String uid) throws InterruptedException, ExecutionException { // [START get_user_by_id] UserRecord userRecord = FirebaseAuth.getInstance().getUserAsync(uid).get(); // See the UserRecord reference doc for the contents of userRecord. System.out.println("Successfully fetched user data: " + userRecord.getUid()); // [END get_user_by_id] } public static void getUserByEmail(String email) throws InterruptedException, ExecutionException { // [START get_user_by_email] UserRecord userRecord = FirebaseAuth.getInstance().getUserByEmailAsync(email).get(); // See the UserRecord reference doc for the contents of userRecord. System.out.println("Successfully fetched user data: " + userRecord.getEmail()); // [END get_user_by_email] } public static void getUserByPhoneNumber( String phoneNumber) throws InterruptedException, ExecutionException { // [START get_user_by_phone] UserRecord userRecord = FirebaseAuth.getInstance().getUserByPhoneNumberAsync(phoneNumber).get(); // See the UserRecord reference doc for the contents of userRecord. System.out.println("Successfully fetched user data: " + userRecord.getPhoneNumber()); // [END get_user_by_phone] } public static void createUser() throws InterruptedException, ExecutionException { // [START create_user] CreateRequest request = new CreateRequest() .setEmail("user@example.com") .setEmailVerified(false) .setPassword("secretPassword") .setPhoneNumber("+11234567890") .setDisplayName("John Doe") .setPhotoUrl("http: .setDisabled(false); UserRecord userRecord = FirebaseAuth.getInstance().createUserAsync(request).get(); System.out.println("Successfully created new user: " + userRecord.getUid()); // [END create_user] } public static void createUserWithUid() throws InterruptedException, ExecutionException { // [START create_user_with_uid] CreateRequest request = new CreateRequest() .setUid("some-uid") .setEmail("user@example.com") .setPhoneNumber("+11234567890"); UserRecord userRecord = FirebaseAuth.getInstance().createUserAsync(request).get(); System.out.println("Successfully created new user: " + userRecord.getUid()); // [END create_user_with_uid] } public static void updateUser(String uid) throws InterruptedException, ExecutionException { // [START update_user] UpdateRequest request = new UpdateRequest(uid) .setEmail("user@example.com") .setPhoneNumber("+11234567890") .setEmailVerified(true) .setPassword("newPassword") .setDisplayName("Jane Doe") .setPhotoUrl("http: .setDisabled(true); UserRecord userRecord = FirebaseAuth.getInstance().updateUserAsync(request).get(); System.out.println("Successfully updated user: " + userRecord.getUid()); // [END update_user] } public static void setCustomUserClaims( String uid) throws InterruptedException, ExecutionException { // [START set_custom_user_claims] // Set admin privilege on the user corresponding to uid. Map<String, Object> claims = new HashMap<>(); claims.put("admin", true); FirebaseAuth.getInstance().setCustomUserClaimsAsync(uid, claims).get(); // The new custom claims will propagate to the user's ID token the // next time a new one is issued. // [END set_custom_user_claims] String idToken = "id_token"; // [START verify_custom_claims] // Verify the ID token first. FirebaseToken decoded = FirebaseAuth.getInstance().verifyIdTokenAsync(idToken).get(); if (Boolean.TRUE.equals(decoded.getClaims().get("admin"))) { // Allow access to requested admin resource. } // [END verify_custom_claims] // [START read_custom_user_claims] // Lookup the user associated with the specified uid. UserRecord user = FirebaseAuth.getInstance().getUserAsync(uid).get(); System.out.println(user.getCustomClaims().get("admin")); // [END read_custom_user_claims] } public static void setCustomUserClaimsScript() throws InterruptedException, ExecutionException { // [START set_custom_user_claims_script] UserRecord user = FirebaseAuth.getInstance() .getUserByEmailAsync("user@admin.example.com").get(); // Confirm user is verified. if (user.isEmailVerified()) { Map<String, Object> claims = new HashMap<>(); claims.put("admin", true); FirebaseAuth.getInstance().setCustomUserClaimsAsync(user.getUid(), claims).get(); } // [END set_custom_user_claims_script] } public static void setCustomUserClaimsInc() throws InterruptedException, ExecutionException { // [START set_custom_user_claims_incremental] UserRecord user = FirebaseAuth.getInstance() .getUserByEmailAsync("user@admin.example.com").get(); // Add incremental custom claim without overwriting the existing claims. Map<String, Object> currentClaims = user.getCustomClaims(); if (Boolean.TRUE.equals(currentClaims.get("admin"))) { // Add level. currentClaims.put("level", 10); // Add custom claims for additional privileges. FirebaseAuth.getInstance().setCustomUserClaimsAsync(user.getUid(), currentClaims).get(); } // [END set_custom_user_claims_incremental] } public static void listAllUsers() throws InterruptedException, ExecutionException { // [START list_all_users] // Start listing users from the beginning, 1000 at a time. ListUsersPage page = FirebaseAuth.getInstance().listUsersAsync(null).get(); while (page != null) { for (ExportedUserRecord user : page.getValues()) { System.out.println("User: " + user.getUid()); } page = page.getNextPage(); } // Iterate through all users. This will still retrieve users in batches, // buffering no more than 1000 users in memory at a time. page = FirebaseAuth.getInstance().listUsersAsync(null).get(); for (ExportedUserRecord user : page.iterateAll()) { System.out.println("User: " + user.getUid()); } // [END list_all_users] } public static void deleteUser(String uid) throws InterruptedException, ExecutionException { // [START delete_user] FirebaseAuth.getInstance().deleteUserAsync(uid).get(); System.out.println("Successfully deleted user."); // [END delete_user] } public static void createCustomToken() throws InterruptedException, ExecutionException { // [START custom_token] String uid = "some-uid"; String customToken = FirebaseAuth.getInstance().createCustomTokenAsync(uid).get(); // Send token back to client // [END custom_token] System.out.println("Created custom token: " + customToken); } public static void createCustomTokenWithClaims() throws InterruptedException, ExecutionException { // [START custom_token_with_claims] String uid = "some-uid"; Map<String, Object> additionalClaims = new HashMap<String, Object>(); additionalClaims.put("premiumAccount", true); String customToken = FirebaseAuth.getInstance() .createCustomTokenAsync(uid, additionalClaims).get(); // Send token back to client // [END custom_token_with_claims] System.out.println("Created custom token: " + customToken); } public static void verifyIdToken(String idToken) throws InterruptedException, ExecutionException { // [START verify_id_token] // idToken comes from the client app (shown above) FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdTokenAsync(idToken).get(); String uid = decodedToken.getUid(); // [END verify_id_token] System.out.println("Decoded ID token from user: " + uid); } public static void verifyIdTokenCheckRevoked(String idToken) throws InterruptedException, ExecutionException { // [START verify_id_token_check_revoked] try { // Verify the ID token while checking if the token is revoked by passing checkRevoked // as true. boolean checkRevoked = true; FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdTokenAsync(idToken, checkRevoked).get(); // Token is valid and not revoked. String uid = decodedToken.getUid(); } catch (ExecutionException e) { if (e.getCause() instanceof FirebaseAuthException) { FirebaseAuthException authError = (FirebaseAuthException) e.getCause(); if (authError.getErrorCode().equals("id-token-revoked")) { // Token has been revoked. Inform the user to reauthenticate or signOut() the user. } else { // Token is invalid. } } } // [END verify_id_token_check_revoked] } public static void revokeIdTokens(String idToken) throws InterruptedException, ExecutionException { String uid="someUid"; // [START revoke_tokens] FirebaseAuth.getInstance().revokeRefreshTokensAsync(uid).get(); UserRecord user = FirebaseAuth.getInstance().getUserAsync(uid).get(); // Convert to seconds as the auth_time in the token claims is in seconds too. long revocationSecond = user.getTokensValidAfterTimestamp() / 1000; System.out.println("Tokens revoked at: " + revocationSecond); // [END revoke_tokens] // [START save_revocation_in_db] DatabaseReference ref = FirebaseDatabase.getInstance().getReference("metadata/" + uid); ref.setValueAsync(new HashMap<String, Object>().put("revokeTime", revocationSecond)).get(); // [END save_revocation_in_db] } public static void main(String[] args) throws InterruptedException, ExecutionException { System.out.println("Hello, AuthSnippets!"); // Initialize Firebase try { // [START initialize] FileInputStream serviceAccount = new FileInputStream("service-account.json"); FirebaseOptions options = new FirebaseOptions.Builder() .setCredentials(GoogleCredentials.fromStream(serviceAccount)) .build(); FirebaseApp.initializeApp(options); // [END initialize] } catch (IOException e) { System.out.println("ERROR: invalid service account credentials. See README."); System.out.println(e.getMessage()); System.exit(1); } // Smoke test createUserWithUid(); getUserById("some-uid"); getUserByEmail("user@example.com"); getUserByPhoneNumber("+11234567890"); updateUser("some-uid"); //setCustomUserClaims("some-uid"); listAllUsers(); deleteUser("some-uid"); createCustomToken(); createCustomTokenWithClaims(); System.out.println("Done!"); } }
package Tetrlais; import java.util.Vector; import messages.TetrlaisStateResponse; import rlVizLib.Environments.EnvironmentBase; import rlVizLib.general.ParameterHolder; import rlVizLib.general.RLVizVersion; import rlVizLib.messaging.environment.EnvironmentMessageParser; import rlVizLib.messaging.environment.EnvironmentMessages; import rlVizLib.messaging.interfaces.RLVizEnvInterface; import rlglue.types.Action; import rlglue.types.Observation; import rlglue.types.Random_seed_key; import rlglue.types.Reward_observation; import rlglue.types.State_key; public class Tetrlais extends EnvironmentBase implements RLVizEnvInterface { private int timeStep=0; private int episodeNumber=0; private int totalSteps=0; private int currentScore =0; private GameState gameState = null; static final int terminalScore = 0; // /*Hold all the possible bricks that can fall*/ Vector<TetrlaisPiece> possibleBlocks=new Vector<TetrlaisPiece>(); //Default width and height. Static because of the use in getDefaultParameters() static int defaultWidth=6; static int defaultHeight=12; public Tetrlais(){ super(); //Defaults possibleBlocks.add(TetrlaisPiece.makeLine()); gameState=new GameState(width,height,possibleBlocks); timeStep=0; episodeNumber=0; totalSteps=0; } public Tetrlais(ParameterHolder p){ super(); if(p!=null){ if(!p.isNull()){ width=p.getIntParam("Width"); height=p.getIntParam("Height"); if(p.getBooleanParam("LongBlock")) possibleBlocks.add(TetrlaisPiece.makeLine()); if(p.getBooleanParam("SquareBlock")) possibleBlocks.add(TetrlaisPiece.makeSquare()); if(p.getBooleanParam("TriBlock")) possibleBlocks.add(TetrlaisPiece.makeTri()); if(p.getBooleanParam("SBlock")) possibleBlocks.add(TetrlaisPiece.makeSShape()); if(p.getBooleanParam("ZBlock")) possibleBlocks.add(TetrlaisPiece.makeZShape()); if(p.getBooleanParam("LBlock")) possibleBlocks.add(TetrlaisPiece.makeLShape()); if(p.getBooleanParam("JBlock")) possibleBlocks.add(TetrlaisPiece.makeJShape()); } } gameState=new GameState(width,height,possibleBlocks); timeStep=0; episodeNumber=0; totalSteps=0; } //This method creates the object that can be used to easily set different problem parameters public static ParameterHolder getDefaultParameters(){ ParameterHolder p = new ParameterHolder(); p.addIntParam("Width",defaultWidth); p.addIntParam("Height",defaultHeight); p.addBooleanParam("LongBlock",true); p.addBooleanParam("SquareBlock",true); p.addBooleanParam("TriBlock",true); p.addBooleanParam("SBlock", true); p.addBooleanParam("ZBlock", true); p.addBooleanParam("LBlock", true); p.addBooleanParam("JBlock", true); return p; } /*Base RL-Glue Functions*/ public String env_init() { /* initialize the environment, construct a task_spec to pass on. The tetris environment * has 200 binary observation variables and 1 action variable which ranges between 0 and 4. These are all * integer values. */ /*NOTE: THE GAME STATE WIDTH AND HEIGHT MUST MULTIPLY TO EQUAL THE NUMBER OF OBSERVATION VARIABLES*/ int numStates=gameState.getHeight()*gameState.getWidth(); timeStep=0; episodeNumber=0; String task_spec = "2.0:e:"+numStates+"_["; for(int i = 0; i< numStates-1; i++) task_spec = task_spec + "i,"; task_spec = task_spec + "i]"; for(int i=0; i<numStates;i++) task_spec = task_spec + "_[0,1]"; task_spec = task_spec + ":1_[i]_[0,5]"; return task_spec; } public Observation env_start() { gameState.reset(); currentScore =0; timeStep=0; episodeNumber++; Observation o = gameState.get_observation(); return o; } public Reward_observation env_step(Action actionObject) { int theAction=actionObject.intArray[0]; if(theAction>5||theAction<0){ System.err.println("Invalid action selected in Tetrlais: "+theAction); Thread.dumpStack(); System.exit(1); } Reward_observation ro = new Reward_observation(); timeStep++; totalSteps++; ro.terminal = 1; if(!gameState.gameOver()) { ro.terminal=0; gameState.update(); gameState.take_action(theAction); ro.r = gameState.get_score() - currentScore; currentScore = gameState.get_score(); } else{ ro.r = Tetrlais.terminalScore; currentScore = 0; } ro.o = gameState.get_observation(); return ro; } public void env_cleanup() { // TODO Auto-generated method stub } public Random_seed_key env_get_random_seed() { // TODO Auto-generated method stub System.out.println("The Tetris Environment does not implement env_get_random_seed. Sorry."); return null; } public State_key env_get_state() { // TODO Auto-generated method stub System.out.println("The Tetris Environment does not implement env_get_state. Sorry."); return null; } public String env_message(String theMessage) { EnvironmentMessages theMessageObject; try { theMessageObject = EnvironmentMessageParser.parseMessage(theMessage); } catch (Exception e) { System.err.println("Someone sent Tetrlais a message that wasn't RL-Viz compatible"); return "I only respond to RL-Viz messages!"; } if(theMessageObject.canHandleAutomatically(this)){ return theMessageObject.handleAutomatically(this); } if(theMessageObject.getTheMessageType()==rlVizLib.messaging.environment.EnvMessageType.kEnvCustom.id()){ String theCustomType=theMessageObject.getPayLoad(); if(theCustomType.equals("GETTETRLAISSTATE")){ //It is a request for the state TetrlaisStateResponse theResponseObject=new TetrlaisStateResponse(episodeNumber,timeStep, totalSteps,currentScore,gameState.getWidth(), gameState.getHeight(), gameState.getWorldState(), gameState.getCurrentPiece()); return theResponseObject.makeStringResponse(); } System.out.println("We need some code written in Env Message for Tetrlais.. unknown custom message type received"); Thread.dumpStack(); return null; } System.out.println("We need some code written in Env Message for Tetrlais!"); Thread.dumpStack(); return null; } public void env_set_random_seed(Random_seed_key arg0) { // TODO Auto-generated method stub System.out.println("The Tetris Environment does not implement env_set_random_seed. Sorry."); } public void env_set_state(State_key arg0) { // TODO Auto-generated method stub System.out.println("The Tetris Environment does not implement env_set_state. Sorry."); } /*End of Base RL-Glue Functions */ /*RL-Viz Methods*/ @Override protected Observation makeObservation() { // TODO Auto-generated method stub return gameState.get_observation(); } /*End of RL-Viz Methods*/ public RLVizVersion getTheVersionISupport() { // TODO Auto-generated method stub return new RLVizVersion(1,0); } /*Tetris Helper Functions*/ /*End of Tetris Helper Functions*/ }
package sgdk.rescomp.processor; import java.io.IOException; import sgdk.rescomp.Processor; import sgdk.rescomp.Resource; import sgdk.rescomp.resource.Align; import sgdk.tool.StringUtil; public class AlignProcessor implements Processor { @Override public String getId() { return "ALIGN"; } @Override public Resource execute(String[] fields) throws IOException { if (fields.length < 1) { System.out.println("Wrong ALIGN definition"); System.out.println("ALIGN [alignment]"); System.out.println( " alignment specifies the minimum binary data alignment in bytes (default is 524288)"); return null; } // get alignment int alignment = 524288; if (fields.length > 1) StringUtil.parseInt(fields[1], alignment); // build ALIGN resource return new Align("align", alignment); } }
package com.jarvis.cache; import com.jarvis.cache.to.CacheKeyTO; import com.jarvis.cache.to.CacheWrapper; public class MSetParam { private CacheKeyTO cacheKey; private CacheWrapper<Object> result; public MSetParam(CacheKeyTO cacheKey, CacheWrapper<Object> result) { this.cacheKey = cacheKey; this.result = result; } public CacheKeyTO getCacheKey() { return cacheKey; } public CacheWrapper<Object> getResult() { return result; } }
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Game { static Scanner in = new Scanner(System.in); public static void main(String[] args) { Person p = new Person(0, 5); Maze maze = new Maze( "", "........................", "..............", "...................", "................", "................ ", "...............", "................", "................", "O................", ".................X", "................", "...................", ".....................", "" ); System.out.println("Welcome to the maze. "); while (maze.at(p.x, p.y) != 'X') { System.out.println(); // This prints the map. for (int j = 2; j >= -2; j for (int i = -2; i <= 2; i++) { if (i == 0 && j == 0) System.out.print(""); else System.out.print(maze.at(p.x + i, p.y + j)); } System.out.println(); } // This prints where you can go. List<String> dir = new ArrayList<>(); if (!maze.isWall(p.x - 1, p.y)) dir.add("(w)est"); if (!maze.isWall(p.x + 1, p.y)) dir.add("(e)ast"); if (!maze.isWall(p.x, p.y + 1)) dir.add("(n)north"); if (!maze.isWall(p.x, p.y - 1)) dir.add("(s)outh"); System.out.println("you can go " + dir + " x: " + p.x + " y: " + p.y); System.out.println("Where would you like to go?"); String ans = in.nextLine().toLowerCase(); switch (ans) { case "w": case "west": if (!maze.isWall(p.x - 1, p.y)) p.x else System.out.println("You can't go west"); break; case "e": case "east": if (!maze.isWall(p.x + 1, p.y)) p.x++; else System.out.println("That's too scary !!!"); break; case "n": case "north": if (!maze.isWall(p.x, p.y + 1)) p.y++; else System.out.println("no can do"); break; case "s": case "south": if (!maze.isWall(p.x, p.y - 1)) p.y else System.out.println("Try again"); break; default: System.out.println("I don't know how to " + (ans)); } } System.out.println("Good choice, you escape the maze"); } } class Person { int x, y; public Person(int x, int y) { this.x = x; this.y = y; } } class Maze { String[] layout; Maze(String... layout) { this.layout = layout; } public char at(int x, int y) { if (y < 0 || y >= layout.length || x < 0 || x >= layout[layout.length - 1 - y].length()) return ' return layout[layout.length - 1 - y].charAt(x); } public boolean isWall(int x, int y) { return (at(x, y) & 0x2580) == 0x2500; } }
package uk.ac.ebi.gxa.dao; import oracle.jdbc.OracleTypes; import oracle.sql.ARRAY; import oracle.sql.ArrayDescriptor; import oracle.sql.STRUCT; import oracle.sql.StructDescriptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.*; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcCall; import org.springframework.jdbc.core.support.AbstractSqlTypeValue; import uk.ac.ebi.microarray.atlas.model.*; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.*; /** * A data access object designed for retrieving common sorts of data from the atlas database. This DAO should be * configured with a spring {@link JdbcTemplate} object which will be used to query the database. * * @author Tony Burdett * @date 21-Sep-2009 */ public class AtlasDAO { // load monitor private static final String LOAD_MONITOR_SELECT = "SELECT accession, status, netcdf, similarity, ranking, searchindex, load_type " + "FROM load_monitor"; private static final String LOAD_MONITOR_BY_ACC_SELECT = LOAD_MONITOR_SELECT + " " + "WHERE accession=?"; // experiment queries private static final String EXPERIMENTS_COUNT = "SELECT COUNT(*) FROM a2_experiment"; private static final String EXPERIMENTS_SELECT = "SELECT accession, description, performer, lab, experimentid " + "FROM a2_experiment"; private static final String EXPERIMENTS_PENDING_INDEX_SELECT = "SELECT e.accession, e.description, e.performer, e.lab, e.experimentid " + "FROM a2_experiment e, load_monitor lm " + "WHERE e.accession=lm.accession " + "AND (lm.searchindex='pending' OR lm.searchindex='failed') " + "AND lm.load_type='experiment'"; private static final String EXPERIMENTS_PENDING_NETCDF_SELECT = "SELECT e.accession, e.description, e.performer, e.lab, e.experimentid " + "FROM a2_experiment e, load_monitor lm " + "WHERE e.accession=lm.accession " + "AND (lm.netcdf='pending' OR lm.netcdf='failed') " + "AND lm.load_type='experiment'"; private static final String EXPERIMENTS_PENDING_ANALYTICS_SELECT = "SELECT e.accession, e.description, e.performer, e.lab, e.experimentid " + "FROM a2_experiment e, load_monitor lm " + "WHERE e.accession=lm.accession " + "AND (lm.ranking='pending' OR lm.ranking='failed') " + // fixme: similarity? "AND lm.load_type='experiment'"; private static final String EXPERIMENT_BY_ACC_SELECT = EXPERIMENTS_SELECT + " " + "WHERE accession=?"; // gene queries private static final String GENES_COUNT = "SELECT COUNT(*) FROM a2_gene"; private static final String GENES_SELECT = "SELECT DISTINCT g.geneid, g.identifier, g.name, s.name AS species " + "FROM a2_gene g, a2_spec s " + "WHERE g.specid=s.specid"; private static final String GENE_BY_IDENTIFIER = "SELECT DISTINCT g.geneid, g.identifier, g.name, s.name AS species " + "FROM a2_gene g, a2_spec s " + "WHERE g.identifier=?"; private static final String DESIGN_ELEMENTS_AND_GENES_SELECT = "SELECT de.geneid, de.designelementid " + "FROM a2_designelement de"; private static final String GENES_PENDING_SELECT = "SELECT DISTINCT g.geneid, g.identifier, g.name, s.name AS species " + "FROM a2_gene g, a2_spec s, load_monitor lm " + "WHERE g.specid=s.specid " + "AND g.identifier=lm.accession " + "AND (lm.searchindex='pending' OR lm.searchindex='failed') " + "AND lm.load_type='gene'"; private static final String DESIGN_ELEMENTS_AND_GENES_PENDING_SELECT = "SELECT de.geneid, de.designelementid " + "FROM a2_designelement de, a2_gene g, load_monitor lm " + "WHERE de.geneid=g.geneid " + "AND g.identifier=lm.accession " + "AND (lm.searchindex='pending' OR lm.searchindex='failed') " + "AND lm.load_type='gene'"; private static final String GENES_BY_EXPERIMENT_ACCESSION = "SELECT DISTINCT g.geneid, g.identifier, g.name, s.name AS species " + "FROM a2_gene g, a2_spec s, a2_designelement d, a2_assay a, " + "a2_experiment e " + "WHERE g.geneid=d.geneid " + "AND g.specid = s.specid " + "AND d.arraydesignid=a.arraydesignid " + "AND a.experimentid=e.experimentid " + "AND e.accession=?"; private static final String DESIGN_ELEMENTS_AND_GENES_BY_EXPERIMENT_ACCESSION = "SELECT de.geneid, de.designelementid " + "FROM a2_designelement de, a2_assay a, a2_experiment e " + "WHERE de.arraydesignid=a.arraydesignid " + "AND a.experimentid=e.experimentid " + "AND e.accession=?"; private static final String PROPERTIES_BY_RELATED_GENES = "SELECT gpv.geneid, gp.name AS property, gpv.value AS propertyvalue " + "FROM a2_geneproperty gp, a2_genepropertyvalue gpv " + "WHERE gpv.genepropertyid=gp.genepropertyid " + "AND gpv.geneid IN (:geneids)"; private static final String GENE_COUNT_SELECT = "SELECT COUNT(DISTINCT identifier) FROM a2_gene"; // assay queries private static final String ASSAYS_COUNT = "SELECT COUNT(*) FROM a2_assay"; private static final String ASSAYS_SELECT = "SELECT a.accession, e.accession, ad.accession, a.assayid " + "FROM a2_assay a, a2_experiment e, a2_arraydesign ad " + "WHERE e.experimentid=a.experimentid " + "AND a.arraydesignid=ad.arraydesignid"; private static final String ASSAYS_BY_EXPERIMENT_ACCESSION = ASSAYS_SELECT + " " + "AND e.accession=?"; private static final String ASSAYS_BY_EXPERIMENT_AND_ARRAY_ACCESSION = ASSAYS_BY_EXPERIMENT_ACCESSION + " " + "AND ad.accession=?"; private static final String ASSAYS_BY_RELATED_SAMPLES = "SELECT s.sampleid, a.accession " + "FROM a2_assay a, a2_assaysample s " + "WHERE a.assayid=s.assayid " + "AND s.sampleid IN (:sampleids)"; private static final String PROPERTIES_BY_RELATED_ASSAYS = "SELECT apv.assayid, p.name AS property, pv.name AS propertyvalue, apv.isfactorvalue " + "FROM a2_property p, a2_propertyvalue pv, a2_assaypropertyvalue apv " + "WHERE apv.propertyvalueid=pv.propertyvalueid " + "AND pv.propertyid=p.propertyid " + "AND apv.assayid IN (:assayids)"; // expression value queries private static final String EXPRESSION_VALUES_BY_RELATED_ASSAYS = "SELECT ev.assayid, ev.designelementid, ev.value " + "FROM a2_expressionvalue ev, a2_designelement de " + "WHERE ev.designelementid=de.designelementid " + "AND ev.assayid IN (:assayids)"; private static final String EXPRESSION_VALUES_BY_EXPERIMENT_AND_ARRAY = "SELECT ev.assayid, ev.designelementid, ev.value " + "FROM a2_expressionvalue ev " + "JOIN a2_designelement de ON de.designelementid=ev.designelementid " + "JOIN a2_assay a ON a.assayid = ev.assayid " + "WHERE a.experimentid=? AND de.arraydesignid=?"; // sample queries private static final String SAMPLES_BY_ASSAY_ACCESSION = "SELECT s.accession, s.species, s.channel, s.sampleid " + "FROM a2_sample s, a2_assay a, a2_assaysample ass " + "WHERE s.sampleid=ass.sampleid " + "AND a.assayid=ass.assayid " + "AND a.accession=?"; private static final String SAMPLES_BY_EXPERIMENT_ACCESSION = "SELECT s.accession, s.species, s.channel, s.sampleid " + "FROM a2_sample s, a2_assay a, a2_assaysample ass, a2_experiment e " + "WHERE s.sampleid=ass.sampleid " + "AND a.assayid=ass.assayid " + "AND a.experimentid=e.experimentid " + "AND e.accession=?"; private static final String PROPERTIES_BY_RELATED_SAMPLES = "SELECT spv.sampleid, p.name AS property, pv.name AS propertyvalue, spv.isfactorvalue " + "FROM a2_property p, a2_propertyvalue pv, a2_samplepropertyvalue spv " + "WHERE spv.propertyvalueid=pv.propertyvalueid " + "AND pv.propertyid=p.propertyid " + "AND spv.sampleid IN (:sampleids)"; // query for counts, for statistics private static final String PROPERTY_VALUE_COUNT_SELECT = "SELECT COUNT(DISTINCT name) FROM a2_propertyvalue"; // array and design element queries private static final String ARRAY_DESIGN_SELECT = "SELECT accession, type, name, provider, arraydesignid " + "FROM a2_arraydesign"; private static final String ARRAY_DESIGN_BY_ACC_SELECT = ARRAY_DESIGN_SELECT + " " + "WHERE accession=?"; private static final String ARRAY_DESIGN_BY_EXPERIMENT_ACCESSION = "SELECT " + "DISTINCT d.accession, d.type, d.name, d.provider, d.arraydesignid " + "FROM a2_arraydesign d, a2_assay a, a2_experiment e " + "WHERE e.experimentid=a.experimentid " + "AND a.arraydesignid=d.arraydesignid " + "AND e.accession=?"; private static final String DESIGN_ELEMENTS_BY_ARRAY_ACCESSION = "SELECT de.designelementid, de.accession " + "FROM A2_ARRAYDESIGN ad, A2_DESIGNELEMENT de " + "WHERE de.arraydesignid=ad.arraydesignid " + "AND ad.accession=?"; private static final String DESIGN_ELEMENTS_BY_ARRAY_ID = "SELECT de.designelementid, de.accession " + "FROM a2_designelement de " + "WHERE de.arraydesignid=?"; private static final String DESIGN_ELEMENTS_BY_RELATED_ARRAY = "SELECT de.arraydesignid, de.designelementid, de.accession " + "FROM a2_designelement de " + "WHERE de.arraydesignid IN (:arraydesignids)"; private static final String DESIGN_ELEMENTS_BY_GENEID = "SELECT de.designelementid, de.accession " + "FROM a2_designelement de " + "WHERE de.geneid=?"; // other useful queries private static final String EXPRESSIONANALYTICS_BY_EXPERIMENTID = "SELECT ef.name AS ef, efv.name AS efv, a.experimentid, " + "a.designelementid, a.tstat, a.pvaladj, " + "ef.propertyid as efid, efv.propertyvalueid as efvid " + "FROM a2_expressionanalytics a " + "JOIN a2_propertyvalue efv ON efv.propertyvalueid=a.propertyvalueid " + "JOIN a2_property ef ON ef.propertyid=efv.propertyid " + "JOIN a2_designelement de ON de.designelementid=a.designelementID " + "WHERE a.experimentid=?"; private static final String EXPRESSIONANALYTICS_BY_GENEID = "SELECT ef, efv, experimentid, null, tstat, min(pvaladj), efid, efvid FROM " + "(SELECT ef.name AS ef, efv.name AS efv, a.experimentid AS experimentid, " + "first_value(a.tstat) over (partition BY ef.name, efv.name, a.experimentid ORDER BY a.pvaladj ASC) AS tstat, " + "(a.pvaladj ) AS pvaladj," + "ef.propertyid AS efid, efv.propertyvalueid as efvid " + "FROM a2_expressionanalytics a " + "JOIN a2_propertyvalue efv ON efv.propertyvalueid=a.propertyvalueid " + "JOIN a2_property ef ON ef.propertyid=efv.propertyid " + "JOIN a2_designelement de ON de.designelementid=a.designelementid " + "WHERE de.geneid=?) GROUP BY ef, efv, experimentid, tstat, efid, efvid"; private static final String EXPRESSIONANALYTICS_BY_GENEID_EF_EFV = "SELECT ef.name AS ef, efv.name AS efv, a.experimentid, a.designelementid, " + "a.tstat, a.pvaladj, " + "ef.propertyid as efid, efv.propertyvalueid as efvid " + "FROM a2_expressionanalytics a " + "JOIN a2_propertyvalue efv ON efv.propertyvalueid=a.propertyvalueid " + "JOIN a2_property ef ON ef.propertyid=efv.propertyid " + "WHERE a.geneid=? AND ef.name=? AND efv.name=?"; private static final String EXPRESSIONANALYTICS_BY_GENEID_EFO = "SELECT ef.name AS ef, efv.name AS efv, a.experimentid, a.designelementid, " + "a.tstat, a.pvaladj, " + "ef.propertyid as efid, efv.propertyvalueid as efvid " + "FROM a2_expressionanalytics a " + "JOIN a2_propertyvalue efv ON efv.propertyvalueid=a.propertyvalueid " + "JOIN a2_property ef ON ef.propertyid=efv.propertyid " + "JOIN a2_ontologymapping efo ON efo.propertyvalueid=a.propertyvalueid " + "WHERE a.geneid=? AND efo.accession IN (?)"; private static final String EXPRESSIONANALYTICS_BY_DESIGNELEMENTID = "SELECT ef.name AS ef, efv.name AS efv, a.experimentid, a.designelementid, " + "a.tstat, a.pvaladj, " + "ef.propertyid as efid, efv.propertyvalueid as efvid " + "FROM a2_expressionanalytics a " + "JOIN a2_propertyvalue efv ON efv.propertyvalueid=a.propertyvalueid " + "JOIN a2_property ef ON ef.propertyid=efv.propertyid " + "WHERE a.designelementid=?"; private static final String ONTOLOGY_MAPPINGS_SELECT = "SELECT DISTINCT accession, property, propertyvalue, ontologyterm, " + "issampleproperty, isassayproperty, isfactorvalue, experimentid " + "FROM a2_ontologymapping"; private static final String ONTOLOGY_MAPPINGS_BY_ONTOLOGY_NAME = ONTOLOGY_MAPPINGS_SELECT + " " + "WHERE ontologyname=?"; private static final String ONTOLOGY_MAPPINGS_BY_EXPERIMENT_ACCESSION = ONTOLOGY_MAPPINGS_SELECT + " " + "WHERE accession=?"; // queries for atlas interface private static final String ATLAS_RESULTS_SELECT = "SELECT " + "ea.experimentid, " + "g.geneid, " + "p.name AS property, " + "pv.name AS propertyvalue, " + "CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END AS updn, " + "min(ea.pvaladj), " + "FROM a2_expressionanalytics ea " + "JOIN a2_propertyvalue pv ON pv.propertyvalueid=ea.propertyvalueid " + "JOIN a2_property p ON p.propertyid=pv.propertyid " + "JOIN a2_designelement de ON de.designelementid=ea.designelementid " + "JOIN a2_gene g ON g.geneid=de.geneid"; // same as results, but counts geneids instead of returning them private static final String ATLAS_COUNTS_SELECT = "SELECT " + "ea.experimentid, " + "p.name AS property, " + "pv.name AS propertyvalue, " + "CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END AS updn, " + "min(ea.pvaladj), " + "COUNT(DISTINCT(g.geneid)) AS genes, " + "min(p.propertyid) AS propertyid, " + "min(pv.propertyvalueid) AS propertyvalueid " + "FROM a2_expressionanalytics ea " + "JOIN a2_propertyvalue pv ON pv.propertyvalueid=ea.propertyvalueid " + "JOIN a2_property p ON p.propertyid=pv.propertyid " + "JOIN a2_designelement de ON de.designelementid=ea.designelementid " + "JOIN a2_gene g ON g.geneid=de.geneid"; private static final String ATLAS_COUNTS_BY_EXPERIMENTID = ATLAS_COUNTS_SELECT + " " + "WHERE ea.experimentid=? " + "GROUP BY ea.experimentid, p.name, pv.name, " + "CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END"; private static final String ATLAS_RESULTS_UP_BY_EXPERIMENTID_GENEID_AND_EFV = ATLAS_RESULTS_SELECT + " " + "WHERE ea.experimentid IN (:exptids) " + "AND g.geneid IN (:geneids) " + "AND pv.name IN (:efvs) " + "AND updn='1' " + "AND TOPN<=20 " + "ORDER BY ea.pvaladj " + "GROUP BY ea.experimentid, g.geneid, p.name, pv.name, " + "CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END"; private static final String ATLAS_RESULTS_DOWN_BY_EXPERIMENTID_GENEID_AND_EFV = ATLAS_RESULTS_SELECT + " " + "WHERE ea.experimentid IN (:exptids) " + "AND g.geneid IN (:geneids) " + "AND pv.name IN (:efvs) " + "AND updn='-1' " + "AND TOPN<=20 " + "ORDER BY ea.pvaladj " + "GROUP BY ea.experimentid, g.geneid, p.name, pv.name, ea.pvaladj, " + "CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END"; private static final String ATLAS_RESULTS_UPORDOWN_BY_EXPERIMENTID_GENEID_AND_EFV = ATLAS_RESULTS_SELECT + " " + "WHERE ea.experimentid IN (:exptids) " + "AND g.geneid IN (:geneids) " + "AND pv.name IN (:efvs) " + "AND updn<>0 " + "AND TOPN<=20 " + "ORDER BY ea.pvaladj " + "GROUP BY ea.experimentid, g.geneid, p.name, pv.name, ea.pvaladj, " + "CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END"; // fixme: exclude experiment ids? // old atlas queries contained "NOT IN (211794549,215315583,384555530,411493378,411512559)" private static final String SPECIES_ALL = "SELECT specid, name FROM A2_SPEC"; private static final String PROPERTIES_ALL = "SELECT min(p.propertyid), p.name, min(pv.propertyvalueid), pv.name, 1 as isfactorvalue " + "FROM a2_property p, a2_propertyvalue pv " + "WHERE pv.propertyid=p.propertyid GROUP BY p.name, pv.name"; private static final String GENEPROPERTY_ALL_NAMES = "SELECT name FROM A2_GENEPROPERTY"; private static final String BEST_DESIGNELEMENTID_FOR_GENE = "SELECT topde FROM (SELECT de.designelementid as topde," + " MIN(a.pvaladj) KEEP(DENSE_RANK FIRST ORDER BY a.pvaladj ASC)" + " OVER (PARTITION BY a.propertyvalueid) as minp" + " FROM a2_expressionanalytics a, a2_propertyvalue pv, a2_property p, a2_designelement de" + " WHERE pv.propertyid = p.propertyid" + " AND pv.propertyvalueid = a.propertyvalueid" + " AND a.designelementid = de.designelementid" + " AND p.name = ?" + " AND a.experimentid = ?" + " AND de.geneid = ?" + " and rownum=1)"; private JdbcTemplate template; private int maxQueryParams = 500; private Logger log = LoggerFactory.getLogger(getClass()); public JdbcTemplate getJdbcTemplate() { return template; } public void setJdbcTemplate(JdbcTemplate template) { this.template = template; } /** * Get the maximum allowed number of parameters that can be supplied to a parameterised query. This is effectively * the maximum bound for an "IN" list - i.e. SELECT * FROM foo WHERE foo.bar IN (?,?,?,...,?). If unset, this * defaults to 500. Typically, the limit for oracle databases is 1000. If, for any query that takes a list, the * size of the list is greater than this value, the query will be split into several smaller subqueries and the * results aggregated. As a user, you should not notice any difference. * * @return the maximum bound on the query list size */ public int getMaxQueryParams() { return maxQueryParams; } /** * Set the maximum allowed number of parameters that can be supplied to a parameterised query. This is effectively * the maximum bound for an "IN" list - i.e. SELECT * FROM foo WHERE foo.bar IN (?,?,?,...,?). If unset, this * defaults to 500. Typically, the limit for oracle databases is 1000. If, for any query that takes a list, the * size of the list is greater than this value, the query will be split into several smaller subqueries and the * results aggregated. * * @param maxQueryParams the maximum bound on the query list size - this should never be greater than that allowed * by the database, but can be smaller */ public void setMaxQueryParams(int maxQueryParams) { this.maxQueryParams = maxQueryParams; } /* DAO read methods */ public List<LoadDetails> getLoadDetails() { List results = template.query(LOAD_MONITOR_SELECT, new LoadDetailsMapper()); return (List<LoadDetails>) results; } public LoadDetails getLoadDetailsByAccession(String accession) { List results = template.query(LOAD_MONITOR_BY_ACC_SELECT, new Object[]{accession}, new LoadDetailsMapper()); return results.size() > 0 ? (LoadDetails) results.get(0) : null; } public List<Experiment> getAllExperiments() { List results = template.query(EXPERIMENTS_SELECT, new ExperimentMapper()); return (List<Experiment>) results; } public List<Experiment> getAllExperimentsPendingIndexing() { List results = template.query(EXPERIMENTS_PENDING_INDEX_SELECT, new ExperimentMapper()); return (List<Experiment>) results; } public List<Experiment> getAllExperimentsPendingNetCDFs() { List results = template.query(EXPERIMENTS_PENDING_NETCDF_SELECT, new ExperimentMapper()); return (List<Experiment>) results; } public List<Experiment> getAllExperimentsPendingAnalytics() { List results = template.query(EXPERIMENTS_PENDING_ANALYTICS_SELECT, new ExperimentMapper()); return (List<Experiment>) results; } /** * Gets a single experiment from the Atlas Database, queried by the accession of the experiment. * * @param accession the experiment's accession number (usually in the format E-ABCD-1234) * @return an object modelling this experiment */ public Experiment getExperimentByAccession(String accession) { List results = template.query(EXPERIMENT_BY_ACC_SELECT, new Object[]{accession}, new ExperimentMapper()); return results.size() > 0 ? (Experiment) results.get(0) : null; } /** * Fetches all genes in the database. Note that genes are not automatically prepopulated with property information, * to keep query time down. If you require this data, you can fetch it for the list of genes you want to obtain * properties for by calling {@link #getPropertiesForGenes(java.util.List)}. Genes <b>are</b> prepopulated with * design element information, however. * * @return the list of all genes in the database */ public List<Gene> getAllGenes() { // do the first query to fetch genes without design elements List results = template.query(GENES_SELECT, new GeneMapper()); // do the second query to obtain design elements List<Gene> genes = (List<Gene>) results; // map genes to gene id Map<Integer, Gene> genesByID = new HashMap<Integer, Gene>(); for (Gene gene : genes) { // index this assay genesByID.put(gene.getGeneID(), gene); // also, initialize properties if null - once this method is called, you should never get an NPE if (gene.getDesignElementIDs() == null) { gene.setDesignElementIDs(new HashSet<Integer>()); } } // map of genes and their design elements GeneDesignElementMapper geneDesignElementMapper = new GeneDesignElementMapper(genesByID); // now query for design elements, and genes, by the experiment accession, and map them together template.query(DESIGN_ELEMENTS_AND_GENES_SELECT, geneDesignElementMapper); // and return return genes; } /** * Same as getAllGenes(), but doesn't do design elements. Sometime we just don't need them. * @return list of all genes */ public List<Gene> getAllGenesFast() { // do the query to fetch genes without design elements return (List<Gene>) template.query(GENES_SELECT, new GeneMapper()); } public Gene getGeneByIdentifier(String identifier) { // do the query to fetch gene without design elements List results = template.query(GENE_BY_IDENTIFIER, new Object[]{identifier}, new GeneMapper()); if (results.size() > 0) { Gene gene = (Gene) results.get(0); gene.setDesignElementIDs(getDesignElementsByGeneID(gene.getGeneID()).keySet()); return gene; } return null; } /** * Fetches all genes in the database that are pending indexing. Note that genes are not automatically prepopulated * with property information, to keep query time down. If you require this data, you can fetch it for the list of * genes you want to obtain properties for by calling {@link #getPropertiesForGenes(java.util.List)}. Genes * <b>are</b> prepopulated with design element information, however. * * @return the list of all genes in the database that are pending indexing */ public List<Gene> getAllPendingGenes() { // do the first query to fetch genes without design elements List results = template.query(GENES_PENDING_SELECT, new GeneMapper()); // do the second query to obtain design elements List<Gene> genes = (List<Gene>) results; // map genes to gene id Map<Integer, Gene> genesByID = new HashMap<Integer, Gene>(); for (Gene gene : genes) { // index this assay genesByID.put(gene.getGeneID(), gene); // also, initialize properties if null - once this method is called, you should never get an NPE if (gene.getDesignElementIDs() == null) { gene.setDesignElementIDs(new HashSet<Integer>()); } } // map of genes and their design elements GeneDesignElementMapper geneDesignElementMapper = new GeneDesignElementMapper(genesByID); // now query for design elements, and genes, by the experiment accession, and map them together template.query(DESIGN_ELEMENTS_AND_GENES_PENDING_SELECT, geneDesignElementMapper); // and return return genes; } /** * Fetches all genes in the database that are pending indexing. No properties or design elements, * when you dont' need that. * @return the list of all genes in the database that are pending indexing */ public List<Gene> getAllPendingGenesFast() { // do the query to fetch genes without design elements return (List<Gene>) template.query(GENES_PENDING_SELECT, new GeneMapper()); } /** * Fetches all genes for the given experiment accession. Note that genes are not automatically prepopulated with * property information, to keep query time down. If you require this data, you can fetch it for the list of genes * you want to obtain properties for by calling {@link #getPropertiesForGenes(java.util.List)}. Genes <b>are</b> * prepopulated with design element information, however. * * @param exptAccession the accession number of the experiment to query for * @return the list of all genes in the database for this experiment accession */ public List<Gene> getGenesByExperimentAccession(String exptAccession) { // do the first query to fetch genes without design elements log.debug("Querying for genes by experiment " + exptAccession); List results = template.query(GENES_BY_EXPERIMENT_ACCESSION, new Object[]{exptAccession}, new GeneMapper()); log.debug("Genes for " + exptAccession + " acquired"); // do the second query to obtain design elements List<Gene> genes = (List<Gene>) results; // map genes to gene id Map<Integer, Gene> genesByID = new HashMap<Integer, Gene>(); for (Gene gene : genes) { // index this assay genesByID.put(gene.getGeneID(), gene); // also, initialize properties if null - once this method is called, you should never get an NPE if (gene.getDesignElementIDs() == null) { gene.setDesignElementIDs(new HashSet<Integer>()); } } // map of genes and their design elements GeneDesignElementMapper geneDesignElementMapper = new GeneDesignElementMapper(genesByID); // now query for design elements, and genes, by the experiment accession, and map them together log.debug("Querying for design elements mapped to genes of " + exptAccession); template.query(DESIGN_ELEMENTS_AND_GENES_BY_EXPERIMENT_ACCESSION, new Object[]{exptAccession}, geneDesignElementMapper); log.debug("Design elements for genes of " + exptAccession + " acquired"); // and return return genes; } public void getPropertiesForGenes(List<Gene> genes) { // populate the other info for these genes if (genes.size() > 0) { fillOutGeneProperties(genes); } } public int getGeneCount() { Object result = template.query(GENE_COUNT_SELECT, new ResultSetExtractor() { public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException { if (resultSet.next()) { return resultSet.getInt(1); } else { return 0; } } }); return (Integer) result; } /** * Gets all assays in the database. Note that, unlike other queries for assays, this query does not prepopulate all * property information. This is done to keep the query time don to a minimum. If you need this information, you * should populate it by calling {@link #getPropertiesForAssays(java.util.List)} on the list (or sublist) of assays * you wish to fetch properties for. Bear in mind that doing this for a very large list of assays will result in a * slow query. * * @return the list of all assays in the database */ public List<Assay> getAllAssays() { List results = template.query(ASSAYS_SELECT, new AssayMapper()); // and return return (List<Assay>) results; } public List<Assay> getAssaysByExperimentAccession( String experimentAccession) { List results = template.query(ASSAYS_BY_EXPERIMENT_ACCESSION, new Object[]{experimentAccession}, new AssayMapper()); List<Assay> assays = (List<Assay>) results; // populate the other info for these assays if (assays.size() > 0) { fillOutAssays(assays); } // and return return assays; } public List<Assay> getAssaysByExperimentAndArray(String experimentAccession, String arrayAccession) { List results = template.query(ASSAYS_BY_EXPERIMENT_AND_ARRAY_ACCESSION, new Object[]{experimentAccession, arrayAccession}, new AssayMapper()); List<Assay> assays = (List<Assay>) results; // populate the other info for these assays if (assays.size() > 0) { fillOutAssays(assays); } // and return return assays; } public void getPropertiesForAssays(List<Assay> assays) { // populate the other info for these assays if (assays.size() > 0) { fillOutAssays(assays); } } public void getExpressionValuesForAssays(List<Assay> assays) { // map assays to assay id Map<Integer, Assay> assaysByID = new HashMap<Integer, Assay>(); for (Assay assay : assays) { // index this assay assaysByID.put(assay.getAssayID(), assay); // also, initialize properties if null - once this method is called, you should never get an NPE if (assay.getExpressionValues() == null) { assay.setExpressionValues(new HashMap<Integer, Float>()); } } // maps properties to assays AssayExpressionValueMapper assayExpressionValueMapper = new AssayExpressionValueMapper(assaysByID); // query template for assays NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template); // if we have more than 'maxQueryParams' assays, split into smaller queries List<Integer> assayIDs = new ArrayList<Integer>(assaysByID.keySet()); boolean done = false; int startpos = 0; int endpos = maxQueryParams; while (!done) { List<Integer> assayIDsChunk; if (endpos > assayIDs.size()) { // we've reached the last segment, so query all of these assayIDsChunk = assayIDs.subList(startpos, assayIDs.size()); done = true; } else { // still more left - take next sublist and increment counts assayIDsChunk = assayIDs.subList(startpos, endpos); startpos = endpos; endpos += maxQueryParams; } // now query for properties that map to one of the samples in the sublist MapSqlParameterSource propertyParams = new MapSqlParameterSource(); propertyParams.addValue("assayids", assayIDsChunk); namedTemplate.query(EXPRESSION_VALUES_BY_RELATED_ASSAYS, propertyParams, assayExpressionValueMapper); } } public Map<Integer, Map<Integer, Float>> getExpressionValuesByExperimentAndArray( int experimentID, int arrayDesignID) { Object results = template.query(EXPRESSION_VALUES_BY_EXPERIMENT_AND_ARRAY, new Object[]{experimentID, arrayDesignID}, new ExpressionValueMapper()); return (Map<Integer, Map<Integer, Float>>) results; } public List<Sample> getSamplesByAssayAccession(String assayAccession) { List results = template.query(SAMPLES_BY_ASSAY_ACCESSION, new Object[]{assayAccession}, new SampleMapper()); List<Sample> samples = (List<Sample>) results; // populate the other info for these samples if (samples.size() > 0) { fillOutSamples(samples); } // and return return samples; } public List<Sample> getSamplesByExperimentAccession(String exptAccession) { List results = template.query(SAMPLES_BY_EXPERIMENT_ACCESSION, new Object[]{exptAccession}, new SampleMapper()); List<Sample> samples = (List<Sample>) results; // populate the other info for these samples if (samples.size() > 0) { fillOutSamples(samples); } // and return return samples; } public int getPropertyValueCount() { Object result = template.query(PROPERTY_VALUE_COUNT_SELECT, new ResultSetExtractor() { public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException { if (resultSet.next()) { return resultSet.getInt(1); } else { return 0; } } }); return (Integer) result; } /** * Returns all array designs in the underlying datasource. Note that, to reduce query times, this method does NOT * prepopulate ArrayDesigns with their associated design elements (unlike other methods to retrieve array designs * more specifically). For this reason, you should always ensure that after calling this method you use the {@link * #getDesignElementsForArrayDesigns(java.util.List)} method on the resulting list. * * @return the list of array designs, not prepopulated with design elements. */ public List<ArrayDesign> getAllArrayDesigns() { List results = template.query(ARRAY_DESIGN_SELECT, new ArrayDesignMapper()); return (List<ArrayDesign>) results; } public ArrayDesign getArrayDesignByAccession(String accession) { List results = template.query(ARRAY_DESIGN_BY_ACC_SELECT, new Object[]{accession}, new ArrayDesignMapper()); // get first result only ArrayDesign arrayDesign = results.size() > 0 ? (ArrayDesign) results.get(0) : null; if (arrayDesign != null) { fillOutArrayDesigns(Collections.singletonList(arrayDesign)); } return arrayDesign; } public List<ArrayDesign> getArrayDesignByExperimentAccession( String exptAccession) { List results = template.query(ARRAY_DESIGN_BY_EXPERIMENT_ACCESSION, new Object[]{exptAccession}, new ArrayDesignMapper()); // cast to correct type List<ArrayDesign> arrayDesigns = (List<ArrayDesign>) results; // and populate design elements for each if (arrayDesigns.size() > 0) { fillOutArrayDesigns(arrayDesigns); } return arrayDesigns; } public void getDesignElementsForArrayDesigns(List<ArrayDesign> arrayDesigns) { // populate the other info for these assays if (arrayDesigns.size() > 0) { fillOutArrayDesigns(arrayDesigns); } } /** * A convenience method that fetches the set of design elements by array design accession. Design elements are * recorded as a map, indexed by design element id and with a value of the design element accession. The set of * design element ids contains no duplicates, and the results that are returned are the internal database ids for * design elements. This takes the accession of the array design as a parameter. * * @param arrayDesignAccession the accession number of the array design to query for * @return the map of design element accessions indexed by unique design element id integers */ public Map<Integer, String> getDesignElementsByArrayAccession( String arrayDesignAccession) { Object results = template.query(DESIGN_ELEMENTS_BY_ARRAY_ACCESSION, new Object[]{arrayDesignAccession}, new DesignElementMapper()); return (Map<Integer, String>) results; } public Map<Integer, String> getDesignElementsByArrayID( int arrayDesignID) { Object results = template.query(DESIGN_ELEMENTS_BY_ARRAY_ID, new Object[]{arrayDesignID}, new DesignElementMapper()); return (Map<Integer, String>) results; } public Map<Integer, String> getDesignElementsByGeneID(int geneID) { Object results = template.query(DESIGN_ELEMENTS_BY_GENEID, new Object[]{geneID}, new DesignElementMapper()); return (Map<Integer, String>) results; } public List<ExpressionAnalysis> getExpressionAnalyticsByGeneID( int geneID) { List results = template.query(EXPRESSIONANALYTICS_BY_GENEID, new Object[]{geneID}, new ExpressionAnalyticsMapper()); return (List<ExpressionAnalysis>) results; } public List<ExpressionAnalysis> getExpressionAnalyticsByGeneIDEfEfv( int geneID, String ef, String efv) { List results = template.query(EXPRESSIONANALYTICS_BY_GENEID_EF_EFV, new Object[]{geneID, ef, efv}, new ExpressionAnalyticsMapper()); return (List<ExpressionAnalysis>) results; } public List<ExpressionAnalysis> getExpressionAnalyticsByGeneIDEfo( int geneID, Collection<String> efoAccessions) { List results = template.query(EXPRESSIONANALYTICS_BY_GENEID_EFO, new Object[]{geneID, new ArrayList<String>(efoAccessions)}, new ExpressionAnalyticsMapper()); return (List<ExpressionAnalysis>) results; } public List<ExpressionAnalysis> getExpressionAnalyticsByDesignElementID( int designElementID) { List results = template.query(EXPRESSIONANALYTICS_BY_DESIGNELEMENTID, new Object[]{designElementID}, new ExpressionAnalyticsMapper()); return (List<ExpressionAnalysis>) results; } public List<ExpressionAnalysis> getExpressionAnalyticsByExperimentID( int experimentID) { List results = template.query(EXPRESSIONANALYTICS_BY_EXPERIMENTID, new Object[]{experimentID}, new ExpressionAnalyticsMapper()); return (List<ExpressionAnalysis>) results; } public List<OntologyMapping> getOntologyMappings() { List results = template.query(ONTOLOGY_MAPPINGS_SELECT, new OntologyMappingMapper()); return (List<OntologyMapping>) results; } public List<OntologyMapping> getOntologyMappingsByOntology( String ontologyName) { List results = template.query(ONTOLOGY_MAPPINGS_BY_ONTOLOGY_NAME, new Object[]{ontologyName}, new OntologyMappingMapper()); return (List<OntologyMapping>) results; } public List<OntologyMapping> getOntologyMappingsByExperimentAccession( String experimentAccession) { List results = template.query(ONTOLOGY_MAPPINGS_BY_EXPERIMENT_ACCESSION, new Object[]{experimentAccession}, new OntologyMappingMapper()); return (List<OntologyMapping>) results; } public List<AtlasCount> getAtlasCountsByExperimentID(int experimentID) { List results = template.query(ATLAS_COUNTS_BY_EXPERIMENTID, new Object[]{experimentID}, new AtlasCountMapper()); return (List<AtlasCount>) results; } public List<Species> getAllSpecies() { List results = template.query(SPECIES_ALL, new SpeciesMapper()); return (List<Species>) results; } public List<Property> getAllProperties() { List results = template.query(PROPERTIES_ALL, new PropertyMapper()); return (List<Property>) results; } public Set<String> getAllGenePropertyNames() { List results = template.query(GENEPROPERTY_ALL_NAMES, new RowMapper() { public Object mapRow(ResultSet resultSet, int i) throws SQLException { return resultSet.getString(1); } }); return new HashSet<String>(results); } public List<AtlasTableResult> getAtlasResults(int[] geneIds, int[] exptIds, int upOrDown, String[] efvs) { NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template); MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("geneids", geneIds); parameters.addValue("exptids", exptIds); parameters.addValue("efvs", efvs); List results; if (upOrDown == 1) { results = namedTemplate.query(ATLAS_RESULTS_UP_BY_EXPERIMENTID_GENEID_AND_EFV, parameters, new AtlasResultMapper()); } else if (upOrDown == -1) { results = namedTemplate.query(ATLAS_RESULTS_DOWN_BY_EXPERIMENTID_GENEID_AND_EFV, parameters, new AtlasResultMapper()); } else { results = namedTemplate.query(ATLAS_RESULTS_UPORDOWN_BY_EXPERIMENTID_GENEID_AND_EFV, parameters, new AtlasResultMapper()); } return (List<AtlasTableResult>) results; } public AtlasStatistics getAtlasStatisticsByDataRelease(String dataRelease) { // manually count all experiments/genes/assays AtlasStatistics stats = new AtlasStatistics(); stats.setDataRelease(dataRelease); stats.setExperimentCount(template.queryForInt(EXPERIMENTS_COUNT)); stats.setAssayCount(template.queryForInt(ASSAYS_COUNT)); stats.setGeneCount(template.queryForInt(GENES_COUNT)); stats.setNewExperimentCount(0); stats.setPropertyValueCount(getPropertyValueCount()); return stats; } public Integer getBestDesignElementForExpressionProfile(int geneId, int experimentId, String ef) { try { return template.queryForInt(BEST_DESIGNELEMENTID_FOR_GENE, new Object[] { ef, experimentId, geneId }); } catch(EmptyResultDataAccessException e) { // no statistically best element found return null; } } /* DAO write methods */ public void writeLoadDetails(final String accession, final LoadStage loadStage, final LoadStatus loadStatus) { writeLoadDetails(accession, loadStage, loadStatus, LoadType.EXPERIMENT); } public void writeLoadDetails(final String accession, final LoadStage loadStage, final LoadStatus loadStatus, final LoadType loadType) { // execute this procedure... /* create or replace procedure load_progress( experiment_accession varchar ,stage varchar --load, netcdf, similarity, ranking, searchindex ,status varchar --done, pending ) */ SimpleJdbcCall procedure = new SimpleJdbcCall(template) .withProcedureName("ATLASLDR.LOAD_PROGRESS") .withoutProcedureColumnMetaDataAccess() .useInParameterNames("EXPERIMENT_ACCESSION") .useInParameterNames("STAGE") .useInParameterNames("STATUS") .useInParameterNames("LOAD_TYPE") .declareParameters(new SqlParameter("EXPERIMENT_ACCESSION", Types.VARCHAR)) .declareParameters(new SqlParameter("STAGE", Types.VARCHAR)) .declareParameters(new SqlParameter("STATUS", Types.VARCHAR)) .declareParameters(new SqlParameter("LOAD_TYPE", Types.VARCHAR)); // map parameters... MapSqlParameterSource params = new MapSqlParameterSource() .addValue("EXPERIMENT_ACCESSION", accession) .addValue("STAGE", loadStage.toString().toLowerCase()) .addValue("STATUS", loadStatus.toString().toLowerCase()) .addValue("LOAD_TYPE", loadType.toString().toLowerCase()); log.debug("Invoking load_progress stored procedure with parameters (" + accession + ", " + loadStage + ", " + loadStatus + ", " + loadType + ")"); procedure.execute(params); log.debug("load_progress stored procedure completed"); } /** * Writes the given experiment to the database, using the default transaction strategy configured for the * datasource. * * @param experiment the experiment to write */ public void writeExperiment(final Experiment experiment) { // execute this procedure... /* PROCEDURE "A2_EXPERIMENTSET" ( TheAccession varchar2 ,TheDescription varchar2 ,ThePerformer varchar2 ,TheLab varchar2 ) */ SimpleJdbcCall procedure = new SimpleJdbcCall(template) .withProcedureName("ATLASLDR.A2_EXPERIMENTSET") .withoutProcedureColumnMetaDataAccess() .useInParameterNames("THEACCESSION") .useInParameterNames("THEDESCRIPTION") .useInParameterNames("THEPERFORMER") .useInParameterNames("THELAB") .declareParameters(new SqlParameter("THEACCESSION", Types.VARCHAR)) .declareParameters(new SqlParameter("THEDESCRIPTION", Types.VARCHAR)) .declareParameters(new SqlParameter("THEPERFORMER", Types.VARCHAR)) .declareParameters(new SqlParameter("THELAB", Types.VARCHAR)); // map parameters... MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("THEACCESSION", experiment.getAccession()) .addValue("THEDESCRIPTION", experiment.getDescription()) .addValue("THEPERFORMER", experiment.getPerformer()) .addValue("THELAB", experiment.getLab()); procedure.execute(params); } /** * Writes the given assay to the database, using the default transaction strategy configured for the datasource. * * @param assay the assay to write */ public void writeAssay(final Assay assay) { // execute this procedure... /* PROCEDURE "A2_ASSAYSET" ( TheAccession varchar2 ,TheExperimentAccession varchar2 ,TheArrayDesignAccession varchar2 ,TheProperties PropertyTable ,TheExpressionValues ExpressionValueTable ) */ SimpleJdbcCall procedure = new SimpleJdbcCall(template) .withProcedureName("ATLASLDR.A2_ASSAYSET") .withoutProcedureColumnMetaDataAccess() .useInParameterNames("THEACCESSION") .useInParameterNames("THEEXPERIMENTACCESSION") .useInParameterNames("THEARRAYDESIGNACCESSION") .useInParameterNames("THEPROPERTIES") .useInParameterNames("THEEXPRESSIONVALUES") .declareParameters( new SqlParameter("THEACCESSION", Types.VARCHAR)) .declareParameters( new SqlParameter("THEEXPERIMENTACCESSION", Types.VARCHAR)) .declareParameters( new SqlParameter("THEARRAYDESIGNACCESSION", Types.VARCHAR)) .declareParameters( new SqlParameter("THEPROPERTIES", OracleTypes.ARRAY, "PROPERTYTABLE")) .declareParameters( new SqlParameter("THEEXPRESSIONVALUES", OracleTypes.ARRAY, "EXPRESSIONVALUETABLE")); // map parameters... List<Property> props = assay.getProperties() == null ? new ArrayList<Property>() : assay.getProperties(); Map<String, Float> evs = assay.getExpressionValuesByAccession() == null ? new HashMap<String, Float>() : assay.getExpressionValuesByAccession(); MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("THEACCESSION", assay.getAccession()) .addValue("THEEXPERIMENTACCESSION", assay.getExperimentAccession()) .addValue("THEARRAYDESIGNACCESSION", assay.getArrayDesignAccession()) .addValue("THEPROPERTIES", convertPropertiesToOracleARRAY(props), OracleTypes.ARRAY, "PROPERTYTABLE") .addValue("THEEXPRESSIONVALUES", convertExpressionValuesToOracleARRAY(evs), OracleTypes.ARRAY, "EXPRESSIONVALUETABLE"); // and execute procedure.execute(params); } /** * Writes the given sample to the database, using the default transaction strategy configured for the datasource. * * @param sample the sample to write */ public void writeSample(final Sample sample) { // execute this procedure... /* PROCEDURE "A2_SAMPLESET" ( p_Accession varchar2 , p_Assays AccessionTable , p_Properties PropertyTable , p_Species varchar2 , p_Channel varchar2 ) */ SimpleJdbcCall procedure = new SimpleJdbcCall(template) .withProcedureName("ATLASLDR.A2_SAMPLESET") .withoutProcedureColumnMetaDataAccess() .useInParameterNames("P_ACCESSION") .useInParameterNames("P_ASSAYS") .useInParameterNames("P_PROPERTIES") .useInParameterNames("P_SPECIES") .useInParameterNames("P_CHANNEL") .declareParameters( new SqlParameter("P_ACCESSION", Types.VARCHAR)) .declareParameters( new SqlParameter("P_ASSAYS", OracleTypes.ARRAY, "ACCESSIONTABLE")) .declareParameters( new SqlParameter("P_PROPERTIES", OracleTypes.ARRAY, "PROPERTYTABLE")) .declareParameters( new SqlParameter("P_SPECIES", Types.VARCHAR)) .declareParameters( new SqlParameter("P_CHANNEL", Types.VARCHAR)); // map parameters... MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("P_ACCESSION", sample.getAccession()) .addValue("P_ASSAYS", convertAssayAccessionsToOracleARRAY(sample.getAssayAccessions()), OracleTypes.ARRAY, "ACCESSIONTABLE") .addValue("P_PROPERTIES", convertPropertiesToOracleARRAY(sample.getProperties()), OracleTypes.ARRAY, "PROPERTYTABLE") .addValue("P_SPECIES", sample.getSpecies()) .addValue("P_CHANNEL", sample.getChannel()); // and execute procedure.execute(params); } /** * Writes expression analytics data back to the database, after post-processing by an external analytics process. * Expression analytics consist of p-values and t-statistics for each design element, annotated with a property and * property value. As such, for each annotated design element there should be unique analytics data for each * annotation. * * @param experimentAccession the accession of the experiment these analytics values belong to * @param property the name of the property for this set of analytics * @param propertyValue the property value for this set of analytics * @param pValues a map linking each design element to a pValue (a double) in the context of this * property/property value pair * @param tStatistics a map linking each design element to a tStatistic (a double) in the context of this * property/property value pair */ public void writeExpressionAnalytics(String experimentAccession, String property, String propertyValue, Map<Integer, Double> pValues, Map<Integer, Double> tStatistics) { // execute this procedure... /* PROCEDURE A2_AnalyticsSet( ExperimentAccession IN varchar2 ,Property IN varchar2 ,PropertyValue IN varchar2 ,ExpressionAnalytics ExpressionAnalyticsTable ) */ SimpleJdbcCall procedure = new SimpleJdbcCall(template) .withProcedureName("ATLASLDR.A2_ANALYTICSSET") .withoutProcedureColumnMetaDataAccess() .useInParameterNames("EXPERIMENTACCESSION") .useInParameterNames("PROPERTY") .useInParameterNames("PROPERTYVALUE") .useInParameterNames("EXPRESSIONANALYTICS") .declareParameters( new SqlParameter("EXPERIMENTACCESSION", Types.VARCHAR)) .declareParameters( new SqlParameter("PROPERTY", Types.VARCHAR)) .declareParameters( new SqlParameter("PROPERTYVALUE", Types.VARCHAR)) .declareParameters( new SqlParameter("EXPRESSIONANALYTICS", OracleTypes.ARRAY, "EXPRESSIONANALYTICSTABLE")); // map parameters... MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("EXPERIMENTACCESSION", experimentAccession) .addValue("PROPERTY", property) .addValue("PROPERTYVALUE", propertyValue) .addValue("EXPRESSIONANALYTICS", convertExpressionAnalyticsToOracleArray(pValues, tStatistics)); procedure.execute(params); } /* DAO delete methods */ /** * Deletes the experiment with the given accession from the database. If this experiment is not present, this does * nothing. * * @param experimentAccession the accession of the experiment to remove */ public void deleteExperiment(final String experimentAccession) { // execute this procedure... /* PROCEDURE A2_EXPERIMENTDELETE( Accession varchar2 ) */ SimpleJdbcCall procedure = new SimpleJdbcCall(template) .withProcedureName("ATLASLDR.A2_EXPERIMENTDELETE") .withoutProcedureColumnMetaDataAccess() .useInParameterNames("ACCESSION") .declareParameters(new SqlParameter("THEACCESSION", Types.VARCHAR)); // map parameters... MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("THEACCESSION", experimentAccession); procedure.execute(params); } /* utils methods for doing standard stuff */ private void fillOutArrayDesigns(List<ArrayDesign> arrayDesigns) { // map array designs to array design id Map<Integer, ArrayDesign> arrayDesignsByID = new HashMap<Integer, ArrayDesign>(); for (ArrayDesign array : arrayDesigns) { // index this array arrayDesignsByID.put(array.getArrayDesignID(), array); // also initialize design elements is null - once this method is called, you should never get an NPE if (array.getDesignElements() == null) { array.setDesignElements(new HashMap<Integer, String>()); } } NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template); // now query for design elements that map to one of these array designs ArrayDesignElementMapper arrayDesignElementMapper = new ArrayDesignElementMapper(arrayDesignsByID); MapSqlParameterSource arrayParams = new MapSqlParameterSource(); arrayParams.addValue("arraydesignids", arrayDesignsByID.keySet()); namedTemplate.query(DESIGN_ELEMENTS_BY_RELATED_ARRAY, arrayParams, arrayDesignElementMapper); } private void fillOutGeneProperties(List<Gene> genes) { // map genes to gene id Map<Integer, Gene> genesByID = new HashMap<Integer, Gene>(); for (Gene gene : genes) { // index this assay genesByID.put(gene.getGeneID(), gene); // also, initialize properties if null - once this method is called, you should never get an NPE if (gene.getProperties() == null) { gene.setProperties(new ArrayList<Property>()); } } // map of genes and their properties GenePropertyMapper genePropertyMapper = new GenePropertyMapper(genesByID); // query template for genes NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template); // if we have more than 'maxQueryParams' genes, split into smaller queries List<Integer> geneIDs = new ArrayList<Integer>(genesByID.keySet()); boolean done = false; int startpos = 0; int endpos = maxQueryParams; while (!done) { List<Integer> geneIDsChunk; if (endpos > geneIDs.size()) { // we've reached the last segment, so query all of these geneIDsChunk = geneIDs.subList(startpos, geneIDs.size()); done = true; } else { // still more left - take next sublist and increment counts geneIDsChunk = geneIDs.subList(startpos, endpos); startpos = endpos; endpos += maxQueryParams; } // now query for properties that map to one of these genes MapSqlParameterSource propertyParams = new MapSqlParameterSource(); propertyParams.addValue("geneids", geneIDsChunk); namedTemplate.query(PROPERTIES_BY_RELATED_GENES, propertyParams, genePropertyMapper); } } private void fillOutAssays(List<Assay> assays) { // map assays to assay id Map<Integer, Assay> assaysByID = new HashMap<Integer, Assay>(); for (Assay assay : assays) { // index this assay assaysByID.put(assay.getAssayID(), assay); // also, initialize properties if null - once this method is called, you should never get an NPE if (assay.getProperties() == null) { assay.setProperties(new ArrayList<Property>()); } } // maps properties to assays AssayPropertyMapper assayPropertyMapper = new AssayPropertyMapper(assaysByID); // query template for assays NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template); // if we have more than 'maxQueryParams' assays, split into smaller queries List<Integer> assayIDs = new ArrayList<Integer>(assaysByID.keySet()); boolean done = false; int startpos = 0; int endpos = maxQueryParams; while (!done) { List<Integer> assayIDsChunk; if (endpos > assayIDs.size()) { // we've reached the last segment, so query all of these assayIDsChunk = assayIDs.subList(startpos, assayIDs.size()); done = true; } else { // still more left - take next sublist and increment counts assayIDsChunk = assayIDs.subList(startpos, endpos); startpos = endpos; endpos += maxQueryParams; } // now query for properties that map to one of the samples in the sublist MapSqlParameterSource propertyParams = new MapSqlParameterSource(); propertyParams.addValue("assayids", assayIDsChunk); namedTemplate.query(PROPERTIES_BY_RELATED_ASSAYS, propertyParams, assayPropertyMapper); } } private void fillOutSamples(List<Sample> samples) { // map samples to sample id Map<Integer, Sample> samplesByID = new HashMap<Integer, Sample>(); for (Sample sample : samples) { samplesByID.put(sample.getSampleID(), sample); // also, initialize properties/assays if null - once this method is called, you should never get an NPE if (sample.getProperties() == null) { sample.setProperties(new ArrayList<Property>()); } if (sample.getAssayAccessions() == null) { sample.setAssayAccessions(new ArrayList<String>()); } } // maps properties and assays to relevant sample AssaySampleMapper assaySampleMapper = new AssaySampleMapper(samplesByID); SamplePropertyMapper samplePropertyMapper = new SamplePropertyMapper(samplesByID); // query template for samples NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template); // if we have more than 'maxQueryParams' samples, split into smaller queries List<Integer> sampleIDs = new ArrayList<Integer>(samplesByID.keySet()); boolean done = false; int startpos = 0; int endpos = maxQueryParams; while (!done) { List<Integer> sampleIDsChunk; if (endpos > sampleIDs.size()) { sampleIDsChunk = sampleIDs.subList(startpos, sampleIDs.size()); done = true; } else { sampleIDsChunk = sampleIDs.subList(startpos, endpos); startpos = endpos; endpos += maxQueryParams; } // now query for assays that map to one of these samples MapSqlParameterSource assayParams = new MapSqlParameterSource(); assayParams.addValue("sampleids", sampleIDsChunk); namedTemplate.query(ASSAYS_BY_RELATED_SAMPLES, assayParams, assaySampleMapper); // now query for properties that map to one of these samples MapSqlParameterSource propertyParams = new MapSqlParameterSource(); propertyParams.addValue("sampleids", sampleIDsChunk); namedTemplate.query(PROPERTIES_BY_RELATED_SAMPLES, propertyParams, samplePropertyMapper); } } private SqlTypeValue convertPropertiesToOracleARRAY(final List<Property> properties) { return new AbstractSqlTypeValue() { protected Object createTypeValue(Connection connection, int sqlType, String typeName) throws SQLException { // this should be creating an oracle ARRAY of properties // the array of STRUCTS representing each property Object[] propArrayValues = new Object[properties.size()]; // convert each property to an oracle STRUCT int i = 0; Object[] propStructValues = new Object[4]; for (Property property : properties) { // array representing the values to go in the STRUCT propStructValues[0] = property.getAccession(); propStructValues[1] = property.getName(); propStructValues[2] = property.getValue(); propStructValues[3] = property.isFactorValue(); // descriptor for PROPERTY type StructDescriptor structDescriptor = StructDescriptor.createDescriptor("PROPERTY", connection); // each array value is a new STRUCT propArrayValues[i++] = new STRUCT(structDescriptor, connection, propStructValues); } // created the array of STRUCTs, group into ARRAY ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(typeName, connection); return new ARRAY(arrayDescriptor, connection, propArrayValues); } }; } private SqlTypeValue convertExpressionValuesToOracleARRAY(final Map<String, Float> expressionValues) { return new AbstractSqlTypeValue() { protected Object createTypeValue(Connection connection, int sqlType, String typeName) throws SQLException { // this should be creating an oracle ARRAY of expression values // the array of STRUCTS representing each expression value Object[] evArrayValues = new Object[expressionValues.size()]; // convert each property to an oracle STRUCT // descriptor for EXPRESSIONVALUE type StructDescriptor structDescriptor = StructDescriptor.createDescriptor("EXPRESSIONVALUE", connection); int i = 0; Object[] evStructValues = new Object[2]; for (Map.Entry<String, Float> expressionValue : expressionValues.entrySet()) { // array representing the values to go in the STRUCT evStructValues[0] = expressionValue.getKey(); evStructValues[1] = expressionValue.getValue(); evArrayValues[i++] = new STRUCT(structDescriptor, connection, evStructValues); } // created the array of STRUCTs, group into ARRAY ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(typeName, connection); return new ARRAY(arrayDescriptor, connection, evArrayValues); } }; } private SqlTypeValue convertAssayAccessionsToOracleARRAY(final List<String> assayAccessions) { return new AbstractSqlTypeValue() { protected Object createTypeValue(Connection connection, int sqlType, String typeName) throws SQLException { Object[] accessions = new Object[assayAccessions.size()]; int i = 0; for (String assayAccession : assayAccessions) { accessions[i++] = assayAccession; } // created the array of STRUCTs, group into ARRAY ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(typeName, connection); return new ARRAY(arrayDescriptor, connection, accessions); } }; } private SqlTypeValue convertExpressionAnalyticsToOracleArray(final Map<Integer, Double> pValues, final Map<Integer, Double> tStatistics) { if (pValues.size() != tStatistics.size()) { throw new RuntimeException( "Cannot store analytics - inconsistent design element counts for pValues and tStatistics"); } else { final int deCount = pValues.size(); return new AbstractSqlTypeValue() { protected Object createTypeValue(Connection connection, int sqlType, String typeName) throws SQLException { // this should be creating an oracle ARRAY of 'expressionAnalytics' // the array of STRUCTS representing each property Object[] expressionAnalytics = new Object[deCount]; // convert each expression analytic pair into an oracle STRUCT // descriptor for EXPRESSIONANALYTICS type StructDescriptor structDescriptor = StructDescriptor.createDescriptor("EXPRESSIONANALYTICS", connection); int i=0; Object[] expressionAnalyticsValues = new Object[3]; for (int designElement : pValues.keySet()) { // array representing the values to go in the STRUCT // Note the floatValue - EXPRESSIONANALYTICS structure assumes floats expressionAnalyticsValues[0] = designElement; expressionAnalyticsValues[1] = pValues.get(designElement); expressionAnalyticsValues[2] = tStatistics.get(designElement); expressionAnalytics[i++] = new STRUCT(structDescriptor, connection, expressionAnalyticsValues); } // created the array of STRUCTs, group into ARRAY ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(typeName, connection); return new ARRAY(arrayDescriptor, connection, expressionAnalytics); } }; } } private class LoadDetailsMapper implements RowMapper { public Object mapRow(ResultSet resultSet, int i) throws SQLException { LoadDetails details = new LoadDetails(); // accession, netcdf, similarity, ranking, searchindex details.setAccession(resultSet.getString(1)); details.setStatus(resultSet.getString(2)); details.setNetCDF(resultSet.getString(3)); details.setSimilarity(resultSet.getString(4)); details.setRanking(resultSet.getString(5)); details.setSearchIndex(resultSet.getString(6)); details.setLoadType(resultSet.getString(7)); return details; } } private class ExperimentMapper implements RowMapper { public Object mapRow(ResultSet resultSet, int i) throws SQLException { Experiment experiment = new Experiment(); experiment.setAccession(resultSet.getString(1)); experiment.setDescription(resultSet.getString(2)); experiment.setPerformer(resultSet.getString(3)); experiment.setLab(resultSet.getString(4)); experiment.setExperimentID(resultSet.getInt(5)); return experiment; } } private class GeneMapper implements RowMapper { public Gene mapRow(ResultSet resultSet, int i) throws SQLException { Gene gene = new Gene(); gene.setGeneID(resultSet.getInt(1)); gene.setIdentifier(resultSet.getString(2)); gene.setName(resultSet.getString(3)); gene.setSpecies(resultSet.getString(4)); return gene; } } private class AssayMapper implements RowMapper { public Object mapRow(ResultSet resultSet, int i) throws SQLException { Assay assay = new Assay(); assay.setAccession(resultSet.getString(1)); assay.setExperimentAccession(resultSet.getString(2)); assay.setArrayDesignAcession(resultSet.getString(3)); assay.setAssayID(resultSet.getInt(4)); return assay; } } private class ExpressionValueMapper implements ResultSetExtractor { public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException { // maps assay ID (int) to a map of expression values - which is... // a map of design element IDs (int) to expression value (float) Map<Integer, Map<Integer, Float>> assayToEVs = new HashMap<Integer, Map<Integer, Float>>(); while (resultSet.next()) { // get assay ID key int assayID = resultSet.getInt(1); // get design element id key int designElementID = resultSet.getInt(2); // get expression value float value = resultSet.getFloat(3); // check assay key - can we add new expression value to existing map? if (!assayToEVs.containsKey(assayID)) { // if not, create a new expression values maps assayToEVs.put(assayID, new HashMap<Integer, Float>()); } // insert the expression value map into the assay-linked map assayToEVs.get(assayID).put(designElementID, value); } return assayToEVs; } } private class AssayExpressionValueMapper implements RowMapper { private Map<Integer, Assay> assaysByID; public AssayExpressionValueMapper(Map<Integer, Assay> assaysByID) { this.assaysByID = assaysByID; } public Object mapRow(ResultSet resultSet, int i) throws SQLException { // get assay ID key int assayID = resultSet.getInt(1); // get design element id key int designElementID = resultSet.getInt(2); // get expression value float value = resultSet.getFloat(3); assaysByID.get(assayID).getExpressionValues().put(designElementID, value); return null; } } private class SampleMapper implements RowMapper { public Object mapRow(ResultSet resultSet, int i) throws SQLException { Sample sample = new Sample(); sample.setAccession(resultSet.getString(1)); sample.setSpecies(resultSet.getString(2)); sample.setChannel(resultSet.getString(3)); sample.setSampleID(resultSet.getInt(4)); return sample; } } private class AssaySampleMapper implements RowMapper { Map<Integer, Sample> samplesMap; public AssaySampleMapper(Map<Integer, Sample> samplesMap) { this.samplesMap = samplesMap; } public Object mapRow(ResultSet resultSet, int i) throws SQLException { int sampleID = resultSet.getInt(1); samplesMap.get(sampleID).addAssayAccession(resultSet.getString(2)); return null; } } private class ArrayDesignMapper implements RowMapper { public Object mapRow(ResultSet resultSet, int i) throws SQLException { ArrayDesign array = new ArrayDesign(); array.setAccession(resultSet.getString(1)); array.setType(resultSet.getString(2)); array.setName(resultSet.getString(3)); array.setProvider(resultSet.getString(4)); array.setArrayDesignID(resultSet.getInt(5)); return array; } } private class DesignElementMapper implements ResultSetExtractor { public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException { Map<Integer, String> designElements = new HashMap<Integer, String>(); while (resultSet.next()) { designElements.put(resultSet.getInt(1), resultSet.getString(2)); } return designElements; } } private class ExpressionAnalyticsMapper implements RowMapper { public Object mapRow(ResultSet resultSet, int i) throws SQLException { ExpressionAnalysis ea = new ExpressionAnalysis(); ea.setEfName(resultSet.getString(1)); ea.setEfvName(resultSet.getString(2)); ea.setExperimentID(resultSet.getInt(3)); ea.setDesignElementID(resultSet.getInt(4)); ea.setTStatistic(resultSet.getDouble(5)); ea.setPValAdjusted(resultSet.getDouble(6)); ea.setEfId(resultSet.getInt(7)); ea.setEfvId(resultSet.getInt(8)); return ea; } } private class OntologyMappingMapper implements RowMapper { public Object mapRow(ResultSet resultSet, int i) throws SQLException { OntologyMapping mapping = new OntologyMapping(); mapping.setExperimentAccession(resultSet.getString(1)); mapping.setProperty(resultSet.getString(2)); mapping.setPropertyValue(resultSet.getString(3)); mapping.setOntologyTerm(resultSet.getString(4)); mapping.setSampleProperty(resultSet.getBoolean(5)); mapping.setAssayProperty(resultSet.getBoolean(6)); mapping.setFactorValue(resultSet.getBoolean(7)); mapping.setExperimentId(resultSet.getLong(8)); return mapping; } } private class ArrayDesignElementMapper implements RowMapper { private Map<Integer, ArrayDesign> arrayByID; public ArrayDesignElementMapper(Map<Integer, ArrayDesign> arraysByID) { this.arrayByID = arraysByID; } public Object mapRow(ResultSet resultSet, int i) throws SQLException { int assayID = resultSet.getInt(1); Integer id = resultSet.getInt(2); String acc = resultSet.getString(3); arrayByID.get(assayID).getDesignElements().put(id, acc); return null; } } private class AssayPropertyMapper implements RowMapper { private Map<Integer, Assay> assaysByID; public AssayPropertyMapper(Map<Integer, Assay> assaysByID) { this.assaysByID = assaysByID; } public Object mapRow(ResultSet resultSet, int i) throws SQLException { Property property = new Property(); int assayID = resultSet.getInt(1); property.setName(resultSet.getString(2)); property.setValue(resultSet.getString(3)); property.setFactorValue(resultSet.getBoolean(4)); assaysByID.get(assayID).addProperty(property); return property; } } private class SamplePropertyMapper implements RowMapper { private Map<Integer, Sample> samplesByID; public SamplePropertyMapper(Map<Integer, Sample> samplesByID) { this.samplesByID = samplesByID; } public Object mapRow(ResultSet resultSet, int i) throws SQLException { Property property = new Property(); int sampleID = resultSet.getInt(1); property.setName(resultSet.getString(2)); property.setValue(resultSet.getString(3)); property.setFactorValue(resultSet.getBoolean(4)); samplesByID.get(sampleID).addProperty(property); return property; } } private class GenePropertyMapper implements RowMapper { private Map<Integer, Gene> genesByID; public GenePropertyMapper(Map<Integer, Gene> genesByID) { this.genesByID = genesByID; } public Object mapRow(ResultSet resultSet, int i) throws SQLException { Property property = new Property(); int geneID = resultSet.getInt(1); property.setName(resultSet.getString(2)); property.setValue(resultSet.getString(3)); property.setFactorValue(false); genesByID.get(geneID).addProperty(property); return property; } } private class GeneDesignElementMapper implements RowMapper { private Map<Integer, Gene> genesByID; public GeneDesignElementMapper(Map<Integer, Gene> genesByID) { this.genesByID = genesByID; } public Object mapRow(ResultSet resultSet, int i) throws SQLException { int geneID = resultSet.getInt(1); int designElementID = resultSet.getInt(2); genesByID.get(geneID).getDesignElementIDs().add(designElementID); return designElementID; } } // todo - AtlasCount and AtlasResult can probably be consolidated to link a collection of genes to atlas results private class AtlasCountMapper implements RowMapper { public Object mapRow(ResultSet resultSet, int i) throws SQLException { AtlasCount atlasCount = new AtlasCount(); atlasCount.setProperty(resultSet.getString(2)); atlasCount.setPropertyValue(resultSet.getString(3)); atlasCount.setUpOrDown(resultSet.getString(4)); atlasCount.setGeneCount(resultSet.getInt(6)); atlasCount.setPropertyId(resultSet.getInt(7)); atlasCount.setPropertyValueId(resultSet.getInt(8)); return atlasCount; } } private class AtlasResultMapper implements RowMapper { public Object mapRow(ResultSet resultSet, int i) throws SQLException { AtlasTableResult atlasTableResult = new AtlasTableResult(); atlasTableResult.setExperimentID(resultSet.getInt(1)); atlasTableResult.setGeneID(resultSet.getInt(2)); atlasTableResult.setProperty(resultSet.getString(3)); atlasTableResult.setPropertyValue(resultSet.getString(4)); atlasTableResult.setUpOrDown(resultSet.getString(5)); atlasTableResult.setPValAdj(resultSet.getDouble(6)); return atlasTableResult; } } private static class SpeciesMapper implements RowMapper { public Object mapRow(ResultSet resultSet, int i) throws SQLException { return new Species(resultSet.getInt(1), resultSet.getString(2)); } } private static class PropertyMapper implements RowMapper { public Object mapRow(ResultSet resultSet, int i) throws SQLException { Property property = new Property(); property.setPropertyId(resultSet.getInt(1)); property.setAccession(resultSet.getString(2)); property.setName(resultSet.getString(2)); property.setPropertyValueId(resultSet.getInt(3)); property.setValue(resultSet.getString(4)); property.setFactorValue(resultSet.getInt(5) > 0); return property; } } }
package com.android.library.widget; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.FrameLayout; import android.widget.ListAdapter; import android.widget.ListView; import com.android.library.listener.OnLoadMoreListener; public class JListView extends ListView implements OnScrollListener { private OnLoadMoreListener mOnLoadMoreListener; private JFooter mFooterView; private boolean mIsLoadMoreEnable = true; private boolean mIsLoadingMore; private boolean mIsFooterAdded; public JListView(Context context) { super(context); init(context); } public JListView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { setOnScrollListener(this); mFooterView = new JFooter(context); mFooterView.setOnRetryListener(new JFooter.OnRetryListener() { @Override public void onRetry() { startLoadMore(false); } }); } @Override public void setAdapter(ListAdapter adapter) { if (!mIsFooterAdded) { addFooterView(mFooterView); mIsFooterAdded = true; } super.setAdapter(adapter); } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (!mIsLoadMoreEnable || mIsLoadingMore || isLoadMoreFailed() || totalItemCount <= 1) return; if (visibleItemCount + firstVisibleItem == totalItemCount) { startLoadMore(true); } } private void startLoadMore(boolean isAuto) { if (mIsLoadingMore) return; mIsLoadingMore = true; // mFooterView.ready(); mFooterView.loading(); if (mOnLoadMoreListener != null) mOnLoadMoreListener.onRefresh(isAuto); } public void stopLoadMore() { if (mIsLoadingMore) { mIsLoadingMore = false; // mFooterView.done(); } } public void stopLoadMoreFailed() { if (mIsLoadingMore) { mIsLoadingMore = false; mFooterView.failed(); } } public boolean isLoadingMore() { return mIsLoadingMore; } public boolean isLoadMoreEnable() { return mIsLoadMoreEnable; } public boolean isLoadMoreFailed() { return mFooterView != null && mFooterView.isFailed(); } public void setLoadMoreEnable(boolean enable) { if (mIsLoadMoreEnable == enable) return; mIsLoadMoreEnable = enable; if (enable) { mFooterView.ready(); } else { mFooterView.done(); } } public void setLoadMoreView(View v, FrameLayout.LayoutParams flLp) { mFooterView.setLoadingView(v, flLp); } public void setLoadMoreListener(OnLoadMoreListener l) { mOnLoadMoreListener = l; } }
package org.geomajas.global; /** * Constants which are used in Geomajas (and which are not local to a class). * * @author Joachim Van der Auwera * @since 1.6.0 */ @Api(allMethods = true) public interface GeomajasConstant { /** * Value to use when all aspects of the Feature should be lazy loaded. */ int FEATURE_INCLUDE_NONE = 0; /** * Include attributes in the {@link org.geomajas.layer.feature.Feature}. (speed issue) */ int FEATURE_INCLUDE_ATTRIBUTES = 1; /** * Include geometries in the {@link org.geomajas.layer.feature.Feature}. (speed issue) */ int FEATURE_INCLUDE_GEOMETRY = 2; /** * Include style definitions in the {@link org.geomajas.layer.feature.Feature}. (speed issue) */ int FEATURE_INCLUDE_STYLE = 4; /** * Include label string in the {@link org.geomajas.layer.feature.Feature}. (speed issue) */ int FEATURE_INCLUDE_LABEL = 8; /** * The Features should include all aspects. */ int FEATURE_INCLUDE_ALL = FEATURE_INCLUDE_ATTRIBUTES + FEATURE_INCLUDE_GEOMETRY + FEATURE_INCLUDE_STYLE + FEATURE_INCLUDE_LABEL; /** * Dummy interface implementation to keep GWT happy. */ public static class GeomajasConstantImpl implements GeomajasConstant { /** * Dummy method to keep checkstyle from complaining. */ public void dummy() { // nothing to do, just to keep checkstyle busy } } }
import java.sql.*; import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import static spark.Spark.*; import pro.tmedia.CardController; import pro.tmedia.CardService; import pro.tmedia.JsonUtil; import spark.template.freemarker.FreeMarkerEngine; import spark.ModelAndView; import static spark.Spark.get; import com.heroku.sdk.jdbc.DatabaseUrl; public class Main { public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); new CardController(new CardService()); /*get("/is-server-available-status", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("message", "Server is available!"); return new ModelAndView(attributes, "index.ftl"); }, new FreeMarkerEngine());*/ get("/is-server-available-status", (req, res) -> "Server is available!", JsonUtil.json()); get("/depot", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "depot.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); /* Using DB with recording of "mantras" */ get("/", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS mantra (wisdom varchar, tick timestamp)"); //stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT wisdom FROM mantra"); ArrayList<String> output = new ArrayList<String>(); output.add("<button>Записать</button><button>Сохранить</button><div id=\"speech-box\">...</div><br/>"); while (rs.next()) { //output.add( "Read from DB: " + rs.getTimestamp("tick")); //output.add( "Read from DB: " + rs.getString("wisdom")); output.add( "<div class=\"wisdom\" style=\"background: #CCCCCC;\">" + rs.getString("wisdom") + "</div>"); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); get("/mantra/create", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS mantra (wisdom varchar, tick timestamp)"); stmt.executeUpdate("INSERT INTO mantra (wisdom,tick) VALUES ('" + req.queryParams("wisdom") + "',now())"); } catch (Exception e) { //attributes.put("message", "There was an error: " + e); //return new ModelAndView(attributes, "error.ftl"); return "There was an error: " + e; } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } return "Created OK"; }); get("/mantra/list", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); String output = "["; try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS mantra (wisdom varchar, tick timestamp)"); ResultSet rs = stmt.executeQuery("SELECT wisdom FROM mantra"); if(rs.next()) output += ( "\"" + rs.getString("wisdom") + "\""); while (rs.next()) { output += ( ", \"" + rs.getString("wisdom") + "\""); } } catch (Exception e) { //attributes.put("message", "There was an error: " + e); //return new ModelAndView(attributes, "error.ftl"); return "There was an error: " + e; } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } output += "]"; return output; }); enableCORS("jsbin.com", "GET", ""); } // Enables CORS on requests. This method is an initialization method and should be called once. private static void enableCORS(final String origin, final String methods, final String headers) {
package com.willy.ratingbar; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.DrawableRes; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import java.util.LinkedHashMap; import java.util.Map; public class BaseRatingBar extends LinearLayout implements SimpleRatingBar { public interface OnRatingChangeListener { void onRatingChange(BaseRatingBar ratingBar, int rating); } public static final String TAG = "SimpleRatingBar"; public static final int MAX_CLICK_DURATION = 200; private static final int MAX_CLICK_DISTANCE = 5; private int mNumStars = 5; private int mRating = 0; private int mPreviousRating = 0; private int mPadding = 20; private float mStartX; private float mStartY; protected Drawable mEmptyDrawable; protected Drawable mFilledDrawable; private OnRatingChangeListener mOnRatingChangeListener; protected Map<ImageView, Boolean> mRatingViewStatus; public BaseRatingBar(Context context) { this(context, null); } /* Call by xml layout */ public BaseRatingBar(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } /** * @param context context * @param attrs attributes from XML => app:mainText="mainText" * @param defStyleAttr attributes from default style (Application theme or activity theme) */ public BaseRatingBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatingBarAttributes); mNumStars = typedArray.getInt(R.styleable.RatingBarAttributes_numStars, mNumStars); mPadding = typedArray.getInt(R.styleable.RatingBarAttributes_starPadding, mPadding); mRating = typedArray.getInt(R.styleable.RatingBarAttributes_rating, mRating); mEmptyDrawable = typedArray.getDrawable(R.styleable.RatingBarAttributes_drawableEmpty); mFilledDrawable = typedArray.getDrawable(R.styleable.RatingBarAttributes_drawableFilled); typedArray.recycle(); if (mEmptyDrawable == null) { mEmptyDrawable = getResources().getDrawable(R.drawable.empty); } if (mFilledDrawable == null) { mFilledDrawable = getResources().getDrawable(R.drawable.filled); } initRatingView(); } private void initRatingView() { mRatingViewStatus = new LinkedHashMap<>(); for (int i = 1; i <= mNumStars; i++) { ImageView ratingView; if (i <= mRating) { ratingView = getRatingView(i, mFilledDrawable); mRatingViewStatus.put(ratingView, true); } else { ratingView = getRatingView(i, mEmptyDrawable); mRatingViewStatus.put(ratingView, false); } addView(ratingView); } setRating(mRating); } private ImageView getRatingView(final int ratingViewId, Drawable drawable) { ImageView imageView = new ImageView(getContext()); imageView.setId(ratingViewId); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(mPadding, mPadding, mPadding, mPadding); imageView.setImageDrawable(drawable); return imageView; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return true; } @Override public boolean onTouchEvent(MotionEvent event) { float eventX = event.getX(); float eventY = event.getY(); int rating; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mStartX = eventX; mStartY = eventY; mPreviousRating = mRating; modifyRating(eventX); break; case MotionEvent.ACTION_MOVE: modifyRating(eventX); break; case MotionEvent.ACTION_UP: if (!isClickEvent(mStartX, eventX, mStartY, eventY)) { return false; } for (final ImageView view : mRatingViewStatus.keySet()) { if (!isPositionInRatingView(eventX, view)) { continue; } rating = view.getId(); if (mPreviousRating == rating) { clearRating(); } else { setRating(view.getId()); } break; } } return true; } private void modifyRating(float eventX) { for (final ImageView view : mRatingViewStatus.keySet()) { if (eventX < view.getWidth() / 2f) { setRating(0); return; } if (isPositionInRatingView(eventX, view)) { int rating = view.getId(); setRating(rating); } } } private boolean isPositionInRatingView(float eventX, View ratingView) { return eventX > ratingView.getX() && eventX < ratingView.getX() + ratingView.getWidth(); } private void removeAllRatingViews() { mRatingViewStatus.clear(); removeAllViews(); } private void clearRating() { mRating = 0; if (mOnRatingChangeListener != null) { mOnRatingChangeListener.onRatingChange(BaseRatingBar.this, 0); } emptyRatingBar(); } private boolean isClickEvent(float startX, float endX, float startY, float endY) { float differenceX = Math.abs(startX - endX); float differenceY = Math.abs(startY - endY); return !(differenceX > MAX_CLICK_DISTANCE || differenceY > MAX_CLICK_DISTANCE); } /** * Retain this method to let other RatingBar can custom their decrease animation. */ protected void emptyRatingBar() { fillRatingBar(0); } protected void fillRatingBar(final int rating) { for (final ImageView view : mRatingViewStatus.keySet()) { if (view.getId() <= rating) { view.setImageDrawable(mFilledDrawable); mRatingViewStatus.put(view, true); } else { view.setImageDrawable(mEmptyDrawable); mRatingViewStatus.put(view, false); } } } @Override public void setNumStars(int numStars) { if (numStars <= 0) { return; } removeAllRatingViews(); mNumStars = numStars; initRatingView(); } @Override public int getNumStars() { return mNumStars; } @Override public void setRating(int rating) { if (!hasRatingViews()) { return; } if (rating > mNumStars) { rating = mNumStars; } if (rating < 0) { rating = 0; } if (mRating == rating) { return; } mRating = rating; if (mOnRatingChangeListener != null) { mOnRatingChangeListener.onRatingChange(this, mRating); } fillRatingBar(rating); } @Override public int getRating() { return mRating; } @Override public void setStarPadding(int ratingPadding) { if (ratingPadding < 0) { return; } if (!hasRatingViews()) { return; } mPadding = ratingPadding; for (final ImageView view : mRatingViewStatus.keySet()) { view.setPadding(mPadding, mPadding, mPadding, mPadding); } } @Override public int getStarPadding() { return mPadding; } @Override public void setEmptyDrawable(Drawable drawable) { mEmptyDrawable = drawable; if (!hasRatingViews()) { return; } for (Map.Entry<ImageView, Boolean> entry : mRatingViewStatus.entrySet()) { if (!entry.getValue()) { entry.getKey().setImageDrawable(drawable); } } } @Override public void setEmptyDrawableRes(@DrawableRes int res) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setEmptyDrawable(getContext().getDrawable(res)); } else { setEmptyDrawable(getContext().getResources().getDrawable(res)); } } @Override public void setFilledDrawable(Drawable drawable) { mFilledDrawable = drawable; if (!hasRatingViews()) { return; } for (Map.Entry<ImageView, Boolean> entry : mRatingViewStatus.entrySet()) { if (entry.getValue()) { entry.getKey().setImageDrawable(drawable); } } } @Override public void setFilledDrawableRes(@DrawableRes int res) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setFilledDrawable(getContext().getDrawable(res)); } else { setFilledDrawable(getContext().getResources().getDrawable(res)); } } private boolean hasRatingViews() { return mRatingViewStatus != null && mRatingViewStatus.size() > 0; } public void setOnRatingChangeListener(OnRatingChangeListener onRatingChangeListener) { mOnRatingChangeListener = onRatingChangeListener; } }
package arez.processor; import com.google.auto.common.SuperficialValidation; import com.google.auto.service.AutoService; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.TypeSpec; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedOptions; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import static javax.tools.Diagnostic.Kind.*; /** * Annotation processor that analyzes Arez annotated source and generates models from the annotations. */ @AutoService( Processor.class ) @SupportedAnnotationTypes( { "arez.annotations.*" } ) @SupportedSourceVersion( SourceVersion.RELEASE_8 ) @SupportedOptions( "arez.defer.unresolved" ) public final class ArezProcessor extends AbstractProcessor { @Nonnull private HashSet<TypeElement> _deferred = new HashSet<>(); private int _invalidTypeCount; private RoundEnvironment _env; @Override public boolean process( final Set<? extends TypeElement> annotations, final RoundEnvironment env ) { final TypeElement annotation = processingEnv.getElementUtils().getTypeElement( Constants.COMPONENT_ANNOTATION_CLASSNAME ); final Set<? extends Element> elements = env.getElementsAnnotatedWith( annotation ); final Map<String, String> options = processingEnv.getOptions(); final String deferUnresolvedValue = options.get( "arez.defer.unresolved" ); final boolean deferUnresolved = null == deferUnresolvedValue || "true".equals( deferUnresolvedValue ); _env = env; if ( deferUnresolved ) { final Collection<Element> elementsToProcess = getElementsToProcess( elements ); processElements( elementsToProcess, env ); if ( env.getRootElements().isEmpty() && !_deferred.isEmpty() ) { _deferred.forEach( this::processingErrorMessage ); _deferred.clear(); } } else { processElements( new ArrayList<>( elements ), env ); } if ( _env.processingOver() ) { if ( 0 != _invalidTypeCount ) { processingEnv .getMessager() .printMessage( ERROR, "ArezProcessor failed to process " + _invalidTypeCount + " types. See earlier warnings for further details." ); } _invalidTypeCount = 0; } _env = null; return true; } private void processingErrorMessage( @Nonnull final TypeElement target ) { reportError( "ArezProcessor unable to process " + target.getQualifiedName() + " because not all of its dependencies could be resolved. Check for " + "compilation errors or a circular dependency with generated code.", target ); } private void reportError( @Nonnull final String message, @Nullable final Element element ) { _invalidTypeCount++; if ( _env.errorRaised() || _env.processingOver() ) { processingEnv.getMessager().printMessage( ERROR, message, element ); } else { processingEnv.getMessager().printMessage( MANDATORY_WARNING, message, element ); } } private void processElements( @Nonnull final Collection<Element> elements, @Nonnull final RoundEnvironment env ) { for ( final Element element : elements ) { try { process( element ); } catch ( final IOException ioe ) { reportError( ioe.getMessage(), element ); } catch ( final ArezProcessorException e ) { final Element errorLocation = e.getElement(); final Element outerElement = getOuterElement( errorLocation ); if ( !env.getRootElements().contains( outerElement ) ) { final String location; if ( errorLocation instanceof ExecutableElement ) { final ExecutableElement executableElement = (ExecutableElement) errorLocation; final TypeElement typeElement = (TypeElement) executableElement.getEnclosingElement(); location = typeElement.getQualifiedName() + "." + executableElement.getSimpleName(); } else if ( errorLocation instanceof VariableElement ) { final VariableElement variableElement = (VariableElement) errorLocation; final TypeElement typeElement = (TypeElement) variableElement.getEnclosingElement(); location = typeElement.getQualifiedName() + "." + variableElement.getSimpleName(); } else { assert errorLocation instanceof TypeElement; final TypeElement typeElement = (TypeElement) errorLocation; location = typeElement.getQualifiedName().toString(); } final StringWriter sw = new StringWriter(); processingEnv.getElementUtils().printElements( sw, errorLocation ); sw.flush(); final String message = "An error was generated processing the element " + element.getSimpleName() + " but the error was triggered by code not currently being compiled but inherited or " + "implemented by the element and may not be highlighted by your tooling or IDE. The " + "error occurred at " + location + " and may look like:\n" + sw.toString(); reportError( e.getMessage(), element ); reportError( message, null ); } reportError( e.getMessage(), e.getElement() ); } catch ( final Throwable e ) { final StringWriter sw = new StringWriter(); e.printStackTrace( new PrintWriter( sw ) ); sw.flush(); final String message = "Unexpected error running the " + getClass().getName() + " processor. This has " + "resulted in a failure to process the code and has left the compiler in an invalid " + "state. Please report the failure to the developers so that it can be fixed.\n" + " Report the error at: https://github.com/arez/arez/issues\n" + "\n\n" + sw.toString(); reportError( message, element ); } } } @Nonnull private Collection<Element> getElementsToProcess( @Nonnull final Set<? extends Element> elements ) { final List<TypeElement> deferred = _deferred .stream() .map( e -> processingEnv.getElementUtils().getTypeElement( e.getQualifiedName() ) ) .collect( Collectors.toList() ); _deferred = new HashSet<>(); final ArrayList<Element> elementsToProcess = new ArrayList<>(); collectElementsToProcess( elements, elementsToProcess ); collectElementsToProcess( deferred, elementsToProcess ); return elementsToProcess; } private void collectElementsToProcess( @Nonnull final Collection<? extends Element> elements, @Nonnull final ArrayList<Element> elementsToProcess ) { for ( final Element element : elements ) { if ( SuperficialValidation.validateElement( element ) ) { elementsToProcess.add( element ); } else { _deferred.add( (TypeElement) element ); } } } /** * Return the outer enclosing element. * This is either the top-level class, interface, enum, etc within a package. * This helps identify the top level compilation units. */ @Nonnull private Element getOuterElement( @Nonnull final Element element ) { Element result = element; while ( !( result.getEnclosingElement() instanceof PackageElement ) ) { result = result.getEnclosingElement(); } return result; } private void process( @Nonnull final Element element ) throws IOException, ArezProcessorException { final PackageElement packageElement = processingEnv.getElementUtils().getPackageOf( element ); final TypeElement typeElement = (TypeElement) element; final ComponentDescriptor descriptor = parse( packageElement, typeElement ); emitTypeSpec( descriptor.getPackageName(), descriptor.buildType( processingEnv.getTypeUtils() ) ); if ( descriptor.needsDaggerIntegration() ) { if ( descriptor.needsDaggerComponentExtension() ) { if ( ComponentDescriptor.InjectMode.PROVIDE == descriptor.getInjectMode() ) { emitTypeSpec( descriptor.getPackageName(), Generator.buildProviderDaggerComponentExtension( descriptor ) ); } else { emitTypeSpec( descriptor.getPackageName(), Generator.buildConsumerDaggerComponentExtension( descriptor ) ); } } else if ( descriptor.needsDaggerModule() ) { emitTypeSpec( descriptor.getPackageName(), descriptor.buildComponentDaggerModule() ); } } if ( descriptor.hasRepository() ) { emitTypeSpec( descriptor.getPackageName(), descriptor.buildRepository( processingEnv.getTypeUtils() ) ); } } @Nonnull private ComponentDescriptor parse( @Nonnull final PackageElement packageElement, @Nonnull final TypeElement typeElement ) throws ArezProcessorException { if ( ElementKind.CLASS != typeElement.getKind() && ElementKind.INTERFACE != typeElement.getKind() ) { throw new ArezProcessorException( "@ArezComponent target must be a class or an interface", typeElement ); } else if ( typeElement.getModifiers().contains( Modifier.FINAL ) ) { throw new ArezProcessorException( "@ArezComponent target must not be final", typeElement ); } else if ( NestingKind.TOP_LEVEL != typeElement.getNestingKind() && !typeElement.getModifiers().contains( Modifier.STATIC ) ) { throw new ArezProcessorException( "@ArezComponent target must not be a non-static nested class", typeElement ); } // Is the component marked as generated final boolean generated = null != ProcessorUtil.findAnnotationByType( typeElement, Constants.GENERATED_ANNOTATION_CLASSNAME ) || null != ProcessorUtil.findAnnotationByType( typeElement, Constants.JAVA9_GENERATED_ANNOTATION_CLASSNAME ); final AnnotationMirror arezComponent = ProcessorUtil.getAnnotationByType( typeElement, Constants.COMPONENT_ANNOTATION_CLASSNAME ); final String declaredType = getAnnotationParameter( arezComponent, "name" ); final AnnotationValue nameIncludesIdValue = ProcessorUtil.findAnnotationValueNoDefaults( arezComponent, "nameIncludesId" ); final AnnotationMirror singletonAnnotation = ProcessorUtil.findAnnotationByType( typeElement, Constants.SINGLETON_ANNOTATION_CLASSNAME ); final boolean nameIncludesIdDefault = null == singletonAnnotation; final boolean nameIncludesId = null == nameIncludesIdValue ? nameIncludesIdDefault : (boolean) nameIncludesIdValue.getValue(); final boolean disposeOnDeactivate = getAnnotationParameter( arezComponent, "disposeOnDeactivate" ); final boolean observableFlag = isComponentObservableRequired( arezComponent, typeElement, disposeOnDeactivate ); final boolean disposeNotifierFlag = ProcessorUtil.isDisposableTrackableRequired( processingEnv.getElementUtils(), typeElement ); final boolean allowConcrete = getAnnotationParameter( arezComponent, "allowConcrete" ); final boolean allowEmpty = getAnnotationParameter( arezComponent, "allowEmpty" ); final List<AnnotationMirror> scopeAnnotations = typeElement.getAnnotationMirrors().stream().filter( this::isScopeAnnotation ).collect( Collectors.toList() ); final AnnotationMirror scopeAnnotation = scopeAnnotations.isEmpty() ? null : scopeAnnotations.get( 0 ); final List<VariableElement> fields = ProcessorUtil.getFieldElements( typeElement ); final boolean fieldInjections = fields.stream().anyMatch( this::hasInjectAnnotation ); final boolean methodInjections = ProcessorUtil.getMethods( typeElement, processingEnv.getElementUtils(), processingEnv.getTypeUtils() ) .stream() .anyMatch( this::hasInjectAnnotation ); final boolean nonConstructorInjections = fieldInjections || methodInjections; final VariableElement daggerParameter = getAnnotationParameter( arezComponent, "dagger" ); final String daggerMode = daggerParameter.getSimpleName().toString(); final String injectMode = getInjectMode( arezComponent, typeElement, scopeAnnotation, daggerMode, fieldInjections, methodInjections ); final boolean dagger = "ENABLE".equals( daggerMode ) || ( "AUTODETECT".equals( daggerMode ) && !"NONE".equals( injectMode ) && null != processingEnv.getElementUtils().getTypeElement( Constants.DAGGER_MODULE_CLASSNAME ) ); final boolean requireEquals = isEqualsRequired( arezComponent, typeElement ); final boolean requireVerify = isVerifyRequired( arezComponent, typeElement ); final boolean deferSchedule = getAnnotationParameter( arezComponent, "deferSchedule" ); final boolean isClassAbstract = typeElement.getModifiers().contains( Modifier.ABSTRACT ); if ( !isClassAbstract && !allowConcrete ) { throw new ArezProcessorException( "@ArezComponent target must be abstract unless the allowConcrete " + "parameter is set to true", typeElement ); } else if ( isClassAbstract && allowConcrete ) { throw new ArezProcessorException( "@ArezComponent target must be concrete if the allowConcrete " + "parameter is set to true", typeElement ); } final String type = ProcessorUtil.isSentinelName( declaredType ) ? typeElement.getSimpleName().toString() : declaredType; if ( !SourceVersion.isIdentifier( type ) ) { throw new ArezProcessorException( "@ArezComponent target specified an invalid type '" + type + "'. The " + "type must be a valid java identifier.", typeElement ); } else if ( SourceVersion.isKeyword( type ) ) { throw new ArezProcessorException( "@ArezComponent target specified an invalid type '" + type + "'. The " + "type must not be a java keyword.", typeElement ); } if ( !scopeAnnotations.isEmpty() && ProcessorUtil.getConstructors( typeElement ).size() > 1 ) { throw new ArezProcessorException( "@ArezComponent target has specified a scope annotation but has more than " + "one constructor and thus is not a candidate for injection", typeElement ); } if ( !"NONE".equals( injectMode ) && ProcessorUtil.getConstructors( typeElement ).size() > 1 ) { throw new ArezProcessorException( "@ArezComponent specified inject parameter but has more than one constructor", typeElement ); } if ( scopeAnnotations.size() > 1 ) { final List<String> scopes = scopeAnnotations.stream() .map( a -> processingEnv.getTypeUtils().asElement( a.getAnnotationType() ).asType().toString() ) .collect( Collectors.toList() ); throw new ArezProcessorException( "@ArezComponent target has specified multiple scope annotations: " + scopes, typeElement ); } if ( !observableFlag && disposeOnDeactivate ) { throw new ArezProcessorException( "@ArezComponent target has specified observable = DISABLE and " + "disposeOnDeactivate = true which is not a valid combination", typeElement ); } boolean generatesFactoryToInject = false; if ( dagger ) { final ExecutableElement ctor = ProcessorUtil.getConstructors( typeElement ).get( 0 ); assert null != ctor; final List<? extends VariableElement> perInstanceParameters = ctor.getParameters() .stream() .filter( f -> null != ProcessorUtil.findAnnotationByType( f, Constants.PER_INSTANCE_ANNOTATION_CLASSNAME ) ) .collect( Collectors.toList() ); if ( !perInstanceParameters.isEmpty() ) { if ( "PROVIDE".equals( injectMode ) ) { throw new ArezProcessorException( "@ArezComponent target has specified at least one @PerInstance " + "parameter on the constructor but has set inject parameter to PROVIDE. " + "The component cannot be provided to other components if the invoker " + "must supply per-instance parameters so either change the inject " + "parameter to CONSUME or remove the @PerInstance parameter.", ctor ); } generatesFactoryToInject = true; } } final List<ExecutableElement> methods = ProcessorUtil.getMethods( typeElement, processingEnv.getElementUtils(), processingEnv.getTypeUtils() ); final boolean generateToString = methods.stream(). noneMatch( m -> m.getSimpleName().toString().equals( "toString" ) && m.getParameters().size() == 0 && !( m.getEnclosingElement().getSimpleName().toString().equals( "Object" ) && "java.lang".equals( processingEnv.getElementUtils(). getPackageOf( m.getEnclosingElement() ).getQualifiedName().toString() ) ) ); final ComponentDescriptor descriptor = new ComponentDescriptor( processingEnv.getSourceVersion(), processingEnv.getElementUtils(), processingEnv.getTypeUtils(), type, nameIncludesId, allowEmpty, generated, observableFlag, disposeNotifierFlag, disposeOnDeactivate, injectMode, dagger, generatesFactoryToInject, nonConstructorInjections, requireEquals, requireVerify, scopeAnnotation, deferSchedule, generateToString, packageElement, typeElement ); descriptor.analyzeCandidateMethods( methods, processingEnv.getTypeUtils() ); descriptor.validate(); for ( final ObservableDescriptor observable : descriptor.getObservables() ) { if ( observable.expectSetter() ) { final TypeMirror returnType = observable.getGetterType().getReturnType(); final TypeMirror parameterType = observable.getSetterType().getParameterTypes().get( 0 ); if ( !processingEnv.getTypeUtils().isSameType( parameterType, returnType ) && !parameterType.toString().equals( returnType.toString() ) ) { throw new ArezProcessorException( "@Observable property defines a setter and getter with different types." + " Getter type: " + returnType + " Setter type: " + parameterType + ".", observable.getGetter() ); } } } final AnnotationMirror repository = ProcessorUtil.findAnnotationByType( typeElement, Constants.REPOSITORY_ANNOTATION_CLASSNAME ); if ( null != repository ) { final List<TypeElement> extensions = ProcessorUtil.getTypeMirrorsAnnotationParameter( processingEnv.getElementUtils(), typeElement, Constants.REPOSITORY_ANNOTATION_CLASSNAME, "extensions" ).stream(). map( typeMirror -> (TypeElement) processingEnv.getTypeUtils().asElement( typeMirror ) ). collect( Collectors.toList() ); final String name = getAnnotationParameter( repository, "name" ); final String repositoryInjectConfig = getRepositoryInjectMode( repository ); final String repositoryDaggerConfig = getRepositoryDaggerConfig( repository ); descriptor.configureRepository( name, extensions, repositoryInjectConfig, repositoryDaggerConfig ); } if ( !observableFlag && descriptor.hasRepository() ) { throw new ArezProcessorException( "@ArezComponent target has specified observable = DISABLE and " + "but is also annotated with the @Repository annotation which requires " + "that the observable != DISABLE.", typeElement ); } if ( descriptor.hasRepository() && null != ProcessorUtil.findAnnotationByType( typeElement, Constants.SINGLETON_ANNOTATION_CLASSNAME ) ) { throw new ArezProcessorException( "@ArezComponent target is annotated with both the " + "@arez.annotations.Repository annotation and the " + "javax.inject.Singleton annotation which is an invalid " + "combination.", typeElement ); } if ( !descriptor.isDisposeNotifier() && descriptor.hasRepository() ) { throw new ArezProcessorException( "@ArezComponent target has specified the disposeNotifier = DISABLE " + "annotation parameter but is also annotated with @Repository that " + "requires disposeNotifier = ENABLE.", typeElement ); } final boolean idRequired = isIdRequired( descriptor, arezComponent ); descriptor.setIdRequired( idRequired ); if ( !idRequired ) { if ( descriptor.hasRepository() ) { throw new ArezProcessorException( "@ArezComponent target has specified the idRequired = DISABLE " + "annotation parameter but is also annotated with @Repository that " + "requires idRequired = ENABLE.", typeElement ); } if ( descriptor.hasComponentIdMethod() ) { throw new ArezProcessorException( "@ArezComponent target has specified the idRequired = DISABLE " + "annotation parameter but also has annotated a method with @ComponentId " + "that requires idRequired = ENABLE.", typeElement ); } if ( descriptor.hasComponentIdRefMethod() ) { throw new ArezProcessorException( "@ArezComponent target has specified the idRequired = DISABLE " + "annotation parameter but also has annotated a method with @ComponentIdRef " + "that requires idRequired = ENABLE.", typeElement ); } } return descriptor; } private boolean isScopeAnnotation( @Nonnull final AnnotationMirror a ) { final Element element = processingEnv.getTypeUtils().asElement( a.getAnnotationType() ); return null != ProcessorUtil.findAnnotationByType( element, Constants.SCOPE_ANNOTATION_CLASSNAME ); } private boolean isComponentObservableRequired( @Nonnull final AnnotationMirror arezComponent, @Nonnull final TypeElement typeElement, final boolean disposeOnDeactivate ) { final VariableElement variableElement = getAnnotationParameter( arezComponent, "observable" ); switch ( variableElement.getSimpleName().toString() ) { case "ENABLE": return true; case "DISABLE": return false; default: return disposeOnDeactivate || null != ProcessorUtil.findAnnotationByType( typeElement, Constants.REPOSITORY_ANNOTATION_CLASSNAME ); } } @Nonnull private String getInjectMode( @Nonnull final AnnotationMirror arezComponent, @Nonnull final TypeElement typeElement, @Nullable final AnnotationMirror scopeAnnotation, final String daggerMode, final boolean fieldInjections, final boolean methodInjections ) { final VariableElement injectParameter = getAnnotationParameter( arezComponent, "inject" ); final String mode = injectParameter.getSimpleName().toString(); if ( "AUTODETECT".equals( mode ) ) { final boolean shouldInject = daggerMode.equals( "ENABLE" ) || null != scopeAnnotation || fieldInjections || methodInjections; return shouldInject ? "PROVIDE" : "NONE"; } else if ( "NONE".equals( mode ) ) { if ( daggerMode.equals( "ENABLE" ) ) { throw new ArezProcessorException( "@ArezComponent target has a dagger parameter that resolved to ENABLE " + "but the inject parameter is set to NONE and this is not a valid " + "combination of parameters.", typeElement ); } if ( fieldInjections ) { throw new ArezProcessorException( "@ArezComponent target has fields annotated with the javax.inject.Inject " + "annotation but the inject parameter is set to NONE and this is not a " + "valid scenario. Remove the @Inject annotation(s) or change the inject " + "parameter to a value other than NONE.", typeElement ); } if ( methodInjections ) { throw new ArezProcessorException( "@ArezComponent target has methods annotated with the javax.inject.Inject " + "annotation but the inject parameter is set to NONE and this is not a " + "valid scenario. Remove the @Inject annotation(s) or change the inject " + "parameter to a value other than NONE.", typeElement ); } if ( null != scopeAnnotation ) { throw new ArezProcessorException( "@ArezComponent target is annotated with scope annotation " + scopeAnnotation + " but the inject parameter is set to NONE and this " + "is not a valid scenario. Remove the scope annotation or change the " + "inject parameter to a value other than NONE.", typeElement ); } return mode; } else { return mode; } } private boolean isVerifyRequired( @Nonnull final AnnotationMirror arezComponent, @Nonnull final TypeElement typeElement ) { final VariableElement daggerParameter = getAnnotationParameter( arezComponent, "verify" ); switch ( daggerParameter.getSimpleName().toString() ) { case "ENABLE": return true; case "DISABLE": return false; default: return ProcessorUtil.getMethods( typeElement, processingEnv.getElementUtils(), processingEnv.getTypeUtils() ). stream().anyMatch( this::hasReferenceAnnotations ); } } private boolean hasReferenceAnnotations( @Nonnull final Element method ) { return null != ProcessorUtil.findAnnotationByType( method, Constants.REFERENCE_ANNOTATION_CLASSNAME ) || null != ProcessorUtil.findAnnotationByType( method, Constants.REFERENCE_ID_ANNOTATION_CLASSNAME ) || null != ProcessorUtil.findAnnotationByType( method, Constants.INVERSE_ANNOTATION_CLASSNAME ); } private boolean isEqualsRequired( @Nonnull final AnnotationMirror arezComponent, @Nonnull final TypeElement typeElement ) { final VariableElement injectParameter = getAnnotationParameter( arezComponent, "requireEquals" ); switch ( injectParameter.getSimpleName().toString() ) { case "ENABLE": return true; case "DISABLE": return false; default: return null != ProcessorUtil.findAnnotationByType( typeElement, Constants.REPOSITORY_ANNOTATION_CLASSNAME ); } } private boolean isIdRequired( @Nonnull final ComponentDescriptor descriptor, @Nonnull final AnnotationMirror arezComponent ) { final VariableElement injectParameter = getAnnotationParameter( arezComponent, "requireId" ); switch ( injectParameter.getSimpleName().toString() ) { case "ENABLE": return true; case "DISABLE": return false; default: return descriptor.hasRepository() || descriptor.hasComponentIdMethod() || descriptor.hasComponentIdRefMethod() || descriptor.hasInverses(); } } @Nonnull private String getRepositoryInjectMode( @Nonnull final AnnotationMirror repository ) { final VariableElement injectParameter = getAnnotationParameter( repository, "inject" ); return injectParameter.getSimpleName().toString(); } @Nonnull private String getRepositoryDaggerConfig( @Nonnull final AnnotationMirror repository ) { final VariableElement daggerParameter = getAnnotationParameter( repository, "dagger" ); return daggerParameter.getSimpleName().toString(); } private boolean hasInjectAnnotation( final Element method ) { return null != ProcessorUtil.findAnnotationByType( method, Constants.INJECT_ANNOTATION_CLASSNAME ); } @Nonnull private <T> T getAnnotationParameter( @Nonnull final AnnotationMirror annotation, @Nonnull final String parameterName ) { return ProcessorUtil.getAnnotationValue( processingEnv.getElementUtils(), annotation, parameterName ); } private void emitTypeSpec( @Nonnull final String packageName, @Nonnull final TypeSpec typeSpec ) throws IOException { JavaFile.builder( packageName, typeSpec ). skipJavaLangImports( true ). build(). writeTo( processingEnv.getFiler() ); } }
import java.sql.*; import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import java.net.URI; import java.net.URISyntaxException; import static spark.Spark.*; import spark.template.freemarker.FreeMarkerEngine; import spark.ModelAndView; import static spark.Spark.get; import com.heroku.sdk.jdbc.DatabaseUrl; public class Main { public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); Object r = new SignUpServer(); get("/hello", (req, res) -> "Hello World"); // get("/", (request, response) -> { // Map<String, Object> attributes = new HashMap<>(); // attributes.put("message", "Hello World!!!"); // return new ModelAndView(attributes, "index.ftl"); // }, new FreeMarkerEngine()); get("/db", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); } }
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import freemarker.template.Template; import freemarker.template.TemplateException; import org.telegram.telegrambots.ApiContextInitializer; import org.telegram.telegrambots.TelegramBotsApi; import org.telegram.telegrambots.exceptions.TelegramApiException; import spark.ModelAndView; import spark.template.freemarker.FreeMarkerEngine; import java.io.IOException; import java.io.StringWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static spark.Spark.*; public class Main { public static void main(String[] args) { testDrive(); } private static void initTelegram(){ ApiContextInitializer.init(); TelegramBotsApi botsApi = new TelegramBotsApi(); try { botsApi.registerBot(new AwesomeBot()); } catch (TelegramApiException e) { e.printStackTrace(); } } private static void testDrive(){ init(); render(System.getenv("JDBC_DB_URL")); renderDB(); } private static void init(){ port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); } private static void render(String output) { get("/", (request, response)-> { Map<String, Object> attributes = new HashMap<>(); attributes.put("message", output); return new ModelAndView(attributes, "error.ftl"); }, new FreeMarkerEngine()); } private static void renderDB(){ HikariConfig config = new HikariConfig(); //config.setDriverClassName("org.postgresql.Driver"); config.setJdbcUrl(System.getenv("JDBC_DB_URL") ); final HikariDataSource dataSource = (config.getJdbcUrl() != null) ? new HikariDataSource(config) : new HikariDataSource(); get("/db", (req, res) -> { Map<String, Object> attributes = new HashMap<>(); try(Connection connection = dataSource.getConnection()) { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id, full_name, username, photo, smile_at FROM employee"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getString("full_name")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } }, new FreeMarkerEngine()); } }
package aQute.bnd.url; import static aQute.libg.slf4j.GradleLogging.LIFECYCLE; import java.net.URL; import java.net.URLConnection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import aQute.bnd.service.Plugin; import aQute.bnd.service.Registry; import aQute.bnd.service.RegistryPlugin; import aQute.bnd.service.url.URLConnectionHandler; import aQute.lib.strings.Strings; import aQute.libg.glob.Glob; import aQute.service.reporter.Reporter; /** * Base class for the URL Connection handlers. This class implements some * convenient methods like the matching. In general you should subclass and * implement {@link #handle(URLConnection)}. Be aware to call the * {@link #matches(URLConnection)} method to verify the plugin is applicable. */ public class DefaultURLConnectionHandler implements URLConnectionHandler, Plugin, RegistryPlugin, Reporter { private final static Logger logger = LoggerFactory.getLogger(DefaultURLConnectionHandler.class); interface Config { String match(); } private final Set<Glob> matchers = new HashSet<Glob>(); private Reporter reporter; protected Registry registry = null; /** * Not doing anything is perfect ok */ public void handle(URLConnection connection) throws Exception {} /** * Verify if the URL matches one of our globs. If there are no globs, we * always return true. */ public boolean matches(URL url) { if (matchers.isEmpty()) return true; String string = url.toString(); for (Glob g : matchers) { if (g.matcher(string).matches()) return true; } return false; } /** * Convenience method to make it easier to verify connections * * @param connection The connection to match * @return true if this connection should be handled. */ protected boolean matches(URLConnection connection) { return matches(connection.getURL()); } /** * We are a @link {@link RegistryPlugin} for convenience to our subclasses. */ public void setRegistry(Registry registry) { this.registry = registry; } /** * Set the properties for this plugin. Subclasses should call this method * before they handle their own properties. */ public void setProperties(Map<String,String> map) throws Exception { String matches = map.get(MATCH); if (matches != null) { for (String p : matches.split("\\s*,\\s*")) { matchers.add(new Glob(p)); } } } public void setReporter(Reporter processor) { this.reporter = processor; } // Delegated reporter methods for convenience public List<String> getWarnings() { return reporter.getWarnings(); } public List<String> getErrors() { return reporter.getErrors(); } public Location getLocation(String msg) { return reporter.getLocation(msg); } public boolean isOk() { return reporter.isOk(); } public SetLocation error(String format, Object... args) { return reporter.error(format, args); } public SetLocation warning(String format, Object... args) { return reporter.warning(format, args); } /** * @deprecated Use SLF4J Logger.debug instead. */ @Deprecated public void trace(String format, Object... args) { if (logger.isDebugEnabled()) { logger.debug("{}", Strings.format(format, args)); } } /** * @deprecated Use SLF4J * Logger.info(aQute.libg.slf4j.GradleLogging.LIFECYCLE) * instead. */ @Deprecated public void progress(float progress, String format, Object... args) { if (logger.isInfoEnabled(LIFECYCLE)) { String message = Strings.format(format, args); if (progress > 0) logger.info(LIFECYCLE, "[{}] {}", (int) progress, message); else logger.info(LIFECYCLE, "{}", message); } } public SetLocation exception(Throwable t, String format, Object... args) { return reporter.exception(t, format, args); } public boolean isPedantic() { return reporter.isPedantic(); } }
/** * An Image Picker Plugin for Cordova/PhoneGap. */ package com.synconset; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import android.app.Activity; import android.content.Intent; import android.util.Log; public class ImagePicker extends CordovaPlugin { public static String TAG = "ImagePicker"; private CallbackContext callbackContext; private JSONObject params; public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { this.callbackContext = callbackContext; this.params = args.getJSONObject(0); if (action.equals("getPictures")) { Intent intent = new Intent(cordova.getActivity(), MultiImageChooserActivity.class); int max = 20; int desiredWidth = 0; int desiredHeight = 0; int quality = 100; int outputType = 0; if (this.params.has("maximumImagesCount")) { max = this.params.getInt("maximumImagesCount"); } if (this.params.has("width")) { desiredWidth = this.params.getInt("width"); } if (this.params.has("height")) { desiredWidth = this.params.getInt("height"); } if (this.params.has("quality")) { quality = this.params.getInt("quality"); } if (this.params.has("outputType")) { outputType = this.params.getInt("outputType"); } intent.putExtra("MAX_IMAGES", max); intent.putExtra("WIDTH", desiredWidth); intent.putExtra("HEIGHT", desiredHeight); intent.putExtra("QUALITY", quality); intent.putExtra("OUTPUT_TYPE", outputType); if (this.cordova != null) { this.cordova.startActivityForResult((CordovaPlugin) this, intent, 0); } } return true; } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && data != null) { ArrayList<String> fileNames = data.getStringArrayListExtra("MULTIPLEFILENAMES"); JSONArray res = new JSONArray(fileNames); this.callbackContext.success(res); } else if (resultCode == Activity.RESULT_CANCELED && data != null) { String error = data.getStringExtra("ERRORMESSAGE"); this.callbackContext.error(error); } else if (resultCode == Activity.RESULT_CANCELED) { JSONArray res = new JSONArray(); this.callbackContext.success(res); } else { this.callbackContext.error("No images selected"); } } }
package net.hearthstats.ocr; import net.hearthstats.analysis.HearthstoneAnalyser; import org.apache.commons.lang3.StringUtils; import java.awt.image.BufferedImage; public class RankLevelOcr extends OcrBase { public Integer processNumber(BufferedImage bufferedImage) throws OcrException { String result = process(bufferedImage); try { if (StringUtils.isEmpty(result)) { return null; } else { int rank = Integer.valueOf(result); if (rank < 0 || rank > 25) { debugLog.debug("Rank {} is invalid, rank detection has failed"); return null; } else { return rank; } } } catch (NumberFormatException e) { debugLog.debug("Ignoring NumberFormatException parsing " + result); return null; } } @Override protected BufferedImage crop(BufferedImage image, int iteration) { float ratio = HearthstoneAnalyser.getRatio(image); int xOffset = HearthstoneAnalyser.getXOffset(image, ratio); int retryOffset = (iteration - 1) % 3; int x = (int) ((875 + retryOffset) * ratio + xOffset); int y = (int) (162 * ratio); int width = (int) (32 * ratio); int height = (int) (22 * ratio); return image.getSubimage(x, y, width, height); } @Override protected String parseString(String ocrResult, int iteration) { if (ocrResult != null) { // Change easily-mistaken letters into numbers ocrResult = StringUtils.replaceChars(ocrResult, "lIiSsOo", "1115500"); // Remove all other unknown letters ocrResult = ocrResult.replaceAll("[^\\d]", ""); } return ocrResult; } @Override protected boolean tryProcessingAgain(String ocrResult, int iteration) { try { if (ocrResult != null && !ocrResult.isEmpty() && Integer.parseInt(ocrResult) > 0 && Integer.parseInt(ocrResult) < 26) { // A valid rank number has been found return false; } } catch (NumberFormatException e) { debugLog.debug("Ignoring NumberFormatException parsing " + ocrResult); } if (iteration <= 5) { // Rank level needs multiple iterations to try slightly shifted each time, so try five times debugLog.debug("rank detection try #" + iteration); return true; } else { // Hasn't matched after five tries, so give up return false; } } @Override protected String getFilename() { return "ranklevel"; } }
package com.rahulrav.cordova.amazon.plugin; import android.content.Context; import android.util.Log; import com.amazon.inapp.purchasing.GetUserIdResponse; import com.amazon.inapp.purchasing.GetUserIdResponse.GetUserIdRequestStatus; import com.amazon.inapp.purchasing.ItemDataResponse; import com.amazon.inapp.purchasing.PurchaseResponse; import com.amazon.inapp.purchasing.PurchaseUpdatesResponse; import com.amazon.inapp.purchasing.PurchasingObserver; import org.apache.cordova.PluginResult; import org.apache.cordova.PluginResult.Status; import org.json.JSONException; import org.json.JSONObject; import java.util.concurrent.ConcurrentHashMap; /** * Provides a basic implementation of the basic {@link PurchasingObserver} * * @author Rahul Ravikumar * */ public class AmazonPurchasingObserver extends PurchasingObserver { private static AmazonPurchasingObserver instance; public static AmazonPurchasingObserver getPurchasingObserver(final AmazonInAppPurchasing plugin, final Context context) { if (instance == null) { instance = new AmazonPurchasingObserver(plugin, context); } return instance; } private final AmazonInAppPurchasing plugin; // is set to true when the sdk initialization is complete private boolean isInitialized; private JSONObject sdkAvailableResponse; // is the callback requestId used to initialize the PurchaseObserver private String initCallbackId; // represents the mapping from requestId -> callbackIds private final ConcurrentHashMap<String, String> requestCallbacks; /** * Associate the {@link AmazonPurchasingObserver} with the In-App Purchasing * plugin */ private AmazonPurchasingObserver(final AmazonInAppPurchasing plugin, final Context context) { super(context); this.plugin = plugin; requestCallbacks = new ConcurrentHashMap<String, String>(); isInitialized = false; sdkAvailableResponse = null; } protected AmazonInAppPurchasing getPlugin() { return plugin; } public boolean isAlreadyInitialized() { return isInitialized; } public JSONObject sdkAvailableResponse() { return sdkAvailableResponse; } public void addRequest(final String requestId, final String callbackId) { requestCallbacks.put(requestId, callbackId); } public void registerInitialization(final String initCallbackId) { this.initCallbackId = initCallbackId; } @Override public void onGetUserIdResponse(final GetUserIdResponse userIdResponse) { if (userIdResponse == null) { // should never happen throw new AmazonInAppException("'null' userId response."); } final String requestId = userIdResponse.getRequestId(); final String callbackId = requestCallbacks.remove(requestId); try { final JSONObject jobj = new JSONObject(); final GetUserIdRequestStatus userIdRequestStatus = userIdResponse.getUserIdRequestStatus(); jobj.put("requestId", userIdResponse.getRequestId()); jobj.put("userIdRequestStatus", userIdRequestStatus); if (userIdRequestStatus == GetUserIdRequestStatus.SUCCESSFUL) { jobj.put("userId", userIdResponse.getUserId()); } final PluginResult pluginInResult = new PluginResult(Status.OK, jobj); pluginInResult.setKeepCallback(false); plugin.webView.sendPluginResult(pluginInResult, callbackId); } catch (final JSONException e) { final PluginResult pluginInResult = new PluginResult(Status.JSON_EXCEPTION); pluginInResult.setKeepCallback(false); plugin.webView.sendPluginResult(pluginInResult, callbackId); } } @Override public void onItemDataResponse(final ItemDataResponse itemDataResponse) { if (itemDataResponse == null) { // should never happen throw new AmazonInAppException("'null' item data response."); } final String requestId = itemDataResponse.getRequestId(); final String callbackId = requestCallbacks.remove(requestId); try { final AmazonItemDataResponse amazonItemDataResponse = new AmazonItemDataResponse(itemDataResponse); final PluginResult pluginResult = new PluginResult(Status.OK, amazonItemDataResponse.toJSON()); pluginResult.setKeepCallback(false); plugin.webView.sendPluginResult(pluginResult, callbackId); } catch (final JSONException e) { final PluginResult pluginInResult = new PluginResult(Status.JSON_EXCEPTION); pluginInResult.setKeepCallback(false); plugin.webView.sendPluginResult(pluginInResult, callbackId); } } @Override public void onPurchaseResponse(final PurchaseResponse purchaseResponse) { if (purchaseResponse == null) { // should never happen throw new AmazonInAppException("'null' purchase response."); } final String requestId = purchaseResponse.getRequestId(); final String callbackId = requestCallbacks.remove(requestId); try { final AmazonPurchaseResponse amazonPurchaseResponse = new AmazonPurchaseResponse(purchaseResponse); final PluginResult pluginResult = new PluginResult(Status.OK, amazonPurchaseResponse.toJSON()); pluginResult.setKeepCallback(false); plugin.webView.sendPluginResult(pluginResult, callbackId); } catch (final JSONException e) { final PluginResult pluginInResult = new PluginResult(Status.JSON_EXCEPTION); pluginInResult.setKeepCallback(false); plugin.webView.sendPluginResult(pluginInResult, callbackId); } } @Override public void onPurchaseUpdatesResponse(final PurchaseUpdatesResponse purchaseUpdatesResponse) { if (purchaseUpdatesResponse == null) { // should never happen throw new AmazonInAppException("'null' purchase updates response."); } final String requestId = purchaseUpdatesResponse.getRequestId(); final String callbackId = requestCallbacks.remove(requestId); try { final AmazonPurchaseUpdatesResponse amazonPurchaseUpdatesResponse = new AmazonPurchaseUpdatesResponse(purchaseUpdatesResponse); final PluginResult pluginResult = new PluginResult(Status.OK, amazonPurchaseUpdatesResponse.toJSON()); pluginResult.setKeepCallback(false); plugin.webView.sendPluginResult(pluginResult, callbackId); } catch (final JSONException e) { final PluginResult pluginInResult = new PluginResult(Status.JSON_EXCEPTION); pluginInResult.setKeepCallback(false); plugin.webView.sendPluginResult(pluginInResult, callbackId); } } @Override public void onSdkAvailable(final boolean isSandboxMode) { isInitialized = true; try { final JSONObject jobj = new JSONObject(); jobj.put("isSandboxMode", isSandboxMode); // update the sdk available response sdkAvailableResponse = jobj; final PluginResult pluginInResult = new PluginResult(Status.OK, jobj); pluginInResult.setKeepCallback(false); plugin.webView.sendPluginResult(pluginInResult, this.initCallbackId); } catch (final JSONException e) { final PluginResult pluginInResult = new PluginResult(Status.JSON_EXCEPTION); pluginInResult.setKeepCallback(false); plugin.webView.sendPluginResult(pluginInResult, this.initCallbackId); } } }
package org.aktin.broker.node; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import org.aktin.broker.client.BrokerClient; import org.aktin.broker.client.auth.ClientAuthenticator; import org.aktin.broker.xml.SoftwareModule; import org.w3c.dom.Document; public abstract class AbstractNode { protected long startup; protected BrokerClient broker; private Transformer transformer; public AbstractNode(){ this.startup = System.currentTimeMillis(); } public final void connectBroker(String broker_endpoint, ClientAuthenticator auth) throws IOException{ try { this.broker = new BrokerClient(new URI(broker_endpoint)); } catch (URISyntaxException e) { throw new IOException(e); } broker.setClientAuthenticator(auth); // optional status exchange broker.getBrokerStatus(); broker.postMyStatus(startup, new SoftwareModule("org.aktin.broker.node", AbstractNode.class.getPackage().getImplementationVersion()), new SoftwareModule(getModuleName(), getModuleVersion()) ); } /** * Override this method to specify a name for your module. * Default implementation uses {@code getClass().getName()}. * @return module name */ public String getModuleName(){ return getClass().getName(); } /** * Override this method to specify a module version number. * @return version number */ public String getModuleVersion(){ return getClass().getPackage().getImplementationVersion(); } public void loadTransformer(String path) throws TransformerException{ TransformerFactory tf = TransformerFactory.newInstance(); this.transformer = tf.newTransformer(new StreamSource(new File(path))); } public boolean hasTransformer(){ return transformer != null; } public Document transform(Document source) throws TransformerException{ DOMSource dom = new DOMSource(source); DocumentBuilder b; try { b = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new TransformerException("Failed to create document builder", e); } Document doc = b.newDocument(); DOMResult res = new DOMResult(doc); transformer.transform(dom, res); return doc; } }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.*; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.*; import java.net.URI; import java.net.URISyntaxException; import java.sql.*; public class Main extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getRequestURI().endsWith("/db")) { showDatabase(req,resp); } else { showHome(req,resp); } } private void showHome(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().print("My Change1: Hello from Java!"); } private void showDatabase(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { Connection connection = getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); String out = "Hello!\n"; while (rs.next()) { out += "Read from DB: " + rs.getTimestamp("tick") + "\n"; } resp.getWriter().print(out); } catch (Exception e) { resp.getWriter().print("There was an error: " + e.getMessage()); } } private Connection getConnection() throws URISyntaxException, SQLException { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath(); return DriverManager.getConnection(dbUrl, username, password); } public static void main(String[] args) throws Exception{ Server server = new Server(Integer.valueOf(System.getenv("PORT"))); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context);
import org.apache.http.HttpEntity; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpResponseException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.BufferedReader; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; import java.net.URL; import java.nio.charset.Charset; import java.util.Map; public class Main extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { URL proximo = new URL(System.getenv("PROXIMO_URL")); String userInfo = proximo.getUserInfo(); String user = userInfo.substring(0, userInfo.indexOf(':')); String password = userInfo.substring(userInfo.indexOf(':') + 1); System.setProperty("socksProxyHost", proximo.getHost()); // System.setProperty('socksProxyPort', PROXIMO_PORT); Authenticator.setDefault(new ProxyAuthenticator(user, password)); String urlStr = "http://httpbin.org/ip"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet request = new HttpGet(urlStr); CloseableHttpResponse response = httpClient.execute(request); try { resp.getWriter().print("Hello from Java! " + handleResponse(response)); } catch (Exception e) { resp.getWriter().print(e.getMessage()); } } private static String handleResponse(CloseableHttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException( statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response contains no content"); } return readStream(entity.getContent()); } private static String readStream(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String output = ""; String tmp = reader.readLine(); while (tmp != null) { output += tmp; tmp = reader.readLine(); } return output; } private class ProxyAuthenticator extends Authenticator { private final PasswordAuthentication passwordAuthentication; private ProxyAuthenticator(String user, String password) { passwordAuthentication = new PasswordAuthentication(user, password.toCharArray()); } @Override protected PasswordAuthentication getPasswordAuthentication() { return passwordAuthentication; } } }
package cz.muni.fi.pa165.entity; import java.util.Collections; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Temporal; @Entity public class Loan { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) @Temporal(javax.persistence.TemporalType.DATE) private Date loanDate; @Column(nullable = false) private Boolean returned; @Column(nullable = false) @Temporal(javax.persistence.TemporalType.DATE) private Date returnDate; @Column(nullable = false) private BookState returnBookState; @Column(nullable = false) @ManyToOne private Book book; public void setBook(Book book) { this.book = book; } public Book getBook() { return book; } public void setId(Long id){ this.id=id; } public Long getId(){ return this.id; } public void setDate(Date loanDate){ this.loanDate=loanDate; } public Date getDate(){ return this.loanDate; } public Boolean isReturned(){ return this.returned; } public void returnLoan(){ this.returned=true; } public Date getReturnDate(){ return this.returnDate; } public void setReturnDate(Date returnDate){ this.returnDate=returnDate; } public BookState getReturnBookState(){ return this.returnBookState; } public void setReturnBookState(Date returnBookState){ this.returnDate=returnBookState; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.getDate() == null) ? 0 : this.getDate().hashCode()); result = prime * result + ((this.isReturned() == null) ? 0 : this.isReturned().hashCode()); result = prime * result + ((this.getReturnDate() == null) ? 0 : this.getReturnDate().hashCode()); result = prime * result + ((this.getReturnBookState() == null) ? 0 : this.getReturnBookState().hashCode()); result = prime * result + ((this.getBook() == null) ? 0 : this.getBook().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Loan)) { return false; } Loan other = (Loan) obj; if (this.getDate() == null && other.getDate() != null) { return false; } else if (!this.getDate().equals(other.getDate())){ return false; } if (this.isReturned() == null && other.isReturned() != null) { return false; } else if(isReturned()!=other.isReturned()){ return false; } if (this.getReturnDate() == null && other.getReturnDate() != null) { return false; } else if(!this.getReturnDate().equals(other.getReturnDate())){ return false; } if (this.getReturnBookState() == null && other.getReturnBookState() != null) { return false; } else if(!this.getReturnBookState().equals(other.getReturnBookState())){ return false; } if (this.getBook() == null && other.getBook() != null) { return false; } else if(!this.getBook().equals(other.getBook())){ return false; } return true; } }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import spark.ModelAndView; import spark.template.freemarker.FreeMarkerEngine; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import static spark.Spark.*; public class Main { private static final Logger LOG = Logger.getLogger(Main.class.getName()); public static String toJson(Object obj) { try { return new ObjectMapper().writeValueAsString(obj); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); get("/hello", (req, res) -> "Hello World"); post("/company", (req, res) -> { ObjectMapper mapper = new ObjectMapper(); Company company = mapper.readValue(req.body(), Company.class); LOG.info("creating company: " + company); if (company.getOwners() == null || company.getOwners().isEmpty()) { throw new IllegalArgumentException("At least one company owner is required."); } return new IdResponse(DB.get().createCompany(company)); }, Main::toJson); get("/company", (req, res) -> { return DB.get().listCompanies(); }, Main::toJson); get("/company/:id", (req, res) -> { String idStr = req.params(":id"); long id; try { id = Long.parseLong(idStr); } catch (NumberFormatException e) { throw new IllegalArgumentException("id is not valid"); } return DB.get().getCompany(id); }, Main::toJson); get("/", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("message", "Hello World!"); return new ModelAndView(attributes, "index.ftl"); }, new FreeMarkerEngine()); after((req, res) -> { res.type("application/json"); }); exception(IllegalArgumentException.class, (e, req, res) -> { res.status(400); res.body(toJson(new ResponseError(e))); }); exception(ConstraintViolationException.class, (e, req, res) -> { res.status(400); res.body(toJson(new ResponseError(e))); }); exception(ValidationException.class, (e, req, res) -> { res.status(400); res.body(toJson(new ResponseError(e))); }); exception(Exception.class, (e, req, res) -> { res.status(400); LOG.throwing("", "", e); LOG.log(Level.SEVERE, "", e); res.body(toJson(new ResponseError(e.getClass().getName() + e.getMessage() + e.getCause()))); }); get("/db", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { // connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add("Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try { connection.close(); } catch (SQLException e) { } } }, new FreeMarkerEngine()); } }
import java.sql.*; import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import java.net.URI; import java.net.URISyntaxException; import static spark.Spark.*; import spark.template.freemarker.FreeMarkerEngine; import spark.ModelAndView; import static spark.Spark.get; import com.heroku.sdk.jdbc.DatabaseUrl; public class Main { public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); get("/ucsb", (req, res) -> "Go Gauchos!"); get("/", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("message", "Hello World!"); return new ModelAndView(attributes, "index.ftl"); }, new FreeMarkerEngine()); get("/db", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); } }
import com.google.gson.Gson; import java.sql.*; import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import org.json.JSONObject; import java.net.URI; import java.net.URISyntaxException; import static spark.Spark.*; import spark.template.freemarker.FreeMarkerEngine; import spark.ModelAndView; import static spark.Spark.get; import static javax.measure.unit.SI.KILOGRAM; import javax.measure.quantity.Mass; import org.jscience.physics.model.RelativisticModel; import org.jscience.physics.amount.Amount; import static javax.measure.unit.SI.KILOGRAM; import javax.measure.quantity.Mass; import org.jscience.physics.model.RelativisticModel; import org.jscience.physics.amount.Amount; import com.heroku.sdk.jdbc.DatabaseUrl; public class Main { public static void main(String[] args) { Gson gson = new Gson(); port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); get("/hello", (req, res) -> "Hello World"); /* get("/user", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("message", "Hello World!"); return new ModelAndView(attributes, "user.ftl"); }, new FreeMarkerEngine()); */ get("/db", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db2.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); get("/user", (req, res) -> { ArrayList<String> users = new ArrayList<String>(); users.add("John Doe"); users.add("Tony Doe"); users.add("test one"); Map<String, Object> attributes = new HashMap<>(); attributes.put("users", users); return new ModelAndView(attributes, "user.ftl"); }, new FreeMarkerEngine()); get("/api/timeline_info", (req, res) -> { Map<String, Object> data = new HashMap<>(); data.put("header_username","Smith"); data.put("title1", "sport"); data.put("content1", "today night, gym"); data.put("image1", "background: #FFC1C1;"); data.put("title2","sport"); data.put("content2", "monday moring, swimming with John"); data.put("image2", "background: #BFEFFF;"); data.put("title3","sport"); data.put("content3", "friday, a basketball competition"); data.put("image3", "background: #FFC1C1;"); return data; }, gson::toJson); get("/recommendation", (req, res) -> { ArrayList<String> users = new ArrayList<String>(); users.add("John Doe"); users.add("Smith"); users.add("Daniel"); users.add("Mark"); users.add("Ellen"); users.add("Lily"); users.add("Julio"); users.add("Chela"); users.add("Bells"); ArrayList<String> images = new ArrayList<String>(); images.add("picture/image1.jpg"); images.add("picture/image2.jpg"); images.add("picture/image3.jpg"); images.add("picture/image4.jpg"); images.add("picture/image5.jpg"); images.add("picture/image6.jpg"); images.add("picture/image7.jpg"); images.add("picture/image8.jpg"); images.add("picture/image9.jpg"); Map<String, Object> attributes = new HashMap<>(); attributes.put("users", users); attributes.put("images", images); return new ModelAndView(attributes, "recommendation.ftl"); }, new FreeMarkerEngine()); get("/api/info", (req, res ) -> { Map<String, Object> data = new HashMap<>(); data.put("username","Smith"); String xml= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<user_profile>" + "<user_name> Allan </user_name>"+ "<num_timeline> 10 </num_timeline>" + "</user_profile>" ; res.type("text/xml"); return xml; }); get("/users", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try{ connection = DatabaseUrl.extract().getConnection(); System.out.println(req.body()); // JSONObject obj = new JSONObject(req.body()); // String email = obj.getString("signin-email"); // String password = obj.getString("signin-password"); //Statement stmt = connection.createStatement(); // stmt.executeUpdate("create table if not exists users (email_address json, password json)"); // stmt.executeUpdate("insert into users" + // "(email_address, password)" + // "values('" + email + "','" + password + "')"); // stmt.executeUpdate("insert into users" + // "(email_address, password)" + // "values('wefwef@sdfs','12345')"); // ResultSet rs = stmt.executeQuery("select email_address from users"); ArrayList<String> output = new ArrayList<String>(); // while(rs.next()) // output.add("read from users: " + rs.getString("email_address")); output.add("read from users: " + "email_address"); output.add("read fasdf" + "sfsaf"); attributes.put("results",output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} }}, new FreeMarkerEngine()); /* get("/testuser", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); */ } }
package org.basex.http; import static javax.servlet.http.HttpServletResponse.*; import static org.basex.http.HTTPText.*; import static org.basex.util.Token.*; import static org.basex.util.http.HttpText.*; import java.io.*; import java.net.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import org.basex.*; import org.basex.core.*; import org.basex.core.StaticOptions.AuthMethod; import org.basex.core.users.*; import org.basex.io.*; import org.basex.io.out.*; import org.basex.io.serial.*; import org.basex.server.Log.LogType; import org.basex.server.*; import org.basex.util.*; import org.basex.util.http.*; import org.basex.util.http.HttpText.Request; import org.basex.util.options.*; public final class HTTPContext { /** Global static database context. */ private static Context context; /** Initialization flag. */ private static boolean init; /** Initialized failed. */ private static IOException exception; /** Server instance. */ private static BaseXServer server; /** Servlet request. */ public final HttpServletRequest req; /** Servlet response. */ public final HttpServletResponse res; /** Request method. */ public final String method; /** Request method. */ public final HTTPParams params; /** Authentication method. */ public AuthMethod auth; /** User name. */ public String username; /** Password (plain text). */ public String password; /** Performance. */ private final Performance perf = new Performance(); /** Path, starting with a slash. */ private final String path; /** Client database context. */ private Context ctx; /** Serialization parameters. */ private SerializerOptions sopts; /** * Constructor. * @param req request * @param res response * @param servlet calling servlet instance */ HTTPContext(final HttpServletRequest req, final HttpServletResponse res, final BaseXServlet servlet) { this.req = req; this.res = res; params = new HTTPParams(this); method = req.getMethod(); final StringBuilder uri = new StringBuilder(req.getRequestURL()); final String qs = req.getQueryString(); if(qs != null) uri.append('?').append(qs); context.log.write(address(), context.user(), LogType.REQUEST, '[' + method + "] " + uri, null); // set UTF8 as default encoding (can be overwritten) res.setCharacterEncoding(Strings.UTF8); path = decode(normalize(req.getPathInfo())); final StaticOptions mprop = context.soptions; if(servlet.username.isEmpty()) { // adopt existing servlet-specific credentials username = mprop.get(StaticOptions.USER); password = mprop.get(StaticOptions.PASSWORD); } else { // otherwise, adopt global credentials username = servlet.username; password = servlet.password; } // prefer safest authorization method final String value = req.getHeader(AUTHORIZATION); final String am = value == null ? AuthMethod.BASIC.toString() : Strings.split(value, ' ', 2)[0]; auth = StaticOptions.AUTHMETHOD.get(am) == AuthMethod.DIGEST ? AuthMethod.DIGEST : servlet.auth != null ? servlet.auth : mprop.get(StaticOptions.AUTHMETHOD); } /** * Authorizes a request. * @throws BaseXException database exception */ void authorize() throws BaseXException { final String value = req.getHeader(AUTHORIZATION); if(value == null) return; final String[] ams = Strings.split(value, ' ', 2); final AuthMethod am = StaticOptions.AUTHMETHOD.get(ams[0]); if(am == null) throw new BaseXException(WHICHAUTH, value); // overwrite credentials with client data (basic or digest) if(am == AuthMethod.BASIC) { final String details = ams.length > 1 ? ams[1] : ""; final String[] cred = Strings.split(org.basex.util.Base64.decode(details), ':', 2); if(cred.length != 2) throw new BaseXException(NOUSERNAME); username = cred[0]; password = cred[1]; } else { // (will always be) digest final EnumMap<Request, String> map = HttpClient.digestHeaders(value); username = map.get(Request.USERNAME); password = map.get(Request.RESPONSE); } } /** * Returns the content type of a request, or an empty string. * @return content type */ public MediaType contentType() { final String ct = req.getContentType(); return new MediaType(ct == null ? "" : ct); } /** * Initializes the output. Sets the expected encoding and content type. */ public void initResponse() { // set content type and encoding final SerializerOptions opts = sopts(); final String enc = opts.get(SerializerOptions.ENCODING); res.setCharacterEncoding(enc); res.setContentType(new MediaType(mediaType(opts) + "; " + CHARSET + '=' + enc).toString()); } /** * Returns the media type defined in the specified serialization parameters. * @param sopts serialization parameters * @return media type */ public static MediaType mediaType(final SerializerOptions sopts) { // set content type final String type = sopts.get(SerializerOptions.MEDIA_TYPE); if(!type.isEmpty()) return new MediaType(type); // determine content type dependent on output method final SerialMethod sm = sopts.get(SerializerOptions.METHOD); if(sm == SerialMethod.RAW) return MediaType.APPLICATION_OCTET_STREAM; if(sm == SerialMethod.ADAPTIVE || sm == SerialMethod.XML) return MediaType.APPLICATION_XML; if(sm == SerialMethod.XHTML || sm == SerialMethod.HTML) return MediaType.TEXT_HTML; if(sm == SerialMethod.JSON) return MediaType.APPLICATION_JSON; return MediaType.TEXT_PLAIN; } /** * Returns the URL path. * @return path path */ public String path() { return path; } /** * Returns the database path (i.e., all path entries except for the first). * @return database path */ public String dbpath() { final int s = path.indexOf('/', 1); return s == -1 ? "" : path.substring(s + 1); } /** * Returns the addressed database (i.e., the first path entry). * @return database, or {@code null} if the root directory was specified. */ public String db() { final int s = path.indexOf('/', 1); return path.substring(1, s == -1 ? path.length() : s); } /** * Returns all accepted media types. * @return accepted media types */ public MediaType[] accepts() { final String accept = req.getHeader(ACCEPT); final ArrayList<MediaType> list = new ArrayList<>(); if(accept == null) { list.add(MediaType.ALL_ALL); } else { for(final String produce : accept.split("\\s*,\\s*")) { // check if quality factor was specified final MediaType type = new MediaType(produce); final String qf = type.parameters().get("q"); final double d = qf != null ? toDouble(token(qf)) : 1; // only accept media types with valid double values if(d > 0 && d <= 1) { final StringBuilder sb = new StringBuilder(); final String main = type.main(), sub = type.sub(); sb.append(main.isEmpty() ? "*" : main).append('/'); sb.append(sub.isEmpty() ? "*" : sub).append("; q=").append(d); list.add(new MediaType(sb.toString())); } } } return list.toArray(new MediaType[list.size()]); } /** * Sets a status and sends an info message. * @param code status code * @param info info message (can be {@code null}) * @param error treat as error (use web server standard output) * @throws IOException I/O exception */ public void status(final int code, final String info, final boolean error) throws IOException { try { log(code, info); res.resetBuffer(); if(code == SC_UNAUTHORIZED) { final TokenBuilder header = new TokenBuilder(auth.toString()); final String nonce = Strings.md5(Long.toString(System.nanoTime())); if(auth == AuthMethod.DIGEST) { header.add(" "); header.addExt(Request.REALM).add("=\"").add(Prop.NAME).add("\","); header.addExt(Request.QOP).add("=\"").add(AUTH).add(',').add(AUTH_INT).add("\","); header.addExt(Request.NONCE).add("=\"").add(nonce).add('"'); } res.setHeader(WWW_AUTHENTICATE, header.toString()); } if(error && code >= SC_BAD_REQUEST) { res.sendError(code, info); } else { res.setStatus(code); if(info != null) { res.setContentType(MediaType.TEXT_PLAIN.toString()); final ArrayOutput ao = new ArrayOutput(); ao.write(token(info)); res.getOutputStream().write(ao.normalize().finish()); } } } catch(final IllegalStateException ex) { log(SC_INTERNAL_SERVER_ERROR, Util.message(ex)); } } /** * Updates the credentials. * @param user user * @param pass password */ public void credentials(final String user, final String pass) { username = user; password = pass; } /** * Returns the client database context. Authenticates the user if necessary. * @param authenticate authenticate user * @return client database context * @throws IOException I/O exception */ public Context context(final boolean authenticate) throws IOException { if(ctx == null) { ctx = new Context(context); ctx.user(authenticate ? authenticate() : context.users.get(UserText.ADMIN)); } return ctx; } /** * Authenticates the user and returns a new client {@link Context} instance. * @return user * @throws IOException I/O exception */ private User authenticate() throws IOException { final byte[] address = token(req.getRemoteAddr()); try { if(username == null || username.isEmpty()) throw new LoginException(NOUSERNAME); final User us = context.users.get(username); if(us == null) throw new LoginException(); if(auth == AuthMethod.BASIC) { if(password == null || !us.matches(password)) throw new LoginException(); } else { // digest authentication final EnumMap<Request, String> map = HttpClient.digestHeaders(req.getHeader(AUTHORIZATION)); final String am = map.get(Request.AUTH_METHOD); if(!AuthMethod.DIGEST.toString().equals(am)) throw new LoginException(DIGESTAUTH); final String nonce = map.get(Request.NONCE), cnonce = map.get(Request.CNONCE); String ha1 = us.code(Algorithm.DIGEST, Code.HASH); if(Strings.eq(map.get(Request.ALGORITHM), MD5_SESS)) ha1 = Strings.md5(ha1 + ':' + nonce + ':' + cnonce); String h2 = method + ':' + map.get(Request.URI); final String qop = map.get(Request.QOP); if(Strings.eq(qop, AUTH_INT)) h2 += ':' + Strings.md5(params.body().toString()); final String ha2 = Strings.md5(h2); final StringBuilder rsp = new StringBuilder(ha1).append(':').append(nonce); if(Strings.eq(qop, AUTH, AUTH_INT)) { rsp.append(':').append(map.get(Request.NC)); rsp.append(':').append(cnonce); rsp.append(':').append(qop); } rsp.append(':').append(ha2); if(!Strings.md5(rsp.toString()).equals(password)) throw new LoginException(); } context.blocker.remove(address); return us; } catch(final LoginException ex) { // delay users with wrong passwords context.blocker.delay(address); throw ex; } } /** * Returns an exception that may have been caught by the initialization of the database server. * @return exception */ public static IOException exception() { return exception; } /** * Assigns serialization parameters. * @param opts serialization parameters. */ public void sopts(final SerializerOptions opts) { sopts = opts; } /** * Returns the serialization parameters. * @return serialization parameters. */ public SerializerOptions sopts() { if(sopts == null) sopts = new SerializerOptions(); return sopts; } /** * Writes a log message. * @param type log type * @param info info string (can be {@code null}) */ void log(final int type, final String info) { context.log.write(address(), context.user(), type, info, perf); } /** * Sends a redirect. * @param location location * @throws IOException I/O exception */ public void redirect(final String location) throws IOException { res.sendRedirect(resolve(location)); } /** * Normalizes a redirection location. Prefixes absolute locations with the request URI. * @param location location * @return normalized representation */ public String resolve(final String location) { String loc = location; if(location.startsWith("/")) { final String uri = req.getRequestURI(), info = req.getPathInfo(); if(info == null) { loc = uri + location; } else { loc = uri.substring(0, uri.length() - info.length()) + location; } } return loc; } /** * Sends a forward. * @param location location * @throws IOException I/O exception * @throws ServletException servlet exception */ public void forward(final String location) throws IOException, ServletException { req.getRequestDispatcher(resolve(location)).forward(req, res); } /** * Initializes the HTTP context. * @return context; */ public static synchronized Context init() { if(context == null) context = new Context(); return context; } /** * Initializes the database context, based on the initial servlet context. * Parses all context parameters and passes them on to the database context. * @param sc servlet context * @throws IOException I/O exception */ public static synchronized void init(final ServletContext sc) throws IOException { // check if HTTP context has already been initialized if(init) return; init = true; // set web application path as home directory and HTTPPATH final String webapp = sc.getRealPath("/"); Options.setSystem(Prop.PATH, webapp); Options.setSystem(StaticOptions.WEBPATH, webapp); // bind all parameters that start with "org.basex." to system properties final Enumeration<String> en = sc.getInitParameterNames(); while(en.hasMoreElements()) { final String key = en.nextElement(); if(!key.startsWith(Prop.DBPREFIX)) continue; String val = sc.getInitParameter(key); if(key.endsWith("path") && !new File(val).isAbsolute()) { // prefix relative path with absolute servlet path Util.debug(key.toUpperCase(Locale.ENGLISH) + ": " + val); val = new IOFile(webapp, val).path(); } Options.setSystem(key, val); } // create context, update options if(context == null) { context = new Context(false); } else { context.soptions.setSystem(); context.options.setSystem(); } // start server instance if(!context.soptions.get(StaticOptions.HTTPLOCAL)) { try { server = new BaseXServer(context); } catch(final IOException ex) { exception = ex; throw ex; } } } /** * Closes the database context. */ public static synchronized void close() { if(server == null) return; try { server.stop(); } catch(final IOException ex) { Util.stack(ex); } server = null; } public static String decode(final String segments) { try { return URLDecoder.decode(segments, Prop.ENCODING); } catch(final UnsupportedEncodingException ex) { throw new IllegalArgumentException(ex); } } /** * Normalizes the path information. * @param path path, or {@code null} * @return normalized path */ private static String normalize(final String path) { final TokenBuilder tmp = new TokenBuilder(); if(path != null) { final TokenBuilder tb = new TokenBuilder(); final int pl = path.length(); for(int p = 0; p < pl; p++) { final char ch = path.charAt(p); if(ch == '/') { if(tb.isEmpty()) continue; tmp.add('/').add(tb.toArray()); tb.reset(); } else { tb.add(ch); } } if(!tb.isEmpty()) tmp.add('/').add(tb.finish()); } if(tmp.isEmpty()) tmp.add('/'); return tmp.toString(); } /** * Returns a string with the remote user address. * @return user address */ private String address() { return req.getRemoteAddr() + ':' + req.getRemotePort(); } }
package pbl1; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import posmining.utils.CSKV; import posmining.utils.PosUtils; /** * () : add comment * @author thuy * */ public class CondomSalesBySex { // MapReduce public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { // MapperReducer Job job = new Job(new Configuration()); job.setJarByClass(CondomSalesBySex.class); job.setMapperClass(MyMapper.class); job.setReducerClass(MyReducer.class); job.setJobName("2014019"); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); // MapperReducer job.setMapOutputKeyClass(CSKV.class); job.setMapOutputValueClass(CSKV.class); job.setOutputKeyClass(CSKV.class); job.setOutputValueClass(CSKV.class); String inputpath = "posdata"; String outputpath = "out/condomSalesBySex"; if (args.length > 0) { inputpath = args[0]; } FileInputFormat.setInputPaths(job, new Path(inputpath)); FileOutputFormat.setOutputPath(job, new Path(outputpath)); PosUtils.deleteOutputDir(outputpath); // Reducer job.setNumReduceTasks(8); // MapReduce job.waitForCompletion(true); } // Mappermap public static class MyMapper extends Mapper<LongWritable, Text, CSKV, CSKV> { protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // csv String csv[] = value.toString().split(","); if (csv[PosUtils.ITEM_CATEGORY_NAME].equals("") == false) { return; } // key String sex = csv[PosUtils.BUYER_SEX]; // value int price = Integer.parseInt(csv[PosUtils.ITEM_COUNT]) * Integer.parseInt(csv[PosUtils.ITEM_PRICE]); // emit context.write(new CSKV(sex), new CSKV(price)); } } // Reducerreduce public static class MyReducer extends Reducer<CSKV, CSKV, CSKV, CSKV> { protected void reduce(CSKV key, Iterable<CSKV> values, Context context) throws IOException, InterruptedException { int count = 0; for (CSKV value : values) { count += value.toInt(); } // emit context.write(key, new CSKV(count)); } } }
package ifc.lang; import lib.MultiMethodTest; import com.sun.star.lang.XTypeProvider; import com.sun.star.uno.Type; /** * Testing <code>com.sun.star.lang.XTypeProvider</code> * interface methods : * <ul> * <li><code> getTypes()</code></li> * <li><code> getImplementationId()</code></li> * </ul> <p> * Test is <b> NOT </b> multithread compilant. <p> * @see com.sun.star.lang.XTypeProvider */ public class _XTypeProvider extends MultiMethodTest { public static XTypeProvider oObj = null; public static Type[] types = null; /** * Just calls the method.<p> * Has <b>OK</b> status if no runtime exceptions occured. */ public void _getImplementationId() { boolean result = true; log.println("testing getImplementationId() ... "); log.println("The ImplementationId is "+oObj.getImplementationId()); result = true; tRes.tested("getImplementationId()", result); } // end getImplementationId() /** * Calls the method and checks the return value.<p> * Has <b>OK</b> status if one of the return value equals to the * type <code>com.sun.star.lang.XTypeProvider</code>. */ public void _getTypes() { boolean result = false; log.println("getting Types..."); types = oObj.getTypes(); for (int i=0;i<types.length;i++) { int k = i+1; log.println(k+". Type is "+types[i].toString()); if (types[i].toString().equals ("Type[com.sun.star.lang.XTypeProvider]")) { result = true; } } if (!result) { log.println("Component must provide Type " +"<com.sun.star.lang.XTypeProvider>"); } tRes.tested("getTypes()", result); } // end getTypes() }
package lombok.launch; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; public class Delombok { private final Object delombokInstance; private final Method addDirectory; private final Method delombok; private final Method formatOptionsToMap; private final Method setVerbose; private final Method setCharset; private final Method setClasspath; private final Method setFormatPreferences; private final Method setOutput; private final Method setSourcepath; public Delombok () throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException { final ClassLoader shadowClassLoader = Main.createShadowClassLoader(); final Class<?> delombokClass = shadowClassLoader.loadClass("lombok.delombok.Delombok"); this.delombokInstance = delombokClass.newInstance(); // Get method handles... this.addDirectory = delombokClass.getMethod("addDirectory", File.class); this.delombok = delombokClass.getMethod("delombok"); this.formatOptionsToMap = delombokClass.getMethod("formatOptionsToMap", List.class); this.setVerbose = delombokClass.getMethod("setVerbose", boolean.class); this.setCharset = delombokClass.getMethod("setCharset", String.class); this.setClasspath = delombokClass.getMethod("setClasspath", String.class); this.setFormatPreferences = delombokClass.getMethod("setFormatPreferences", Map.class); this.setOutput = delombokClass.getMethod("setOutput", File.class); this.setSourcepath = delombokClass.getMethod("setSourcepath", String.class); } public void addDirectory (final File base) throws IllegalAccessException, IOException, InvocationTargetException { addDirectory.invoke(delombokInstance, base); } public boolean delombok () throws IllegalAccessException, IOException, InvocationTargetException { return Boolean.parseBoolean( delombok.invoke(delombokInstance).toString() ); } @SuppressWarnings("unchecked") public Map<String, String> formatOptionsToMap (final List<String> formatOptions) throws Exception { return (Map<String, String>)formatOptionsToMap.invoke(null, formatOptions); } public void setVerbose (final boolean verbose) throws IllegalAccessException, InvocationTargetException { setVerbose.invoke(delombokInstance, verbose); } public void setCharset (final String charset) throws IllegalAccessException, InvocationTargetException { setCharset.invoke(delombokInstance, charset); } public void setClasspath (final String classpath) throws IllegalAccessException, InvocationTargetException { setClasspath.invoke(delombokInstance, classpath); } public void setFormatPreferences (final Map<String, String> prefs) throws IllegalAccessException, InvocationTargetException { setFormatPreferences.invoke(delombokInstance, prefs); } public void setOutput (final File dir) throws IllegalAccessException, InvocationTargetException { setOutput.invoke(delombokInstance, dir); } public void setSourcepath (final String sourcepath) throws IllegalAccessException, InvocationTargetException { setSourcepath.invoke(delombokInstance, sourcepath); } }
package wolf.parser; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; /** * Generates a parse table * @author Joseph Alacqua * @author Kevin Dittmar * @author William Ezekiel * @version Mar 14, 2016 */ public class ParseTableGenerator { /** * Generate a parse table. * @param fsm a finite state machine * @param terminals a set of terminals * @param nonterminals a set of nonterminals * @param terminal_lookup_table the terminal lookup table. * @return the generated parse table. */ public ParseTable generate( FSM fsm, Set<Terminal> terminals, Set<Nonterminal> nonterminals, Map<String, Terminal> terminal_lookup_table) { ArrayList<LinkedHashMap<Symbol,TableCell>> parse_table = new ArrayList(); for(State state:fsm.states) { Set<Arc> arcSet = new LinkedHashSet<>(fsm.findArcsWithFromState(state)); LinkedHashMap<Symbol,TableCell> row = new LinkedHashMap(); // shifts and gotos for(Arc arc :arcSet) { TableCell tc = new TableCell(); if(arc.transition_symbol instanceof Nonterminal) { tc.action = TableCell.Action.GOTO; tc.id_number = arc.to.id; row.put(arc.transition_symbol,tc); } else if(arc.transition_symbol instanceof Terminal) { tc.action = TableCell.Action.SHIFT; tc.id_number = arc.to.id; row.put(arc.transition_symbol,tc); } else{ //error just pretend okay } } //reduce for(Item item: state.items) { if(item.atEnd()) { Rule rule = item.getRule(); int rule_id = fsm.getProductions().indexOf(rule); if(rule_id == -1) { System.err.println("Unknown Rule: " + rule); System.exit(1); } TableCell tc = new TableCell( TableCell.Action.REDUCE, rule_id ); TableCell existingCell = row.get(item.lookahead); if(existingCell == null){ row.put(item.lookahead,tc); } else if(!existingCell.equals(tc)){ System.err.println("Conflict: " + tc + " vs " + row.get(item.lookahead)); System.exit(1); } } else if(item.getCurrentSymbol() instanceof EndSymbol) { // accept row.put(item.getCurrentSymbol(), new TableCell(TableCell.Action.ACCEPT,-1)); } } parse_table.add(row); } // We want all of the terminals to be in the parse_table, including // the end symbol Set<Symbol> parse_table_symbols = new LinkedHashSet(terminals); // We want all of the nonterminals to be in the parse_table... parse_table_symbols.addAll(nonterminals); // ... but we don't want the start symbol to be in the parse_table. parse_table_symbols.remove(fsm.start_symbol); return new ParseTable( parse_table, parse_table_symbols, terminal_lookup_table ); } }
package org.appwork.utils.logging2.sendlogs; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.appwork.exceptions.WTFException; import org.appwork.swing.action.BasicAction; import org.appwork.utils.Application; import org.appwork.utils.Files; import org.appwork.utils.IO; import org.appwork.utils.Regex; import org.appwork.utils.swing.dialog.Dialog; import org.appwork.utils.swing.dialog.DialogCanceledException; import org.appwork.utils.swing.dialog.DialogClosedException; import org.appwork.utils.swing.dialog.ProgressDialog; import org.appwork.utils.swing.dialog.ProgressDialog.ProgressGetter; import org.appwork.utils.zip.ZipIOException; import org.appwork.utils.zip.ZipIOWriter; /** * @author Thomas * */ public abstract class AbstractLogAction extends BasicAction { protected int total; protected int current; public AbstractLogAction() { } @Override public void actionPerformed(final ActionEvent e) { final ProgressDialog p = new ProgressDialog(new ProgressGetter() { @Override public int getProgress() { return -1; } @Override public String getString() { return T.T.LogAction_getString_uploading_(); } @Override public void run() throws Exception { create(); } @Override public String getLabelString() { return null; } }, Dialog.BUTTONS_HIDE_OK, T.T.LogAction_actionPerformed_zip_title_(), T.T.LogAction_actionPerformed_wait_(), null, null, null); try { Dialog.getInstance().showDialog(p); } catch (final Throwable e1) { } } protected void create() throws DialogClosedException, DialogCanceledException { final File[] logs = Application.getResource("logs").listFiles(); final java.util.List<LogFolder> folders = new ArrayList<LogFolder>(); LogFolder latest = null; if (logs != null) { for (final File f : logs) { final String timestampString = new Regex(f.getName(), "(\\d+)_\\d\\d\\.\\d\\d").getMatch(0); if (timestampString != null) { final long timestamp = Long.parseLong(timestampString); LogFolder lf; lf = new LogFolder(f, timestamp); if (isCurrentLogFolder(timestamp)) { /* * this is our current logfolder, flush it before we can * upload it */ lf.setNeedsFlush(true); } if (Files.getFiles(new FileFilter() { @Override public boolean accept(final File pathname) { return pathname.isFile() && pathname.length() > 0; } }, f).size() == 0) { continue; } folders.add(lf); if (latest == null || lf.getCreated() > latest.getCreated()) { latest = lf; } } } } if (latest != null) { latest.setSelected(true); } if (folders.size() == 0) { Dialog.getInstance().showExceptionDialog("WTF!", "At Least the current Log should be available", new WTFException()); return; } final SendLogDialog d = new SendLogDialog(folders); Dialog.getInstance().showDialog(d); final java.util.List<LogFolder> selection = d.getSelectedFolders(); if (selection.size() == 0) { return; } total = selection.size(); current = 0; final ProgressDialog p = new ProgressDialog(new ProgressGetter() { @Override public int getProgress() { if (current == 0) { return -1; } return Math.min(99,current * 100 / total); } @Override public String getString() { return T.T.LogAction_getString_uploading_(); } @Override public void run() throws Exception { try { createPackage(selection); } catch (final WTFException e) { throw new InterruptedException(); } } @Override public String getLabelString() { return null; } }, Dialog.BUTTONS_HIDE_OK, T.T.LogAction_actionPerformed_zip_title_(), T.T.LogAction_actionPerformed_wait_(), null, null, null); Dialog.getInstance().showDialog(p); } /** * @param selection * */ protected void createPackage(final List<LogFolder> selection) throws Exception { for (final LogFolder lf : selection) { final File zip = Application.getResource("tmp/logs/logPackage.zip"); zip.delete(); zip.getParentFile().mkdirs(); ZipIOWriter writer = null; final String name =lf.getFolder().getName()+"-"+ format(lf.getCreated()) + " to " + format(lf.getLastModified()); final File folder = Application.getResource("tmp/logs/" + name); try { if (lf.isNeedsFlush()) { flushLogs(); } writer = new ZipIOWriter(zip) { public void addFile(final File addFile, final boolean compress, final String fullPath) throws FileNotFoundException, ZipIOException, IOException { if (addFile.getName().endsWith(".lck") || (addFile.isFile() && addFile.length() == 0)) { return; } if (Thread.currentThread().isInterrupted()) { throw new WTFException("INterrupted"); } super.addFile(addFile, compress, fullPath); } }; if (folder.exists()) { Files.deleteRecursiv(folder); } IO.copyFolderRecursive(lf.getFolder(), folder, true); writer.addDirectory(folder, true, null); } finally { try { writer.close(); } catch (final Throwable e) { } } onNewPackage(zip,format(lf.getCreated()) + "-" + format(lf.getLastModified())); current++; } } /** * @param created * @return */ protected String format(final long created) { final Date date = new Date(created); return new SimpleDateFormat("dd.MM.yy HH.mm.ss",Locale.GERMANY).format(date); } /** * @param timestamp * @return */ abstract protected boolean isCurrentLogFolder(long timestamp); /** * @param zip * @param string * @throws IOException */ abstract protected void onNewPackage(File zip, String string) throws IOException; abstract protected void flushLogs(); }
package org.griphyn.cPlanner.transfer.implementation; import org.griphyn.cPlanner.classes.ADag; import org.griphyn.cPlanner.classes.SubInfo; import org.griphyn.cPlanner.classes.TransferJob; import org.griphyn.cPlanner.classes.PlannerOptions; import org.griphyn.cPlanner.classes.FileTransfer; import org.griphyn.cPlanner.classes.SiteInfo; import org.griphyn.cPlanner.classes.JobManager; import org.griphyn.cPlanner.classes.NameValue; import org.griphyn.cPlanner.common.LogManager; import org.griphyn.cPlanner.common.PegasusProperties; import org.griphyn.cPlanner.transfer.Implementation; import org.griphyn.cPlanner.transfer.MultipleFTPerXFERJob; import org.griphyn.common.catalog.TransformationCatalogEntry; import org.griphyn.common.classes.TCType; import org.griphyn.common.util.Separator; import org.griphyn.cPlanner.cluster.aggregator.JobAggregatorFactory; import org.griphyn.cPlanner.cluster.JobAggregator; import java.io.File; import java.io.FileWriter; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.LinkedList; import java.util.Iterator; import org.griphyn.cPlanner.transfer.Refiner; import org.griphyn.cPlanner.classes.Profile; import java.util.ArrayList; /** * A Windward implementation that uses the seqexec client to execute * * -DC Transfer client to fetch the raw data sources * -Pegasus transfer client to fetch the patterns from the pattern catalog. * * @author Karan Vahi * @version $Revision$ */ public class Windward extends Abstract implements MultipleFTPerXFERJob { /** * The prefix to identify the raw data sources. */ public static final String DATA_SOURCE_PREFIX = "DS"; /** * A short description of the transfer implementation. */ public static final String DESCRIPTION = "Seqexec Transfer Wrapper around Pegasus Transfer and DC Transfer Client"; /** * The transformation namespace for for the transfer job. */ public static final String TRANSFORMATION_NAMESPACE = "windward"; /** * The name of the underlying transformation that is queried for in the * Transformation Catalog. */ public static final String TRANSFORMATION_NAME = "dc-transfer"; /** * The version number for the transfer job. */ public static final String TRANSFORMATION_VERSION = null; /** * The derivation namespace for for the transfer job. */ public static final String DERIVATION_NAMESPACE = "windward"; /** * The name of the underlying derivation. */ public static final String DERIVATION_NAME = "dc-transfer"; /** * The derivation version number for the transfer job. */ public static final String DERIVATION_VERSION = null; /** * The handle to the transfer implementation. */ private Transfer mPegasusTransfer; /** * The seqexec job aggregator. */ private JobAggregator mSeqExecAggregator; /** * The overloaded constructor, that is called by the Factory to load the * class. * * @param properties the properties object. * @param options the options passed to the Planner. */ public Windward( PegasusProperties properties, PlannerOptions options) { super(properties, options); //should probably go through the factory mPegasusTransfer = new Transfer( properties, options ); //just to pass the label have to send an empty ADag. //should be fixed ADag dag = new ADag(); dag.dagInfo.setLabel( "windward" ); mSeqExecAggregator = JobAggregatorFactory.loadInstance( JobAggregatorFactory.SEQ_EXEC_CLASS, properties, options.getSubmitDirectory(), dag ); } /** * Sets the callback to the refiner, that has loaded this implementation. * * @param refiner the transfer refiner that loaded the implementation. */ public void setRefiner(Refiner refiner){ super.setRefiner( refiner ); //also set the refiner for hte internal pegasus transfer mPegasusTransfer.setRefiner( refiner ); } /** * * * @param job the SubInfo object for the job, in relation to which * the transfer node is being added. Either the transfer * node can be transferring this jobs input files to * the execution pool, or transferring this job's output * files to the output pool. * @param files collection of <code>FileTransfer</code> objects * representing the data files and staged executables to be * transferred. * @param execFiles subset collection of the files parameter, that identifies * the executable files that are being transferred. * @param txJobName the name of transfer node. * @param jobClass the job Class for the newly added job. Can be one of the * following: * stage-in * stage-out * inter-pool transfer * * @return the created TransferJob. */ public TransferJob createTransferJob( SubInfo job, Collection files, Collection execFiles, String txJobName, int jobClass) { //iterate through all the files and identify the patterns //and the other data sources Collection rawDataSources = new LinkedList(); Collection patterns = new LinkedList(); for( Iterator it = files.iterator(); it.hasNext(); ){ FileTransfer ft = ( FileTransfer )it.next(); if( ft.getLFN().startsWith( DATA_SOURCE_PREFIX ) ){ //it a raw data source rawDataSources.add( ft ); } else{ //everything else is a pattern patterns.add( ft ); } } List txJobs = new LinkedList(); //use the Pegasus Transfer to handle the patterns TransferJob patternTXJob = null; String patternTXJobStdin = null; if( !patterns.isEmpty() ){ patternTXJob = mPegasusTransfer.createTransferJob( job, patterns, null, txJobName, jobClass ); //get the stdin and set it as lof in the arguments patternTXJobStdin = patternTXJob.getStdIn(); StringBuffer patternArgs = new StringBuffer(); patternArgs.append( patternTXJob.getArguments() ).append( " " ). append( patternTXJobStdin ); patternTXJob.setArguments( patternArgs.toString() ); patternTXJob.setStdIn( "" ); txJobs.add( patternTXJob ); } TransformationCatalogEntry tcEntry = this.getTransformationCatalogEntry( job.getSiteHandle() ); if(tcEntry == null){ //should throw a TC specific exception StringBuffer error = new StringBuffer(); error.append( "Could not find entry in tc for lfn " ).append( getCompleteTCName() ). append(" at site " ).append( job.getSiteHandle()); mLogger.log( error.toString(), LogManager.ERROR_MESSAGE_LEVEL); throw new RuntimeException( error.toString() ); } //this should in fact only be set // for non third party pools //we first check if there entry for transfer universe, //if no then go for globus SiteInfo ePool = mSCHandle.getTXPoolEntry( job.getSiteHandle() ); JobManager jobmanager = ePool.selectJobManager(this.TRANSFER_UNIVERSE,true); //use the DC transfer client to handle the data sources for( Iterator it = rawDataSources.iterator(); it.hasNext(); ){ FileTransfer ft = (FileTransfer)it.next(); TransferJob dcTXJob = new TransferJob(); dcTXJob.namespace = tcEntry.getLogicalNamespace(); dcTXJob.logicalName = tcEntry.getLogicalName(); dcTXJob.version = tcEntry.getLogicalVersion(); dcTXJob.dvNamespace = this.DERIVATION_NAMESPACE; dcTXJob.dvName = this.DERIVATION_NAME; dcTXJob.dvVersion = this.DERIVATION_VERSION; dcTXJob.setRemoteExecutable( tcEntry.getPhysicalTransformation() ); dcTXJob.globusScheduler = (jobmanager == null) ? null : jobmanager.getInfo(JobManager.URL); dcTXJob.setArguments( quote( ((NameValue)ft.getSourceURL()).getValue() ) + " " + quote( ((NameValue)ft.getDestURL()).getValue() ) ); dcTXJob.setStdIn( "" ); dcTXJob.setStdOut( "" ); dcTXJob.setStdErr( "" ); dcTXJob.setSiteHandle( job.getSiteHandle() ); //the profile information from the transformation //catalog needs to be assimilated into the job dcTXJob.updateProfiles(tcEntry); txJobs.add( dcTXJob ); } //now lets merge all these jobs SubInfo merged = mSeqExecAggregator.construct( txJobs, "transfer", txJobName ); TransferJob txJob = new TransferJob( merged ); //set the name of the merged job back to the name of //transfer job passed in the function call txJob.setName( txJobName ); txJob.setJobType( jobClass ); //if a pattern job was constructed add the pattern stdin //as an input file for condor to transfer if( patternTXJobStdin != null ){ txJob.condorVariables.addIPFileForTransfer( patternTXJobStdin ); } //take care of transfer of proxies this.checkAndTransferProxy( txJob ); //apply the priority to the transfer job this.applyPriority( txJob ); if(execFiles != null){ //we need to add setup jobs to change the XBit super.addSetXBitJobs( job, txJob, execFiles ); } return txJob; } /** * Returns a textual description of the transfer implementation. * * @return a short textual description */ public String getDescription(){ return this.DESCRIPTION; } /** * Returns a boolean indicating whether the transfer protocol being used by * the implementation preserves the X Bit or not while staging. * * @return boolean */ public boolean doesPreserveXBit(){ return false; } /** * Return a boolean indicating whether the transfers to be done always in * a third party transfer mode. A value of false, results in the * direct or peer to peer transfers being done. * <p> * A value of false does not preclude third party transfers. They still can * be done, by setting the property "pegasus.transfer.*.thirdparty.sites". * * @return boolean indicating whether to always use third party transfers * or not. * * @see PegasusProperties#getThirdPartySites(String) */ public boolean useThirdPartyTransferAlways(){ return false; } /** * Retrieves the transformation catalog entry for the executable that is * being used to transfer the files in the implementation. * * @param siteHandle the handle of the site where the transformation is * to be searched. * * @return the transformation catalog entry if found, else null. */ public TransformationCatalogEntry getTransformationCatalogEntry( String siteHandle ){ List tcentries = null; try { //namespace and version are null for time being tcentries = mTCHandle.getTCEntries(this.TRANSFORMATION_NAMESPACE, this.TRANSFORMATION_NAME, this.TRANSFORMATION_VERSION, siteHandle, TCType.INSTALLED); } catch (Exception e) { mLogger.log( "Unable to retrieve entry from TC for " + getCompleteTCName() + " Cause:" + e, LogManager.DEBUG_MESSAGE_LEVEL ); } return ( tcentries == null ) ? this.defaultTCEntry( this.TRANSFORMATION_NAMESPACE, this.TRANSFORMATION_NAME, this.TRANSFORMATION_VERSION, siteHandle ): //try using a default one (TransformationCatalogEntry) tcentries.get(0); } /** * Quotes a URL and returns it * * @param url String * @return quoted url */ protected String quote( String url ){ StringBuffer q = new StringBuffer(); q.append( "'" ).append( url ).append( "'" ); return q.toString(); } /** * Returns a default TC entry to be used for the DC transfer client. * * @param namespace the namespace of the transfer transformation * @param name the logical name of the transfer transformation * @param version the version of the transfer transformation * * @param site the site for which the default entry is required. * * * @return the default entry. */ protected TransformationCatalogEntry defaultTCEntry( String namespace, String name, String version, String site ){ TransformationCatalogEntry defaultTCEntry = null; //check if DC_HOME is set String dcHome = mSCHandle.getEnvironmentVariable( site, "DC_HOME" ); mLogger.log( "Creating a default TC entry for " + Separator.combine( namespace, name, version ) + " at site " + site, LogManager.DEBUG_MESSAGE_LEVEL ); //if home is still null if ( dcHome == null ){ //cannot create default TC mLogger.log( "Unable to create a default entry for " + Separator.combine( namespace, name, version ) + " as DC_HOME is not set in Site Catalog" , LogManager.DEBUG_MESSAGE_LEVEL ); //set the flag back to true return defaultTCEntry; } //get the essential environment variables required to get //it to work correctly List envs = this.getEnvironmentVariables( site ); if( envs == null ){ //cannot create default TC mLogger.log( "Unable to create a default entry for as could not construct necessary environment " + Separator.combine( namespace, name, version ) , LogManager.DEBUG_MESSAGE_LEVEL ); //set the flag back to true return defaultTCEntry; } //add the DC home to environments envs.add( new Profile( Profile.ENV, "DC_HOME", dcHome ) ); //remove trailing / if specified dcHome = ( dcHome.charAt( dcHome.length() - 1 ) == File.separatorChar )? dcHome.substring( 0, dcHome.length() - 1 ): dcHome; //construct the path to the jar StringBuffer path = new StringBuffer(); path.append( dcHome ).append( File.separator ). append( "bin" ).append( File.separator ). append( "dc-transfer" ); defaultTCEntry = new TransformationCatalogEntry( namespace, name, version ); defaultTCEntry.setPhysicalTransformation( path.toString() ); defaultTCEntry.setResourceId( site ); defaultTCEntry.setType( TCType.INSTALLED ); defaultTCEntry.setProfiles( envs ); //register back into the transformation catalog //so that we do not need to worry about creating it again try{ mTCHandle.addTCEntry( defaultTCEntry , false ); } catch( Exception e ){ //just log as debug. as this is more of a performance improvement //than anything else mLogger.log( "Unable to register in the TC the default entry " + defaultTCEntry.getLogicalTransformation() + " for site " + site, e, LogManager.DEBUG_MESSAGE_LEVEL ); } mLogger.log( "Created entry with path " + defaultTCEntry.getPhysicalTransformation(), LogManager.DEBUG_MESSAGE_LEVEL ); return defaultTCEntry; } /** * Returns the environment profiles that are required for the default * entry to sensibly work. * * @param site the site where the job is going to run. * * @return List of environment variables, else null in case where the * required environment variables could not be found. */ protected List getEnvironmentVariables( String site ){ List result = new ArrayList(1) ; //create the CLASSPATH from home String java = mSCHandle.getEnvironmentVariable( site, "JAVA_HOME" ); if( java == null ){ mLogger.log( "JAVA_HOME not set in site catalog for site " + site, LogManager.DEBUG_MESSAGE_LEVEL ); return null; } //we have both the environment variables result.add( new Profile( Profile.ENV, "JAVA_HOME", java ) ); return result; } /** * Returns the complete name for the transformation. * * @return the complete name. */ protected String getCompleteTCName(){ return Separator.combine(this.TRANSFORMATION_NAMESPACE, this.TRANSFORMATION_NAME, this.TRANSFORMATION_VERSION); } }
package org.jgroups.protocols.pbcast; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Vector; import org.jgroups.Address; import org.jgroups.Channel; import org.jgroups.Event; import org.jgroups.Global; import org.jgroups.Header; import org.jgroups.Message; import org.jgroups.TimeoutException; import org.jgroups.View; import org.jgroups.stack.IpAddress; import org.jgroups.stack.Protocol; import org.jgroups.stack.StateTransferInfo; import org.jgroups.util.Promise; import org.jgroups.util.Streamable; import org.jgroups.util.Util; import EDU.oswego.cs.dl.util.concurrent.PooledExecutor; import EDU.oswego.cs.dl.util.concurrent.ThreadFactory; /** * <code>STREAMING_STATE_TRANSFER</code>, as its name implies, allows a streaming * state transfer between two channel instances. * * <p> * * Major advantage of this approach is that transfering application state to a * joining member of a group does not entail loading of the complete application * state into memory. Application state, for example, might be located entirely * on some form of disk based storage. The default <code>STATE_TRANSFER</code> * requires this state to be loaded entirely into memory before being transferred * to a group member while <code>STREAMING_STATE_TRANSFER</code> does not. * Thus <code>STREAMING_STATE_TRANSFER</code> protocol is able to transfer * application state that is very large (>1Gb) without a likelihood of such transfer * resulting in OutOfMemoryException. * * <p> * * Channel instance can be configured with either <code>STREAMING_STATE_TRANSFER</code> * or <code>STATE_TRANSFER</code> but not both protocols at the same time. * * <p> * * In order to process streaming state transfer an application has to implement * <code>ExtendedMessageListener</code> if it is using channel in a push style * mode or it has to process <code>StreamingSetStateEvent</code> and * <code>StreamingGetStateEvent</code> if it is using channel in a pull style mode. * * * @author Vladimir Blagojevic * @see org.jgroups.ExtendedMessageListener * @see org.jgroups.StreamingGetStateEvent * @see org.jgroups.StreamingSetStateEvent * @see org.jgroups.protocols.pbcast.STATE_TRANSFER * @since 2.4 * * @version $Id$ * */ public class STREAMING_STATE_TRANSFER extends Protocol { Address local_addr = null; final Vector members = new Vector(); final Map state_requesters = new HashMap(); /** set to true while waiting for a STATE_RSP */ boolean waiting_for_state_response = false; Digest digest = null; final HashMap map = new HashMap(); // to store configuration information int num_state_reqs = 0; long num_bytes_sent = 0; double avg_state_size = 0; final static String NAME = "STREAMING_STATE_TRANSFER"; private InetAddress bind_addr; private int bind_port = 0; private StateProviderThreadSpawner spawner; private int max_pool = 5; private long pool_thread_keep_alive; private int socket_buffer_size = 8 * 1024; private boolean use_reading_thread; private Promise flush_promise = new Promise();; private volatile boolean use_flush; private long flush_timeout = 4000; private final Object poolLock = new Object(); private int threadCounter; public final String getName() { return NAME; } public int getNumberOfStateRequests() { return num_state_reqs; } public long getNumberOfStateBytesSent() { return num_bytes_sent; } public double getAverageStateSize() { return avg_state_size; } public Vector requiredDownServices() { Vector retval = new Vector(); retval.addElement(new Integer(Event.GET_DIGEST_STATE)); retval.addElement(new Integer(Event.SET_DIGEST)); return retval; } public Vector requiredUpServices() { Vector retval = new Vector(); if (use_flush) { retval.addElement(new Integer(Event.SUSPEND)); retval.addElement(new Integer(Event.RESUME)); } return retval; } public void resetStats() { super.resetStats(); num_state_reqs = 0; num_bytes_sent = 0; avg_state_size = 0; } public boolean setProperties(Properties props) { super.setProperties(props); use_flush = Util.parseBoolean(props, "use_flush", false); flush_timeout = Util.parseLong(props, "flush_timeout", flush_timeout); try { bind_addr = Util.parseBindAddress(props, "bind_addr"); } catch (UnknownHostException e) { log.error("(bind_addr): host " + e.getLocalizedMessage() + " not known"); return false; } bind_port = Util.parseInt(props, "start_port", 0); socket_buffer_size = Util.parseInt(props, "socket_buffer_size", 8 * 1024); max_pool = Util.parseInt(props, "max_pool", 5); pool_thread_keep_alive = Util.parseLong(props, "pool_thread_keep_alive", 1000 * 30); //30 sec use_reading_thread = Util.parseBoolean(props, "use_reading_thread", false); if (props.size() > 0) { log.error("the following properties are not recognized: " + props); return false; } return true; } public void init() throws Exception { map.put("state_transfer", Boolean.TRUE); map.put("protocol_class", getClass().getName()); } public void start() throws Exception { passUp(new Event(Event.CONFIG, map)); } public void stop() { super.stop(); waiting_for_state_response = false; if (spawner != null) { spawner.stop(); } } public void up(Event evt) { switch (evt.getType()) { case Event.BECOME_SERVER : break; case Event.SET_LOCAL_ADDRESS : local_addr = (Address) evt.getArg(); break; case Event.TMP_VIEW : case Event.VIEW_CHANGE : handleViewChange((View) evt.getArg()); break; case Event.GET_DIGEST_STATE_OK : synchronized (state_requesters) { digest = (Digest) evt.getArg(); if (log.isDebugEnabled()) log.debug("GET_DIGEST_STATE_OK: digest is " + digest); } respondToStateRequester(); return; case Event.MSG : Message msg = (Message) evt.getArg(); StateHeader hdr = (StateHeader) msg.removeHeader(getName()); if (hdr != null) { switch (hdr.type) { case StateHeader.STATE_REQ : handleStateReq(hdr); break; case StateHeader.STATE_RSP : handleStateRsp(hdr); break; case StateHeader.STATE_REMOVE_REQUESTER : removeFromStateRequesters(hdr.sender, hdr.state_id); break; default : if (log.isErrorEnabled()) log.error("type " + hdr.type + " not known in StateHeader"); break; } return; } break; case Event.CONFIG : Map config = (Map) evt.getArg(); if (bind_addr == null && (config != null && config.containsKey("bind_addr"))) { bind_addr = (InetAddress) config.get("bind_addr"); if (log.isDebugEnabled()) log.debug("using bind_addr from CONFIG event " + bind_addr); } break; } passUp(evt); } public void down(Event evt) { Address target; StateTransferInfo info; switch (evt.getType()) { case Event.TMP_VIEW : case Event.VIEW_CHANGE : handleViewChange((View) evt.getArg()); break; case Event.GET_STATE : info = (StateTransferInfo) evt.getArg(); if (info.target == null) { target = determineCoordinator(); } else { target = info.target; if (target.equals(local_addr)) { if (log.isErrorEnabled()) log.error("GET_STATE: cannot fetch state from myself !"); target = null; } } if (target == null) { if (log.isDebugEnabled()) log.debug("GET_STATE: first member (no state)"); passUp(new Event(Event.GET_STATE_OK, new StateTransferInfo())); } else { if (use_flush) { startFlush(flush_timeout); } Message state_req = new Message(target, null, null); state_req.putHeader(NAME, new StateHeader(StateHeader.STATE_REQ, local_addr, info.state_id)); if (log.isDebugEnabled()) log.debug("GET_STATE: asking " + target + " for state"); // suspend sending and handling of mesage garbage collection gossip messages, // fixes bugs #943480 and #938584). Wake up when state has been received if (log.isDebugEnabled()) log.debug("passing down a SUSPEND_STABLE event"); passDown(new Event(Event.SUSPEND_STABLE, new Long(info.timeout))); waiting_for_state_response = true; passDown(new Event(Event.MSG, state_req)); } return; // don't pass down any further ! case Event.STATE_TRANSFER_INPUTSTREAM_CLOSED : if (use_flush) { stopFlush(); } if (log.isDebugEnabled()) log.debug("STATE_TRANSFER_INPUTSTREAM_CLOSED received"); //resume sending and handling of message garbage collection gossip messages, // fixes bugs #943480 and #938584). Wakes up a previously suspended message garbage // collection protocol (e.g. STABLE) if (log.isDebugEnabled()) log.debug("passing down a RESUME_STABLE event"); passDown(new Event(Event.RESUME_STABLE)); return; case Event.SUSPEND_OK : if (use_flush) { flush_promise.setResult(Boolean.TRUE); } break; case Event.CONFIG : Map config = (Map) evt.getArg(); if(config != null && config.containsKey("flush_timeout")) { Long ftimeout = (Long) config.get("flush_timeout"); use_flush = true; flush_timeout = ftimeout.longValue(); } break; } passDown(evt); // pass on to the layer below us } /** * When FLUSH is used we do not need to pass digests between members * * see JGroups/doc/design/PArtialStateTransfer.txt * see JGroups/doc/design/FLUSH.txt * * @return true if use of digests is required, false otherwise */ private boolean isDigestNeeded() { return !use_flush; } private void respondToStateRequester() { // setup the plumbing if needed if (spawner == null) { ServerSocket serverSocket = Util.createServerSocket(bind_addr, bind_port); spawner = new StateProviderThreadSpawner(setupThreadPool(), serverSocket); new Thread(Util.getGlobalThreadGroup(), spawner, "StateProviderThreadSpawner").start(); } synchronized (state_requesters) { if (state_requesters.isEmpty()) { if (warn) log.warn("Should be responding to state requester, but there are no requesters !"); return; } if (digest == null && isDigestNeeded()) { if (warn) log.warn("Should be responding to state requester, but there is no digest !"); else digest = digest.copy(); } if (log.isDebugEnabled()) log.debug("Iterating state requesters " + state_requesters); for (Iterator it = state_requesters.keySet().iterator(); it.hasNext();) { String tmp_state_id = (String) it.next(); Set requesters = (Set) state_requesters.get(tmp_state_id); for (Iterator iter = requesters.iterator(); iter.hasNext();) { Address requester = (Address) iter.next(); Message state_rsp = new Message(requester); StateHeader hdr = new StateHeader(StateHeader.STATE_RSP, local_addr, spawner.getServerSocketAddress(), digest, tmp_state_id); state_rsp.putHeader(NAME, hdr); if (log.isDebugEnabled()) log.debug("Responding to state requester " + requester + " with address " + spawner.getServerSocketAddress() + " and digest " + digest); passDown(new Event(Event.MSG, state_rsp)); if (stats) { num_state_reqs++; } } } } } private boolean startFlush(long timeout) { boolean successfulFlush = false; passUp(new Event(Event.SUSPEND)); try { flush_promise.reset(); flush_promise.getResultWithTimeout(timeout); successfulFlush = true; } catch (TimeoutException e) { log.warn("Initiator of flush and state requesting member " + local_addr + " timed out waiting for flush responses after " + timeout + " msec"); } return successfulFlush; } private void stopFlush() { passUp(new Event(Event.RESUME)); } private PooledExecutor setupThreadPool() { PooledExecutor threadPool = new PooledExecutor(max_pool); threadPool.waitWhenBlocked(); threadPool.setMinimumPoolSize(1); threadPool.setKeepAliveTime(pool_thread_keep_alive); threadPool.setThreadFactory(new ThreadFactory() { public Thread newThread(final Runnable command) { synchronized (poolLock) { threadCounter++; } return new Thread(Util.getGlobalThreadGroup(), "STREAMING_STATE_TRANSFER.poolid=" + threadCounter) { public void run() { if (log.isDebugEnabled()) { log.debug(Thread.currentThread() + " started."); } command.run(); if (log.isDebugEnabled()) { log.debug(Thread.currentThread() + " stopped."); } } }; } }); return threadPool; } private Address determineCoordinator() { Address ret = null; synchronized (members) { if (members != null && !members.isEmpty()) { for (int i = 0; i < members.size(); i++) if (!local_addr.equals(members.elementAt(i))) return (Address) members.elementAt(i); } } return ret; } private void handleViewChange(View v) { Address old_coord; Vector new_members = v.getMembers(); boolean send_up_null_state_rsp = false; synchronized (members) { old_coord = (Address) (members.size() > 0 ? members.firstElement() : null); members.clear(); members.addAll(new_members); // this handles the case where a coord dies during a state transfer; prevents clients from hanging forever // Note this only takes a coordinator crash into account, a getState(target, timeout), where target is not // null is not handled ! (Usually we get the state from the coordinator) if (waiting_for_state_response && old_coord != null && !members.contains(old_coord)) { send_up_null_state_rsp = true; } } if (send_up_null_state_rsp) { log.warn("discovered that the state provider (" + old_coord + ") crashed; will return null state to application"); } } private void handleStateReq(StateHeader hdr) { Object sender = hdr.sender; if (sender == null) { if (log.isErrorEnabled()) log.error("sender is null !"); return; } String id = hdr.state_id; synchronized (state_requesters) { boolean empty = state_requesters.isEmpty(); Set requesters = (Set) state_requesters.get(id); if (requesters == null) { requesters = new HashSet(); } requesters.add(sender); state_requesters.put(id, requesters); if (!isDigestNeeded()) { respondToStateRequester(); } else if (empty) { digest = null; if (log.isDebugEnabled()) log.debug("passing down GET_DIGEST_STATE"); passDown(new Event(Event.GET_DIGEST_STATE)); } } } void handleStateRsp(StateHeader hdr) { Digest tmp_digest = hdr.my_digest; waiting_for_state_response = false; if (isDigestNeeded()) { if (tmp_digest == null) { if (warn) log.warn("digest received from " + hdr.sender + " is null, skipping setting digest !"); } else { // set the digest (e.g.in NAKACK) passDown(new Event(Event.SET_DIGEST, tmp_digest)); } } connectToStateProvider(hdr); } void removeFromStateRequesters(Address address, String state_id) { synchronized (state_requesters) { Set requesters = (Set) state_requesters.get(state_id); if (requesters != null && !requesters.isEmpty()) { boolean removed = requesters.remove(address); if (log.isDebugEnabled()) { log.debug("Attempted to clear " + address + " from requesters, successful=" + removed); } if (requesters.isEmpty()) { state_requesters.remove(state_id); if (log.isDebugEnabled()) { log.debug("Cleared all requesters for state " + state_id + ",state_requesters=" + state_requesters); } } } else { if (warn) { log.warn("Attempted to clear " + address + " and state_id " + state_id + " from requesters,but the entry does not exist"); } } } } private void connectToStateProvider(StateHeader hdr) { IpAddress address = hdr.bind_addr; String tmp_state_id = hdr.getStateId(); StreamingInputStreamWrapper wrapper = null; StateTransferInfo sti = null; Socket socket = new Socket(); try { socket.bind(new InetSocketAddress(bind_addr, 0)); int bufferSize = socket.getReceiveBufferSize(); socket.setReceiveBufferSize(socket_buffer_size); if (log.isDebugEnabled()) log.debug("Connecting to state provider " + address.getIpAddress() + ":" + address.getPort() + ", original buffer size was " + bufferSize + " and was reset to " + socket.getReceiveBufferSize()); socket.connect(new InetSocketAddress(address.getIpAddress(), address.getPort())); if (log.isDebugEnabled()) log.debug("Connected to state provider, my end of the socket is " + socket.getLocalAddress() + ":" + socket.getLocalPort() + " passing inputstream up..."); //write out our state_id and address so state provider can clear this request ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); out.writeObject(tmp_state_id); out.writeObject(local_addr); wrapper = new StreamingInputStreamWrapper(socket); sti = new StateTransferInfo(hdr.sender, wrapper, tmp_state_id); } catch (IOException e) { if (warn) { log.warn("State reader socket thread spawned abnormaly", e); } //pass null stream up so that JChannel.getState() returns false InputStream is = null; sti = new StateTransferInfo(hdr.sender, is, tmp_state_id); } finally { if (!socket.isConnected()) { if (warn) log.warn("Could not connect to state provider. Closing socket..."); try { if (wrapper != null) { wrapper.close(); } else { socket.close(); } } catch (IOException e) { } //since socket did not connect properly we have to //clear our entry in state providers hashmap "manually" Message m = new Message(hdr.sender); StateHeader mhdr = new StateHeader(StateHeader.STATE_REMOVE_REQUESTER, local_addr, tmp_state_id); m.putHeader(NAME, mhdr); passDown(new Event(Event.MSG, m)); } passStreamUp(sti); } } private void passStreamUp(final StateTransferInfo sti) { Runnable readingThread = new Runnable() { public void run() { passUp(new Event(Event.STATE_TRANSFER_INPUTSTREAM, sti)); } }; if (use_reading_thread) { new Thread(Util.getGlobalThreadGroup(), readingThread, "STREAMING_STATE_TRANSFER.reader").start(); } else { readingThread.run(); } } private class StateProviderThreadSpawner implements Runnable { PooledExecutor pool; ServerSocket serverSocket; IpAddress address; volatile boolean running = true; public StateProviderThreadSpawner(PooledExecutor pool, ServerSocket stateServingSocket) { super(); this.pool = pool; this.serverSocket = stateServingSocket; this.address = new IpAddress(STREAMING_STATE_TRANSFER.this.bind_addr, serverSocket.getLocalPort()); } public void run() { for (; running;) { try { if (log.isDebugEnabled()) log.debug("StateProviderThreadSpawner listening at " + getServerSocketAddress() + "..."); if (log.isDebugEnabled()) log.debug("Pool has " + pool.getPoolSize() + " active threads"); final Socket socket = serverSocket.accept(); pool.execute(new Runnable() { public void run() { if (log.isDebugEnabled()) log.debug("Accepted request for state transfer from " + socket.getInetAddress() + ":" + socket.getPort() + " handing of to PooledExecutor thread"); new StateProviderHandler().process(socket); } }); } catch (IOException e) { if (warn) { //we get this exception when we close server socket //exclude that case if (serverSocket != null && !serverSocket.isClosed()) { log.warn("Spawning socket from server socket finished abnormaly", e); } } } catch (InterruptedException e) { // should not happen } } } public IpAddress getServerSocketAddress() { return address; } public void stop() { running = false; try { if (serverSocket != null && !serverSocket.isClosed()) { serverSocket.close(); } } catch (IOException e) { } finally { if (log.isDebugEnabled()) log.debug("Shutting the thread pool down... "); pool.shutdownNow(); } } } private class StateProviderHandler { public void process(Socket socket) { StreamingOutputStreamWrapper wrapper = null; ObjectInputStream ois = null; try { int bufferSize = socket.getSendBufferSize(); socket.setSendBufferSize(socket_buffer_size); if (log.isDebugEnabled()) log.debug("Running on " + Thread.currentThread() + ". Accepted request for state transfer from " + socket.getInetAddress() + ":" + socket.getPort() + ", original buffer size was " + bufferSize + " and was reset to " + socket.getSendBufferSize() + ", passing outputstream up... "); //read out state requesters state_id and address and clear this request ois = new ObjectInputStream(socket.getInputStream()); String state_id = (String) ois.readObject(); Address stateRequester = (Address) ois.readObject(); removeFromStateRequesters(stateRequester, state_id); wrapper = new StreamingOutputStreamWrapper(socket); StateTransferInfo sti = new StateTransferInfo(stateRequester, wrapper, state_id); passUp(new Event(Event.STATE_TRANSFER_OUTPUTSTREAM, sti)); } catch (IOException e) { if (warn) { log.warn("State writer socket thread spawned abnormaly", e); } } catch (ClassNotFoundException e) { //thrown by ois.readObject() //should never happen since String/Address are core classes } finally { if (socket != null && !socket.isConnected()) { if (warn) log.warn("Accepted request for state transfer but socket " + socket + " not connected properly. Closing it..."); try { if (wrapper != null) { wrapper.close(); } else { socket.close(); } } catch (IOException e) { } } } } } private class StreamingInputStreamWrapper extends InputStream { private Socket inputStreamOwner; private InputStream delegate; private Channel channelOwner; public StreamingInputStreamWrapper(Socket inputStreamOwner) throws IOException { super(); this.inputStreamOwner = inputStreamOwner; this.delegate = new BufferedInputStream(inputStreamOwner.getInputStream()); this.channelOwner = stack.getChannel(); } public int available() throws IOException { return delegate.available(); } public void close() throws IOException { if (log.isDebugEnabled()) { log.debug("State reader " + inputStreamOwner + " is closing the socket "); } if (channelOwner != null && channelOwner.isConnected()) { channelOwner.down(new Event(Event.STATE_TRANSFER_INPUTSTREAM_CLOSED)); } inputStreamOwner.close(); } public synchronized void mark(int readlimit) { delegate.mark(readlimit); } public boolean markSupported() { return delegate.markSupported(); } public int read() throws IOException { return delegate.read(); } public int read(byte[] b, int off, int len) throws IOException { return delegate.read(b, off, len); } public int read(byte[] b) throws IOException { return delegate.read(b); } public synchronized void reset() throws IOException { delegate.reset(); } public long skip(long n) throws IOException { return delegate.skip(n); } } private class StreamingOutputStreamWrapper extends OutputStream { private Socket outputStreamOwner; private OutputStream delegate; private long bytesWrittenCounter = 0; public StreamingOutputStreamWrapper(Socket outputStreamOwner) throws IOException { super(); this.outputStreamOwner = outputStreamOwner; this.delegate = new BufferedOutputStream(outputStreamOwner.getOutputStream()); } public void close() throws IOException { if (log.isDebugEnabled()) { log.debug("State writer " + outputStreamOwner + " is closing the socket "); } try { outputStreamOwner.close(); } catch (IOException e) { throw e; } finally { if (stats) { synchronized (state_requesters) { num_bytes_sent += bytesWrittenCounter; avg_state_size = num_bytes_sent / (double) num_state_reqs; } } } } public void flush() throws IOException { delegate.flush(); } public void write(byte[] b, int off, int len) throws IOException { delegate.write(b, off, len); bytesWrittenCounter += len; } public void write(byte[] b) throws IOException { delegate.write(b); if (b != null) { bytesWrittenCounter += b.length; } } public void write(int b) throws IOException { delegate.write(b); bytesWrittenCounter += 1; } } public static class StateHeader extends Header implements Streamable { public static final byte STATE_REQ = 1; public static final byte STATE_RSP = 2; public static final byte STATE_REMOVE_REQUESTER = 3; long id = 0; // state transfer ID (to separate multiple state transfers at the same time) byte type = 0; Address sender; // sender of state STATE_REQ or STATE_RSP Digest my_digest = null; // digest of sender (if type is STATE_RSP) IpAddress bind_addr = null; String state_id = null; // for partial state transfer public StateHeader() { // for externalization } public StateHeader(byte type, Address sender, String state_id) { this.type = type; this.sender = sender; this.state_id = state_id; } public StateHeader(byte type, Address sender, long id, Digest digest) { this.type = type; this.sender = sender; this.id = id; this.my_digest = digest; } public StateHeader(byte type, Address sender, IpAddress bind_addr, Digest digest, String state_id) { this.type = type; this.sender = sender; this.my_digest = digest; this.bind_addr = bind_addr; this.state_id = state_id; } public int getType() { return type; } public Digest getDigest() { return my_digest; } public String getStateId() { return state_id; } public boolean equals(Object o) { StateHeader other; if (sender != null && o != null) { if (!(o instanceof StateHeader)) return false; other = (StateHeader) o; return sender.equals(other.sender) && id == other.id; } return false; } public int hashCode() { if (sender != null) return sender.hashCode() + (int) id; else return (int) id; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("type=").append(type2Str(type)); if (sender != null) sb.append(", sender=").append(sender).append(" id=").append(id); if (my_digest != null) sb.append(", digest=").append(my_digest); return sb.toString(); } static String type2Str(int t) { switch (t) { case STATE_REQ : return "STATE_REQ"; case STATE_RSP : return "STATE_RSP"; case STATE_REMOVE_REQUESTER : return "STATE_REMOVE_REQUESTER"; default : return "<unknown>"; } } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(sender); out.writeLong(id); out.writeByte(type); out.writeObject(my_digest); out.writeObject(bind_addr); out.writeUTF(state_id); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { sender = (Address) in.readObject(); id = in.readLong(); type = in.readByte(); my_digest = (Digest) in.readObject(); bind_addr = (IpAddress) in.readObject(); state_id = in.readUTF(); } public void writeTo(DataOutputStream out) throws IOException { out.writeByte(type); out.writeLong(id); Util.writeAddress(sender, out); Util.writeStreamable(my_digest, out); Util.writeStreamable(bind_addr, out); Util.writeString(state_id, out); } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { type = in.readByte(); id = in.readLong(); sender = Util.readAddress(in); my_digest = (Digest) Util.readStreamable(Digest.class, in); bind_addr = (IpAddress) Util.readStreamable(IpAddress.class, in); state_id = Util.readString(in); } public long size() { long retval = Global.LONG_SIZE + Global.BYTE_SIZE; // id and type retval += Util.size(sender); retval += Global.BYTE_SIZE; // presence byte for my_digest if (my_digest != null) retval += my_digest.serializedSize(); retval += Global.BYTE_SIZE; // presence byte for state_id if (state_id != null) retval += state_id.length() + 2; return retval; } } }
package org.opencms.ade.containerpage; import org.opencms.ade.configuration.CmsADEConfigData; import org.opencms.ade.configuration.CmsADEManager; import org.opencms.ade.configuration.CmsElementView; import org.opencms.ade.configuration.CmsModelPageConfig; import org.opencms.ade.configuration.CmsResourceTypeConfig; import org.opencms.ade.configuration.CmsResourceTypeConfig.AddMenuVisibility; import org.opencms.ade.containerpage.inherited.CmsInheritanceReference; import org.opencms.ade.containerpage.inherited.CmsInheritanceReferenceParser; import org.opencms.ade.containerpage.inherited.CmsInheritedContainerState; import org.opencms.ade.containerpage.shared.CmsCntPageData; import org.opencms.ade.containerpage.shared.CmsCntPageData.ElementReuseMode; import org.opencms.ade.containerpage.shared.CmsContainer; import org.opencms.ade.containerpage.shared.CmsContainerElement; import org.opencms.ade.containerpage.shared.CmsContainerElement.ModelGroupState; import org.opencms.ade.containerpage.shared.CmsContainerElementData; import org.opencms.ade.containerpage.shared.CmsContainerPageRpcContext; import org.opencms.ade.containerpage.shared.CmsCreateElementData; import org.opencms.ade.containerpage.shared.CmsElementViewInfo; import org.opencms.ade.containerpage.shared.CmsFormatterConfig; import org.opencms.ade.containerpage.shared.CmsGroupContainer; import org.opencms.ade.containerpage.shared.CmsGroupContainerSaveResult; import org.opencms.ade.containerpage.shared.CmsInheritanceContainer; import org.opencms.ade.containerpage.shared.CmsInheritanceInfo; import org.opencms.ade.containerpage.shared.CmsRemovedElementStatus; import org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService; import org.opencms.ade.detailpage.CmsDetailPageResourceHandler; import org.opencms.ade.galleries.CmsGalleryService; import org.opencms.ade.galleries.shared.CmsGalleryDataBean; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.CmsUser; import org.opencms.file.types.CmsResourceTypeFolder; import org.opencms.file.types.CmsResourceTypeImage; import org.opencms.file.types.CmsResourceTypeXmlContainerPage; import org.opencms.file.types.I_CmsResourceType; import org.opencms.flex.CmsFlexController; import org.opencms.gwt.CmsDefaultResourceStatusProvider; import org.opencms.gwt.CmsGwtActionElement; import org.opencms.gwt.CmsGwtService; import org.opencms.gwt.CmsRpcException; import org.opencms.gwt.CmsVfsService; import org.opencms.gwt.shared.CmsGwtConstants; import org.opencms.gwt.shared.CmsListInfoBean; import org.opencms.gwt.shared.CmsModelResourceInfo; import org.opencms.gwt.shared.CmsTemplateContextInfo; import org.opencms.i18n.CmsLocaleManager; import org.opencms.jsp.CmsJspTagContainer; import org.opencms.jsp.util.CmsJspStandardContextBean.TemplateBean; import org.opencms.loader.CmsTemplateContextManager; import org.opencms.lock.CmsLock; import org.opencms.lock.CmsLockType; import org.opencms.main.CmsException; import org.opencms.main.CmsIllegalArgumentException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.relations.CmsRelation; import org.opencms.relations.CmsRelationFilter; import org.opencms.relations.CmsRelationType; import org.opencms.search.CmsSearchIndex; import org.opencms.search.CmsSearchManager; import org.opencms.search.galleries.CmsGallerySearch; import org.opencms.search.galleries.CmsGallerySearchResult; import org.opencms.security.CmsPermissionSet; import org.opencms.security.CmsRole; import org.opencms.util.CmsPair; import org.opencms.util.CmsRequestUtil; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.workplace.CmsWorkplace; import org.opencms.workplace.CmsWorkplaceSettings; import org.opencms.workplace.editors.CmsWorkplaceEditorManager; import org.opencms.workplace.explorer.CmsNewResourceXmlContent; import org.opencms.workplace.explorer.CmsResourceUtil; import org.opencms.xml.CmsXmlException; import org.opencms.xml.containerpage.CmsADESessionCache; import org.opencms.xml.containerpage.CmsContainerBean; import org.opencms.xml.containerpage.CmsContainerElementBean; import org.opencms.xml.containerpage.CmsContainerPageBean; import org.opencms.xml.containerpage.CmsFormatterConfiguration; import org.opencms.xml.containerpage.CmsGroupContainerBean; import org.opencms.xml.containerpage.CmsXmlContainerPage; import org.opencms.xml.containerpage.CmsXmlContainerPageFactory; import org.opencms.xml.containerpage.CmsXmlGroupContainer; import org.opencms.xml.containerpage.CmsXmlGroupContainerFactory; import org.opencms.xml.containerpage.I_CmsFormatterBean; import org.opencms.xml.content.CmsXmlContent; import org.opencms.xml.content.CmsXmlContentFactory; import org.opencms.xml.content.CmsXmlContentProperty; import org.opencms.xml.content.CmsXmlContentPropertyHelper; import java.util.ArrayList; import java.util.Arrays; 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.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; /** * The RPC service used by the container-page editor.<p> * * @since 8.0.0 */ public class CmsContainerpageService extends CmsGwtService implements I_CmsContainerpageService { /** The model group pages path fragment. */ public static final String MODEL_GROUP_PATH_FRAGMENT = "/.content/.modelgroups/"; /** The source container page id settings key. */ public static final String SOURCE_CONTAINERPAGE_ID_SETTING = "source_containerpage_id"; /** Additional info key for storing the "edit small elements" setting on the user. */ public static final String ADDINFO_EDIT_SMALL_ELEMENTS = "EDIT_SMALL_ELEMENTS"; /** Session attribute name used to store the selected clipboard tab. */ public static final String ATTR_CLIPBOARD_TAB = "clipboardtab"; /** Static reference to the log. */ private static final Log LOG = CmsLog.getLog(CmsContainerpageService.class); /** Serial version UID. */ private static final long serialVersionUID = -6188370638303594280L; /** The session cache. */ private CmsADESessionCache m_sessionCache; /** The workplace settings. */ private CmsWorkplaceSettings m_workplaceSettings; /** The configuration data of the current container page context. */ private CmsADEConfigData m_configData; /** * Generates the model resource data list.<p> * * @param cms the cms context * @param resourceType the resource type name * @param modelResources the model resource * @param contentLocale the content locale * * @return the model resources data * * @throws CmsException if something goes wrong reading the resource information */ public static List<CmsModelResourceInfo> generateModelResourceList( CmsObject cms, String resourceType, List<CmsResource> modelResources, Locale contentLocale) throws CmsException { List<CmsModelResourceInfo> result = new ArrayList<CmsModelResourceInfo>(); Locale wpLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); CmsModelResourceInfo defaultInfo = new CmsModelResourceInfo(Messages.get().getBundle(wpLocale).key( Messages.GUI_TITLE_DEFAULT_RESOURCE_CONTENT_0), Messages.get().getBundle(wpLocale).key( Messages.GUI_DESCRIPTION_DEFAULT_RESOURCE_CONTENT_0), null); defaultInfo.setResourceType(resourceType); result.add(defaultInfo); for (CmsResource model : modelResources) { CmsGallerySearchResult searchInfo = CmsGallerySearch.searchById(cms, model.getStructureId(), contentLocale); CmsModelResourceInfo modelInfo = new CmsModelResourceInfo( searchInfo.getTitle(), searchInfo.getDescription(), null); modelInfo.addAdditionalInfo( Messages.get().getBundle(wpLocale).key(Messages.GUI_LABEL_PATH_0), cms.getSitePath(model)); modelInfo.setResourceType(resourceType); modelInfo.setStructureId(model.getStructureId()); result.add(modelInfo); } return result; } /** * Returns serialized container data.<p> * * @param container the container * * @return the serialized data * * @throws Exception if serialization fails */ public static String getSerializedContainerInfo(CmsContainer container) throws Exception { return CmsGwtActionElement.serialize(I_CmsContainerpageService.class.getMethod("getContainerInfo"), container); } /** * Returns the serialized element data.<p> * * @param cms the cms context * @param request the servlet request * @param response the servlet response * @param elementBean the element to serialize * @param page the container page * * @return the serialized element data * * @throws Exception if something goes wrong */ public static String getSerializedElementInfo( CmsObject cms, HttpServletRequest request, HttpServletResponse response, CmsContainerElementBean elementBean, CmsContainerPageBean page) throws Exception { CmsContainerElement result = new CmsContainerElement(); CmsElementUtil util = new CmsElementUtil( cms, cms.getRequestContext().getUri(), page, null, request, response, cms.getRequestContext().getLocale()); util.setElementInfo(elementBean, result); return CmsGwtActionElement.serialize(I_CmsContainerpageService.class.getMethod("getElementInfo"), result); } /** * Checks whether the current page is a model group page.<p> * * @param cms the CMS context * @param containerPage the current page * * @return <code>true</code> if the current page is a model group page */ public static boolean isEditingModelGroups(CmsObject cms, CmsResource containerPage) { return (CmsResource.getParentFolder(containerPage.getRootPath()).endsWith(MODEL_GROUP_PATH_FRAGMENT) && OpenCms.getRoleManager().hasRole( cms, CmsRole.DEVELOPER)); } /** * Fetches the container page data.<p> * * @param request the current request * * @return the container page data * * @throws CmsRpcException if something goes wrong */ public static CmsCntPageData prefetch(HttpServletRequest request) throws CmsRpcException { CmsContainerpageService srv = new CmsContainerpageService(); srv.setCms(CmsFlexController.getCmsObject(request)); srv.setRequest(request); CmsCntPageData result = null; try { result = srv.prefetch(); } finally { srv.clearThreadStorage(); } return result; } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#addToFavoriteList(org.opencms.ade.containerpage.shared.CmsContainerPageRpcContext, java.lang.String) */ public void addToFavoriteList(CmsContainerPageRpcContext context, String clientId) throws CmsRpcException { try { ensureSession(); List<CmsContainerElementBean> list = OpenCms.getADEManager().getFavoriteList(getCmsObject()); CmsResource containerPage = getCmsObject().readResource(context.getPageStructureId()); updateFavoriteRecentList(containerPage, clientId, list); OpenCms.getADEManager().saveFavoriteList(getCmsObject(), list); } catch (Throwable e) { error(e); } } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#addToRecentList(org.opencms.ade.containerpage.shared.CmsContainerPageRpcContext, java.lang.String) */ public void addToRecentList(CmsContainerPageRpcContext context, String clientId) throws CmsRpcException { try { ensureSession(); List<CmsContainerElementBean> list = OpenCms.getADEManager().getRecentList(getCmsObject()); CmsResource containerPage = getCmsObject().readResource(context.getPageStructureId()); updateFavoriteRecentList(containerPage, clientId, list); OpenCms.getADEManager().saveRecentList(getCmsObject(), list); } catch (Throwable e) { error(e); } } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#checkContainerpageOrElementsChanged(org.opencms.util.CmsUUID, org.opencms.util.CmsUUID) */ public boolean checkContainerpageOrElementsChanged(CmsUUID structureId, CmsUUID detailContentId) throws CmsRpcException { try { List<CmsUUID> additionalIds = new ArrayList<CmsUUID>(); additionalIds.add(structureId); if (detailContentId != null) { additionalIds.add(detailContentId); } CmsRelationTargetListBean result = CmsDefaultResourceStatusProvider.getContainerpageRelationTargets( getCmsObject(), structureId, additionalIds, true); return result.isChanged(); } catch (Throwable e) { error(e); return false; // will never be reached } } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#checkCreateNewElement(org.opencms.util.CmsUUID, java.lang.String, java.lang.String, java.lang.String) */ public CmsCreateElementData checkCreateNewElement( CmsUUID pageStructureId, String clientId, String resourceType, String locale) throws CmsRpcException { CmsObject cms = getCmsObject(); CmsCreateElementData result = new CmsCreateElementData(); try { CmsResource currentPage = cms.readResource(pageStructureId); List<CmsResource> modelResources = CmsNewResourceXmlContent.getModelFiles( getCmsObject(), CmsResource.getFolderPath(cms.getSitePath(currentPage)), resourceType); if (modelResources.isEmpty()) { result.setCreatedElement(createNewElement(pageStructureId, clientId, resourceType, null, locale)); } else { result.setModelResources(generateModelResourceList( getCmsObject(), resourceType, modelResources, CmsLocaleManager.getLocale(locale))); } } catch (CmsException e) { error(e); } return result; } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#checkNewWidgetsAvailable(org.opencms.util.CmsUUID) */ public boolean checkNewWidgetsAvailable(CmsUUID structureId) throws CmsRpcException { try { CmsObject cms = getCmsObject(); CmsResource resource = cms.readResource(structureId); return CmsWorkplaceEditorManager.checkAcaciaEditorAvailable(cms, resource); } catch (Throwable t) { error(t); } return false; } public CmsUUID convertToServerId(String id) throws CmsIllegalArgumentException { if (id == null) { throw new CmsIllegalArgumentException(org.opencms.xml.containerpage.Messages.get().container( org.opencms.xml.containerpage.Messages.ERR_INVALID_ID_1, id)); } String serverId = id; try { if (serverId.contains(CmsADEManager.CLIENT_ID_SEPERATOR)) { serverId = serverId.substring(0, serverId.indexOf(CmsADEManager.CLIENT_ID_SEPERATOR)); } return new CmsUUID(serverId); } catch (NumberFormatException e) { throw new CmsIllegalArgumentException(org.opencms.xml.containerpage.Messages.get().container( org.opencms.xml.containerpage.Messages.ERR_INVALID_ID_1, id)); } } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#copyElement(org.opencms.util.CmsUUID, org.opencms.util.CmsUUID) */ public CmsUUID copyElement(CmsUUID pageId, CmsUUID originalElementId) throws CmsRpcException { try { CmsObject cms = getCmsObject(); CmsResource page = cms.readResource(pageId, CmsResourceFilter.IGNORE_EXPIRATION); CmsResource element = cms.readResource(originalElementId, CmsResourceFilter.IGNORE_EXPIRATION); CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(cms, page.getRootPath()); String typeName = OpenCms.getResourceManager().getResourceType(element.getTypeId()).getTypeName(); CmsResourceTypeConfig typeConfig = config.getResourceType(typeName); if (typeConfig == null) { LOG.error("copyElement: Type not configured in ADE configuration: " + typeName); return originalElementId; } else { CmsResource newResource = typeConfig.createNewElement( cms, element, CmsResource.getParentFolder(page.getRootPath())); return newResource.getStructureId(); } } catch (Throwable e) { error(e); return null; // will never be reached } } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#createImageWrapperContent(org.opencms.ade.containerpage.shared.CmsContainerPageRpcContext, java.lang.String) */ public String createImageWrapperContent(CmsContainerPageRpcContext context, String clientId) throws CmsRpcException { try { CmsUUID structureId = new CmsUUID(clientId); CmsObject cms = OpenCms.initCmsObject(getCmsObject()); // Copy CmsObject because we want to set a request context attribute CmsResource resource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION); if (OpenCms.getResourceManager().matchResourceType( CmsResourceTypeImage.getStaticTypeName(), resource.getTypeId())) { CmsResource pageResource = cms.readResource(context.getPageStructureId()); CmsADEConfigData configData = getConfigData(pageResource.getRootPath()); CmsResourceTypeConfig resTypeConfig = configData.getResourceType(CmsGwtConstants.TYPE_XML_IMAGE); Locale locale = OpenCms.getLocaleManager().getDefaultLocale(cms, pageResource); cms.getRequestContext().setLocale(locale); CmsResource newResource = resTypeConfig.createNewElement(cms, pageResource.getRootPath()); CmsFile file = cms.readFile(newResource); CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, file); content.getValue(XPATH_XMLIMAGE_IMAGE, locale).setStringValue(cms, cms.getSitePath(resource)); String title = resource.getName(); List<CmsProperty> propertyList = cms.readPropertyObjects(cms.getSitePath(resource), false); Map<String, CmsProperty> properties = CmsProperty.toObjectMap(propertyList); for (String propName : Arrays.asList( CmsPropertyDefinition.PROPERTY_TITLE, CmsPropertyDefinition.PROPERTY_DESCRIPTION)) { CmsProperty currentProperty = properties.get(propName); if (currentProperty != null) { title = currentProperty.getValue(); break; } } content.getValue(XPATH_XMLIMAGE_TITLE, locale).setStringValue(cms, title); byte[] newContentBytes = content.marshal(); file.setContents(newContentBytes); cms.lockResource(file); cms.writeFile(file); cms.unlockResource(file); return "" + file.getStructureId(); } else { return null; } } catch (Exception e) { error(e); return null; } } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#createNewElement(org.opencms.util.CmsUUID, java.lang.String, java.lang.String, org.opencms.util.CmsUUID, java.lang.String) */ public CmsContainerElement createNewElement( CmsUUID pageStructureId, String clientId, String resourceType, CmsUUID modelResourceStructureId, String locale) throws CmsRpcException { CmsContainerElement element = null; try { ensureSession(); CmsObject cms = getCmsObject(); CmsResource pageResource = cms.readResource(pageStructureId); CmsADEConfigData configData = getConfigData(pageResource.getRootPath()); CmsResourceTypeConfig typeConfig = configData.getResourceType(resourceType); CmsObject cloneCms = OpenCms.initCmsObject(cms); cloneCms.getRequestContext().setLocale(CmsLocaleManager.getLocale(locale)); CmsResource modelResource = null; if (modelResourceStructureId != null) { modelResource = cms.readResource(modelResourceStructureId); } CmsResource newResource = typeConfig.createNewElement( cloneCms, modelResource, CmsResource.getParentFolder(pageResource.getRootPath())); CmsContainerElementBean bean = getCachedElement(clientId, pageResource.getRootPath()); CmsContainerElementBean newBean = new CmsContainerElementBean( newResource.getStructureId(), null, bean.getIndividualSettings(), !typeConfig.isCopyInModels()); String newClientId = newBean.editorHash(); getSessionCache().setCacheContainerElement(newClientId, newBean); element = new CmsContainerElement(); element.setNewEditorDisabled(!CmsWorkplaceEditorManager.checkAcaciaEditorAvailable(cms, newResource)); element.setClientId(newClientId); element.setSitePath(cms.getSitePath(newResource)); element.setResourceType(resourceType); } catch (CmsException e) { error(e); } return element; } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#getContainerInfo() */ public CmsContainer getContainerInfo() { throw new UnsupportedOperationException("This method is used for serialization only."); } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#getElementInfo() */ public CmsContainerElement getElementInfo() { throw new UnsupportedOperationException("This method is used for serialization only."); } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#getElementsData(org.opencms.ade.containerpage.shared.CmsContainerPageRpcContext, org.opencms.util.CmsUUID, java.lang.String, java.util.Collection, java.util.Collection, boolean, java.lang.String, java.lang.String) */ public Map<String, CmsContainerElementData> getElementsData( CmsContainerPageRpcContext context, CmsUUID detailContentId, String reqParams, Collection<String> clientIds, Collection<CmsContainer> containers, boolean allowNested, String dndSource, String locale) throws CmsRpcException { Map<String, CmsContainerElementData> result = null; try { ensureSession(); CmsResource pageResource = getCmsObject().readResource(context.getPageStructureId()); initRequestFromRpcContext(context); String containerpageUri = getCmsObject().getSitePath(pageResource); result = getElements( pageResource, clientIds, containerpageUri, detailContentId, containers, allowNested, dndSource, CmsLocaleManager.getLocale(locale)); } catch (Throwable e) { error(e); } return result; } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#getElementWithSettings(org.opencms.ade.containerpage.shared.CmsContainerPageRpcContext, org.opencms.util.CmsUUID, java.lang.String, java.lang.String, java.util.Map, java.util.Collection, boolean, java.lang.String) */ public CmsContainerElementData getElementWithSettings( CmsContainerPageRpcContext context, CmsUUID detailContentId, String uriParams, String clientId, Map<String, String> settings, Collection<CmsContainer> containers, boolean allowNested, String locale) throws CmsRpcException { CmsContainerElementData element = null; try { ensureSession(); CmsObject cms = getCmsObject(); CmsResource pageResource = cms.readResource(context.getPageStructureId()); initRequestFromRpcContext(context); String containerpageUri = cms.getSitePath(pageResource); Locale contentLocale = CmsLocaleManager.getLocale(locale); CmsElementUtil elemUtil = new CmsElementUtil(cms, containerpageUri, generateContainerPageForContainers( containers, pageResource.getRootPath()), detailContentId, getRequest(), getResponse(), contentLocale); CmsContainerElementBean elementBean = getCachedElement(clientId, pageResource.getRootPath()); elementBean.initResource(cms); // make sure to keep the element instance id if (!settings.containsKey(CmsContainerElement.ELEMENT_INSTANCE_ID) && elementBean.getIndividualSettings().containsKey(CmsContainerElement.ELEMENT_INSTANCE_ID)) { settings.put( CmsContainerElement.ELEMENT_INSTANCE_ID, elementBean.getIndividualSettings().get(CmsContainerElement.ELEMENT_INSTANCE_ID)); } elementBean = CmsContainerElementBean.cloneWithSettings( elementBean, convertSettingValues(elementBean.getResource(), settings, contentLocale)); getSessionCache().setCacheContainerElement(elementBean.editorHash(), elementBean); element = elemUtil.getElementData(pageResource, elementBean, containers, allowNested); } catch (Throwable e) { error(e); } return element; } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#getFavoriteList(org.opencms.util.CmsUUID, org.opencms.util.CmsUUID, java.util.Collection, boolean, java.lang.String) */ public List<CmsContainerElementData> getFavoriteList( CmsUUID pageStructureId, CmsUUID detailContentId, Collection<CmsContainer> containers, boolean allowNested, String locale) throws CmsRpcException { List<CmsContainerElementData> result = null; try { ensureSession(); CmsResource containerpage = getCmsObject().readResource(pageStructureId); String containerpageUri = getCmsObject().getSitePath(containerpage); result = getListElementsData( OpenCms.getADEManager().getFavoriteList(getCmsObject()), containerpageUri, detailContentId, containers, allowNested, CmsLocaleManager.getLocale(locale)); } catch (Throwable e) { error(e); } return result; } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#getGalleryDataForPage(java.util.List, org.opencms.util.CmsUUID, java.lang.String, java.lang.String) */ public CmsGalleryDataBean getGalleryDataForPage( List<CmsContainer> containers, CmsUUID elementView, String uri, String locale) throws CmsRpcException { CmsGalleryDataBean data = null; try { CmsObject cms = getCmsObject(); CmsADEConfigData config = getConfigData(cms.getRequestContext().addSiteRoot(uri)); CmsResource pageResource = cms.readResource(uri, CmsResourceFilter.IGNORE_EXPIRATION); List<I_CmsResourceType> resourceTypes = new ArrayList<I_CmsResourceType>(); Set<String> disabledTypes = new HashSet<String>(); final Set<String> typesAtTheEndOfTheList = Sets.newHashSet(); for (CmsResourceTypeConfig typeConfig : config.getResourceTypes()) { boolean isModelGroup = CmsResourceTypeXmlContainerPage.MODEL_GROUP_TYPE_NAME.equals(typeConfig.getTypeName()); try { AddMenuVisibility visibility = typeConfig.getAddMenuVisibility(elementView); if (visibility == AddMenuVisibility.disabled) { continue; } if (isModelGroup || (visibility == AddMenuVisibility.fromOtherView)) { typesAtTheEndOfTheList.add(typeConfig.getTypeName()); } if (typeConfig.checkViewable(cms, uri)) { String typeName = typeConfig.getTypeName(); I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(typeName); if (!isModelGroup && !config.hasFormatters(cms, resType, containers)) { disabledTypes.add(typeName); } resourceTypes.add(resType); } } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } } Set<String> creatableTypes = new HashSet<String>(); for (CmsResourceTypeConfig typeConfig : config.getCreatableTypes( getCmsObject(), CmsResource.getParentFolder(pageResource.getRootPath()))) { if (typeConfig.isHiddenFromAddMenu(elementView) || disabledTypes.contains(typeConfig.getTypeName())) { continue; } String typeName = typeConfig.getTypeName(); creatableTypes.add(typeName); } CmsGalleryService srv = new CmsGalleryService(); srv.setCms(cms); srv.setRequest(getRequest()); // we put the types 'imported' from other views at the end of the list. Since the sort is stable, // relative position of other types remains unchanged Collections.sort(resourceTypes, new Comparator<I_CmsResourceType>() { public int compare(I_CmsResourceType first, I_CmsResourceType second) { return ComparisonChain.start().compare(rank(first), rank(second)).result(); } int rank(I_CmsResourceType type) { return typesAtTheEndOfTheList.contains(type.getTypeName()) ? 1 : 0; } }); data = srv.getInitialSettingsForContainerPage(resourceTypes, creatableTypes, disabledTypes, uri, locale); } catch (Exception e) { error(e); } return data; } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#getNewElementData(org.opencms.ade.containerpage.shared.CmsContainerPageRpcContext, org.opencms.util.CmsUUID, java.lang.String, java.lang.String, java.util.Collection, boolean, java.lang.String) */ public CmsContainerElementData getNewElementData( CmsContainerPageRpcContext context, CmsUUID detailContentId, String reqParams, String resourceType, Collection<CmsContainer> containers, boolean allowNested, String localeName) throws CmsRpcException { CmsContainerElementData result = null; try { ensureSession(); CmsResource pageResource = getCmsObject().readResource(context.getPageStructureId()); initRequestFromRpcContext(context); String containerpageUri = getCmsObject().getSitePath(pageResource); Locale locale = CmsLocaleManager.getLocale(localeName); result = getNewElement(resourceType, containerpageUri, detailContentId, containers, allowNested, locale); } catch (Throwable e) { error(e); } return result; } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#getRecentList(org.opencms.util.CmsUUID, org.opencms.util.CmsUUID, java.util.Collection, boolean, java.lang.String) */ public List<CmsContainerElementData> getRecentList( CmsUUID pageStructureId, CmsUUID detailContentId, Collection<CmsContainer> containers, boolean allowNested, String locale) throws CmsRpcException { List<CmsContainerElementData> result = null; try { ensureSession(); CmsResource containerpage = getCmsObject().readResource(pageStructureId); String containerpageUri = getCmsObject().getSitePath(containerpage); result = getListElementsData( OpenCms.getADEManager().getRecentList(getCmsObject()), containerpageUri, detailContentId, containers, allowNested, CmsLocaleManager.getLocale(locale)); } catch (Throwable e) { error(e); } return result; } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#getRemovedElementStatus(java.lang.String, org.opencms.util.CmsUUID) */ public CmsRemovedElementStatus getRemovedElementStatus(String id, CmsUUID containerpageId) throws CmsRpcException { if ((id == null) || !id.matches(CmsUUID.UUID_REGEX + ".*$")) { return new CmsRemovedElementStatus(null, null, false); } try { CmsUUID structureId = convertToServerId(id); return internalGetRemovedElementStatus(structureId, containerpageId); } catch (CmsException e) { error(e); return null; } } /** * Internal helper method to get the status of a removed element.<p> * * @param structureId the structure id of the removed element * @param containerpageId the id of the page to exclude from the relation check, or null if no page should be excluded * * @return the status of the removed element * * @throws CmsException in case reading the resource fails */ public CmsRemovedElementStatus internalGetRemovedElementStatus(CmsUUID structureId, CmsUUID containerpageId) throws CmsException { CmsObject cms = getCmsObject(); CmsResource elementResource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION); boolean hasWritePermissions = cms.hasPermissions( elementResource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL); boolean isSystemResource = elementResource.getRootPath().startsWith(CmsResource.VFS_FOLDER_SYSTEM + "/"); CmsRelationFilter relationFilter = CmsRelationFilter.relationsToStructureId(structureId); List<CmsRelation> relationsToElement = cms.readRelations(relationFilter); Iterator<CmsRelation> iter = relationsToElement.iterator(); // ignore XML_STRONG (i.e. container element) relations from the container page, this must be checked on the client side. while (iter.hasNext()) { CmsRelation relation = iter.next(); if ((containerpageId != null) && containerpageId.equals(relation.getSourceId()) && relation.getType().equals(CmsRelationType.XML_STRONG)) { iter.remove(); } } boolean hasNoRelations = relationsToElement.isEmpty(); boolean deletionCandidate = hasNoRelations && hasWritePermissions && !isSystemResource; CmsListInfoBean elementInfo = CmsVfsService.getPageInfo(cms, elementResource); return new CmsRemovedElementStatus(structureId, elementInfo, deletionCandidate); } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#loadClipboardTab() */ public int loadClipboardTab() { Integer clipboardTab = (Integer)(getRequest().getSession().getAttribute(ATTR_CLIPBOARD_TAB)); if (clipboardTab == null) { clipboardTab = Integer.valueOf(0); } return clipboardTab.intValue(); } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#prefetch() */ public CmsCntPageData prefetch() throws CmsRpcException { CmsCntPageData data = null; CmsObject cms = getCmsObject(); HttpServletRequest request = getRequest(); try { CmsTemplateContextInfo info = OpenCms.getTemplateContextManager().getContextInfoBean(cms, request); CmsResource containerPage = getContainerpage(cms); boolean isModelPage = isModelPage(cms, containerPage); TemplateBean templateBean = (TemplateBean)getRequest().getAttribute( CmsTemplateContextManager.ATTR_TEMPLATE_BEAN); CmsADESessionCache sessionCache = CmsADESessionCache.getCache(getRequest(), cms); sessionCache.setTemplateBean(containerPage.getRootPath(), templateBean); long lastModified = containerPage.getDateLastModified(); String editorUri = OpenCms.getWorkplaceManager().getEditorHandler().getEditorUri( cms, "xmlcontent", "User agent", false); boolean useClassicEditor = (editorUri == null) || !editorUri.contains("acacia"); CmsResource detailResource = CmsDetailPageResourceHandler.getDetailResource(request); String noEditReason; String detailContainerPage = null; if (detailResource != null) { CmsObject rootCms = OpenCms.initCmsObject(cms); rootCms.getRequestContext().setSiteRoot(""); detailContainerPage = CmsJspTagContainer.getDetailOnlyPageName(detailResource.getRootPath()); if (rootCms.existsResource(detailContainerPage)) { noEditReason = getNoEditReason(rootCms, rootCms.readResource(detailContainerPage)); } else { String permissionFolder = CmsResource.getFolderPath(detailContainerPage); if (!rootCms.existsResource(permissionFolder)) { permissionFolder = CmsResource.getParentFolder(permissionFolder); } noEditReason = getNoEditReason(rootCms, rootCms.readResource(permissionFolder)); } } else { noEditReason = getNoEditReason(cms, containerPage); } String sitemapPath = ""; boolean sitemapManager = OpenCms.getRoleManager().hasRole(cms, CmsRole.EDITOR); if (sitemapManager) { sitemapPath = CmsADEManager.PATH_SITEMAP_EDITOR_JSP; } CmsCntPageData.ElementReuseMode reuseMode = ElementReuseMode.reuse; String reuseModeString = getWorkplaceSettings().getUserSettings().getAdditionalPreference( "elementReuseMode", true); try { reuseMode = ElementReuseMode.valueOf(reuseModeString); } catch (Exception e) { LOG.info("Invalid reuse mode : " + reuseModeString); } data = new CmsCntPageData( noEditReason, CmsRequestUtil.encodeParams(request), sitemapPath, sitemapManager, detailResource != null ? detailResource.getStructureId() : null, detailContainerPage, lastModified, getLockInfo(containerPage), cms.getRequestContext().getLocale().toString(), useClassicEditor, info, isEditSmallElements(request, cms), Lists.newArrayList(getElementViews().values()), getSessionCache().getElementView(), reuseMode, isModelPage, isEditingModelGroups(cms, containerPage)); } catch (Throwable e) { error(e); } return data; } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#saveClipboardTab(int) */ public void saveClipboardTab(int tabIndex) { getRequest().getSession().setAttribute(ATTR_CLIPBOARD_TAB, new Integer(tabIndex)); } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#saveContainerpage(org.opencms.util.CmsUUID, java.util.List) */ public void saveContainerpage(CmsUUID pageStructureId, List<CmsContainer> containers) throws CmsRpcException { CmsObject cms = getCmsObject(); try { ensureSession(); CmsResource containerpage = cms.readResource(pageStructureId); ensureLock(containerpage); String containerpageUri = cms.getSitePath(containerpage); saveContainers(cms, containerpage, containerpageUri, containers); } catch (Throwable e) { error(e); } } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#saveDetailContainers(java.lang.String, java.util.List) */ public void saveDetailContainers(String detailContainerResource, List<CmsContainer> containers) throws CmsRpcException { CmsObject cms = getCmsObject(); try { CmsObject rootCms = OpenCms.initCmsObject(cms); rootCms.getRequestContext().setSiteRoot(""); CmsResource containerpage; ensureSession(); if (rootCms.existsResource(detailContainerResource)) { containerpage = rootCms.readResource(detailContainerResource); } else { String parentFolder = CmsResource.getFolderPath(detailContainerResource); // ensure the parent folder exists if (!rootCms.existsResource(parentFolder)) { CmsResource parentRes = rootCms.createResource( parentFolder, OpenCms.getResourceManager().getResourceType(CmsResourceTypeFolder.getStaticTypeName())); // set the search exclude property on parent folder rootCms.writePropertyObject(parentFolder, new CmsProperty( CmsPropertyDefinition.PROPERTY_SEARCH_EXCLUDE, CmsSearchIndex.PROPERTY_SEARCH_EXCLUDE_VALUE_ALL, null)); tryUnlock(parentRes); } containerpage = rootCms.createResource( detailContainerResource, OpenCms.getResourceManager().getResourceType(CmsResourceTypeXmlContainerPage.getStaticTypeName())); } ensureLock(containerpage); saveContainers(rootCms, containerpage, detailContainerResource, containers); } catch (Throwable e) { error(e); } } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#saveElementSettings(org.opencms.ade.containerpage.shared.CmsContainerPageRpcContext, org.opencms.util.CmsUUID, java.lang.String, java.lang.String, java.util.Map, java.util.List, boolean, java.lang.String) */ public CmsContainerElementData saveElementSettings( CmsContainerPageRpcContext context, CmsUUID detailContentId, String reqParams, String clientId, Map<String, String> settings, List<CmsContainer> containers, boolean allowNested, String locale) throws CmsRpcException { CmsContainerElementData element = null; try { ensureSession(); CmsObject cms = getCmsObject(); CmsResource pageResource = cms.readResource(context.getPageStructureId()); initRequestFromRpcContext(context); Locale contentLocale = CmsLocaleManager.getLocale(locale); CmsContainerElementBean elementBean = getCachedElement(clientId, pageResource.getRootPath()); elementBean.initResource(cms); // make sure to keep the element instance id if (!settings.containsKey(CmsContainerElement.ELEMENT_INSTANCE_ID) && elementBean.getIndividualSettings().containsKey(CmsContainerElement.ELEMENT_INSTANCE_ID)) { settings.put( CmsContainerElement.ELEMENT_INSTANCE_ID, elementBean.getIndividualSettings().get(CmsContainerElement.ELEMENT_INSTANCE_ID)); } if (isEditingModelGroups(cms, pageResource)) { if ((ModelGroupState.evaluate(settings.get(CmsContainerElement.MODEL_GROUP_STATE)) == ModelGroupState.isModelGroup)) { // make sure to keep the model group id if (elementBean.getIndividualSettings().containsKey(CmsContainerElement.MODEL_GROUP_ID)) { settings.put( CmsContainerElement.MODEL_GROUP_ID, elementBean.getIndividualSettings().get(CmsContainerElement.MODEL_GROUP_ID)); } else { // no model group resource assigned yet, create it CmsResource modelGroup = CmsModelGroupHelper.createModelGroup( cms, getConfigData(pageResource.getRootPath())); settings.put(CmsContainerElement.MODEL_GROUP_ID, modelGroup.getStructureId().toString()); } } } else { if (elementBean.getIndividualSettings().containsKey(CmsContainerElement.MODEL_GROUP_ID)) { // make sure to keep the model group id settings.put( CmsContainerElement.MODEL_GROUP_ID, elementBean.getIndividualSettings().get(CmsContainerElement.MODEL_GROUP_ID)); } if (elementBean.getIndividualSettings().containsKey(CmsContainerElement.MODEL_GROUP_STATE)) { settings.put( CmsContainerElement.MODEL_GROUP_STATE, elementBean.getIndividualSettings().get(CmsContainerElement.MODEL_GROUP_STATE)); } } elementBean = CmsContainerElementBean.cloneWithSettings( elementBean, convertSettingValues(elementBean.getResource(), settings, contentLocale)); getSessionCache().setCacheContainerElement(elementBean.editorHash(), elementBean); // update client id within container data for (CmsContainer container : containers) { for (CmsContainerElement child : container.getElements()) { if (child.getClientId().equals(clientId)) { child.setClientId(elementBean.editorHash()); } } } if (detailContentId == null) { saveContainers(cms, pageResource, cms.getSitePath(pageResource), containers); } else { List<CmsContainer> detailContainers = new ArrayList<CmsContainer>(); for (CmsContainer container : containers) { if (container.isDetailOnly()) { detailContainers.add(container); } } CmsObject rootCms = OpenCms.initCmsObject(cms); rootCms.getRequestContext().setSiteRoot(""); CmsResource detailResource = rootCms.readResource(detailContentId); ensureLock(detailResource); saveContainers(rootCms, detailResource, detailResource.getRootPath(), detailContainers); } String containerpageUri = cms.getSitePath(pageResource); CmsElementUtil elemUtil = new CmsElementUtil(cms, containerpageUri, generateContainerPageForContainers( containers, pageResource.getRootPath()), detailContentId, getRequest(), getResponse(), contentLocale); element = elemUtil.getElementData(pageResource, elementBean, containers, allowNested); } catch (Throwable e) { error(e); } return element; } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#saveFavoriteList(java.util.List, java.lang.String) */ public void saveFavoriteList(List<String> clientIds, String uri) throws CmsRpcException { try { ensureSession(); OpenCms.getADEManager().saveFavoriteList( getCmsObject(), getCachedElements(clientIds, getCmsObject().getRequestContext().addSiteRoot(uri))); } catch (Throwable e) { error(e); } } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#saveGroupContainer(org.opencms.ade.containerpage.shared.CmsContainerPageRpcContext, org.opencms.util.CmsUUID, java.lang.String, org.opencms.ade.containerpage.shared.CmsGroupContainer, java.util.Collection, java.lang.String) */ public CmsGroupContainerSaveResult saveGroupContainer( CmsContainerPageRpcContext context, CmsUUID detailContentId, String reqParams, CmsGroupContainer groupContainer, Collection<CmsContainer> containers, String locale) throws CmsRpcException { CmsObject cms = getCmsObject(); List<CmsRemovedElementStatus> removedElements = null; try { CmsPair<CmsContainerElement, List<CmsRemovedElementStatus>> saveResult = internalSaveGroupContainer( cms, context.getPageStructureId(), groupContainer); removedElements = saveResult.getSecond(); } catch (Throwable e) { error(e); } Collection<String> ids = new ArrayList<String>(); ids.add(groupContainer.getClientId()); // update offline indices OpenCms.getSearchManager().updateOfflineIndexes(2 * CmsSearchManager.DEFAULT_OFFLINE_UPDATE_FREQNENCY); return new CmsGroupContainerSaveResult(getElementsData( context, detailContentId, reqParams, ids, containers, false, null, locale), removedElements); } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#saveInheritanceContainer(org.opencms.util.CmsUUID, org.opencms.util.CmsUUID, org.opencms.ade.containerpage.shared.CmsInheritanceContainer, java.util.Collection, java.lang.String) */ public Map<String, CmsContainerElementData> saveInheritanceContainer( CmsUUID pageStructureId, CmsUUID detailContentId, CmsInheritanceContainer inheritanceContainer, Collection<CmsContainer> containers, String locale) throws CmsRpcException { try { CmsObject cms = getCmsObject(); CmsResource containerPage = cms.readResource(pageStructureId); String sitePath = cms.getSitePath(containerPage); Locale requestedLocale = CmsLocaleManager.getLocale(locale); CmsResource referenceResource = null; if (inheritanceContainer.isNew()) { CmsADEConfigData config = getConfigData(containerPage.getRootPath()); CmsResourceTypeConfig typeConfig = config.getResourceType(CmsResourceTypeXmlContainerPage.INHERIT_CONTAINER_TYPE_NAME); referenceResource = typeConfig.createNewElement(cms, containerPage.getRootPath()); inheritanceContainer.setClientId(referenceResource.getStructureId().toString()); } if (referenceResource == null) { CmsUUID id = convertToServerId(inheritanceContainer.getClientId()); referenceResource = cms.readResource(id, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED); } ensureLock(referenceResource); saveInheritanceGroup(referenceResource, inheritanceContainer); tryUnlock(referenceResource); List<CmsContainerElementBean> elements = new ArrayList<CmsContainerElementBean>(); for (CmsContainerElement clientElement : inheritanceContainer.getElements()) { CmsContainerElementBean elementBean = getCachedElement( clientElement.getClientId(), containerPage.getRootPath()); elementBean = CmsContainerElementBean.cloneWithSettings( elementBean, elementBean.getIndividualSettings()); CmsInheritanceInfo inheritanceInfo = clientElement.getInheritanceInfo(); // if a local elements misses the key it was newly added if (inheritanceInfo.isNew() && CmsStringUtil.isEmptyOrWhitespaceOnly(inheritanceInfo.getKey())) { // generating new key inheritanceInfo.setKey(CmsResource.getFolderPath(sitePath) + new CmsUUID().toString()); } elementBean.setInheritanceInfo(inheritanceInfo); elements.add(elementBean); } cms.getRequestContext().setLocale(requestedLocale); if (inheritanceContainer.getElementsChanged()) { OpenCms.getADEManager().saveInheritedContainer( cms, containerPage, inheritanceContainer.getName(), true, elements); } return getElements( containerPage, new ArrayList<String>(Collections.singletonList(inheritanceContainer.getClientId())), sitePath, detailContentId, containers, false, null, requestedLocale); } catch (Exception e) { error(e); } return null; } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#saveRecentList(java.util.List, java.lang.String) */ public void saveRecentList(List<String> clientIds, String uri) throws CmsRpcException { try { ensureSession(); OpenCms.getADEManager().saveRecentList( getCmsObject(), getCachedElements(clientIds, getCmsObject().getRequestContext().addSiteRoot(uri))); } catch (Throwable e) { error(e); } } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#setEditSmallElements(boolean) */ public void setEditSmallElements(boolean editSmallElements) throws CmsRpcException { try { CmsObject cms = getCmsObject(); CmsUser user = cms.getRequestContext().getCurrentUser(); user.getAdditionalInfo().put(ADDINFO_EDIT_SMALL_ELEMENTS, "" + editSmallElements); cms.writeUser(user); } catch (Throwable t) { error(t); } } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#setElementView(org.opencms.util.CmsUUID) */ public void setElementView(CmsUUID elementView) { getSessionCache().setElementView(elementView); } /** * Sets the session cache.<p> * * @param cache the session cache */ public void setSessionCache(CmsADESessionCache cache) { m_sessionCache = cache; } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#syncSaveContainerpage(org.opencms.util.CmsUUID, java.util.List) */ public void syncSaveContainerpage(CmsUUID pageStructureId, List<CmsContainer> containers) throws CmsRpcException { saveContainerpage(pageStructureId, containers); } /** * @see org.opencms.ade.containerpage.shared.rpc.I_CmsContainerpageService#syncSaveDetailContainers(java.lang.String, java.util.List) */ public void syncSaveDetailContainers(String detailContainerResource, List<CmsContainer> containers) throws CmsRpcException { saveDetailContainers(detailContainerResource, containers); } /** * Gets the settings which should be updated for an element in the DND case.<p> * * @param originalSettings the original settings * @param formatterConfig the formatter configuration for the element * @param containers the containers * @param dndContainer the id of the DND origin container * @param allowNested true if nested containers are allowed * * @return the map of settings to update */ Map<String, String> getSettingsToChangeForDnd( Map<String, String> originalSettings, CmsFormatterConfiguration formatterConfig, Collection<CmsContainer> containers, String dndContainer, boolean allowNested) { Map<String, String> result = Maps.newHashMap(); if (dndContainer == null) { return result; } String key = CmsFormatterConfig.getSettingsKeyForContainer(dndContainer); String formatterId = originalSettings.get(key); if (formatterId == null) { return result; } for (CmsContainer container : containers) { if (container.getName().equals(dndContainer)) { continue; } Map<String, I_CmsFormatterBean> formatterSelection = formatterConfig.getFormatterSelection( container.getType(), container.getWidth(), allowNested); if (formatterSelection.containsKey(formatterId)) { String newKey = CmsFormatterConfig.getSettingsKeyForContainer(container.getName()); result.put(newKey, formatterId); } } return result; } /** * Creates a new container element bean from an existing one, but changes some of the individual settings in the copy.<p> * * @param element the original container element * @param settingsToOverride the map of settings to change * * @return the new container element bean with the changed settings */ CmsContainerElementBean overrideSettings(CmsContainerElementBean element, Map<String, String> settingsToOverride) { Map<String, String> settings = Maps.newHashMap(element.getIndividualSettings()); settings.putAll(settingsToOverride); CmsContainerElementBean result = new CmsContainerElementBean( element.getId(), element.getFormatterId(), settings, element.isCreateNew()); return result; } /** * Converts the given setting values according to the setting configuration of the given resource.<p> * * @param resource the resource * @param settings the settings to convert * @param locale the locale used for accessing the element settings * * @return the converted settings * @throws CmsException if something goes wrong */ private Map<String, String> convertSettingValues(CmsResource resource, Map<String, String> settings, Locale locale) throws CmsException { CmsObject cms = getCmsObject(); Locale origLocale = cms.getRequestContext().getLocale(); try { cms.getRequestContext().setLocale(locale); Map<String, CmsXmlContentProperty> settingsConf = OpenCms.getADEManager().getElementSettings(cms, resource); Map<String, String> changedSettings = new HashMap<String, String>(); if (settings != null) { for (Map.Entry<String, String> entry : settings.entrySet()) { String settingName = entry.getKey(); String settingType = "string"; if (settingsConf.get(settingName) != null) { settingType = settingsConf.get(settingName).getType(); } changedSettings.put( settingName, CmsXmlContentPropertyHelper.getPropValueIds(getCmsObject(), settingType, entry.getValue())); } } return changedSettings; } finally { cms.getRequestContext().setLocale(origLocale); } } /** * Generates the XML container page bean for the given containers.<p> * * @param containers the containers * @param containerpageRootPath the container page root path * * @return the container page bean */ private CmsContainerPageBean generateContainerPageForContainers( Collection<CmsContainer> containers, String containerpageRootPath) { List<CmsContainerBean> containerBeans = new ArrayList<CmsContainerBean>(); for (CmsContainer container : containers) { CmsContainerBean containerBean = getContainerBeanToSave(container, containerpageRootPath); containerBeans.add(containerBean); } CmsContainerPageBean page = new CmsContainerPageBean(containerBeans); return page; } /** * Reads the cached element-bean for the given client-side-id from cache.<p> * * @param clientId the client-side-id * @param pageRootPath the container page root path * * @return the cached container element bean * * @throws CmsException in case reading the element resource fails */ private CmsContainerElementBean getCachedElement(String clientId, String pageRootPath) throws CmsException { String id = clientId; CmsContainerElementBean element = null; element = getSessionCache().getCacheContainerElement(id); if (element != null) { return element; } if (id.contains(CmsADEManager.CLIENT_ID_SEPERATOR)) { id = id.substring(0, id.indexOf(CmsADEManager.CLIENT_ID_SEPERATOR)); element = getSessionCache().getCacheContainerElement(id); if (element != null) { return element; } } // this is necessary if the element has not been cached yet CmsResource resource = getCmsObject().readResource(convertToServerId(id), CmsResourceFilter.IGNORE_EXPIRATION); CmsADEConfigData configData = getConfigData(pageRootPath); CmsResourceTypeConfig typeConfig = configData.getResourceType(OpenCms.getResourceManager().getResourceType( resource).getTypeName()); element = new CmsContainerElementBean(convertToServerId(id), null, null, (typeConfig != null) && typeConfig.isCopyInModels()); getSessionCache().setCacheContainerElement(element.editorHash(), element); return element; } /** * Returns a list of container elements from a list with client id's.<p> * * @param clientIds list of client id's * @param pageRootPath the container page root path * * @return a list of element beans * @throws CmsException in case reading the element resource fails */ private List<CmsContainerElementBean> getCachedElements(List<String> clientIds, String pageRootPath) throws CmsException { List<CmsContainerElementBean> result = new ArrayList<CmsContainerElementBean>(); for (String id : clientIds) { try { result.add(getCachedElement(id, pageRootPath)); } catch (CmsIllegalArgumentException e) { log(e.getLocalizedMessage(), e); } } return result; } /** * Returns the configuration data of the current container page context.<p> * * @param pageRootPath the container page root path * * @return the configuration data of the current container page context */ private CmsADEConfigData getConfigData(String pageRootPath) { if (m_configData == null) { m_configData = OpenCms.getADEManager().lookupConfiguration(getCmsObject(), pageRootPath); } return m_configData; } /** * Helper method for converting a CmsContainer to a CmsContainerBean when saving a container page.<p> * * @param container the container for which the CmsContainerBean should be created * @param containerpageRootPath the container page root path * * @return a container bean */ private CmsContainerBean getContainerBeanToSave(CmsContainer container, String containerpageRootPath) { CmsObject cms = getCmsObject(); List<CmsContainerElementBean> elements = new ArrayList<CmsContainerElementBean>(); for (CmsContainerElement elementData : container.getElements()) { try { CmsContainerElementBean newElementBean = getContainerElementBeanToSave( cms, containerpageRootPath, container, elementData); if (newElementBean != null) { elements.add(newElementBean); } } catch (Exception e) { log(e.getLocalizedMessage(), e); } } CmsContainerBean result = new CmsContainerBean( container.getName(), container.getType(), container.getParentInstanceId(), elements); return result; } /** * Converts container page element data to a bean which can be saved in a container page.<p> * * @param cms the current CMS context * @param containerpageRootPath the container page root path * @param container the container containing the element * @param elementData the data for the single element * * @return the container element bean * * @throws CmsException if something goes wrong */ private CmsContainerElementBean getContainerElementBeanToSave( CmsObject cms, String containerpageRootPath, CmsContainer container, CmsContainerElement elementData) throws CmsException { String elementClientId = elementData.getClientId(); boolean hasUuidPrefix = (elementClientId != null) && elementClientId.matches(CmsUUID.UUID_REGEX + ".*$"); boolean isCreateNew = elementData.isCreateNew(); if (elementData.isNew() && !hasUuidPrefix) { // Due to the changed save system without the save button, we need to make sure that new elements // want to save changes to non-new elements on the page, so we skip new elements while saving. return null; } CmsContainerElementBean element = getCachedElement(elementData.getClientId(), containerpageRootPath); // make sure resource is readable, CmsResource resource = cms.readResource(element.getId(), CmsResourceFilter.IGNORE_EXPIRATION); // check if there is a valid formatter int containerWidth = container.getWidth(); CmsADEConfigData config = getConfigData(containerpageRootPath); CmsFormatterConfiguration formatters = config.getFormatters(cms, resource); String containerType = null; containerType = container.getType(); I_CmsFormatterBean formatter = null; if ((element.getIndividualSettings() != null) && element.getIndividualSettings().containsKey( CmsFormatterConfig.getSettingsKeyForContainer(container.getName()))) { String formatterConfigId = element.getIndividualSettings().get( CmsFormatterConfig.getSettingsKeyForContainer(container.getName())); if (CmsUUID.isValidUUID(formatterConfigId)) { formatter = OpenCms.getADEManager().getCachedFormatters(false).getFormatters().get( new CmsUUID(formatterConfigId)); } if (formatter == null) { formatter = formatters.getDefaultSchemaFormatter(containerType, containerWidth); } } if (formatter == null) { formatter = formatters.getDefaultFormatter(containerType, containerWidth, true); } CmsContainerElementBean newElementBean = null; if (formatter != null) { Map<String, String> settings = new HashMap<String, String>(element.getIndividualSettings()); settings.put(CmsFormatterConfig.getSettingsKeyForContainer(container.getName()), formatter.getId()); newElementBean = new CmsContainerElementBean( element.getId(), formatter.getJspStructureId(), settings, isCreateNew); } return newElementBean; } /** * Returns the requested container-page resource.<p> * * @param cms the current cms object * * @return the container-page resource * * @throws CmsException if the resource could not be read for any reason */ private CmsResource getContainerpage(CmsObject cms) throws CmsException { String currentUri = cms.getRequestContext().getUri(); CmsResource containerPage = cms.readResource(currentUri); if (!CmsResourceTypeXmlContainerPage.isContainerPage(containerPage)) { // container page is used as template String cntPagePath = cms.readPropertyObject( containerPage, CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS, true).getValue(""); try { containerPage = cms.readResource(cntPagePath); } catch (CmsException e) { if (!LOG.isDebugEnabled()) { LOG.warn(e.getLocalizedMessage()); } LOG.debug(e.getLocalizedMessage(), e); } } return containerPage; } /** * Returns the data of the given elements.<p> * * @param page the current container page * @param clientIds the list of IDs of the elements to retrieve the data for * @param uriParam the current URI * @param detailContentId the detail content structure id * @param containers the containers for which the element data should be fetched * @param allowNested if nested containers are allowed * @param dndOriginContainer the container from which an element was dragged (null if this method is not called for DND) * @param locale the locale to use * * @return the elements data * * @throws CmsException if something really bad happens */ private Map<String, CmsContainerElementData> getElements( CmsResource page, Collection<String> clientIds, String uriParam, CmsUUID detailContentId, Collection<CmsContainer> containers, boolean allowNested, String dndOriginContainer, Locale locale) throws CmsException { CmsObject cms = getCmsObject(); CmsContainerPageBean pageBean = generateContainerPageForContainers( containers, cms.getRequestContext().addSiteRoot(uriParam)); Map<String, CmsContainerElementBean> idMapping = new HashMap<String, CmsContainerElementBean>(); for (String elemId : clientIds) { if ((elemId == null)) { continue; } CmsContainerElementBean element = getCachedElement(elemId, cms.getRequestContext().addSiteRoot(uriParam)); if (element.getInstanceId() == null) { element = element.clone(); getSessionCache().setCacheContainerElement(element.editorHash(), element); } element.initResource(cms); idMapping.put(elemId, element); } if (CmsContainerElement.MENU_CONTAINER_ID.equals(dndOriginContainer)) { // this indicates the element is added to the page and not being repositioned, check for model group data CmsModelGroupHelper modelHelper = new CmsModelGroupHelper( cms, getConfigData(uriParam), getSessionCache(), isEditingModelGroups(cms, page)); pageBean = modelHelper.prepareforModelGroupContent(idMapping, pageBean, locale); } CmsElementUtil elemUtil = new CmsElementUtil( cms, uriParam, pageBean, detailContentId, getRequest(), getResponse(), locale); Map<String, CmsContainerElementData> result = new HashMap<String, CmsContainerElementData>(); Set<String> ids = new HashSet<String>(); for (Entry<String, CmsContainerElementBean> entry : idMapping.entrySet()) { CmsContainerElementBean element = entry.getValue(); String dndId = null; if (ids.contains(element.editorHash())) { continue; } if ((dndOriginContainer != null) && !CmsContainerElement.MENU_CONTAINER_ID.equals(dndOriginContainer)) { CmsFormatterConfiguration formatterConfig = elemUtil.getFormatterConfiguration(element.getResource()); Map<String, String> dndSettings = getSettingsToChangeForDnd( element.getIndividualSettings(), formatterConfig, containers, dndOriginContainer, allowNested); if (!dndSettings.isEmpty()) { CmsContainerElementBean dndElementBean = overrideSettings(element, dndSettings); getSessionCache().setCacheContainerElement(dndElementBean.editorHash(), dndElementBean); dndId = dndElementBean.editorHash(); Map<String, CmsContainerElementData> dndResults = getElements( page, Arrays.asList(dndId), uriParam, detailContentId, containers, allowNested, null, locale); result.putAll(dndResults); } } CmsContainerElementData elementData = elemUtil.getElementData(page, element, containers, allowNested); if (elementData == null) { continue; } elementData.setDndId(dndId); result.put(entry.getKey(), elementData); if (elementData.isGroupContainer() || elementData.isInheritContainer()) { // this is a group-container CmsResource elementRes = cms.readResource(element.getId()); List<CmsContainerElementBean> subElements = elementData.isGroupContainer() ? getGroupContainerElements(elementRes) : getInheritedElements(elementRes, locale, uriParam); // adding all sub-items to the elements data for (CmsContainerElementBean subElement : subElements) { getSessionCache().setCacheContainerElement(subElement.editorHash(), subElement); if (!ids.contains(subElement.editorHash())) { CmsContainerElementData subItemData = elemUtil.getElementData( page, subElement, containers, allowNested); ids.add(subElement.editorHash()); result.put(subElement.editorHash(), subItemData); } } } ids.add(element.editorHash()); } return result; } /** * Returns the available element views.<p> * * @return the element views */ private Map<CmsUUID, CmsElementViewInfo> getElementViews() { Map<CmsUUID, CmsElementViewInfo> result = new LinkedHashMap<CmsUUID, CmsElementViewInfo>(); CmsObject cms = getCmsObject(); // collect the actually used element view ids CmsADEConfigData config = getConfigData(cms.getRequestContext().addSiteRoot(cms.getRequestContext().getUri())); Set<CmsUUID> usedIds = new HashSet<CmsUUID>(); for (CmsResourceTypeConfig typeConfig : config.getResourceTypes()) { usedIds.add(typeConfig.getElementView()); } Locale wpLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); for (CmsElementView view : OpenCms.getADEManager().getElementViews(cms).values()) { if (usedIds.contains(view.getId()) && view.hasPermission(cms)) { result.put(view.getId(), new CmsElementViewInfo(view.getTitle(cms, wpLocale), view.getId())); } } return result; } /** * Helper method for converting a CmsGroupContainer to a CmsGroupContainerBean when saving a group container.<p> * * @param groupContainer the group-container data * @param containerPage the container page * @param locale the locale to use * * @return the group-container bean */ private CmsGroupContainerBean getGroupContainerBean( CmsGroupContainer groupContainer, CmsResource containerPage, String locale) { CmsObject cms = getCmsObject(); List<CmsContainerElementBean> elements = new ArrayList<CmsContainerElementBean>(); for (CmsContainerElement elementData : groupContainer.getElements()) { try { if (elementData.isNew()) { elementData = createNewElement( containerPage.getStructureId(), elementData.getClientId(), elementData.getResourceType(), null, locale); } CmsContainerElementBean element = getCachedElement( elementData.getClientId(), containerPage.getRootPath()); // make sure resource is readable, if (cms.existsResource(element.getId(), CmsResourceFilter.IGNORE_EXPIRATION)) { elements.add(element); } } catch (Exception e) { log(e.getLocalizedMessage(), e); } } return new CmsGroupContainerBean( groupContainer.getTitle(), groupContainer.getDescription(), elements, groupContainer.getTypes()); } /** * Returns the sub-elements of this group container resource.<p> * * @param resource the group container resource * * @return the sub-elements * * @throws CmsException if something goes wrong reading the resource */ private List<CmsContainerElementBean> getGroupContainerElements(CmsResource resource) throws CmsException { CmsXmlGroupContainer xmlGroupContainer = CmsXmlGroupContainerFactory.unmarshal( getCmsObject(), resource, getRequest()); CmsGroupContainerBean groupContainer = xmlGroupContainer.getGroupContainer(getCmsObject()); return groupContainer.getElements(); } /** * Gets the structure ids of group container elements from an unmarshalled group container for a single locale.<p> * * @param groupContainer the group container * @param locale the locale for which we want the element ids * * @return the group container's element ids for the given locale */ private Set<CmsUUID> getGroupElementIds(CmsXmlGroupContainer groupContainer, Locale locale) { Set<CmsUUID> idSet = new HashSet<CmsUUID>(); CmsGroupContainerBean groupContainerBean = groupContainer.getGroupContainer(getCmsObject()); if (groupContainerBean != null) { for (CmsContainerElementBean element : groupContainerBean.getElements()) { idSet.add(element.getId()); } } return idSet; } /** * Returns the sub-elements of this inherit container resource.<p> * * @param resource the inherit container resource * @param locale the requested locale * @param uriParam the current URI * * @return the sub-elements * * @throws CmsException if something goes wrong reading the resource */ private List<CmsContainerElementBean> getInheritedElements(CmsResource resource, Locale locale, String uriParam) throws CmsException { CmsObject cms = getCmsObject(); cms.getRequestContext().setLocale(locale); CmsInheritanceReferenceParser parser = new CmsInheritanceReferenceParser(cms); parser.parse(resource); CmsInheritanceReference ref = parser.getReference(locale); if (ref == null) { // new inheritance reference, return an empty list return Collections.emptyList(); } String name = ref.getName(); CmsADEManager adeManager = OpenCms.getADEManager(); CmsInheritedContainerState result = adeManager.getInheritedContainerState(cms, cms.addSiteRoot(uriParam), name); return result.getElements(true); } /** * Returns the data of the given elements.<p> * * @param listElements the list of element beans to retrieve the data for * @param containerpageUri the current URI * @param detailContentId the detail content structure id * @param containers the containers which exist on the container page * @param allowNested if nested containers are allowed * @param locale the locale to use * * @return the elements data * * @throws CmsException if something really bad happens */ private List<CmsContainerElementData> getListElementsData( List<CmsContainerElementBean> listElements, String containerpageUri, CmsUUID detailContentId, Collection<CmsContainer> containers, boolean allowNested, Locale locale) throws CmsException { CmsObject cms = getCmsObject(); CmsElementUtil elemUtil = new CmsElementUtil( cms, containerpageUri, generateContainerPageForContainers(containers, cms.getRequestContext().addSiteRoot(containerpageUri)), detailContentId, getRequest(), getResponse(), locale); CmsADESessionCache cache = getSessionCache(); List<CmsContainerElementData> result = new ArrayList<CmsContainerElementData>(); for (CmsContainerElementBean element : listElements) { // checking if resource exists if (cms.existsResource(element.getId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED.addRequireFile())) { cache.setCacheContainerElement(element.editorHash(), element); CmsContainerElementData elementData = elemUtil.getElementData( elemUtil.getPage(), element, containers, allowNested); result.add(elementData); } } return result; } /** * Returns the lock information to the given resource.<p> * * @param resource the resource * * @return lock information, if the page is locked by another user * * @throws CmsException if something goes wrong reading the lock owner user */ private String getLockInfo(CmsResource resource) throws CmsException { CmsObject cms = getCmsObject(); CmsResourceUtil resourceUtil = new CmsResourceUtil(cms, resource); CmsLock lock = resourceUtil.getLock(); String lockInfo = null; if (!lock.isLockableBy(cms.getRequestContext().getCurrentUser())) { if (lock.getType() == CmsLockType.PUBLISH) { lockInfo = Messages.get().getBundle(OpenCms.getWorkplaceManager().getWorkplaceLocale(cms)).key( Messages.GUI_LOCKED_FOR_PUBLISH_0); } else { CmsUser lockOwner = cms.readUser(lock.getUserId()); lockInfo = Messages.get().getBundle(OpenCms.getWorkplaceManager().getWorkplaceLocale(cms)).key( Messages.GUI_LOCKED_BY_1, lockOwner.getFullName()); } } return lockInfo; } /** * Returns the element data for a new element not existing in the VFS yet.<p> * * @param resourceTypeName the resource type name * @param uriParam the request parameters * @param detailContentId the detail content structure id * @param containers the containers of the template * @param allowNested if nested containers are allowed * @param locale the current locale * * @return the element data * * @throws CmsException if something goes wrong */ private CmsContainerElementData getNewElement( String resourceTypeName, String uriParam, CmsUUID detailContentId, Collection<CmsContainer> containers, boolean allowNested, Locale locale) throws CmsException { CmsObject cms = getCmsObject(); CmsElementUtil elemUtil = new CmsElementUtil(cms, uriParam, generateContainerPageForContainers( containers, cms.getRequestContext().addSiteRoot(uriParam)), detailContentId, getRequest(), getResponse(), locale); CmsContainerElementBean elementBean = getSessionCache().getCacheContainerElement(resourceTypeName); if (elementBean == null) { CmsADEConfigData configData = getConfigData(cms.getRequestContext().addSiteRoot(uriParam)); CmsResourceTypeConfig typeConfig = configData.getResourceType(resourceTypeName); elementBean = CmsContainerElementBean.createElementForResourceType( cms, OpenCms.getResourceManager().getResourceType(resourceTypeName), "/", Collections.<String, String> emptyMap(), typeConfig.isCopyInModels(), locale); getSessionCache().setCacheContainerElement(elementBean.editorHash(), elementBean); } return elemUtil.getElementData(elemUtil.getPage(), elementBean, containers, allowNested); } /** * Returns the no-edit reason for the given resource.<p> * * @param cms the current cms object * @param containerPage the resource * * @return the no-edit reason, empty if editing is allowed * * @throws CmsException is something goes wrong */ private String getNoEditReason(CmsObject cms, CmsResource containerPage) throws CmsException { return new CmsResourceUtil(cms, containerPage).getNoEditReason(OpenCms.getWorkplaceManager().getWorkplaceLocale( cms)); } /** * Returns the session cache.<p> * * @return the session cache */ private CmsADESessionCache getSessionCache() { if (m_sessionCache == null) { m_sessionCache = CmsADESessionCache.getCache(getRequest(), getCmsObject()); } return m_sessionCache; } /** * Returns the workplace settings of the current user.<p> * * @return the workplace settings */ private CmsWorkplaceSettings getWorkplaceSettings() { if (m_workplaceSettings == null) { m_workplaceSettings = CmsWorkplace.getWorkplaceSettings(getCmsObject(), getRequest()); } return m_workplaceSettings; } /** * Initializes request attributes using data from the RPC context.<p> * * @param context the RPC context */ private void initRequestFromRpcContext(CmsContainerPageRpcContext context) { if (context.getTemplateContext() != null) { getRequest().setAttribute(CmsTemplateContextManager.ATTR_RPC_CONTEXT_OVERRIDE, context.getTemplateContext()); } } /** * Internal method for saving a group container.<p> * * @param cms the cms context * @param pageStructureId the container page structure id * @param groupContainer the group container to save * * @return the container element representing the group container * * @throws CmsException if something goes wrong * @throws CmsXmlException if the XML processing goes wrong */ private CmsPair<CmsContainerElement, List<CmsRemovedElementStatus>> internalSaveGroupContainer( CmsObject cms, CmsUUID pageStructureId, CmsGroupContainer groupContainer) throws CmsException, CmsXmlException { ensureSession(); CmsResource pageResource = getCmsObject().readResource(pageStructureId, CmsResourceFilter.IGNORE_EXPIRATION); CmsResource groupContainerResource = null; if (groupContainer.isNew()) { CmsADEConfigData config = getConfigData(pageResource.getRootPath()); CmsResourceTypeConfig typeConfig = config.getResourceType(CmsResourceTypeXmlContainerPage.GROUP_CONTAINER_TYPE_NAME); groupContainerResource = typeConfig.createNewElement(getCmsObject(), pageResource.getRootPath()); String resourceName = cms.getSitePath(groupContainerResource); groupContainer.setSitePath(resourceName); groupContainer.setClientId(groupContainerResource.getStructureId().toString()); } if (groupContainerResource == null) { CmsUUID id = convertToServerId(groupContainer.getClientId()); groupContainerResource = cms.readResource(id, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED); } CmsGroupContainerBean groupContainerBean = getGroupContainerBean( groupContainer, pageResource, Locale.ENGLISH.toString()); cms.lockResourceTemporary(groupContainerResource); CmsFile groupContainerFile = cms.readFile(groupContainerResource); Locale locale = Locale.ENGLISH; CmsXmlGroupContainer xmlGroupContainer = CmsXmlGroupContainerFactory.unmarshal(cms, groupContainerFile); Set<CmsUUID> oldElementIds = getGroupElementIds(xmlGroupContainer, locale); xmlGroupContainer.clearLocales(); xmlGroupContainer.save(cms, groupContainerBean, locale); cms.unlockResource(groupContainerResource); Set<CmsUUID> newElementIds = getGroupElementIds(xmlGroupContainer, locale); Set<CmsUUID> removedElementIds = Sets.difference(oldElementIds, newElementIds); List<CmsRemovedElementStatus> deletionCandidateStatuses = new ArrayList<CmsRemovedElementStatus>(); for (CmsUUID removedId : removedElementIds) { CmsRemovedElementStatus status = internalGetRemovedElementStatus(removedId, null); if (status.isDeletionCandidate()) { deletionCandidateStatuses.add(status); } } CmsContainerElement element = new CmsContainerElement(); element.setClientId(groupContainerFile.getStructureId().toString()); element.setSitePath(cms.getSitePath(groupContainerFile)); element.setResourceType(CmsResourceTypeXmlContainerPage.GROUP_CONTAINER_TYPE_NAME); return CmsPair.create(element, deletionCandidateStatuses); } /** * Checks if small elements in a container page should be initially editable.<p> * * @param request the current request * @param cms the current CMS context * @return true if small elements should be initially editable */ private boolean isEditSmallElements(HttpServletRequest request, CmsObject cms) { CmsUser user = cms.getRequestContext().getCurrentUser(); String editSmallElementsStr = (String)(user.getAdditionalInfo().get(ADDINFO_EDIT_SMALL_ELEMENTS)); if (editSmallElementsStr == null) { return true; } else { return Boolean.valueOf(editSmallElementsStr).booleanValue(); } } /** * Checks if a page is a model page.<p> * * @param cms the CMS context to use * @param containerPage the page to check * * @return true if the resource is a model page */ private boolean isModelPage(CmsObject cms, CmsResource containerPage) { CmsADEConfigData config = getConfigData(containerPage.getRootPath()); for (CmsModelPageConfig modelConfig : config.getModelPages()) { if (modelConfig.getResource().getStructureId().equals(containerPage.getStructureId())) { return true; } } return false; } /** * Saves the given containers to the container page resource.<p> * * @param cms the cms context * @param containerpage the container page resource * @param containerpageUri the container page site path * @param containers the container to save * * @throws CmsException if something goes wrong writing the file */ private void saveContainers( CmsObject cms, CmsResource containerpage, String containerpageUri, List<CmsContainer> containers) throws CmsException { CmsContainerPageBean page = generateContainerPageForContainers(containers, containerpage.getRootPath()); CmsModelGroupHelper modelHelper = new CmsModelGroupHelper( getCmsObject(), getConfigData(containerpage.getRootPath()), getSessionCache(), isEditingModelGroups(cms, containerpage)); if (isEditingModelGroups(cms, containerpage)) { page = modelHelper.saveModelGroups(page); } else { page = modelHelper.removeModelGroupContainers(page); } CmsXmlContainerPage xmlCnt = CmsXmlContainerPageFactory.unmarshal(cms, cms.readFile(containerpageUri)); xmlCnt.save(cms, page); } /** * Saves the inheritance group.<p> * * @param resource the inheritance group resource * @param inheritanceContainer the inherited group container data * * @throws CmsException if something goes wrong */ private void saveInheritanceGroup(CmsResource resource, CmsInheritanceContainer inheritanceContainer) throws CmsException { CmsObject cms = getCmsObject(); CmsFile file = cms.readFile(resource); CmsXmlContent document = CmsXmlContentFactory.unmarshal(cms, file); for (Locale docLocale : document.getLocales()) { document.removeLocale(docLocale); } Locale locale = Locale.ENGLISH; document.addLocale(cms, locale); document.getValue("Title", locale).setStringValue(cms, inheritanceContainer.getTitle()); document.getValue("Description", locale).setStringValue(cms, inheritanceContainer.getDescription()); document.getValue("ConfigName", locale).setStringValue(cms, inheritanceContainer.getName()); byte[] content = document.marshal(); file.setContents(content); cms.writeFile(file); } /** * Update favorite or recent list with the given element.<p> * * @param containerPage the edited container page * @param clientId the elements client id * @param list the list to update * * @return the updated list * * @throws CmsException in case reading the element resource fails */ private List<CmsContainerElementBean> updateFavoriteRecentList( CmsResource containerPage, String clientId, List<CmsContainerElementBean> list) throws CmsException { CmsContainerElementBean element = getCachedElement(clientId, containerPage.getRootPath()); Map<String, String> settings = new HashMap<String, String>(element.getIndividualSettings()); settings.put(SOURCE_CONTAINERPAGE_ID_SETTING, containerPage.getStructureId().toString()); element = CmsContainerElementBean.cloneWithSettings(element, settings); Iterator<CmsContainerElementBean> listIt = list.iterator(); while (listIt.hasNext()) { CmsContainerElementBean listElem = listIt.next(); if (element.getInstanceId().equals(listElem.getInstanceId())) { listIt.remove(); } } list.add(0, element); return list; } }
package org.sotorrent.posthistoryextractor.gt; import org.sotorrent.posthistoryextractor.blocks.CodeBlockVersion; import org.sotorrent.posthistoryextractor.blocks.PostBlockVersion; import org.sotorrent.posthistoryextractor.blocks.TextBlockVersion; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.csv.QuoteMode; import org.sotorrent.util.FileUtils; import org.sotorrent.util.LogUtils; import java.io.FileReader; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class PostGroundTruth extends LinkedList<PostBlockLifeSpanVersion> { public static final Pattern fileNamePattern = Pattern.compile("completed_(\\d+)\\.csv"); private static Logger logger = null; private static final CSVFormat csvFormatGT; private int postId; private List<Integer> postHistoryIds; private Map<Integer, List<PostBlockLifeSpanVersion>> versions; // postHistoryId -> PostBlockLifeSpanVersions static { // configure logger try { logger = LogUtils.getClassLogger(PostGroundTruth.class, false); } catch (IOException e) { e.printStackTrace(); } // configure CSV format for ground truth csvFormatGT = CSVFormat.DEFAULT .withHeader("PostId", "PostHistoryId", "PostBlockTypeId", "LocalId", "PredLocalId", "SuccLocalId", "Comment") .withDelimiter(';') .withQuote('"') .withQuoteMode(QuoteMode.MINIMAL) .withEscape('\\') .withNullString("null") .withFirstRecordAsHeader(); } PostGroundTruth(int postId) { this.postId = postId; this.versions = null; } public static PostGroundTruth readFromCSV(Path dir, int postId) { // ensure that input directory exists try { FileUtils.ensureDirectoryExists(dir); } catch (IOException e) { e.printStackTrace(); } Path pathToCSVFile = Paths.get(dir.toString(), "completed_" + postId + ".csv"); PostGroundTruth gt = new PostGroundTruth(postId); try (CSVParser csvParser = new CSVParser(new FileReader(pathToCSVFile.toFile()), csvFormatGT)) { logger.info("Reading GT from CSV file " + pathToCSVFile.toFile().toString() + " ..."); for (CSVRecord currentRecord : csvParser) { int postIdFile = Integer.parseInt(currentRecord.get("PostId")); if (postIdFile != postId) { String msg = "Wrong post id in GT: " + postIdFile + " instead of " + postId; logger.warning(msg); throw new IllegalArgumentException(msg); } int postHistoryId = Integer.parseInt(currentRecord.get("PostHistoryId")); byte postBlockTypeId = Byte.parseByte(currentRecord.get("PostBlockTypeId")); int localId = Integer.parseInt(currentRecord.get("LocalId")); Integer predLocalId = currentRecord.get("PredLocalId") == null ? null : Integer.parseInt(currentRecord.get("PredLocalId")); Integer succLocalId = currentRecord.get("SuccLocalId") == null ? null : Integer.parseInt(currentRecord.get("SuccLocalId")); String comment = currentRecord.get("Comment"); gt.add(new PostBlockLifeSpanVersion(postId, postHistoryId, postBlockTypeId, localId, predLocalId, succLocalId, comment)); } } catch (IOException e) { e.printStackTrace(); } gt.sort(); gt.orderByVersions(); return gt; } public static List<PostGroundTruth> readFromDirectory(Path dir) { return FileUtils.processFiles(dir, file -> fileNamePattern.matcher(file.toFile().getName()).matches(), file -> { Matcher m = fileNamePattern.matcher(file.toFile().getName()); if (!m.find()) { String msg = "Invalid file name for a ground truth CSV: " + dir; logger.warning(msg); throw new IllegalArgumentException(msg); } return PostGroundTruth.readFromCSV( dir, Integer.parseInt(m.group(1)) ); } ); } private void sort() { this.sort((gtBlock1, gtBlock2) -> { int result = Integer.compare(gtBlock1.getPostHistoryId(), gtBlock2.getPostHistoryId()); if (result != 0) { return result; } else { return Integer.compare(gtBlock1.getLocalId(), gtBlock2.getLocalId()); } }); } private void orderByVersions() { versions = new HashMap<>(); Map<Integer, List<PostBlockLifeSpanVersion>> versionsPerPostHistoryId = this.stream() .collect(Collectors.groupingBy(PostBlockLifeSpanVersion::getPostHistoryId)); postHistoryIds = new LinkedList<>(versionsPerPostHistoryId.keySet()); postHistoryIds.sort(Integer::compare); for (int postHistoryId : postHistoryIds) { List<PostBlockLifeSpanVersion> versions = versionsPerPostHistoryId.get(postHistoryId); this.versions.put(postHistoryId, versions); } } public List<PostBlockLifeSpan> getPostBlockLifeSpans() { return getPostBlockLifeSpans(PostBlockVersion.getAllPostBlockTypeIdFilters()); } public List<PostBlockLifeSpan> getPostBlockLifeSpans(Set<Byte> postBlockTypeFilter) { List<PostBlockLifeSpan> postBlockLifeSpans = new LinkedList<>(); for (int i = 0; i< postHistoryIds.size(); i++) { List<PostBlockLifeSpanVersion> currentVersion = versions.get(postHistoryIds.get(i)); for (PostBlockLifeSpanVersion currentLifeSpanVersion : currentVersion) { // apply filter if (!currentLifeSpanVersion.isSelected(postBlockTypeFilter)) { continue; } PostBlockLifeSpan lifeSpan = new PostBlockLifeSpan( currentLifeSpanVersion.getPostId(), currentLifeSpanVersion.getPostBlockTypeId() ); // find successor of this lifespan version int versionCount = 0; while (i+versionCount < postHistoryIds.size()) { // skip life span versions that have already been processed if (currentLifeSpanVersion.isProcessed()) { break; } currentLifeSpanVersion.setProcessed(true); lifeSpan.add(currentLifeSpanVersion); // this version does not have a successor if (currentLifeSpanVersion.getSuccLocalId() == null) { break; } // retrieve successor from candidates List<PostBlockLifeSpanVersion> nextVersion = versions.get(postHistoryIds.get(i+versionCount+1)); currentLifeSpanVersion = retrieveSuccessor(currentLifeSpanVersion, nextVersion); versionCount++; } if (lifeSpan.size() > 0) { postBlockLifeSpans.add(lifeSpan); } } } int lifeSpanVersionCount = postBlockLifeSpans.stream() .map(List::size) .mapToInt(Integer::intValue) .sum(); // validate number of lifespan versions String msg = "The number of lifespan versions differs from the number of versions in the ground truth " + "(expected: " + lifeSpanVersionCount + "; actual: "; if (postBlockTypeFilter.equals(PostBlockVersion.getAllPostBlockTypeIdFilters()) && lifeSpanVersionCount != this.size()) { msg += this.size() + ")"; logger.warning(msg); throw new IllegalStateException(msg); } else if (postBlockTypeFilter.equals(TextBlockVersion.getPostBlockTypeIdFilter()) && lifeSpanVersionCount != this.getTextBlocks().size()) { msg += + this.getTextBlocks().size() + ")"; logger.warning(msg); throw new IllegalStateException(msg); } else if (postBlockTypeFilter.equals(CodeBlockVersion.getPostBlockTypeIdFilter()) && lifeSpanVersionCount != this.getCodeBlocks().size()) { msg += + this.getCodeBlocks().size() + ")"; logger.warning(msg); throw new IllegalStateException(msg); } return postBlockLifeSpans; } private PostBlockLifeSpanVersion retrieveSuccessor( PostBlockLifeSpanVersion currentLifeSpanVersion, List<PostBlockLifeSpanVersion> successorCandidates) { final int succLocalId = currentLifeSpanVersion.getSuccLocalId(); List<PostBlockLifeSpanVersion> selectedSuccessorCandidates = successorCandidates.stream() .filter(v -> v.getLocalId() == succLocalId) .collect(Collectors.toList()); if (selectedSuccessorCandidates.size() == 0) { String msg = "No successor found for " + currentLifeSpanVersion; logger.warning(msg); throw new IllegalStateException(msg); } if (selectedSuccessorCandidates.size() > 1) { String msg = "More than one successor found for " + currentLifeSpanVersion; logger.warning(msg); throw new IllegalStateException(msg); } PostBlockLifeSpanVersion successor = selectedSuccessorCandidates.get(0); if (!successor.getPredLocalId().equals(currentLifeSpanVersion.getLocalId())) { String msg = "Predecessor LocalIds do not match for postId " + postId + ", postHistoryId (" + currentLifeSpanVersion.getPostHistoryId() + ", " + successor.getPostHistoryId() + ") " + "(expected: " + currentLifeSpanVersion.getLocalId() + "; actual: " + successor.getPredLocalId() + ")"; logger.warning(msg); throw new IllegalStateException(msg); } if (!currentLifeSpanVersion.getSuccLocalId().equals(successor.getLocalId())) { String msg = "Successor LocalIds do not match " + postId + ", postHistoryId (" + currentLifeSpanVersion.getPostHistoryId() + ", " + successor.getPostHistoryId() + ") " + "(expected: " + currentLifeSpanVersion.getSuccLocalId() + "; actual: " + successor.getLocalId() + ")"; logger.warning(msg); throw new IllegalStateException(msg); } return successor; } private PostBlockLifeSpanVersion retrievePredecessor( PostBlockLifeSpanVersion currentLifeSpanVersion, List<PostBlockLifeSpanVersion> predecessorCandidates) { final int predLocalId = currentLifeSpanVersion.getPredLocalId(); final int postBlockTypeId = currentLifeSpanVersion.getPostBlockTypeId(); List<PostBlockLifeSpanVersion> selectedPredecessorCandidates = predecessorCandidates.stream() .filter(v -> v.getLocalId() == predLocalId && v.getPostBlockTypeId() == postBlockTypeId) .collect(Collectors.toList()); if (selectedPredecessorCandidates.size() == 0) { String msg = "No predecessor found for " + currentLifeSpanVersion; logger.warning(msg); throw new IllegalStateException(msg); } if (selectedPredecessorCandidates.size() > 1) { String msg = "More than one predecessor found for " + currentLifeSpanVersion; logger.warning(msg); throw new IllegalStateException(msg); } PostBlockLifeSpanVersion predecessor = selectedPredecessorCandidates.get(0); if (!currentLifeSpanVersion.getPredLocalId().equals(predecessor.getLocalId())) { String msg = "Predecessor LocalIds do not match for post " + postId + ", postHistoryId " + currentLifeSpanVersion.getPostHistoryId() + " (expected: " + currentLifeSpanVersion.getPredLocalId() + "; actual: " + predecessor.getLocalId() + ")"; logger.warning(msg); throw new IllegalStateException(msg); } if (!predecessor.getSuccLocalId().equals(currentLifeSpanVersion.getLocalId())) { String msg = "Successor LocalIds do not match for post " + postId + ", postHistoryId " + currentLifeSpanVersion.getPostHistoryId() + " (expected: " + currentLifeSpanVersion.getLocalId() + "; actual: " + predecessor.getSuccLocalId() + ")"; logger.warning(msg); throw new IllegalStateException(msg); } return predecessor; } public List<PostBlockLifeSpanVersion> getTextBlocks() { return this.stream() .filter(v -> v.getPostBlockTypeId() == TextBlockVersion.postBlockTypeId) .collect(Collectors.toList()); } public List<PostBlockLifeSpanVersion> getCodeBlocks() { return this.stream() .filter(v -> v.getPostBlockTypeId() == CodeBlockVersion.postBlockTypeId) .collect(Collectors.toList()); } public List<PostBlockLifeSpanVersion> getPostVersion(int postHistoryId) { return versions.get(postHistoryId); } public Set<PostBlockConnection> getConnections() { return getConnections(PostBlockVersion.getAllPostBlockTypeIdFilters()); } public Set<PostBlockConnection> getConnections(Set<Byte> postBlockTypeFilter) { Set<PostBlockConnection> connections = new HashSet<>(); for (int postHistoryId : postHistoryIds) { connections.addAll(getConnections(postHistoryId, postBlockTypeFilter)); } return connections; } public Set<PostBlockConnection> getConnections(int postHistoryId) { return getConnections(postHistoryId, PostBlockVersion.getAllPostBlockTypeIdFilters()); } public Set<PostBlockConnection> getConnections(int postHistoryId, Set<Byte> postBlockTypeFilter) { Set<PostBlockConnection> connections = new HashSet<>(); int index = postHistoryIds.indexOf(postHistoryId); if (index >= 1) { // first version cannot have connections List<PostBlockLifeSpanVersion> currentVersion = getPostVersion(postHistoryId); List<PostBlockLifeSpanVersion> previousVersion = getPostVersion(postHistoryIds.get(index-1)); for (PostBlockLifeSpanVersion currentLifeSpanVersion : currentVersion) { // apply filter if (!currentLifeSpanVersion.isSelected(postBlockTypeFilter)) { continue; } // first element in a PostBlockLifeSpan -> no connections if (currentLifeSpanVersion.getPredLocalId() == null) { continue; } // search for matching lifespan version(s) in previous post version PostBlockLifeSpanVersion predecessor = retrievePredecessor(currentLifeSpanVersion, previousVersion); // add connections connections.add(new PostBlockConnection(predecessor, currentLifeSpanVersion)); } } return connections; } public int getPossibleComparisons() { return getPossibleComparisons(PostBlockVersion.getAllPostBlockTypeIdFilters()); } public int getPossibleComparisons(Set<Byte> postBlockTypeFilter) { int possibleComparisons = 0; for (int postHistoryId : postHistoryIds) { possibleComparisons += getPossibleComparisons(postHistoryId, postBlockTypeFilter); } return possibleComparisons; } public int getPossibleComparisons(int postHistoryId) { return getPossibleComparisons(postHistoryId, PostBlockVersion.getAllPostBlockTypeIdFilters()); } public int getPossibleComparisons(int postHistoryId, Set<Byte> postBlockTypeFilter) { int index = postHistoryIds.indexOf(postHistoryId); // first version cannot have comparisons if (index < 1) { return 0; } // determine possible comparisons int possibleComparisons = 0; List<PostBlockLifeSpanVersion> currentVersion = versions.get(postHistoryIds.get(index)); List<PostBlockLifeSpanVersion> previousVersion = versions.get(postHistoryIds.get(index-1)); // text blocks if (postBlockTypeFilter.contains(TextBlockVersion.postBlockTypeId)) { int currentVersionTextBlocks = Math.toIntExact(currentVersion.stream() .filter(b -> b.getPostBlockTypeId() == TextBlockVersion.postBlockTypeId) .count()); int previousVersionTextBlocks = Math.toIntExact(previousVersion.stream() .filter(b -> b.getPostBlockTypeId() == TextBlockVersion.postBlockTypeId) .count()); possibleComparisons += currentVersionTextBlocks * previousVersionTextBlocks; } // code blocks if (postBlockTypeFilter.contains(CodeBlockVersion.postBlockTypeId)) { int currentVersionCodeBlocks = Math.toIntExact(currentVersion.stream() .filter(b -> b.getPostBlockTypeId() == CodeBlockVersion.postBlockTypeId) .count()); int previousVersionCodeBlocks = Math.toIntExact(previousVersion.stream() .filter(b -> b.getPostBlockTypeId() == CodeBlockVersion.postBlockTypeId) .count()); possibleComparisons += currentVersionCodeBlocks * previousVersionCodeBlocks; } return possibleComparisons; } public int getPossibleConnections() { return getPossibleConnections(PostBlockVersion.getAllPostBlockTypeIdFilters()); } public int getPossibleConnections(Set<Byte> postBlockTypeFilter) { int possibleConnections = 0; for (int postHistoryId : postHistoryIds) { possibleConnections += getPossibleConnections(postHistoryId, postBlockTypeFilter); } return possibleConnections; } public int getPossibleConnections(int postHistoryId) { return getPossibleConnections(postHistoryId, PostBlockVersion.getAllPostBlockTypeIdFilters()); } public int getPossibleConnections(int postHistoryId, Set<Byte> postBlockTypeFilter) { int index = postHistoryIds.indexOf(postHistoryId); // first version cannot have connections if (index < 1) { return 0; } // determine possible connections int possibleConnections = 0; List<PostBlockLifeSpanVersion> currentVersion = versions.get(postHistoryIds.get(index)); // text blocks if (postBlockTypeFilter.contains(TextBlockVersion.postBlockTypeId)) { int currentVersionTextBlocks = Math.toIntExact(currentVersion.stream() .filter(b -> b.getPostBlockTypeId() == TextBlockVersion.postBlockTypeId) .count()); possibleConnections += currentVersionTextBlocks; } // code blocks if (postBlockTypeFilter.contains(CodeBlockVersion.postBlockTypeId)) { int currentVersionCodeBlocks = Math.toIntExact(currentVersion.stream() .filter(b -> b.getPostBlockTypeId() == CodeBlockVersion.postBlockTypeId) .count()); possibleConnections += currentVersionCodeBlocks; } return possibleConnections; } public List<Integer> getPostHistoryIds() { return postHistoryIds; } public int getPostId() { return postId; } public Map<Integer, List<PostBlockLifeSpanVersion>> getVersions() { return versions; } @Override public String toString() { StringBuilder result = new StringBuilder("PostGroundTruth for PostId " + postId + ":\n"); for (PostBlockLifeSpanVersion version : this) { result.append(version); result.append("\n"); } return result.toString(); } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in th future. package org.usfirst.frc330.Beachbot2013Java.commands; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc330.Beachbot2013Java.Robot; public class PickupUp extends Command { public PickupUp() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES requires(Robot.frisbeePickup); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // Called just before this Command runs the first time protected void initialize() { Robot.frisbeePickup.setFrisbeePickupUp(); Robot.frisbeePickup.setFrisbeePickupMotorStop(); } // Called repeatedly when this Command is scheduled to run protected void execute() { } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
package com.ibm.mil.cafejava; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import com.worklight.wlclient.api.WLClient; import com.worklight.wlclient.api.WLFailResponse; import com.worklight.wlclient.api.WLProcedureInvocationData; import com.worklight.wlclient.api.WLRequestOptions; import com.worklight.wlclient.api.WLResponse; import com.worklight.wlclient.api.WLResponseListener; import rx.Observable; import rx.Subscriber; import rx.functions.Func1; import static rx.Observable.Transformer; public final class CafeJava { private int timeout = 30_000; private Object invocationContext; /** * The timeout that will be used for any MFP call invoked from this instance. * * @param timeout Number of millis to wait for an MFP call to respond. * @return The current instance of {@code CafeJava} to allow for easy call chaining. */ public CafeJava setTimeout(int timeout) { if (timeout >= 0) { this.timeout = timeout; } return this; } /** @return Number of millis to wait for an MFP call to respond. */ public int getTimeout() { return timeout; } /** * An {@code invocationContext} serves as a mechanism for tagging a {@code WLResponse}. This * can be useful when the source of a {@code WLResponse} is unknown. * * @param invocationContext Will be returned as part of any {@code WLResponse} that was * originally invoked from this instance of {@code CafeJava}. * @return The current instance of {@code CafeJava} to allow for easy call chaining. */ @NonNull public CafeJava setInvocationContext(@Nullable Object invocationContext) { this.invocationContext = invocationContext; return this; } /** * @return The object that will be returned as part of any {@code WLResponse} that was * originally invoked from this instance of {@code CafeJava}. */ @Nullable public Object getInvocationContext() { return invocationContext; } /** * Creates an {@code Observable} that emits a {@code WLResponse} and connects to the MFP * instance defined in the {@codewlclient.properties} file when there is a subscriber. The * Observable will automatically perform its work on a dedicated background thread, so there * is usually no need to use the {@code subscribeOn} method of RxJava. * * @param context * @return {@code Observable} that emits a {@code WLResponse} for an MFP connection. */ @NonNull public Observable<WLResponse> connect(@NonNull final Context context) { return Observable.create(new Observable.OnSubscribe<WLResponse>() { @Override public void call(Subscriber<? super WLResponse> subscriber) { WLClient client = WLClient.createInstance(context); client.connect(new RxResponseListener(subscriber), getRequestOptions()); } }); } /** * Creates an {@code Observable} that emits a {@code WLResponse} and invokes the specified * procedure name for the given adapter name when there is a subscriber. The Observable will * automatically perform its work on a dedicated background thread, so there is usually no * need to use the {@code subscribeOn} method of RxJava. * * @param adapterName Name of the targeted adapter. * @param procedureName Name of the targeted procedure that is defined within the adapter * specified in the previous argument. * @param parameters Variable number of parameters that the specified procedure is * expecting. The types of each parameter need to match the type that * the procedure is expecting on the server. * @return {@code Observable} that emits a {@code WLResponse} for an MFP procedure invocation. */ @NonNull public Observable<WLResponse> invokeProcedure(@NonNull final String adapterName, @NonNull final String procedureName, @Nullable final Object... parameters) { return Observable.create(new Observable.OnSubscribe<WLResponse>() { @Override public void call(Subscriber<? super WLResponse> subscriber) { WLClient client = WLClient.getInstance(); if (client == null) { subscriber.onError(new Throwable("WLClient instance does not exist")); return; } WLProcedureInvocationData invocationData = new WLProcedureInvocationData(adapterName, procedureName, false); invocationData.setParameters(parameters); client.invokeProcedure(invocationData, new RxResponseListener(subscriber), getRequestOptions()); } }); } /** * Transforms a {@code WLResponse} that is emitted by an {@code Observable} containing a * valid JSON payload into a new Observable for the targeted {@code Class} type. This can be * done by passing the result of this method to the {@code compose} operator of RxJava. A * variable number of member names can be provided for accessing JSON data that is nested * arbitrarily deep inside the returned payload. * * @param clazz Targeted {@code Class} type for the JSON payload to be serialized into. * @param memberNames Variable number of member names for accessing JSON data that is nested * arbitrarily deep inside the returned payload. * @return {@code Transformer} that can be supplied to the {@code compose} operator of RxJava * . The input {@code Observable} must emit a {@code WLResponse}. */ @NonNull public static <T> Transformer<WLResponse, T> serializeTo(@NonNull final Class<T> clazz, @NonNull final String... memberNames) { return transformJson(new Func1<WLResponse, T>() { @Override public T call(WLResponse wlResponse) { JsonElement element = parseNestedJson(wlResponse, memberNames); return new Gson().fromJson(element, clazz); } }); } /** * Transforms a {@code WLResponse} that is emitted by an {@code Observable} containing a * valid JSON payload into a new Observable for the targeted {@code TypeToken}. This can be * done by passing the result of this method to the {@code compose} operator of RxJava. A * {@code TypeToken} is necessary when the targeted type is parameterized, which is the case * with {@code List}. A variable number of member names can be provided for accessing JSON * data that is nested arbitrarily deep inside the returned payload. * @param typeToken Captures the necessary type information for parameterized types, such as * {@code List}. * @param memberNames Variable number of member names for accessing JSON data that is nested * arbitrarily deep inside the returned payload. * @return {@code Transformer} that can be supplied to the {@code compose} operator of RxJava * . The input {@code Observable} must emit a {@code WLResponse}. */ @NonNull public static <T> Transformer<WLResponse, T> serializeTo(@NonNull final TypeToken<T> typeToken, @NonNull final String... memberNames) { return transformJson(new Func1<WLResponse, T>() { @Override public T call(WLResponse wlResponse) { JsonElement element = parseNestedJson(wlResponse, memberNames); return new Gson().fromJson(element, typeToken.getType()); } }); } private static <T> Transformer<WLResponse, T> transformJson(final Func1<WLResponse, T> func) { return new Transformer<WLResponse, T>() { @Override public Observable<T> call(Observable<WLResponse> wlResponseObservable) { return wlResponseObservable.map(func); } }; } private static JsonElement parseNestedJson(WLResponse wlResponse, String... memberNames) { String json = wlResponse.getResponseJSON().toString(); JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); for (int i = 0, size = memberNames.length; i < size; i++) { String member = memberNames[i]; if (i == size - 1) { return jsonObject.get(member); } else { jsonObject = jsonObject.getAsJsonObject(member); } } return jsonObject; } private WLRequestOptions getRequestOptions() { WLRequestOptions requestOptions = new WLRequestOptions(); requestOptions.setTimeout(timeout); requestOptions.setInvocationContext(invocationContext); return requestOptions; } private static class RxResponseListener implements WLResponseListener { private Subscriber<? super WLResponse> subscriber; RxResponseListener(Subscriber<? super WLResponse> subscriber) { this.subscriber = subscriber; } @Override public void onSuccess(WLResponse wlResponse) { subscriber.onNext(wlResponse); subscriber.onCompleted(); } @Override public void onFailure(WLFailResponse wlFailResponse) { subscriber.onError(new Throwable(wlFailResponse.getErrorMsg())); } } }
package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.app.LoadableListActivity; import com.joelapenna.foursquared.error.LocationException; import com.joelapenna.foursquared.location.BestLocationListener; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.MenuUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.UserUtils; import com.joelapenna.foursquared.widget.SeparatedListAdapter; import com.joelapenna.foursquared.widget.VenueListAdapter; import android.app.Activity; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import java.io.IOException; import java.util.List; import java.util.Locale; import java.util.Observable; import java.util.Observer; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class NearbyVenuesActivity extends LoadableListActivity { static final String TAG = "NearbyVenuesActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_STARTUP_GEOLOC_DELAY = Foursquared.PACKAGE_NAME + ".NearbyVenuesActivity.INTENT_EXTRA_STARTUP_GEOLOC_DELAY"; private long mDelayTimeInMS = 1L; private static final int MENU_REFRESH = 0; private static final int MENU_ADD_VENUE = 1; private static final int MENU_SEARCH = 2; private static final int MENU_MYINFO = 3; private SearchTask mSearchTask; private SearchHolder mSearchHolder = new SearchHolder(); private SearchHandler mSearchHandler = new SearchHandler(); private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver(); private SearchResultsObservable mSearchResultsObservable = new SearchResultsObservable(); private ListView mListView; private SeparatedListAdapter mListAdapter; private LinearLayout mFooterView; private TextView mTextViewFooter; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mListView = getListView(); mListAdapter = new SeparatedListAdapter(this); mListView.setAdapter(mListAdapter); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Venue venue = (Venue) parent.getAdapter().getItem(position); startItemActivity(venue); } }); // We can dynamically add a footer to our loadable listview. LayoutInflater inflater = LayoutInflater.from(this); mFooterView = (LinearLayout)inflater.inflate(R.layout.geo_loc_address_view, null); mTextViewFooter = (TextView)mFooterView.findViewById(R.id.footerTextView); LinearLayout llMain = (LinearLayout)findViewById(R.id.main); llMain.addView(mFooterView); mSearchResultsObservable.addObserver(new Observer() { @Override public void update(Observable observable, Object data) { putSearchResultsInAdapter(((SearchResultsObservable) observable).getSearchResults()); } }); if (getLastNonConfigurationInstance() != null) { if (DEBUG) Log.d(TAG, "Restoring state."); SearchHolder holder = (SearchHolder) getLastNonConfigurationInstance(); if (holder.results != null) { setSearchResults(holder.results, holder.reverseGeoLoc); } populateFooter(holder.reverseGeoLoc); } // We can reparse the delay startup time each onCreate(). if (getIntent().getExtras() != null) { mDelayTimeInMS = getIntent().getLongExtra( INTENT_EXTRA_STARTUP_GEOLOC_DELAY, 1L); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public void onResume() { super.onResume(); if (DEBUG) Log.d(TAG, "onResume"); ((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver); if (mSearchHolder.results == null) { mSearchHandler.sendEmptyMessageDelayed(SearchHandler.MESSAGE_SEARCH, mDelayTimeInMS); } } @Override public void onPause() { super.onPause(); ((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver); if (isFinishing()) { mListAdapter.removeObserver(); } } @Override public void onStop() { super.onStop(); mSearchHandler.sendEmptyMessage(SearchHandler.MESSAGE_STOP_SEARCH); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU_SEARCH, Menu.NONE, R.string.search_label) .setIcon(R.drawable.ic_menu_search) .setAlphabeticShortcut(SearchManager.MENU_KEY); menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh_label) .setIcon(R.drawable.ic_menu_refresh); menu.add(Menu.NONE, MENU_ADD_VENUE, Menu.NONE, R.string.add_venue_label) .setIcon(R.drawable.ic_menu_add); int sdk = new Integer(Build.VERSION.SDK).intValue(); if (sdk < 4) { int menuIcon = UserUtils.getDrawableForMeMenuItemByGender( ((Foursquared) getApplication()).getUserGender()); menu.add(Menu.NONE, MENU_MYINFO, Menu.NONE, R.string.myinfo_label) .setIcon(menuIcon); } MenuUtils.addPreferencesToMenu(this, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_SEARCH: Intent intent = new Intent(NearbyVenuesActivity.this, SearchVenuesActivity.class); intent.setAction(Intent.ACTION_SEARCH); startActivity(intent); return true; case MENU_REFRESH: mSearchHandler.sendEmptyMessage(SearchHandler.MESSAGE_FORCE_SEARCH); return true; case MENU_ADD_VENUE: startActivity(new Intent(NearbyVenuesActivity.this, AddVenueActivity.class)); return true; case MENU_MYINFO: Intent intentUser = new Intent(NearbyVenuesActivity.this, UserDetailsActivity.class); intentUser.putExtra(UserDetailsActivity.EXTRA_USER_ID, ((Foursquared) getApplication()).getUserId()); startActivity(intentUser); return true; } return super.onOptionsItemSelected(item); } @Override public Object onRetainNonConfigurationInstance() { return mSearchHolder; } @Override public int getNoSearchResultsStringId() { return R.string.no_nearby_venues; } public void putSearchResultsInAdapter(Group<Group<Venue>> searchResults) { if (DEBUG) Log.d(TAG, "putSearchResultsInAdapter"); mListAdapter.removeObserver(); mListAdapter = new SeparatedListAdapter(this); if (searchResults != null) { int groupCount = searchResults.size(); for (int groupsIndex = 0; groupsIndex < groupCount; groupsIndex++) { Group<Venue> group = searchResults.get(groupsIndex); if (group.size() > 0) { VenueListAdapter groupAdapter = new VenueListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); groupAdapter.setGroup(group); if (DEBUG) Log.d(TAG, "Adding Section: " + group.getType()); mListAdapter.addSection(group.getType(), groupAdapter); } } } mListView.setAdapter(mListAdapter); } public void setSearchResults(Group<Group<Venue>> searchResults, String reverseGeoLoc) { if (DEBUG) Log.d(TAG, "Setting search results."); mSearchHolder.results = searchResults; mSearchResultsObservable.notifyObservers(); mSearchHolder.reverseGeoLoc = reverseGeoLoc; } void startItemActivity(Venue venue) { Intent intent = new Intent(NearbyVenuesActivity.this, VenueActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(Foursquared.EXTRA_VENUE_ID, venue.getId()); startActivity(intent); } private void ensureTitle(boolean finished) { if (finished) { setTitle(getString(R.string.title_search_finished_noquery)); } else { setTitle(getString(R.string.title_search_inprogress_noquery)); } } private void populateFooter(String reverseGeoLoc) { mFooterView.setVisibility(View.VISIBLE); mTextViewFooter.setText(reverseGeoLoc); } private class SearchTask extends AsyncTask<Void, Void, Group<Group<Venue>>> { private Exception mReason = null; private String mReverseGeoLoc; private boolean mClearGeolocationOnSearch; public SearchTask(boolean clearGeolocationOnSearch) { super(); mClearGeolocationOnSearch = clearGeolocationOnSearch; } @Override public void onPreExecute() { if (DEBUG) Log.d(TAG, "SearchTask: onPreExecute()"); setProgressBarIndeterminateVisibility(true); ensureTitle(false); setLoadingView(); if (mClearGeolocationOnSearch) { Foursquared foursquared = ((Foursquared) getApplication()); foursquared.clearLastKnownLocation(); foursquared.removeLocationUpdates(mSearchLocationObserver); foursquared.requestLocationUpdates(mSearchLocationObserver); } } @Override public Group<Group<Venue>> doInBackground(Void... params) { Foursquare foursquare = ((Foursquared) getApplication()).getFoursquare(); try { // If the user has chosen to clear their geolocation on each search, wait briefly // for a new fix to come in. The two-second wait time is arbitrary and can be // changed to something more intelligent. if (mClearGeolocationOnSearch) { Thread.sleep(2000); } Location location = ((Foursquared) getApplication()).getLastKnownLocationOrThrow(); Group<Group<Venue>> results = search(foursquare, location); // Try to get the geolocation associated with the search. mReverseGeoLoc = getGeocode(location); return results; } catch (Exception e) { mReason = e; } return null; } @Override public void onPostExecute(Group<Group<Venue>> groups) { try { if (groups == null) { NotificationsUtil.ToastReasonForFailure(NearbyVenuesActivity.this, mReason); } setSearchResults(groups, mReverseGeoLoc); } finally { setProgressBarIndeterminateVisibility(false); ensureTitle(true); setEmptyView(); } populateFooter(mReverseGeoLoc); } public Group<Group<Venue>> search(Foursquare foursquare, Location location) throws FoursquareException, LocationException, IOException { Group<Group<Venue>> groups = foursquare.venues(LocationUtils .createFoursquareLocation(location), mSearchHolder.query, 30); // We can sort the returned venues by distance, but now the foursquare api should // do a smart-sort for us by popularity and distance, see here for more info: //for (int i = 0; i < groups.size(); i++) { // Collections.sort(groups.get(i), Comparators.getVenueDistanceComparator()); return groups; } private String getGeocode(Location location) { Geocoder geocoded = new Geocoder(getApplicationContext(), Locale.getDefault()); try { List<Address> addresses = geocoded.getFromLocation( location.getLatitude(), location.getLongitude(), 1); if (addresses.size() > 0) { Address address = addresses.get(0); StringBuilder sb = new StringBuilder(128); sb.append("Near "); sb.append(address.getAddressLine(0)); if (addresses.size() > 1) { sb.append(", "); sb.append(address.getAddressLine(1)); } if (addresses.size() > 2) { sb.append(", "); sb.append(address.getAddressLine(2)); } if (!TextUtils.isEmpty(address.getLocality())) { if (sb.length() > 0) { sb.append(", "); } sb.append(address.getLocality()); } return sb.toString(); } } catch (Exception ex) { if (DEBUG) Log.d(TAG, "SearchTask: error geocoding current location.", ex); } return null; } } private class SearchHandler extends Handler { public static final int MESSAGE_FORCE_SEARCH = 0; public static final int MESSAGE_STOP_SEARCH = 1; public static final int MESSAGE_SEARCH = 2; private boolean mFirstSearchCompleted = false; @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (DEBUG) Log.d(TAG, "handleMessage: " + String.valueOf(msg.what)); switch (msg.what) { case MESSAGE_FORCE_SEARCH: mSearchTask = (SearchTask) new SearchTask( getClearGeolocationOnSearch()).execute(); return; case MESSAGE_STOP_SEARCH: if (mSearchTask != null) { mSearchTask.cancel(true); mSearchTask = null; } return; case MESSAGE_SEARCH: if (mSearchTask == null || AsyncTask.Status.FINISHED.equals(mSearchTask.getStatus()) && !mFirstSearchCompleted) { mFirstSearchCompleted = true; mSearchTask = (SearchTask) new SearchTask( getClearGeolocationOnSearch()).execute(); } return; default: } } } private boolean getClearGeolocationOnSearch() { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); boolean cacheGeolocation = settings.getBoolean(Preferences.PREFERENCE_CACHE_GEOLOCATION_FOR_SEARCHES, true); return !cacheGeolocation; } private class SearchResultsObservable extends Observable { @Override public void notifyObservers(Object data) { setChanged(); super.notifyObservers(data); } public Group<Group<Venue>> getSearchResults() { return mSearchHolder.results; } } private class SearchLocationObserver implements Observer { private boolean mRequestedFirstSearch = false; @Override public void update(Observable observable, Object data) { Location location = (Location) data; // Fire a search if we haven't done so yet. if (!mRequestedFirstSearch && ((BestLocationListener) observable).isAccurateEnough(location)) { mRequestedFirstSearch = true; mSearchHandler.removeMessages(SearchHandler.MESSAGE_SEARCH); mSearchHandler.sendEmptyMessage(SearchHandler.MESSAGE_SEARCH); } } } private static class SearchHolder { Group<Group<Venue>> results; String query; String reverseGeoLoc; } }
package hudson.maven; import org.apache.maven.project.MavenProject; import org.apache.maven.model.Plugin; import org.apache.maven.model.ReportPlugin; import org.apache.maven.model.Extension; import java.io.Serializable; import hudson.Functions; /** * group id + artifact id + version and a flag to know if it's a plugin * * @author Kohsuke Kawaguchi * @see ModuleName */ public final class ModuleDependency implements Serializable { public final String groupId; public final String artifactId; public final String version; /** * @since 1.395 */ public boolean plugin = false; public ModuleDependency(String groupId, String artifactId, String version) { this.groupId = groupId.intern(); this.artifactId = artifactId.intern(); if(version==null) version=UNKNOWN; this.version = version.intern(); } public ModuleDependency(ModuleName name, String version) { this(name.groupId,name.artifactId,version); } public ModuleDependency(org.apache.maven.model.Dependency dep) { this(dep.getGroupId(),dep.getArtifactId(),dep.getVersion()); } public ModuleDependency(MavenProject project) { this(project.getGroupId(),project.getArtifactId(),project.getVersion()); } public ModuleDependency(Plugin p) { this(p.getGroupId(),p.getArtifactId(), Functions.defaulted(p.getVersion(),NONE)); this.plugin = true; } public ModuleDependency(ReportPlugin p) { this(p.getGroupId(),p.getArtifactId(),p.getVersion()); this.plugin = true; } public ModuleDependency(Extension ext) { this(ext.getGroupId(),ext.getArtifactId(),ext.getVersion()); } public ModuleName getName() { return new ModuleName(groupId,artifactId); } /** * Returns groupId+artifactId plus unknown version. */ public ModuleDependency withUnknownVersion() { return new ModuleDependency(groupId,artifactId,UNKNOWN); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ModuleDependency that = (ModuleDependency) o; return this.artifactId.equals(that.artifactId) && this.groupId.equals(that.groupId) && this.version.equals(that.version) && this.plugin == that.plugin; } public int hashCode() { int result; result = groupId.hashCode(); result = 31 * result + artifactId.hashCode(); result = 31 * result + version.hashCode(); result = 31 * result + (plugin ? 1 : 2); return result; } /** * Upon reading from the disk, intern strings. */ public ModuleDependency readResolve() { return new ModuleDependency(groupId,artifactId,version); } /** * For compatibility reason, this value may be used in the verion field * to indicate that the version is unknown. */ public static final String UNKNOWN = "*"; /** * When a plugin dependency is specified without giving a version, * the semantics of that is the latest released plugin. * In this case, we don't want the {@link ModuleDependency} version to become * {@link #UNKNOWN}, which would match any builds of the plugin. * * <p> * So we use this constant to indicate a version, and this will not match * anything. * * @see #ModuleDependency(Plugin) */ public static final String NONE = "-"; private static final long serialVersionUID = 1L; }
package com.yahoo.messagebus; import com.yahoo.concurrent.CopyOnWriteHashMap; import com.yahoo.concurrent.SystemTimer; import java.util.logging.Level; import com.yahoo.messagebus.network.Network; import com.yahoo.messagebus.network.NetworkOwner; import com.yahoo.messagebus.routing.Resender; import com.yahoo.messagebus.routing.RetryPolicy; import com.yahoo.messagebus.routing.RoutingPolicy; import com.yahoo.messagebus.routing.RoutingSpec; import com.yahoo.messagebus.routing.RoutingTable; import com.yahoo.messagebus.routing.RoutingTableSpec; import com.yahoo.text.Utf8Array; import com.yahoo.text.Utf8String; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Logger; /** * <p>A message bus contains the factory for creating sessions to send, receive * and forward messages.</p> * * <p>There are three types of sessions:</p> * <ul> * <li>{@link SourceSession Source sessions} sends messages and receives replies</li> * <li>{@link IntermediateSession Intermediate sessions} receives messages on * their way to their final destination, and may decide to forward the messages or reply directly. * <li>{@link DestinationSession Destination sessions} are the final recipient * of messages, and are expected to reply to every one of them, but may not forward messages. * </ul> * * <p>A message bus is configured with a {@link Protocol protocol}. This table * enumerates the permissible routes from intermediates to destinations and the * messaging semantics of each hop.</p> * * The responsibilities of a message bus are: * <ul> * <li>Assign a route to every send message from its routing table * <li>Deliver every message it <i>accepts</i> to the next hop on its route * <i>or</i> deliver a <i>failure reply</i>. * <li>Deliver replies back to message sources through all the intermediate hops. * </ul> * * A runtime will typically * <ul> * <li>Create a message bus implementation and set properties on this implementation once. * <li>Create sessions using that message bus many places.</li> * </ul> * * @author bratseth * @author Simon Thoresen Hult */ public class MessageBus implements ConfigHandler, NetworkOwner, MessageHandler, ReplyHandler { private static Logger log = Logger.getLogger(MessageBus.class.getName()); private final AtomicBoolean destroyed = new AtomicBoolean(false); private final ProtocolRepository protocolRepository = new ProtocolRepository(); private final AtomicReference<Map<String, RoutingTable>> tablesRef = new AtomicReference<>(null); private final Map<String, MessageHandler> sessions = new ConcurrentHashMap<>(); private final Network net; private final Messenger msn; private final Resender resender; private int maxPendingCount; private int maxPendingSize; private int pendingCount = 0; private int pendingSize = 0; private final Thread careTaker = new Thread(this::sendBlockedMessages); private final Map<SendBlockedMessages, Long> blockedSenders = new ConcurrentHashMap<>(); public interface SendBlockedMessages { /** * Do what you want, but dont block. * You will be called regularly until you signal you are done * @return true unless you are done */ boolean trySend(); } public void register(SendBlockedMessages sender) { blockedSenders.put(sender, SystemTimer.INSTANCE.milliTime()); } private void sendBlockedMessages() { while (! destroyed.get()) { for (SendBlockedMessages sender : blockedSenders.keySet()) { if (!sender.trySend()) { blockedSenders.remove(sender); } } try { Thread.sleep(10); } catch (InterruptedException e) { return; } } } /** * <p>Convenience constructor that proxies {@link #MessageBus(Network, * MessageBusParams)} by adding the given protocols to a default {@link * MessageBusParams} object.</p> * * @param net The network to associate with. * @param protocols An array of protocols to register. */ public MessageBus(Network net, List<Protocol> protocols) { this(net, new MessageBusParams().addProtocols(protocols)); } /** * <p>Constructs an instance of message bus. This requires a network object * that it will associate with. This assignment may not change during the * lifetime of this message bus.</p> * * @param net The network to associate with. * @param params The parameters that controls this bus. */ public MessageBus(Network net, MessageBusParams params) { // Add all known protocols to the repository. maxPendingCount = params.getMaxPendingCount(); maxPendingSize = params.getMaxPendingSize(); for (int i = 0, len = params.getNumProtocols(); i < len; ++i) { protocolRepository.putProtocol(params.getProtocol(i)); } // Attach and start network. this.net = net; net.attach(this); if ( ! net.waitUntilReady(120)) throw new IllegalStateException("Network failed to become ready in time."); // Start messenger. msn = new Messenger(); RetryPolicy retryPolicy = params.getRetryPolicy(); if (retryPolicy != null) { resender = new Resender(retryPolicy); msn.addRecurrentTask(new ResenderTask(resender)); } else { resender = null; } careTaker.setDaemon(true); careTaker.start(); msn.start(); } /** * <p>Sets the destroyed flag to true. The very first time this method is * called, it cleans up all its dependencies. Even if you retain a reference * to this object, all of its content is allowed to be garbage * collected.</p> * * @return True if content existed and was destroyed. */ public boolean destroy() { if (!destroyed.getAndSet(true)) { try { careTaker.join(); } catch (InterruptedException e) { } protocolRepository.clearPolicyCache(); net.shutdown(); msn.destroy(); if (resender != null) { resender.destroy(); } return true; } return false; } /** * <p>Synchronize with internal threads. This method will handshake with all * internal threads. This has the implicit effect of waiting for all active * callbacks. Note that this method should never be invoked from a callback * since that would make the thread wait for itself... forever. This method * is typically used to untangle during session shutdown.</p> */ public void sync() { msn.sync(); net.sync(); } /** * <p>This is a convenience method to call {@link * #createSourceSession(SourceSessionParams)} with default values for the * {@link SourceSessionParams} object.</p> * * @param handler The reply handler to receive the replies for the session. * @return The created session. */ public SourceSession createSourceSession(ReplyHandler handler) { return createSourceSession(new SourceSessionParams().setReplyHandler(handler)); } /** * <p>This is a convenience method to call {@link * #createSourceSession(SourceSessionParams)} by first assigning the reply * handler to the parameter object.</p> * * @param handler The reply handler to receive the replies for the session. * @param params The parameters to control the session. * @return The created session. */ public SourceSession createSourceSession(ReplyHandler handler, SourceSessionParams params) { return createSourceSession(new SourceSessionParams(params).setReplyHandler(handler)); } /** * <p>Creates a source session on top of this message bus.</p> * * @param params The parameters to control the session. * @return The created session. */ public SourceSession createSourceSession(SourceSessionParams params) { if (destroyed.get()) { throw new IllegalStateException("Object is destroyed."); } return new SourceSession(this, params); } /** * <p>This is a convenience method to call {@link * #createIntermediateSession(IntermediateSessionParams)} with default * values for the {@link IntermediateSessionParams} object.</p> * * @param name The local unique name for the created session. * @param broadcastName Whether or not to broadcast this session's name on * the network. * @param msgHandler The handler to receive the messages for the session. * @param replyHandler The handler to received the replies for the session. * @return The created session. */ public IntermediateSession createIntermediateSession(String name, boolean broadcastName, MessageHandler msgHandler, ReplyHandler replyHandler) { return createIntermediateSession( new IntermediateSessionParams() .setName(name) .setBroadcastName(broadcastName) .setMessageHandler(msgHandler) .setReplyHandler(replyHandler)); } /** * <p>Creates an intermediate session on top of this message bus using the * given handlers and parameter object.</p> * * @param params The parameters to control the session. * @return The created session. */ public synchronized IntermediateSession createIntermediateSession(IntermediateSessionParams params) { if (destroyed.get()) { throw new IllegalStateException("Object is destroyed."); } if (sessions.containsKey(params.getName())) { throw new IllegalArgumentException("Name '" + params.getName() + "' is not unique."); } IntermediateSession session = new IntermediateSession(this, params); sessions.put(params.getName(), session); if (params.getBroadcastName()) { net.registerSession(params.getName()); } return session; } /** * <p>This is a convenience method to call {@link * #createDestinationSession(DestinationSessionParams)} with default values * for the {@link DestinationSessionParams} object.</p> * * @param name The local unique name for the created session. * @param broadcastName Whether or not to broadcast this session's name on * the network. * @param handler The handler to receive the messages for the session. * @return The created session. */ public DestinationSession createDestinationSession(String name, boolean broadcastName, MessageHandler handler) { return createDestinationSession( new DestinationSessionParams() .setName(name) .setBroadcastName(broadcastName) .setMessageHandler(handler)); } /** * <p>Creates a destination session on top of this message bus using the * given handlers and parameter object.</p> * * @param params The parameters to control the session. * @return The created session. */ public synchronized DestinationSession createDestinationSession(DestinationSessionParams params) { if (destroyed.get()) { throw new IllegalStateException("Object is destroyed."); } if (sessions.containsKey(params.getName())) { throw new IllegalArgumentException("Name '" + params.getName() + "' is not unique."); } DestinationSession session = new DestinationSession(this, params); sessions.put(params.getName(), session); if (params.getBroadcastName()) { net.registerSession(params.getName()); } return session; } /** * <p>This method is invoked by the {@link * com.yahoo.messagebus.IntermediateSession#destroy()} to unregister * sessions from receiving data from message bus.</p> * * @param name The name of the session to remove. * @param broadcastName Whether or not session name was broadcast. */ public synchronized void unregisterSession(String name, boolean broadcastName) { if (broadcastName) { net.unregisterSession(name); } sessions.remove(name); } private boolean doAccounting() { return (maxPendingCount > 0 || maxPendingSize > 0); } /** * <p>This method handles choking input data so that message bus does not * blindly accept everything. This prevents an application running * out-of-memory in case it fail to choke input data itself. If this method * returns false, it means that it should be rejected.</p> * * @param msg The message to count. * @return True if the message was accepted. */ private boolean checkPending(Message msg) { boolean busy = false; int size = msg.getApproxSize(); if (doAccounting()) { synchronized (this) { busy = ((maxPendingCount > 0 && pendingCount >= maxPendingCount) || (maxPendingSize > 0 && pendingSize >= maxPendingSize)); if (!busy) { pendingCount++; pendingSize += size; } } } if (busy) { return false; } msg.setContext(size); msg.pushHandler(this); return true; } @Override public void handleMessage(Message msg) { if (resender != null && msg.hasBucketSequence()) { deliverError(msg, ErrorCode.SEQUENCE_ERROR, "Bucket sequences not supported when resender is enabled."); return; } SendProxy proxy = new SendProxy(this, net, resender); msn.deliverMessage(msg, proxy); } @Override public void handleReply(Reply reply) { if (destroyed.get()) { reply.discard(); return; } if (doAccounting()) { synchronized (this) { --pendingCount; pendingSize -= (Integer)reply.getContext(); } } deliverReply(reply, reply.popHandler()); } @Override public void deliverMessage(Message msg, String session) { MessageHandler msgHandler = sessions.get(session); if (msgHandler == null) { deliverError(msg, ErrorCode.UNKNOWN_SESSION, "Session '" + session + "' does not exist."); } else if (!checkPending(msg)) { deliverError(msg, ErrorCode.SESSION_BUSY, "Session '" + net.getConnectionSpec() + "/" + session + "' is busy, try again later."); } else { msn.deliverMessage(msg, msgHandler); } } /** * <p>Adds a protocol to the internal repository of protocols, replacing any * previous instance of the protocol and clearing the associated routing * policy cache.</p> * * @param protocol The protocol to add. */ public void putProtocol(Protocol protocol) { protocolRepository.putProtocol(protocol); } @Override public Protocol getProtocol(Utf8Array name) { return protocolRepository.getProtocol(name.toString()); } public Protocol getProtocol(Utf8String name) { return getProtocol((Utf8Array)name); } @Override public void deliverReply(Reply reply, ReplyHandler handler) { msn.deliverReply(reply, handler); } @Override public void setupRouting(RoutingSpec spec) { Map<String, RoutingTable> tables = new HashMap<>(); for (int i = 0, len = spec.getNumTables(); i < len; ++i) { RoutingTableSpec table = spec.getTable(i); String name = table.getProtocol(); if (!protocolRepository.hasProtocol(name)) { log.log(Level.INFO, "Protocol '" + name + "' is not supported, ignoring routing table."); continue; } tables.put(name, new RoutingTable(table)); } tablesRef.set(tables); protocolRepository.clearPolicyCache(); } /** * <p>Returns the resender that is running within this message bus.</p> * * @return The resender. */ public Resender getResender() { return resender; } /** * <p>Returns the number of messages received that have not been replied to * yet.</p> * * @return The pending count. */ public synchronized int getPendingCount() { return pendingCount; } /** * <p>Returns the size of messages received that have not been replied to * yet.</p> * * @return The pending size. */ public synchronized int getPendingSize() { return pendingSize; } /** * <p>Sets the maximum number of messages that can be received without being * replied to yet.</p> * * @param maxCount The max count. */ public void setMaxPendingCount(int maxCount) { maxPendingCount = maxCount; } /** * Gets maximum number of messages that can be received without being * replied to yet. */ public int getMaxPendingCount() { return maxPendingCount; } /** * <p>Sets the maximum size of messages that can be received without being * replied to yet.</p> * * @param maxSize The max size. */ public void setMaxPendingSize(int maxSize) { maxPendingSize = maxSize; } /** * Gets maximum combined size of messages that can be received without * being replied to yet. */ public int getMaxPendingSize() { return maxPendingSize; } /** * <p>Returns a named routing table, may return null.</p> * * @param name The name of the routing table to return. * @return The routing table object. */ public RoutingTable getRoutingTable(String name) { Map<String, RoutingTable> tables = tablesRef.get(); if (tables == null) { return null; } return tables.get(name); } /** * <p>Returns a named routing table, may return null.</p> * * @param name The name of the routing table to return. * @return The routing table object. */ public RoutingTable getRoutingTable(Utf8String name) { return getRoutingTable(name.toString()); } /** * <p>Returns a routing policy that corresponds to the argument protocol * name, policy name and policy parameter. This will cache reuse all * policies as soon as they are first requested.</p> * * @param protocolName The name of the protocol to invoke {@link Protocol#createPolicy(String,String)} on. * @param policyName The name of the routing policy to retrieve. * @param policyParam The parameter for the routing policy to retrieve. * @return A corresponding routing policy, or null. */ public RoutingPolicy getRoutingPolicy(String protocolName, String policyName, String policyParam) { return protocolRepository.getRoutingPolicy(protocolName, policyName, policyParam); } /** * <p>Returns a routing policy that corresponds to the argument protocol * name, policy name and policy parameter. This will cache reuse all * policies as soon as they are first requested.</p> * * @param protocolName The name of the protocol to invoke {@link Protocol#createPolicy(String,String)} on. * @param policyName The name of the routing policy to retrieve. * @param policyParam The parameter for the routing policy to retrieve. * @return A corresponding routing policy, or null. */ public RoutingPolicy getRoutingPolicy(Utf8String protocolName, String policyName, String policyParam) { return protocolRepository.getRoutingPolicy(protocolName.toString(), policyName, policyParam); } /** * <p>Returns the connection spec string for the network layer of this * message bus. This is merely a proxy of the same function in the network * layer.</p> * * @return The connection string. */ public String getConnectionSpec() { return net.getConnectionSpec(); } /** * <p>Constructs and schedules a Reply containing an error to the handler of the given Message.</p> * * @param msg The message to reply to. * @param errCode The code of the error to set. * @param errMsg The message of the error to set. */ private void deliverError(Message msg, int errCode, String errMsg) { Reply reply = new EmptyReply(); reply.swapState(msg); reply.addError(new Error(errCode, errMsg)); deliverReply(reply, reply.popHandler()); } /** * <p>Implements a task for running the resender in the messenger * thread. This task acts as a proxy for the resender, allowing the task to * be deleted without affecting the resender itself.</p> */ private static class ResenderTask implements Messenger.Task { final Resender resender; ResenderTask(Resender resender) { this.resender = resender; } public void destroy() { // empty } public void run() { resender.resendScheduled(); } } }
package com.awsmithson.tcx2nikeplus.util; import java.io.PrintWriter; import java.io.StringWriter; import java.util.logging.Formatter; import java.util.logging.LogRecord; public class LogFormatter extends Formatter { private static final String FORMAT_NORMAL = "%1$tF %1$tT (%2$s)\t%3$s\n"; private static final String FORMAT_EXCEPTION = "%1$tF %1$tT (%2$s)\t%3$s\n%4$s\n"; @Override public String format(LogRecord record) { Throwable t = record.getThrown(); if (t != null) { StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); return String.format(FORMAT_EXCEPTION, record.getMillis(), record.getLevel(), record.getMessage(), sw.toString()); } else return String.format(FORMAT_NORMAL, record.getMillis(), record.getLevel(), record.getMessage()); } }
package soot.jimple.infoflow.android; import java.util.List; import soot.SootMethod; import soot.jimple.infoflow.android.data.AndroidMethod; import soot.jimple.infoflow.source.SourceSinkManager; /** * SourceManager implementation for AndroidSources * @author sarzt * */ public class AndroidSourceSinkManager implements SourceSinkManager { private final List<AndroidMethod> sourceMethods; private final List<AndroidMethod> sinkMethods; private final boolean weakMatching; /** * Creates a new instance of the {@link AndroidSourceSinkManager} class with * strong matching, i.e. the methods in the code must exactly match those * in the list. * @param sources The list of source methods * @param sinks The list of sink methods */ public AndroidSourceSinkManager (List<AndroidMethod> sources, List<AndroidMethod> sinks) { this.sourceMethods = sources; this.sinkMethods = sinks; this.weakMatching = false; } /** * Creates a new instance of the {@link AndroidSourceSinkManager} class with * either strong or weak matching. * @param sources The list of source methods * @param sinks The list of sink methods * @param weakMatching True for strong matching: The method signature in the * code exactly match the one in the list. False for weak matching: If an * entry in the list has no return type, it matches arbitrary return types * if the rest of the method signature is compatible. */ public AndroidSourceSinkManager (List<AndroidMethod> sources, List<AndroidMethod> sinks, boolean weakMatching) { this.sourceMethods = sources; this.sinkMethods = sinks; this.weakMatching = weakMatching; } /** * Checks whether the given method matches one of the methods from the list * @param sMethod The method to check for a match * @param aMethods The list of reference methods * @return True if the given method matches an entry in the list, otherwise * false */ private boolean matchesMethod(SootMethod sMethod, List<AndroidMethod> aMethods) { for (AndroidMethod am : aMethods) { if (!am.getClassName().equals(sMethod.getDeclaringClass().getName())) continue; if (!am.getMethodName().equals(sMethod.getName())) continue; if (am.getParameters().size() != sMethod.getParameterCount()) continue; boolean matches = true; for (int i = 0; i < am.getParameters().size(); i++) if (!am.getParameters().get(i).equals(sMethod.getParameterType(i).toString())) { matches = false; break; } if (!matches) continue; if (!weakMatching) if (!am.getReturnType().isEmpty()) if (!am.getReturnType().equals(sMethod.getReturnType().toString())) continue; return true; } return false; } @Override public boolean isSourceMethod(SootMethod sMethod) { return this.matchesMethod(sMethod, this.sourceMethods); } @Override public boolean isSinkMethod(SootMethod sMethod) { return this.matchesMethod(sMethod, this.sinkMethods); } /** * Adds a list of methods as sinks * @param sinks The methods to be added as sinks */ public void addSink(List<AndroidMethod> sinks) { this.sinkMethods.addAll(sinks); } }
package net.saick.android.calcapp; import android.os.Bundle; import android.app.Activity; import android.text.InputType; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import net.saick.android.calcapp.R; public class MainActivity extends Activity implements OnClickListener { private EditText et_xianshi; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EditText edit = (EditText) findViewById(R.id.et_xianshi); edit.setInputType(InputType.TYPE_NULL); et_xianshi = (EditText) findViewById(R.id.et_xianshi); Button bt_num0 = (Button) findViewById(R.id.bt_num0); Button bt_num1 = (Button) findViewById(R.id.bt_num1); Button bt_num2 = (Button) findViewById(R.id.bt_num2); Button bt_num3 = (Button) findViewById(R.id.bt_num3); Button bt_num4 = (Button) findViewById(R.id.bt_num4); Button bt_num5 = (Button) findViewById(R.id.bt_num5); Button bt_num6 = (Button) findViewById(R.id.bt_num6); Button bt_num7 = (Button) findViewById(R.id.bt_num7); Button bt_num8 = (Button) findViewById(R.id.bt_num8); Button bt_num9 = (Button) findViewById(R.id.bt_num9); Button bt_dian = (Button) findViewById(R.id.bt_dian); Button bt_jia = (Button) findViewById(R.id.bt_jia); Button bt_jian = (Button) findViewById(R.id.bt_jian); Button bt_cheng = (Button) findViewById(R.id.bt_cheng); Button bt_chu = (Button) findViewById(R.id.bt_chu); Button bt_shanchu = (Button) findViewById(R.id.bt_shanchu); Button bt_dengyu = (Button) findViewById(R.id.bt_dengyu); bt_num0.setOnClickListener(this); bt_num1.setOnClickListener(this); bt_num2.setOnClickListener(this); bt_num3.setOnClickListener(this); bt_num4.setOnClickListener(this); bt_num5.setOnClickListener(this); bt_num6.setOnClickListener(this); bt_num7.setOnClickListener(this); bt_num8.setOnClickListener(this); bt_num9.setOnClickListener(this); bt_dian.setOnClickListener(this); bt_shanchu.setOnClickListener(this); bt_jia.setOnClickListener(this); bt_jian.setOnClickListener(this); bt_cheng.setOnClickListener(this); bt_chu.setOnClickListener(this); bt_dengyu.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.bt_num0: et_xianshi.append("0"); break; case R.id.bt_num1: et_xianshi.append("1"); break; case R.id.bt_num2: et_xianshi.append("2"); break; case R.id.bt_num3: et_xianshi.append("3"); break; case R.id.bt_num4: et_xianshi.append("4"); break; case R.id.bt_num5: et_xianshi.append("5"); break; case R.id.bt_num6: et_xianshi.append("6"); break; case R.id.bt_num7: et_xianshi.append("7"); break; case R.id.bt_num8: et_xianshi.append("8"); break; case R.id.bt_num9: et_xianshi.append("9"); break; case R.id.bt_dian: et_xianshi.append("."); break; case R.id.bt_shanchu: String s = et_xianshi.getText().toString(); if (!"".equals(s)) { s = s.substring(0, s.length() - 1); et_xianshi.setText(s); } break; case R.id.bt_jia: et_xianshi.append("+"); break; case R.id.bt_jian: et_xianshi.append("-"); break; case R.id.bt_cheng: et_xianshi.append("×"); break; case R.id.bt_chu: et_xianshi.append("÷"); break; case R.id.bt_dengyu: String s1 = et_xianshi.getText().toString(); boolean jia = s1.contains("+"); boolean jian = s1.contains("-"); boolean cheng = s1.contains("×"); boolean chu = s1.contains("÷"); if ("".equals(s1)) { Toast.makeText(this, "", Toast.LENGTH_SHORT).show(); return; } if (!jia && !jian && !cheng && !chu) { Toast.makeText(this, "", Toast.LENGTH_SHORT).show(); return; } if (s1.endsWith(".") || s1.endsWith("+") || s1.endsWith("-") || s1.endsWith("×") || s1.endsWith("÷")) { Toast.makeText(this, "", Toast.LENGTH_SHORT).show(); return; } if (jia) { if (s1.indexOf("+") != s1.lastIndexOf("+") || s1.indexOf("+") < 1) { Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } if(jian||cheng||chu){ Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } int index = s1.indexOf("+"); String a = s1.substring(0, index); String b = s1.substring(index + 1, s1.length()); if(a.contains(".")){ if(a.indexOf(".")!=a.lastIndexOf(".")||a.indexOf(".")==a.length()-1){ Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } } if(b.contains(".")){ if(b.indexOf(".")!=b.lastIndexOf(".")||b.indexOf(".")==0){ Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } } double x = Double.parseDouble(a); double y = Double.parseDouble(b); String s2 = String.valueOf(x + y); et_xianshi.setText(s2); } else if (jian) { if (s1.indexOf("-") != s1.lastIndexOf("-") || s1.indexOf("-") < 1) { Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } if(jia||cheng||chu){ Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } int index = s1.indexOf("-"); String a = s1.substring(0, index); String b = s1.substring(index + 1, s1.length()); if(a.contains(".")){ if(a.indexOf(".")!=a.lastIndexOf(".")||a.indexOf(".")==a.length()-1){ Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } } if(b.contains(".")){ if(b.indexOf(".")!=b.lastIndexOf(".")||b.indexOf(".")==0){ Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } } double x = Double.parseDouble(a); double y = Double.parseDouble(b); String s2 = String.valueOf(x - y); et_xianshi.setText(s2); }else if (cheng) { if (s1.indexOf("×") != s1.lastIndexOf("×") || s1.indexOf("×") < 1) { Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } if(jia||jian||chu){ Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } int index = s1.indexOf("×"); String a = s1.substring(0, index); String b = s1.substring(index + 1, s1.length()); if(a.contains(".")){ if(a.indexOf(".")!=a.lastIndexOf(".")||a.indexOf(".")==a.length()-1){ Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } } if(b.contains(".")){ if(b.indexOf(".")!=b.lastIndexOf(".")||b.indexOf(".")==0){ Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } } double x = Double.parseDouble(a); double y = Double.parseDouble(b); String s2 = String.valueOf(x * y); et_xianshi.setText(s2); }else if (chu) { if (s1.indexOf("÷") != s1.lastIndexOf("÷") || s1.indexOf("÷") < 1) { Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } if(jia||jian||cheng){ Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } int index = s1.indexOf("÷"); String a = s1.substring(0, index); String b = s1.substring(index + 1, s1.length()); if(a.contains(".")){ if(a.indexOf(".")!=a.lastIndexOf(".")||a.indexOf(".")==a.length()-1){ Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } } if(b.contains(".")){ if(b.indexOf(".")!=b.lastIndexOf(".")||b.indexOf(".")==0){ Toast.makeText(this, "", Toast.LENGTH_SHORT) .show(); return; } } double x = Double.parseDouble(a); double y = Double.parseDouble(b); String s2 = String.valueOf(x / y); et_xianshi.setText(s2); } break; default: break; } } }
package com.bkahlert.nebula.widgets.composer; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Future; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.ObjectUtils; import org.apache.log4j.Logger; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.BrowserFunction; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Composite; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import com.bkahlert.nebula.utils.ExecUtils; import com.bkahlert.nebula.utils.IConverter; import com.bkahlert.nebula.utils.IModifiable; import com.bkahlert.nebula.utils.JSONUtils; import com.bkahlert.nebula.utils.ModificationNotifier; import com.bkahlert.nebula.utils.colors.RGB; import com.bkahlert.nebula.widgets.browser.Browser; import com.bkahlert.nebula.widgets.browser.BrowserUtils; import com.bkahlert.nebula.widgets.browser.extended.html.Anker; import com.bkahlert.nebula.widgets.browser.extended.html.IAnker; /** * This is a wrapped CKEditor (ckeditor.com). * <p> * <b>Important developer warning</b>: Do not try to wrap a WYSIWYG editor based * on iframes like TinyMCE. Some internal browsers (verified with Webkit) do not * handle cut, copy and paste actions when the iframe is in focus. CKEditor can * operate in both modes - iframes and divs (and p tags). * * @author bkahlert * */ public class Composer extends Browser implements IModifiable { private static final Logger LOGGER = Logger.getLogger(Composer.class); private static final Pattern URL_PATTERN = Pattern .compile("(.*?)(\\w+://[!#$&-;=?-\\[\\]_a-zA-Z~%]+)(.*?)"); public static enum ToolbarSet { DEFAULT, TERMINAL, NONE; } private final ToolbarSet toolbarSet; private final List<IAnkerLabelProvider> ankerLabelProviders = new ArrayList<IAnkerLabelProvider>(); private RGB background = null; private final ModificationNotifier<String> modificationNotifier; private Object oldHtml; public Composer(Composite parent, int style) { this(parent, style, 1500, ToolbarSet.DEFAULT); } /** * * @param parent * @param style * @param delayChangeEventUpTo * is the delay that must have been passed in order to fire a * change event. If 0 no delay will be applied. The minimal delay * is defined by the CKEditor's config.js. * @throws IOException */ public Composer(Composite parent, int style, final long delayChangeEventUpTo, ToolbarSet toolbarSet) { super(parent, style); this.deactivateNativeMenu(); this.toolbarSet = toolbarSet; this.fixShortcuts(delayChangeEventUpTo); this.listenForModifications(delayChangeEventUpTo); this.open(BrowserUtils.getFileUrl(Composer.class, "html/index.html", "?internal=true&toolbarSet=" + toolbarSet.toString().toLowerCase()), 30000, "typeof jQuery != \"undefined\" && jQuery(\"html\").hasClass(\"ready\")"); this.modificationNotifier = new ModificationNotifier<String>(this, delayChangeEventUpTo); } public void fixShortcuts(final long delayChangeEventUpTo) { this.getBrowser().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if ((e.stateMask & SWT.CTRL) != 0 || (e.stateMask & SWT.COMMAND) != 0) { if (e.keyCode == 97) { // a - select all Composer.this.selectAll(); } /* * The CKEditor plugin "onchange" does not notify on cut and * paste operations. Therefore we need to handle them here. */ if (e.keyCode == 120) { // x - cut // wait for the ui thread to apply the operation ExecUtils.asyncExec(new Runnable() { @Override public void run() { try { Composer.this.modifiedCallback( Composer.this.getSource().get(), false); } catch (Exception e) { LOGGER.error( "Error reporting content modification", e); } } }); } if (e.keyCode == 99) { // c - copy // do nothing } if (e.keyCode == 118) { // v - paste // wait for the ui thread to apply the operation ExecUtils.asyncExec(new Runnable() { @Override public void run() { try { Composer.this.modifiedCallback( Composer.this.getSource().get(), false); } catch (Exception e) { LOGGER.error( "Error reporting content modification", e); } } }); } } } }); } public void listenForModifications(final long delayChangeEventUpTo) { new BrowserFunction(this.getBrowser(), "modified") { @Override public Object function(Object[] arguments) { if (arguments.length >= 1) { if (arguments[0] instanceof String) { String newHtml = (String) arguments[0]; Composer.this.modifiedCallback(newHtml, false); } } return null; } }; this.getBrowser().addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { if (!Composer.this.isLoadingCompleted()) { return; } try { Composer.this.modifiedCallback(Composer.this.getSource() .get(), true); } catch (Exception e1) { LOGGER.error("Error reporting last composer contents", e1); } } }); } protected void modifiedCallback(String html, boolean immediately) { String newHtml = (html == null || html.replace("&nbsp;", " ").trim() .isEmpty()) ? "" : html.trim(); if (ObjectUtils.equals(this.oldHtml, newHtml)) { return; } this.oldHtml = newHtml; // When space entered but widget is not disposing, create links if (!immediately) { String prevCaretCharacter = this.getPrevCaretCharacter(); if (prevCaretCharacter != null && this.getPrevCaretCharacter().matches("[\\s| ]")) { // space // non // breaking // space String autoLinkedHtml = this.createLinks(newHtml); if (!autoLinkedHtml.equals(newHtml)) { this.setSource(autoLinkedHtml, true); newHtml = autoLinkedHtml; } } } this.modificationNotifier.modified(newHtml); if (immediately) { this.modificationNotifier.notifyNow(); } } private String createLinks(String html) { boolean htmlChanged = false; Document doc = Jsoup.parseBodyFragment(html); for (Element e : doc.getAllElements()) { if (e.tagName().equals("a")) { IAnker anker = new Anker(e); IAnker newAnker = this.createAnkerFromLabelProviders(anker); if (newAnker == null && !anker.getHref().equals(anker.getContent())) { newAnker = new Anker(anker.getContent(), anker.getClasses(), anker.getContent()); } if (newAnker != null) { e.html(newAnker.toHtml()); htmlChanged = true; } } else { String ownText = e.ownText(); Matcher matcher = URL_PATTERN.matcher(ownText); if (matcher.matches()) { String uri = matcher.group(2); IAnker anker = new Anker(uri, new String[0], uri); IAnker newAnker = this.createAnkerFromLabelProviders(anker); if (newAnker == null) { newAnker = anker; } String newHtml = e.html().replace(uri, newAnker.toHtml()); e.html(newHtml); htmlChanged = true; } } } String newHtml = htmlChanged ? doc.body().children().toString() : html; return newHtml; } public IAnker createAnkerFromLabelProviders(IAnker oldAnker) { IAnker newAnker = null; for (IAnkerLabelProvider ankerLabelProvider : this.ankerLabelProviders) { if (ankerLabelProvider.isResponsible(oldAnker)) { newAnker = new Anker(ankerLabelProvider.getHref(oldAnker), ankerLabelProvider.getClasses(oldAnker), ankerLabelProvider.getContent(oldAnker)); break; } } return newAnker; } public ToolbarSet getToolbarSet() { return this.toolbarSet; } /** * Checks whether the current editor contents present changes when compared * to the contents loaded into the editor at startup. * * @return */ public Boolean isDirty() { Boolean isDirty = (Boolean) this.getBrowser().evaluate( "return com.bkahlert.nebula.editor.isDirty();"); if (isDirty != null) { return isDirty; } else { return null; } } public void selectAll() { this.run("com.bkahlert.nebula.editor.selectAll();"); } public Future<Boolean> setSource(String html) { return this.setSource(html, false); } public Future<Boolean> setSource(String html, boolean restoreSelection) { this.modificationNotifier.notifyNow(); this.oldHtml = html; return this.run("return com.bkahlert.nebula.editor.setSource(" + JSONUtils.enquote(html) + ", " + (restoreSelection ? "true" : "false") + ");", IConverter.CONVERTER_BOOLEAN); } /** * TODO use this.run * * @return * @throws Exception */ public Future<String> getSource() { if (!this.isLoadingCompleted()) { return null; } Future<String> html = this.run( "return com.bkahlert.nebula.editor.getSource();", IConverter.CONVERTER_STRING); return html; } public void setMode(String mode) { this.run("com.bkahlert.nebula.editor.setMode(\"" + mode + "\");"); } public void showSource() { this.setMode("source"); } public void hideSource() { this.setMode("wysiwyg"); } public String getPrevCaretCharacter() { if (!this.isLoadingCompleted()) { return null; } String html = (String) this.getBrowser().evaluate( "return com.bkahlert.nebula.editor.getPrevCaretCharacter();"); return html; } public void saveSelection() { this.run("com.bkahlert.nebula.editor.saveSelection();"); } public void restoreSelection() { this.run("com.bkahlert.nebula.editor.restoreSelection();"); } @Override public void setEnabled(boolean isEnabled) { this.run("return com.bkahlert.nebula.editor.setEnabled(" + (isEnabled ? "true" : "false") + ");", IConverter.CONVERTER_BOOLEAN); } @Override public void setBackground(Color color) { this.setBackground(color != null ? new RGB(color.getRGB()) : null); } public void setBackground(RGB rgb) { this.background = rgb; String hex = rgb != null ? rgb.toHexString() : "transparent"; this.injectCss("html .cke_reset { background-color: " + hex + "; }"); } public RGB getBackgroundRGB() { return this.background; } public void addAnkerLabelProvider(IAnkerLabelProvider ankerLabelProvider) { this.ankerLabelProviders.add(ankerLabelProvider); } public void removeAnkerLabelProvider(IAnkerLabelProvider ankerLabelProvider) { this.ankerLabelProviders.remove(ankerLabelProvider); } @Override public void addModifyListener(ModifyListener modifyListener) { this.modificationNotifier.addModifyListener(modifyListener); } @Override public void removeModifyListener(ModifyListener modifyListener) { this.modificationNotifier.removeModifyListener(modifyListener); } }
package at.ac.tuwien.kr.alpha.solver; import at.ac.tuwien.kr.alpha.common.AnswerSet; import at.ac.tuwien.kr.alpha.grounder.NaiveGrounder; import at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import org.junit.Ignore; import org.junit.Test; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Set; import static at.ac.tuwien.kr.alpha.Main.parseVisit; import static at.ac.tuwien.kr.alpha.MainTest.stream; import static org.junit.Assert.assertEquals; public class PigeonHoleTest extends AbstractSolverTests { /** * Sets the logging level to TRACE. Useful for debugging; call at beginning of test case. */ private static void enableTracing() { Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); root.setLevel(ch.qos.logback.classic.Level.TRACE); } private static void enableDebugLog() { Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); root.setLevel(Level.DEBUG); } @Test(timeout = 1000) public void test2Pigeons2Holes() throws IOException { testPigeonsHoles(2, 2); } @Test(timeout = 1000) public void test3Pigeons2Holes() throws IOException { testPigeonsHoles(3, 2); } @Test(timeout = 1000) public void test2Pigeons3Holes() throws IOException { testPigeonsHoles(2, 3); } @Test(timeout = 5000) public void test3Pigeons3Holes() throws IOException { testPigeonsHoles(3, 3); } @Test(timeout = 10000) @Ignore("currently not possible within time limit") // TODO public void test4Pigeons3Holes() throws IOException { testPigeonsHoles(4, 3); } @Test(timeout = 10000) @Ignore("currently not possible within time limit") // TODO public void test3Pigeons4Holes() throws IOException { testPigeonsHoles(3, 4); } /** * Tries to solve the problem of assigning P pigeons to H holes. */ private void testPigeonsHoles(int pigeons, int holes) throws IOException { String ls = System.lineSeparator(); StringBuilder testProgram = new StringBuilder(); testProgram.append("n(N) :- pigeon(N).").append(ls); testProgram.append("n(N) :- hole(N).").append(ls); testProgram.append("eq(N,N) :- n(N).").append(ls); testProgram.append("in(P,H) :- pigeon(P), hole(H), not not_in(P,H).").append(ls); testProgram.append("not_in(P,H) :- pigeon(P), hole(H), not in(P,H).").append(ls); testProgram.append(":- in(P,H1), in(P,H2), not eq(H1,H2).").append(ls); testProgram.append(":- in(P1,H), in(P2,H), not eq(P1,P2).").append(ls); testProgram.append("assigned(P) :- pigeon(P), in(P,H).").append(ls); testProgram.append(":- pigeon(P), not assigned(P).").append(ls); addPigeons(testProgram, pigeons); addHoles(testProgram, holes); ParsedProgram parsedProgram = parseVisit(stream(testProgram.toString())); NaiveGrounder grounder = new NaiveGrounder(parsedProgram); Solver solver = getInstance(grounder); Set<AnswerSet> answerSets = solver.collectSet(); assertEquals(numberOfSolutions(pigeons, holes), answerSets.size()); } private void addPigeons(StringBuilder testProgram, int pigeons) { addFacts(testProgram, "pigeon", 1, pigeons); } private void addHoles(StringBuilder testProgram, int holes) { addFacts(testProgram, "hole", 1, holes); } private void addFacts(StringBuilder testProgram, String predicateName, int from, int to) { String ls = System.lineSeparator(); for (int i = from; i <= to; i++) { testProgram.append(String.format("%s(%d).%s", predicateName, i, ls)); } } private long numberOfSolutions(int pigeons, int holes) { if (pigeons > holes) { return 0; } else if (pigeons == holes) { return factorial(pigeons); } else { return factorial(holes) / factorial(holes - pigeons); // could be replaced by more efficient implementaton (but performance is not so important here) } } private long factorial(int n) { return n <= 1 ? 1 : n * factorial(n - 1); // could be replaced by more efficient implementaton (but performance is not so important here) // TODO: we could use Apache Commons Math } }
package ch.goodrick.brewcontrol.mashing; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.io.IOException; import org.junit.Test; import ch.goodrick.brewcontrol.actuator.Actuator; import ch.goodrick.brewcontrol.actuator.FakeActuator; import ch.goodrick.brewcontrol.button.Button; import ch.goodrick.brewcontrol.button.VirtualButton; import ch.goodrick.brewcontrol.common.PhysicalQuantity; import ch.goodrick.brewcontrol.sensor.FakeSensor; import ch.goodrick.brewcontrol.sensor.Sensor; public class MashingTest { @Test public void test() throws IOException { String name = "test"; Mashing mashing = Mashing.getInstance(); mashing.terminate(); Actuator actuator = new FakeActuator(PhysicalQuantity.TEMPERATURE); Sensor sensor = new FakeSensor(actuator); Button button = new VirtualButton(); mashing.initMashing(sensor, actuator, button); mashing.setName(name); assertEquals(mashing.getActuator(), actuator); assertEquals(mashing.getName(), name); mashing.addRest(new Rest(name, 1d, 1, true)); assertNotNull(mashing.getFirstRest()); try { mashing.startMashing(); } catch (MashingException e) { fail(e.getMessage()); } } @Test public void testTerminate() throws IOException, InterruptedException { String name = "test"; Mashing mashing = Mashing.getInstance(); mashing.terminate(); Actuator actuator = new FakeActuator(PhysicalQuantity.TEMPERATURE); Sensor sensor = new FakeSensor(actuator); Button button = new VirtualButton(); mashing.initMashing(sensor, actuator, button); mashing.setName(name); mashing.addRest(new Rest(name, 100d, 1, true)); try { assertEquals(RestState.INACTIVE, mashing.getFirstRest().getState()); mashing.startMashing(); Thread.sleep(50); assertEquals(RestState.HEATING, mashing.getFirstRest().getState()); mashing.terminate(); assertEquals(RestState.INACTIVE, mashing.getFirstRest().getState()); } catch (MashingException e) { fail(e.getMessage()); } } }
package com.cloudbees.jenkins; import com.google.common.base.Charsets; import com.google.common.net.HttpHeaders; import com.jayway.restassured.builder.RequestSpecBuilder; import com.jayway.restassured.response.Header; import com.jayway.restassured.specification.RequestSpecification; import org.apache.commons.io.IOUtils; import org.jenkinsci.plugins.github.config.GitHubPluginConfig; import org.jenkinsci.plugins.github.webhook.GHEventHeader; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExternalResource; import org.jvnet.hudson.test.JenkinsRule; import org.kohsuke.github.GHEvent; import javax.inject.Inject; import java.io.File; import java.io.IOException; import static com.jayway.restassured.RestAssured.given; import static com.jayway.restassured.config.EncoderConfig.encoderConfig; import static com.jayway.restassured.config.RestAssuredConfig.newConfig; import static java.lang.String.format; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED; import static javax.servlet.http.HttpServletResponse.SC_OK; import static org.apache.commons.lang3.ClassUtils.PACKAGE_SEPARATOR; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.notNullValue; import static org.jenkinsci.plugins.github.test.HookSecretHelper.removeSecretIn; import static org.jenkinsci.plugins.github.test.HookSecretHelper.storeSecretIn; import static org.jenkinsci.plugins.github.webhook.RequirePostWithGHHookPayload.Processor.SIGNATURE_HEADER; /** * @author lanwen (Merkushev Kirill) */ public class GitHubWebHookFullTest { public static final String APPLICATION_JSON = "application/json"; public static final String FORM = "application/x-www-form-urlencoded"; public static final Header JSON_CONTENT_TYPE = new Header(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON); public static final Header FORM_CONTENT_TYPE = new Header(HttpHeaders.CONTENT_TYPE, FORM); public static final String NOT_NULL_VALUE = "nonnull"; private RequestSpecification spec; @Inject private GitHubPluginConfig config; @ClassRule public static JenkinsRule jenkins = new JenkinsRule(); @Rule public ExternalResource inject = new ExternalResource() { @Override protected void before() throws Throwable { jenkins.getInstance().getInjector().injectMembers(GitHubWebHookFullTest.this); } }; @Rule public ExternalResource setup = new ExternalResource() { @Override protected void before() throws Throwable { spec = new RequestSpecBuilder() .setBaseUri(jenkins.getInstance().getRootUrl()) .setBasePath(GitHubWebHook.URLNAME.concat("/")) .setConfig(newConfig() .encoderConfig(encoderConfig() .defaultContentCharset(Charsets.UTF_8) .appendDefaultContentCharsetToContentTypeIfUndefined(false))) .build(); } }; @Test public void shouldParseJsonWebHookFromGH() throws Exception { removeSecretIn(config); given().spec(spec) .header(eventHeader(GHEvent.PUSH)) .header(JSON_CONTENT_TYPE) .content(classpath("payloads/push.json")) .log().all() .expect().log().all().statusCode(SC_OK).post(); } @Test public void shouldParseJsonWebHookFromGHWithSignHeader() throws Exception { String hash = "355e155fc3d10c4e5f2c6086a01281d2e947d932"; String secret = "123"; storeSecretIn(config, secret); given().spec(spec) .header(eventHeader(GHEvent.PUSH)) .header(JSON_CONTENT_TYPE) .header(SIGNATURE_HEADER, format("sha1=%s", hash)) .content(classpath(String.format("payloads/ping_hash_%s_secret_%s.json", hash, secret))) .log().all() .expect().log().all().statusCode(SC_OK).post(); } @Test public void shouldParseFormWebHookOrServiceHookFromGH() throws Exception { given().spec(spec) .header(eventHeader(GHEvent.PUSH)) .header(FORM_CONTENT_TYPE) .formParam("payload", classpath("payloads/push.json")) .log().all() .expect().log().all().statusCode(SC_OK).post(); } @Test public void shouldParsePingFromGH() throws Exception { given().spec(spec) .header(eventHeader(GHEvent.PING)) .header(JSON_CONTENT_TYPE) .content(classpath("payloads/ping.json")) .log().all() .expect().log().all() .statusCode(SC_OK) .post(); } @Test public void shouldReturnErrOnEmptyPayloadAndHeader() throws Exception { given().spec(spec) .log().all() .expect().log().all() .statusCode(SC_BAD_REQUEST) .body(containsString("Hook should contain event type")) .post(); } @Test public void shouldReturnErrOnEmptyPayload() throws Exception { given().spec(spec) .header(eventHeader(GHEvent.PUSH)) .log().all() .expect().log().all() .statusCode(SC_BAD_REQUEST) .body(containsString("Hook should contain payload")) .post(); } @Test public void shouldReturnErrOnGetReq() throws Exception { given().spec(spec) .log().all().expect().log().all() .statusCode(SC_METHOD_NOT_ALLOWED) .get(); } @Test public void shouldProcessSelfTest() throws Exception { given().spec(spec) .header(new Header(GitHubWebHook.URL_VALIDATION_HEADER, NOT_NULL_VALUE)) .log().all() .expect().log().all() .statusCode(SC_OK) .header(GitHubWebHook.X_INSTANCE_IDENTITY, notNullValue()) .post(); } public Header eventHeader(GHEvent event) { return eventHeader(event.name().toLowerCase()); } public Header eventHeader(String event) { return new Header(GHEventHeader.PayloadHandler.EVENT_HEADER, event); } public static String classpath(String path) { return classpath(GitHubWebHookFullTest.class, path); } public static String classpath(Class<?> clazz, String path) { try { return IOUtils.toString(clazz.getClassLoader().getResourceAsStream( clazz.getName().replace(PACKAGE_SEPARATOR, File.separator) + File.separator + path ), Charsets.UTF_8); } catch (IOException e) { throw new RuntimeException(format("Can't load %s for class %s", path, clazz), e); } } }
package com.github.klondike.android.campfire; import java.util.ArrayList; import android.app.Activity; import android.app.Dialog; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.github.klondike.java.campfire.Campfire; import com.github.klondike.java.campfire.CampfireException; import com.github.klondike.java.campfire.Room; import com.github.klondike.java.campfire.RoomEvent; public class RoomView extends ListActivity { private static final int MENU_PREFS = 0; private static final int MENU_LOGOUT = 1; private static final int JOINING = 0; private static final int SPEAKING = 1; private static final int POLLING = 2; private static final int MAX_STARTING_MESSAGES = 10; private Campfire campfire; private String roomId; private Room room; private ArrayList<RoomEvent> events; private ArrayList<RoomEvent> newEvents; private RoomEvent newPost; private EditText message; private Button speak, refresh; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.room); roomId = getIntent().getStringExtra("room_id"); verifyLogin(); } // Will only happen after we are definitely logged in, // and the campfire member variable has been loaded with a logged-in Campfire private void onLogin() { joinRoom(); } // Will only happen after we are both logged in and the room has been joined // events has been populated with the starting messages of a room private void onJoined() { setupControls(); loadEvents(); } // newEvents has been populated by a helper thread with the new events private void onPoll() { if (events.size() == 0) events = newEvents; else { int size = newEvents.size(); for (int i=0; i<size; i++) events.add(newEvents.get(i)); } loadEvents(); } // newPost has been populated with the last message the user just posted // and which (currently) is guaranteed to be actually posted private void onSpeak() { events.add(newPost); loadEvents(); } private void setupControls() { //TODO still: // set name of room in window title message = (EditText) this.findViewById(R.id.room_message); message.setEnabled(true); message.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) speak(); else if (event != null) // the event will only be present for "Enter" speak(); return false; } }); speak = (Button) this.findViewById(R.id.room_speak); speak.setEnabled(true); speak.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { speak(); } }); refresh = (Button) this.findViewById(R.id.room_refresh); refresh.setEnabled(true); refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { poll(); } }); } private void loadEvents() { setListAdapter(new RoomAdapter(this, events)); // keep it scrolled to the bottom getListView().setSelection(events.size()-1); } final Handler handler = new Handler(); final Runnable joinSuccess = new Runnable() { public void run() { removeDialog(JOINING); onJoined(); } }; final Runnable joinFailure = new Runnable() { public void run() { removeDialog(JOINING); alert("Couldn't join room. Select the Re-join menu option to try again."); } }; final Runnable speakSuccess = new Runnable() { public void run() { removeDialog(SPEAKING); message.setText(""); speak.setEnabled(true); onSpeak(); } }; final Runnable speakError = new Runnable() { public void run() { alert("Connection error."); removeDialog(SPEAKING); speak.setEnabled(true); } }; final Runnable pollSuccess = new Runnable() { public void run() { removeDialog(POLLING); onPoll(); } }; final Runnable pollFailure = new Runnable() { public void run() { removeDialog(POLLING); alert("Connection error."); } }; private void speak() { final String msg = message.getText().toString(); if (msg.equals("")) return; speak.setEnabled(false); Thread speakThread = new Thread() { public void run() { try { newPost = room.speak(msg); if (newPost != null) handler.post(speakSuccess); else handler.post(speakError); } catch (CampfireException e) { handler.post(speakError); } } }; speakThread.start(); showDialog(SPEAKING); } private void joinRoom() { Thread joinThread = new Thread() { public void run() { room = new Room(campfire, roomId); try { if (room.join()) { events = room.startingEvents(MAX_STARTING_MESSAGES); handler.post(joinSuccess); } else handler.post(joinFailure); } catch(CampfireException e) { handler.post(joinFailure); } } }; joinThread.start(); showDialog(JOINING); } private void poll() { Thread pollThread = new Thread() { public void run() { try { newEvents = room.listen(); handler.post(pollSuccess); } catch(CampfireException e) { handler.post(pollFailure); } } }; pollThread.start(); showDialog(POLLING); } private void verifyLogin() { campfire = Login.getCampfire(this); if (campfire.loggedIn()) onLogin(); else startActivityForResult(new Intent(this, Login.class), Login.RESULT_LOGIN); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case Login.RESULT_LOGIN: if (resultCode == RESULT_OK) { alert("You have been logged in successfully."); campfire = Login.getCampfire(this); onLogin(); } else finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); menu.add(0, MENU_PREFS, 0, "Preferences").setIcon(android.R.drawable.ic_menu_preferences); menu.add(0, MENU_LOGOUT, 0, "Log Out").setIcon(android.R.drawable.ic_menu_close_clear_cancel); return result; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case MENU_PREFS: startActivity(new Intent(this, Preferences.class)); return true; case MENU_LOGOUT: getSharedPreferences("campfire", 0).edit().putString("session", null).commit(); finish(); } return super.onOptionsItemSelected(item); } protected Dialog onCreateDialog(int id) { ProgressDialog loadingDialog = new ProgressDialog(this); loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); switch(id) { case SPEAKING: loadingDialog.setMessage("Speaking..."); return loadingDialog; case JOINING: loadingDialog.setMessage("Joining room..."); loadingDialog.setCancelable(false); return loadingDialog; case POLLING: loadingDialog.setMessage("Polling..."); return loadingDialog; default: return null; } } public void alert(String msg) { Toast.makeText(RoomView.this, msg, Toast.LENGTH_SHORT).show(); } protected class RoomAdapter extends ArrayAdapter<RoomEvent> { private LayoutInflater inflater; public RoomAdapter(Activity context, ArrayList<RoomEvent> events) { super(context, 0, events); inflater = context.getLayoutInflater(); } public View getView(int position, View convertView, ViewGroup parent) { RoomEvent item = getItem(position); LinearLayout view; if (convertView == null) view = (LinearLayout) inflater.inflate(viewForType(item.type), null); else view = (LinearLayout) convertView; ((TextView) view.findViewById(R.id.text)).setText(item.message); if (item.type != RoomEvent.TIMESTAMP) { ((TextView) view.findViewById(R.id.person)).setText(item.person); } else ((TextView) view.findViewById(R.id.person)).setText(""); return view; } public int viewForType(int type) { switch (type) { case RoomEvent.TEXT: return R.layout.event_text; case RoomEvent.TIMESTAMP: return R.layout.event_text; case RoomEvent.ENTRY: return R.layout.event_entry; default: return R.layout.event_text; } } } }
package com.hubspot.jinjava.tree; import static org.assertj.core.api.Assertions.assertThat; import java.nio.charset.StandardCharsets; import org.junit.Before; import org.junit.Test; import com.google.common.base.Throwables; import com.google.common.io.Resources; import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.JinjavaConfig; import com.hubspot.jinjava.interpret.Context; import com.hubspot.jinjava.interpret.JinjavaInterpreter; public class ExpressionNodeTest { private Context context; private JinjavaInterpreter interpreter; @Before public void setup() { interpreter = new Jinjava().newInterpreter(); context = interpreter.getContext(); } @Test public void itRendersResultAsTemplateWhenContainingVarBlocks() throws Exception { context.put("myvar", "hello {{ place }}"); context.put("place", "world"); ExpressionNode node = fixture("simplevar"); assertThat(node.render(interpreter).toString()).isEqualTo("hello world"); } @Test public void itRendersResultWithoutNestedExpressionInterpretation() throws Exception { final JinjavaConfig config = JinjavaConfig.newBuilder().withNestedInterpretationEnabled(false).build(); JinjavaInterpreter noNestedInterpreter = new Jinjava(config).newInterpreter(); Context contextNoNestedInterpretation = noNestedInterpreter.getContext(); contextNoNestedInterpretation.put("myvar", "hello {{ place }}"); contextNoNestedInterpretation.put("place", "world"); ExpressionNode node = fixture("simplevar"); assertThat(node.render(noNestedInterpreter).toString()).isEqualTo("hello {{ place }}"); } @Test public void itAvoidsInfiniteRecursionWhenVarsContainBraceBlocks() throws Exception { context.put("myvar", "hello {{ place }}"); context.put("place", "{{ place }}"); ExpressionNode node = fixture("simplevar"); assertThat(node.render(interpreter).toString()).isEqualTo("hello {{ place }}"); } @Test public void itRendersStringRange() throws Exception { context.put("theString", "1234567890"); ExpressionNode node = fixture("string-range"); assertThat(node.render(interpreter).toString()).isEqualTo("345"); } @Test public void valueExprWithOr() throws Exception { context.put("a", "foo"); context.put("b", "bar"); context.put("c", ""); context.put("d", 0); assertThat(val("{{ a or b }}")).isEqualTo("foo"); assertThat(val("{{ c or a }}")).isEqualTo("foo"); assertThat(val("{{ d or b }}")).isEqualTo("bar"); } @Test public void itEscapesValueWhenContextSet() throws Exception { context.put("a", "foo < bar"); assertThat(val("{{ a }}")).isEqualTo("foo < bar"); context.setAutoEscape(true); assertThat(val("{{ a }}")).isEqualTo("foo &lt; bar"); } private String val(String jinja) { return parse(jinja).render(interpreter).getValue(); } private ExpressionNode parse(String jinja) { return (ExpressionNode) new TreeParser(interpreter, jinja).buildTree().getChildren().getFirst(); } private ExpressionNode fixture(String name) { try { return parse(Resources.toString(Resources.getResource(String.format("varblocks/%s.html", name)), StandardCharsets.UTF_8)); } catch (Exception e) { throw Throwables.propagate(e); } } }
package com.noradltd.cucumberjvm.demo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; public class ReverseBasics { private static final String EMPTY_STRING = ""; @Test public void emptyStringIsReversedToEmptyString() { assertThat(new StringReverser().reverse(EMPTY_STRING), is(EMPTY_STRING)); } @Test public void singleCharacterIsReversedToItself() { assertThat(new StringReverser().reverse("a"), is("a")); } @Test public void singleWordIsReversedToItself() { assertThat(new StringReverser().reverse("werd"), is("werd")); } }
package de.cronn.jira.sync; import static de.cronn.jira.sync.SetUtils.*; import static de.cronn.jira.sync.config.Context.*; import static org.assertj.core.api.Assertions.*; import java.net.URL; import java.time.Instant; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpMethod; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.filter.CommonsRequestLoggingFilter; import de.cronn.jira.sync.config.Context; import de.cronn.jira.sync.config.JiraSyncConfig; import de.cronn.jira.sync.domain.JiraComment; import de.cronn.jira.sync.domain.JiraField; import de.cronn.jira.sync.domain.JiraFieldSchema; import de.cronn.jira.sync.domain.JiraIssue; import de.cronn.jira.sync.domain.JiraIssueFields; import de.cronn.jira.sync.domain.JiraIssueStatus; import de.cronn.jira.sync.domain.JiraIssueType; import de.cronn.jira.sync.domain.JiraIssueUpdate; import de.cronn.jira.sync.domain.JiraPriority; import de.cronn.jira.sync.domain.JiraProject; import de.cronn.jira.sync.domain.JiraRemoteLink; import de.cronn.jira.sync.domain.JiraRemoteLinkObject; import de.cronn.jira.sync.domain.JiraResolution; import de.cronn.jira.sync.domain.JiraTransition; import de.cronn.jira.sync.domain.JiraUser; import de.cronn.jira.sync.domain.JiraVersion; import de.cronn.jira.sync.dummy.JiraDummyService; import de.cronn.jira.sync.dummy.JiraFilter; import de.cronn.jira.sync.service.JiraService; import de.cronn.jira.sync.strategy.SyncResult; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") public class JiraSyncApplicationTests { private static final JiraProject SOURCE_PROJECT = new JiraProject("1", "PROJECT_ONE"); private static final JiraProject SOURCE_PROJECT_OTHER = new JiraProject("2", "PROJECT_OTHER"); private static final JiraProject TARGET_PROJECT = new JiraProject("100", "PRJ_ONE"); private static final JiraProject SOURCE_PROJECT_2 = new JiraProject("20", "SRC_TWO"); private static final JiraProject TARGET_PROJECT_2 = new JiraProject("200", "TRG_TWO"); private static final JiraIssueStatus SOURCE_STATUS_OPEN = new JiraIssueStatus("1", "Open"); private static final JiraIssueStatus SOURCE_STATUS_REOPENED = new JiraIssueStatus("2", "Reopened"); private static final JiraIssueStatus SOURCE_STATUS_IN_PROGRESS = new JiraIssueStatus("3", "In Progress"); private static final JiraIssueStatus SOURCE_STATUS_RESOLVED = new JiraIssueStatus("4", "Resolved"); private static final JiraIssueStatus SOURCE_STATUS_CLOSED = new JiraIssueStatus("5", "Closed"); private static final JiraIssueStatus TARGET_STATUS_OPEN = new JiraIssueStatus("100", "Open"); private static final JiraIssueStatus TARGET_STATUS_REOPENED = new JiraIssueStatus("101", "Reopened"); private static final JiraIssueStatus TARGET_STATUS_RESOLVED = new JiraIssueStatus("102", "Resolved"); private static final JiraIssueStatus TARGET_STATUS_CLOSED = new JiraIssueStatus("103", "Closed"); private static final JiraIssueType SOURCE_TYPE_BUG = new JiraIssueType("1", "Bug"); private static final JiraIssueType SOURCE_TYPE_STORY = new JiraIssueType("2", "Story"); private static final JiraIssueType SOURCE_TYPE_UNKNOWN = new JiraIssueType("3", "Unknown"); private static final JiraIssueType TARGET_TYPE_BUG = new JiraIssueType("100", "Bug"); private static final JiraIssueType TARGET_TYPE_IMPROVEMENT = new JiraIssueType("101", "Improvement"); private static final JiraIssueType TARGET_TYPE_TASK = new JiraIssueType("102", "Task"); private static final JiraPriority SOURCE_PRIORITY_HIGH = new JiraPriority("1", "High"); private static final JiraPriority SOURCE_PRIORITY_UNMAPPED = new JiraPriority("99", "Unmapped priority"); private static final JiraPriority TARGET_PRIORITY_DEFAULT = new JiraPriority("100", "Default"); private static final JiraPriority TARGET_PRIORITY_CRITICAL = new JiraPriority("101", "Critical"); private static final JiraResolution SOURCE_RESOLUTION_FIXED = new JiraResolution("1", "Fixed"); private static final JiraResolution TARGET_RESOLUTION_DONE = new JiraResolution("100", "Done"); private static final JiraVersion SOURCE_VERSION_10 = new JiraVersion("1", "10.0"); private static final JiraVersion SOURCE_VERSION_11 = new JiraVersion("2", "11.0"); private static final JiraVersion SOURCE_VERSION_UNDEFINED = new JiraVersion("98", "Undefined"); private static final JiraVersion SOURCE_VERSION_UNMAPPED = new JiraVersion("99", "Unmapped version"); private static final JiraVersion TARGET_VERSION_10 = new JiraVersion("100", "10"); private static final JiraVersion TARGET_VERSION_11 = new JiraVersion("101", "11"); private static final JiraUser SOURCE_USER_SOME = new JiraUser("some.user", "some.user", "Some User"); private static final JiraUser SOURCE_USER_ANOTHER = new JiraUser("anotheruser", "anotheruser", "Another User"); private static final JiraFieldSchema FIELD_SCHEMA_LABELS = new JiraFieldSchema(null, null, "com.atlassian.jira.plugin.system.customfieldtypes:labels"); private static final JiraFieldSchema FIELD_SCHEMA_SELECT = new JiraFieldSchema(null, null, "com.atlassian.jira.plugin.system.customfieldtypes:select"); private static final JiraField SOURCE_CUSTOM_FIELD_FOUND_IN_VERSION = new JiraField("1", "Found in version", true, FIELD_SCHEMA_LABELS); private static final JiraField TARGET_CUSTOM_FIELD_FOUND_IN_VERSION = new JiraField("100", "Found in software version", true, FIELD_SCHEMA_LABELS); private static final JiraField SOURCE_CUSTOM_FIELD_FIXED_IN_VERSION = new JiraField("2", "Fixed in version", true, FIELD_SCHEMA_SELECT); private static final JiraField TARGET_CUSTOM_FIELD_FIXED_IN_VERSION = new JiraField("200", "Fixed in software version", true, FIELD_SCHEMA_SELECT); private static final String SOURCE_PROJECT_1_FILTER_ID_1 = "12345"; private static final String SOURCE_PROJECT_1_FILTER_ID_2 = "56789"; private static final String SOURCE_PROJECT_2_FILTER_ID = "2222"; @Autowired private TestClock clock; @Autowired private JiraDummyService jiraDummyService; @Autowired private JiraService jiraSource; @Autowired private JiraService jiraTarget; @Autowired private JiraSyncTask syncTask; @Autowired private JiraSyncConfig syncConfig; @Autowired private StoringRequestFilter storingRequestFilter; @LocalServerPort private int port; private String sourceBaseUrl; private String targetBaseUrl; @TestConfiguration static class TestConfig { @Bean public CommonsRequestLoggingFilter requestLoggingFilter() { CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter(); filter.setIncludeQueryString(true); filter.setIncludePayload(true); filter.setMaxPayloadLength(10000); filter.setIncludeHeaders(false); filter.setAfterMessagePrefix("REQUEST DATA : "); return filter; } @Bean public StoringRequestFilter storingRequestFilter() { return new StoringRequestFilter(); } } private static JiraFilter filterByProjectAndTypes(JiraProject project, JiraIssueType... issueTypes) { return issue -> { JiraIssueFields fields = issue.getFields(); return fields.getProject().getId().equals(project.getId()) && Arrays.stream(issueTypes).anyMatch(issueType -> fields.getIssuetype().getId().equals(issueType.getId())); }; } @Before public void resetClock() { clock.reset(); } @Before public void setUp() throws Exception { String commonBaseUrl = "https://localhost:" + port + "/"; sourceBaseUrl = commonBaseUrl + SOURCE + "/"; targetBaseUrl = commonBaseUrl + TARGET + "/"; syncConfig.getSource().setUrl(sourceBaseUrl); syncConfig.getTarget().setUrl(targetBaseUrl); jiraDummyService.reset(); jiraSource.evictAllCaches(); jiraTarget.evictAllCaches(); jiraDummyService.setBaseUrl(SOURCE, sourceBaseUrl); jiraDummyService.setBaseUrl(TARGET, targetBaseUrl); jiraDummyService.addProject(SOURCE, SOURCE_PROJECT); jiraDummyService.addProject(SOURCE, SOURCE_PROJECT_OTHER); jiraDummyService.addProject(TARGET, TARGET_PROJECT); jiraDummyService.addProject(SOURCE, SOURCE_PROJECT_2); jiraDummyService.addProject(TARGET, TARGET_PROJECT_2); jiraDummyService.setFilter(SOURCE, SOURCE_PROJECT_1_FILTER_ID_1, filterByProjectAndTypes(SOURCE_PROJECT, SOURCE_TYPE_BUG, SOURCE_TYPE_UNKNOWN)); jiraDummyService.setFilter(SOURCE, SOURCE_PROJECT_1_FILTER_ID_2, issue -> false); jiraDummyService.associateFilterIdToProject(SOURCE, SOURCE_PROJECT_2_FILTER_ID, SOURCE_PROJECT_2); jiraDummyService.addPriority(SOURCE, SOURCE_PRIORITY_HIGH); jiraDummyService.addPriority(SOURCE, SOURCE_PRIORITY_UNMAPPED); jiraDummyService.addPriority(TARGET, TARGET_PRIORITY_DEFAULT); jiraDummyService.addPriority(TARGET, TARGET_PRIORITY_CRITICAL); jiraDummyService.setDefaultPriority(TARGET, TARGET_PRIORITY_DEFAULT); jiraDummyService.addResolution(SOURCE, SOURCE_RESOLUTION_FIXED); jiraDummyService.addResolution(TARGET, TARGET_RESOLUTION_DONE); jiraDummyService.addTransition(SOURCE, new JiraTransition("1", "Set resolved", SOURCE_STATUS_RESOLVED)); jiraDummyService.addTransition(SOURCE, new JiraTransition("2", "Set in progress", SOURCE_STATUS_IN_PROGRESS)); jiraDummyService.addTransition(SOURCE, new JiraTransition("3", "Close", SOURCE_STATUS_CLOSED)); jiraDummyService.addTransition(SOURCE, new JiraTransition("4", "Reopen", SOURCE_STATUS_REOPENED)); jiraDummyService.addTransition(TARGET, new JiraTransition("100", "Resolve", TARGET_STATUS_RESOLVED)); jiraDummyService.addTransition(TARGET, new JiraTransition("101", "Close", TARGET_STATUS_CLOSED)); jiraDummyService.addTransition(TARGET, new JiraTransition("102", "Reopen", TARGET_STATUS_REOPENED)); jiraDummyService.addVersion(SOURCE, SOURCE_VERSION_10); jiraDummyService.addVersion(SOURCE, SOURCE_VERSION_11); jiraDummyService.addVersion(SOURCE, SOURCE_VERSION_UNDEFINED); jiraDummyService.addVersion(SOURCE, SOURCE_VERSION_UNMAPPED); jiraDummyService.addVersion(TARGET, TARGET_VERSION_10); jiraDummyService.addVersion(TARGET, TARGET_VERSION_11); jiraDummyService.addUser(SOURCE, SOURCE_USER_SOME); jiraDummyService.addUser(SOURCE, SOURCE_USER_ANOTHER); jiraDummyService.addField(SOURCE, SOURCE_CUSTOM_FIELD_FOUND_IN_VERSION, null); jiraDummyService.addField(TARGET, TARGET_CUSTOM_FIELD_FOUND_IN_VERSION, null); jiraDummyService.addField(SOURCE, SOURCE_CUSTOM_FIELD_FIXED_IN_VERSION, Collections.singletonMap("v1", 10L)); jiraDummyService.addField(TARGET, TARGET_CUSTOM_FIELD_FIXED_IN_VERSION, Collections.singletonMap("1.0", 100L)); jiraDummyService.setDefaultStatus(TARGET, TARGET_STATUS_OPEN); TARGET_PROJECT.setIssueTypes(Arrays.asList(TARGET_TYPE_BUG, TARGET_TYPE_IMPROVEMENT, TARGET_TYPE_TASK)); TARGET_PROJECT_2.setIssueTypes(Arrays.asList(TARGET_TYPE_BUG, TARGET_TYPE_IMPROVEMENT, TARGET_TYPE_TASK)); jiraDummyService.expectLoginRequest(SOURCE, "jira-sync", "secret in source"); jiraDummyService.expectLoginRequest(TARGET, "jira-sync", "secret in target"); jiraDummyService.expectBasicAuth(TARGET, "basic-auth-user", "secret"); jiraSource.login(syncConfig.getSource(), true); jiraTarget.login(syncConfig.getTarget(), false); storingRequestFilter.clear(); } @After public void logOut() { jiraSource.logout(); jiraTarget.logout(); } private static Map<String, Object> idValueMap(int id, String value) { Map<String, Object> map = new LinkedHashMap<>(); map.put("id", id); map.put("value", value); return map; } @Test public void testConfiguration() throws Exception { Map<String, String> resolutionMapping = syncConfig.getResolutionMapping(); assertThat(resolutionMapping).containsOnly( entry("Done", "Fixed"), entry("Won't Fix", "Won't Fix"), entry("Won't Do", "Rejected"), entry("Incomplete", "Incomplete"), entry("Fixed", "Fixed"), entry("Cannot Reproduce", "Cannot Reproduce"), entry("Duplicate", "Duplicate") ); } @Test public void testResolutionsAreCached() throws Exception { assertThat(jiraSource).isNotSameAs(jiraTarget); jiraSource.getResolutions(); List<JiraResolution> sourceResolutions1 = jiraSource.getResolutions(); List<JiraResolution> sourceResolutions2 = jiraSource.getResolutions(); assertThat(sourceResolutions1).isSameAs(sourceResolutions2); jiraTarget.getResolutions(); List<JiraResolution> targetResolutions1 = jiraTarget.getResolutions(); List<JiraResolution> targetResolutions2 = jiraTarget.getResolutions(); assertThat(targetResolutions1).isSameAs(targetResolutions2); assertThat(sourceResolutions1).isNotSameAs(targetResolutions1); } @Test public void testResolutionsAndPrioritiesAreCached() throws Exception { jiraSource.getResolutions(); List<JiraResolution> sourceResolutions1 = jiraSource.getResolutions(); List<JiraResolution> sourceResolutions2 = jiraSource.getResolutions(); jiraSource.getPriorities(); List<JiraPriority> sourcePriorities1 = jiraSource.getPriorities(); List<JiraPriority> sourcePriorities2 = jiraSource.getPriorities(); assertThat(sourceResolutions1).isSameAs(sourceResolutions2); assertThat(sourcePriorities1).isSameAs(sourcePriorities2); assertThat(sourcePriorities1).isNotSameAs(sourceResolutions1); } @Test public void testEmptySync() throws Exception { // when syncAndAssertNoChanges(); // then assertThat(jiraDummyService.getAllIssues(TARGET)).isEmpty(); } @Test public void testCreateTicketInTarget() throws Exception { // given JiraIssue sourceIssue = new JiraIssue(null, null, "My first bug", SOURCE_STATUS_OPEN); sourceIssue.getFields().setProject(SOURCE_PROJECT); sourceIssue.getFields().setIssuetype(SOURCE_TYPE_BUG); sourceIssue.getFields().setPriority(SOURCE_PRIORITY_HIGH); sourceIssue.getFields().setLabels(newLinkedHashSet("label1", "label2")); sourceIssue.getFields().setVersions(newLinkedHashSet(SOURCE_VERSION_10, SOURCE_VERSION_11, SOURCE_VERSION_UNDEFINED)); sourceIssue.getFields().setFixVersions(newLinkedHashSet(SOURCE_VERSION_11)); JiraIssue createdSourceIssue = jiraSource.createIssue(sourceIssue); clock.windForwardSeconds(30); // when syncAndCheckResult(); // then JiraIssue targetIssue = getSingleIssue(TARGET); JiraIssueFields targetIssueFields = targetIssue.getFields(); assertThat(targetIssueFields.getSummary()).isEqualTo("PROJECT_ONE-1: My first bug"); assertThat(targetIssueFields.getIssuetype().getName()).isEqualTo(TARGET_TYPE_BUG.getName()); assertThat(targetIssueFields.getPriority().getName()).isEqualTo(TARGET_PRIORITY_CRITICAL.getName()); assertThat(targetIssueFields.getLabels()).containsExactly("label1", "label2"); assertThat(targetIssueFields.getVersions()).extracting(JiraVersion::getName).containsExactlyInAnyOrder("10", "11"); assertThat(targetIssueFields.getFixVersions()).extracting(JiraVersion::getName).containsExactly("11"); assertThat(targetIssueFields.getUpdated().toInstant()).isEqualTo(Instant.now(clock)); JiraIssue updatedSourceIssue = getSingleIssue(SOURCE); assertThat(updatedSourceIssue.getFields().getUpdated().toInstant()).isEqualTo(Instant.now(clock)); List<JiraRemoteLink> remoteLinksInTarget = jiraDummyService.getRemoteLinks(TARGET, targetIssue); List<JiraRemoteLink> remoteLinksInSource = jiraDummyService.getRemoteLinks(SOURCE, createdSourceIssue); assertThat(remoteLinksInTarget).hasSize(1); assertThat(remoteLinksInSource).hasSize(1); JiraRemoteLinkObject firstRemoteLinkInSource = remoteLinksInSource.iterator().next().getObject(); assertThat(firstRemoteLinkInSource.getUrl()).isEqualTo(new URL(targetBaseUrl + "/browse/PRJ_ONE-1")); assertThat(firstRemoteLinkInSource.getIcon().getUrl16x16()).isEqualTo(new URL("https://jira-source/favicon.ico")); JiraRemoteLinkObject firstRemoteLinkInTarget = remoteLinksInTarget.iterator().next().getObject(); assertThat(firstRemoteLinkInTarget.getUrl()).isEqualTo(new URL(sourceBaseUrl + "/browse/PROJECT_ONE-1")); assertThat(firstRemoteLinkInTarget.getIcon().getUrl16x16()).isEqualTo(new URL("https://jira-target/favicon.ico")); syncAndAssertNoChanges(); } @Test public void testCreateTicketInTargetFromSecondFilter() throws Exception { JiraIssue sourceIssue1 = new JiraIssue(null, null, "My first bug", SOURCE_STATUS_OPEN); sourceIssue1.getFields().setProject(SOURCE_PROJECT); sourceIssue1.getFields().setIssuetype(SOURCE_TYPE_BUG); sourceIssue1.getFields().setPriority(SOURCE_PRIORITY_HIGH); sourceIssue1.getFields().setLabels(newLinkedHashSet("label1", "label2")); sourceIssue1.getFields().setVersions(newLinkedHashSet(SOURCE_VERSION_10, SOURCE_VERSION_11, SOURCE_VERSION_UNDEFINED)); sourceIssue1.getFields().setFixVersions(newLinkedHashSet(SOURCE_VERSION_11)); JiraIssue createdSourceIssue1 = jiraSource.createIssue(sourceIssue1); JiraIssue sourceIssue2 = new JiraIssue(null, null, "My second bug", SOURCE_STATUS_OPEN); sourceIssue2.getFields().setProject(SOURCE_PROJECT); sourceIssue2.getFields().setIssuetype(SOURCE_TYPE_STORY); sourceIssue2.getFields().setPriority(SOURCE_PRIORITY_HIGH); sourceIssue2.getFields().setLabels(newLinkedHashSet("label1", "label2")); sourceIssue2.getFields().setVersions(newLinkedHashSet(SOURCE_VERSION_10, SOURCE_VERSION_11, SOURCE_VERSION_UNDEFINED)); sourceIssue2.getFields().setFixVersions(newLinkedHashSet(SOURCE_VERSION_11)); jiraSource.createIssue(sourceIssue2); clock.windForwardSeconds(30); syncAndCheckResult(); JiraIssue targetIssue1 = getSingleIssue(TARGET); JiraIssueFields targetIssueFields1 = targetIssue1.getFields(); assertThat(targetIssueFields1.getSummary()).isEqualTo("PROJECT_ONE-1: My first bug"); jiraDummyService.setFilter(SOURCE, "56789", filterByProjectAndTypes(SOURCE_PROJECT, SOURCE_TYPE_STORY)); clock.windForwardSeconds(30); syncAndCheckResult(); JiraIssue targetIssue2 = jiraDummyService.getIssueByKey(TARGET, "PRJ_ONE-2"); JiraIssueFields targetIssueFields2 = targetIssue2.getFields(); assertThat(targetIssueFields2.getSummary()).isEqualTo("PROJECT_ONE-2: My second bug"); // Let the filters overlap jiraDummyService.setFilter(SOURCE, SOURCE_PROJECT_1_FILTER_ID_1, filterByProjectAndTypes(SOURCE_PROJECT, SOURCE_TYPE_BUG)); jiraDummyService.setFilter(SOURCE, SOURCE_PROJECT_1_FILTER_ID_2, filterByProjectAndTypes(SOURCE_PROJECT, SOURCE_TYPE_BUG)); jiraSource.updateIssue(createdSourceIssue1.getKey(), fields -> fields.setDescription("changed description")); clock.windForwardSeconds(30); syncAndCheckResult(); JiraIssue updatedTargetIssue1 = jiraDummyService.getIssueByKey(TARGET, targetIssue1.getKey()); assertThat(updatedTargetIssue1.getFields().getDescription()).isEqualTo("{panel:title=Original description|titleBGColor=#dddddd|bgColor=#eeeeee}\n" + "changed description\n" + "{panel}"); syncAndAssertNoChanges(); } @Test public void testUnmappedVersionAndUnmappedPriority() throws Exception { // given JiraIssue sourceIssue = new JiraIssue(null, null, "some bug", SOURCE_STATUS_OPEN); sourceIssue.getFields().setProject(SOURCE_PROJECT); sourceIssue.getFields().setIssuetype(SOURCE_TYPE_BUG); sourceIssue.getFields().setPriority(SOURCE_PRIORITY_UNMAPPED); sourceIssue.getFields().setVersions(newLinkedHashSet(SOURCE_VERSION_UNMAPPED)); jiraSource.createIssue(sourceIssue); // when syncAndCheckResult(); // then JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getIssuetype().getName()).isEqualTo(TARGET_TYPE_BUG.getName()); assertThat(targetIssue.getFields().getPriority().getName()).isEqualTo(TARGET_PRIORITY_DEFAULT.getName()); assertThat(targetIssue.getFields().getVersions()).isEmpty(); syncAndAssertNoChanges(); } @Test public void testNotConfiguredVersions() throws Exception { // given JiraIssue sourceIssue = new JiraIssue(null, null, "some bug", SOURCE_STATUS_OPEN); sourceIssue.getFields().setProject(SOURCE_PROJECT_2); sourceIssue.getFields().setPriority(SOURCE_PRIORITY_UNMAPPED); sourceIssue.getFields().setVersions(null); sourceIssue.getFields().setIssuetype(SOURCE_TYPE_BUG); jiraSource.createIssue(sourceIssue); // when syncAndCheckResult(); // then JiraIssue targetIssue = getSingleIssue(TARGET); String payload = storingRequestFilter.getPayload(HttpMethod.POST, "/TARGET/rest/api/2/issue"); assertThat(payload).isNotEmpty(); assertThat(payload).doesNotContain("\"versions\":[]"); assertThat(payload).doesNotContain("\"fixVersions\":[]"); assertThat(targetIssue.getFields().getVersions()).isNull(); syncAndAssertNoChanges(); } private JiraIssue getSingleIssue(Context context) { Set<JiraIssue> issues = jiraDummyService.getAllIssues(context); assertThat(issues).hasSize(1); return issues.iterator().next(); } @Test public void testErrorHandling() throws Exception { assertThatExceptionOfType(JiraSyncException.class) .isThrownBy(() -> jiraSource.createIssue(new JiraIssue())) .withMessage("[https://localhost:" + port + "/SOURCE/] Bad Request: fields are missing"); } @Test public void testCreateTicketInTarget_WithFallbackType() throws Exception { // given createIssueInSource(SOURCE_TYPE_UNKNOWN); // when syncAndCheckResult(); // then JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getIssuetype().getName()).isEqualTo(TARGET_TYPE_TASK.getName()); syncAndAssertNoChanges(); } @Test public void testCreateTicketInTarget_WithCustomFields() throws Exception { // given JiraIssue sourceIssue = new JiraIssue(null, null, "some issue", SOURCE_STATUS_OPEN); sourceIssue.getFields().setProject(SOURCE_PROJECT); sourceIssue.getFields().setIssuetype(SOURCE_TYPE_UNKNOWN); sourceIssue.getFields().setPriority(SOURCE_PRIORITY_HIGH); sourceIssue.getFields().setOther(SOURCE_CUSTOM_FIELD_FOUND_IN_VERSION.getId(), Arrays.asList("1.0", "1.1")); sourceIssue.getFields().setOther(SOURCE_CUSTOM_FIELD_FIXED_IN_VERSION.getId(), Collections.singletonMap("value", "v1")); jiraSource.createIssue(sourceIssue); // when syncAndCheckResult(); // then JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getIssuetype().getName()).isEqualTo(TARGET_TYPE_TASK.getName()); Map<String, Object> other = targetIssue.getFields().getOther(); assertThat(other).containsExactly( entry(TARGET_CUSTOM_FIELD_FOUND_IN_VERSION.getId(), Arrays.asList("1.0", "1.1")), entry(TARGET_CUSTOM_FIELD_FIXED_IN_VERSION.getId(), idValueMap(100, "1.0")) ); syncAndAssertNoChanges(); } @Test public void testUpdateTicketInTarget() throws Exception { // given JiraIssue createdSourceIssue = createIssueInSource(); syncAndCheckResult(); JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getDescription()).isEqualTo(""); // when jiraSource.updateIssue(createdSourceIssue.getKey(), fields -> fields.setDescription("changed description")); Instant beforeSecondUpdate = Instant.now(clock); clock.windForwardSeconds(30); syncAndCheckResult(); // then targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getDescription()).isEqualTo("{panel:title=Original description|titleBGColor=#dddddd|bgColor=#eeeeee}\nchanged description\n{panel}"); assertThat(targetIssue.getFields().getUpdated().toInstant()).isEqualTo(Instant.now(clock)); JiraIssue sourceIssue = getSingleIssue(SOURCE); assertThat(sourceIssue.getFields().getUpdated().toInstant()).isEqualTo(beforeSecondUpdate); syncAndAssertNoChanges(); } @Test public void testSetTicketToResolvedInSourceWhenTargetTicketIsClosed() throws Exception { // given createIssueInSource(); syncAndCheckResult(); JiraIssue targetIssue = getSingleIssue(TARGET); // when JiraTransition transition = findTransition(TARGET, targetIssue.getKey(), TARGET_STATUS_CLOSED); JiraIssueUpdate update = new JiraIssueUpdate(); update.setTransition(transition); update.getOrCreateFields().setResolution(TARGET_RESOLUTION_DONE); update.getOrCreateFields().setFixVersions(newLinkedHashSet(TARGET_VERSION_10)); jiraDummyService.transitionIssue(TARGET, targetIssue.getKey(), update); syncAndCheckResult(); // then JiraIssue updatedSourceIssue = getSingleIssue(SOURCE); assertThat(updatedSourceIssue.getFields().getStatus()).isEqualTo(SOURCE_STATUS_RESOLVED); assertThat(updatedSourceIssue.getFields().getResolution()).isEqualTo(SOURCE_RESOLUTION_FIXED); assertThat(updatedSourceIssue.getFields().getFixVersions()).containsExactly(SOURCE_VERSION_10); syncAndAssertNoChanges(); } @Test public void testSetTicketToResolvedInSourceWhenTargetTicketIsClosed_KeepUnmappedVersionInSource() throws Exception { // given JiraIssue issueInSource = createIssueInSource(); JiraIssueUpdate updateSourceVersion = new JiraIssueUpdate(); updateSourceVersion.getOrCreateFields().setFixVersions(newLinkedHashSet(SOURCE_VERSION_UNMAPPED)); jiraDummyService.updateIssue(SOURCE, issueInSource.getKey(), updateSourceVersion); syncAndCheckResult(); JiraIssue targetIssue = getSingleIssue(TARGET); // when JiraTransition transition = findTransition(TARGET, targetIssue.getKey(), TARGET_STATUS_CLOSED); JiraIssueUpdate update = new JiraIssueUpdate(); update.setTransition(transition); update.getOrCreateFields().setResolution(TARGET_RESOLUTION_DONE); update.getOrCreateFields().setFixVersions(newLinkedHashSet(TARGET_VERSION_10)); jiraDummyService.transitionIssue(TARGET, targetIssue.getKey(), update); syncAndCheckResult(); // then JiraIssue updatedSourceIssue = getSingleIssue(SOURCE); assertThat(updatedSourceIssue.getFields().getStatus()).isEqualTo(SOURCE_STATUS_RESOLVED); assertThat(updatedSourceIssue.getFields().getResolution()).isEqualTo(SOURCE_RESOLUTION_FIXED); assertThat(updatedSourceIssue.getFields().getFixVersions()).containsExactly(SOURCE_VERSION_UNMAPPED, SOURCE_VERSION_10); syncAndAssertNoChanges(); } @Test public void testCopyCustomFieldsWhenIssueIsClosed() throws Exception { // given JiraIssue sourceIssue = new JiraIssue(null, null, "My first bug", SOURCE_STATUS_OPEN); sourceIssue.getFields().setProject(SOURCE_PROJECT); sourceIssue.getFields().setIssuetype(SOURCE_TYPE_BUG); sourceIssue.getFields().setPriority(SOURCE_PRIORITY_HIGH); jiraSource.createIssue(sourceIssue); syncAndCheckResult(); JiraIssue targetIssue = getSingleIssue(TARGET); // when JiraTransition transition = findTransition(TARGET, targetIssue.getKey(), TARGET_STATUS_CLOSED); JiraIssueUpdate update = new JiraIssueUpdate(); update.setTransition(transition); update.getOrCreateFields().setResolution(TARGET_RESOLUTION_DONE); update.getOrCreateFields().setFixVersions(newLinkedHashSet(TARGET_VERSION_10)); update.getOrCreateFields().setOther(TARGET_CUSTOM_FIELD_FIXED_IN_VERSION.getId(), Collections.singletonMap("value", "1.0")); jiraDummyService.transitionIssue(TARGET, targetIssue.getKey(), update); syncAndCheckResult(); // then JiraIssue updatedSourceIssue = getSingleIssue(SOURCE); assertThat(updatedSourceIssue.getFields().getStatus()).isEqualTo(SOURCE_STATUS_RESOLVED); Map<String, Object> expectedCustomFieldValue = idValueMap(10, "v1"); assertThat(updatedSourceIssue.getFields().getOther()).containsExactly(entry(SOURCE_CUSTOM_FIELD_FIXED_IN_VERSION.getId(), expectedCustomFieldValue)); syncAndAssertNoChanges(); } @Test public void testCopyCustomFieldsWhenIssueIsClosed_Feature() throws Exception { // given createIssueInSource(SOURCE_TYPE_UNKNOWN); syncAndCheckResult(); JiraIssue targetIssue = getSingleIssue(TARGET); // when JiraTransition transition = findTransition(TARGET, targetIssue.getKey(), TARGET_STATUS_CLOSED); JiraIssueUpdate update = new JiraIssueUpdate(); update.setTransition(transition); update.getOrCreateFields().setResolution(TARGET_RESOLUTION_DONE); update.getOrCreateFields().setFixVersions(newLinkedHashSet(TARGET_VERSION_10)); update.getOrCreateFields().setOther(TARGET_CUSTOM_FIELD_FIXED_IN_VERSION.getId(), Collections.singletonMap("value", "1.0")); jiraDummyService.transitionIssue(TARGET, targetIssue.getKey(), update); syncAndCheckResult(); // then JiraIssue updatedSourceIssue = getSingleIssue(SOURCE); assertThat(updatedSourceIssue.getFields().getStatus()).isEqualTo(SOURCE_STATUS_RESOLVED); assertThat(updatedSourceIssue.getFields().getOther()).isEmpty(); syncAndAssertNoChanges(); } @Test public void testDoNotTriggerTransitionAfterTicketWasMovedBetweenProjects() throws Exception { // given JiraIssue createdSourceIssue = createIssueInSource(); syncAndCheckResult(); moveTicketForwardAndBack(createdSourceIssue.getKey()); JiraIssue targetIssue = getSingleIssue(TARGET); JiraTransition transition = findTransition(TARGET, targetIssue.getKey(), TARGET_STATUS_CLOSED); JiraIssueUpdate update = new JiraIssueUpdate(); update.setTransition(transition); update.getOrCreateFields().setResolution(TARGET_RESOLUTION_DONE); update.getOrCreateFields().setFixVersions(newLinkedHashSet(TARGET_VERSION_10)); jiraDummyService.transitionIssue(TARGET, targetIssue.getKey(), update); // when syncAndCheckResult(); // then JiraIssue updatedSourceIssue = getSingleIssue(SOURCE); assertThat(updatedSourceIssue.getFields().getStatus()).isEqualTo(SOURCE_STATUS_OPEN); syncAndAssertNoChanges(); } private void moveTicketForwardAndBack(String issueKey) { jiraDummyService.moveIssue(SOURCE, issueKey, SOURCE_PROJECT_OTHER.getKey()); jiraDummyService.moveIssue(SOURCE, issueKey, SOURCE_PROJECT.getKey()); JiraIssue sourceIssueMovedBack = getSingleIssue(SOURCE); assertThat(sourceIssueMovedBack.getKey()).isNotEqualTo(issueKey); } @Test @DirtiesContext public void testTriggerTransitionAfterTicketWasMovedBetweenProjects() throws Exception { // given JiraIssue createdSourceIssue = createIssueInSource(); syncAndCheckResult(); moveTicketForwardAndBack(createdSourceIssue.getKey()); JiraIssue targetIssue = getSingleIssue(TARGET); JiraTransition transition = findTransition(TARGET, targetIssue.getKey(), TARGET_STATUS_CLOSED); JiraIssueUpdate update = new JiraIssueUpdate(); update.setTransition(transition); update.getOrCreateFields().setResolution(TARGET_RESOLUTION_DONE); update.getOrCreateFields().setFixVersions(newLinkedHashSet(TARGET_VERSION_10)); jiraDummyService.transitionIssue(TARGET, targetIssue.getKey(), update); syncConfig.getProjects().get("PRJ_ONE").getTransition("ResolveWhenClosed").setTriggerIfIssueWasMovedBetweenProjects(true); // when syncAndCheckResult(); // then JiraIssue updatedSourceIssue = getSingleIssue(SOURCE); assertThat(updatedSourceIssue.getFields().getStatus()).isEqualTo(SOURCE_STATUS_RESOLVED); syncAndAssertNoChanges(); } private JiraIssue createIssueInSource() { return createIssueInSource(SOURCE_TYPE_BUG); } private JiraIssue createIssueInSource(JiraIssueType issueType) { JiraIssue sourceIssue = new JiraIssue(null, null, "some issue", SOURCE_STATUS_OPEN); sourceIssue.getFields().setProject(SOURCE_PROJECT); sourceIssue.getFields().setIssuetype(issueType); sourceIssue.getFields().setPriority(SOURCE_PRIORITY_HIGH); return jiraSource.createIssue(sourceIssue); } private JiraTransition findTransition(Context context, String issueKey, JiraIssueStatus statusToTransitionTo) { List<JiraTransition> transitions = jiraDummyService.getTransitions(context, issueKey).getTransitions(); List<JiraTransition> filteredTransitions = transitions.stream() .filter(transition -> transition.getTo().getName().equals(statusToTransitionTo.getName())) .collect(Collectors.toList()); assertThat(filteredTransitions).hasSize(1); return filteredTransitions.iterator().next(); } @Test public void testSetTicketToInProgressInSourceWhenTargetGetsAssigned() throws Exception { // given JiraIssue createdSourceIssue = createIssueInSource(); syncAndCheckResult(); syncAndAssertNoChanges(); JiraIssue currentTargetIssue = getSingleIssue(TARGET); assertThat(currentTargetIssue.getFields().getStatus()).isEqualTo(TARGET_STATUS_OPEN); // when JiraIssue targetIssue = getSingleIssue(TARGET); targetIssue.getFields().setAssignee(new JiraUser("some", "body")); syncAndCheckResult(); // then JiraIssue updatedSourceIssue = jiraDummyService.getIssueByKey(SOURCE, createdSourceIssue.getKey()); assertThat(updatedSourceIssue.getFields().getStatus()).isEqualTo(SOURCE_STATUS_IN_PROGRESS); assertThat(updatedSourceIssue.getFields().getAssignee().getKey()).isEqualTo("myself"); syncAndAssertNoChanges(); } @Test public void testSetTicketToReopenedInTargetWhenSourceIsReopened() throws Exception { // given JiraIssue createdSourceIssue = createIssueInSource(SOURCE_TYPE_BUG); syncAndCheckResult(); syncAndAssertNoChanges(); JiraIssue targetIssue = getSingleIssue(TARGET); transitionIssue(TARGET, targetIssue, TARGET_STATUS_CLOSED); // when transitionIssue(SOURCE, createdSourceIssue, SOURCE_STATUS_REOPENED); syncAndCheckResult(); // then JiraIssue updatedTargetIssue = getSingleIssue(TARGET); assertThat(updatedTargetIssue.getFields().getStatus()).isEqualTo(TARGET_STATUS_REOPENED); syncAndAssertNoChanges(); } private void transitionIssue(Context context, JiraIssue targetIssue, JiraIssueStatus statusToTransitionTo) { JiraTransition transition = findTransition(context, targetIssue.getKey(), statusToTransitionTo); JiraIssueUpdate update = new JiraIssueUpdate(); update.setTransition(transition); jiraDummyService.transitionIssue(context, targetIssue.getKey(), update); } @Test public void testCreateTicketInTarget_WithComments() throws Exception { // given JiraIssue createdIssue = createIssueInSource(SOURCE_TYPE_UNKNOWN); jiraSource.addComment(createdIssue.getKey(), "some comment"); clock.windForwardSeconds(120); jiraSource.addComment(createdIssue.getKey(), "some other comment"); // when syncAndCheckResult(); // then JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getIssuetype().getName()).isEqualTo(TARGET_TYPE_TASK.getName()); List<JiraComment> comments = targetIssue.getFields().getComment().getComments(); assertThat(comments).hasSize(2); assertThat(comments.iterator().next().getBody()).isEqualTo("{panel:title=my self - 2016-05-23 20:00:00 CEST|titleBGColor=#dddddd|bgColor=#eeeeee}\n" + "some comment\n" + "~??[comment 1_1|https://localhost:" + port + "/SOURCE/browse/PROJECT_ONE-1?focusedCommentId=1_1&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-1_1]??~\n" + "{panel}"); assertThat(comments.get(1).getBody()).isEqualTo("{panel:title=my self - 2016-05-23 20:02:00 CEST|titleBGColor=#dddddd|bgColor=#eeeeee}\n" + "some other comment\n" + "~??[comment 1_2|https://localhost:" + port + "/SOURCE/browse/PROJECT_ONE-1?focusedCommentId=1_2&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-1_2]??~\n" + "{panel}"); syncAndAssertNoChanges(); } @Test public void testCreateTicket_UsernameReferences() throws Exception { // given JiraIssue sourceIssue = new JiraIssue(null, null, "some issue", SOURCE_STATUS_OPEN); sourceIssue.getFields().setDescription("mentioning [~" + SOURCE_USER_SOME.getName() + "] in description"); sourceIssue.getFields().setProject(SOURCE_PROJECT); sourceIssue.getFields().setIssuetype(SOURCE_TYPE_UNKNOWN); sourceIssue.getFields().setPriority(SOURCE_PRIORITY_HIGH); JiraIssue createdIssue = jiraSource.createIssue(sourceIssue); jiraSource.addComment(createdIssue.getKey(), "[~" + SOURCE_USER_ANOTHER.getName() + "]: some comment"); jiraSource.addComment(createdIssue.getKey(), "[~yetanotheruser]: some comment"); // when syncAndCheckResult(); // then JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getDescription()).isEqualTo("{panel:title=Original description|titleBGColor=#dddddd|bgColor=#eeeeee}\n" + "mentioning [Some User|https://localhost:" + port + "/SOURCE/secure/ViewProfile.jspa?name=some.user] in description\n" + "{panel}\n\n"); List<JiraComment> comments = targetIssue.getFields().getComment().getComments(); assertThat(comments).hasSize(2); assertThat(comments.get(0).getBody()).isEqualTo("{panel:title=my self - 2016-05-23 20:00:00 CEST|titleBGColor=#dddddd|bgColor=#eeeeee}\n" + "[Another User|https://localhost:" + port + "/SOURCE/secure/ViewProfile.jspa?name=anotheruser]: some comment\n" + "~??[comment 1_1|https://localhost:" + port + "/SOURCE/browse/PROJECT_ONE-1?focusedCommentId=1_1&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-1_1]??~\n" + "{panel}"); assertThat(comments.get(1).getBody()).isEqualTo("{panel:title=my self - 2016-05-23 20:00:00 CEST|titleBGColor=#dddddd|bgColor=#eeeeee}\n" + "[~yetanotheruser]: some comment\n" + "~??[comment 1_2|https://localhost:" + port + "/SOURCE/browse/PROJECT_ONE-1?focusedCommentId=1_2&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-1_2]??~\n" + "{panel}"); syncAndAssertNoChanges(); } @Test public void testCreateTicket_TicketReferences() throws Exception { // given JiraIssue sourceIssue = new JiraIssue(null, null, "some issue", SOURCE_STATUS_OPEN); sourceIssue.getFields().setDescription("mentioning " + SOURCE_PROJECT.getKey() + "-123 in description"); sourceIssue.getFields().setProject(SOURCE_PROJECT); sourceIssue.getFields().setIssuetype(SOURCE_TYPE_UNKNOWN); sourceIssue.getFields().setPriority(SOURCE_PRIORITY_HIGH); JiraIssue createdIssue = jiraSource.createIssue(sourceIssue); jiraSource.addComment(createdIssue.getKey(), "see ticket " + SOURCE_PROJECT.getKey() + "-456"); // when syncAndCheckResult(); // then JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getDescription()).isEqualTo("{panel:title=Original description|titleBGColor=#dddddd|bgColor=#eeeeee}\n" + "mentioning [PROJECT_ONE-123|https://localhost:" + port + "/SOURCE/browse/PROJECT_ONE-123] in description\n" + "{panel}\n\n"); List<JiraComment> comments = targetIssue.getFields().getComment().getComments(); assertThat(comments).hasSize(1); assertThat(comments.get(0).getBody()).isEqualTo("{panel:title=my self - 2016-05-23 20:00:00 CEST|titleBGColor=#dddddd|bgColor=#eeeeee}\n" + "see ticket [PROJECT_ONE-456|https://localhost:" + port + "/SOURCE/browse/PROJECT_ONE-456]\n" + "~??[comment 1_1|https://localhost:" + this.port + "/SOURCE/browse/PROJECT_ONE-1?focusedCommentId=1_1&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-1_1]??~\n" + "{panel}"); syncAndAssertNoChanges(); } @Test public void testUpdateTicketInTarget_addComment() throws Exception { // given JiraIssue createdSourceIssue = createIssueInSource(); syncAndCheckResult(); JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getComment()).isNull(); // when clock.windForwardSeconds(30); jiraSource.addComment(createdSourceIssue.getKey(), "some comment"); clock.windForwardSeconds(30); syncAndCheckResult(); // then targetIssue = getSingleIssue(TARGET); List<JiraComment> comments = targetIssue.getFields().getComment().getComments(); assertThat(comments).hasSize(1); assertThat(comments.get(0).getBody()).isEqualTo("{panel:title=my self - 2016-05-23 20:00:30 CEST|titleBGColor=#dddddd|bgColor=#eeeeee}\n" + "some comment\n" + "~??[comment 1_1|https://localhost:" + port + "/SOURCE/browse/PROJECT_ONE-1?focusedCommentId=1_1&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-1_1]??~\n" + "{panel}"); syncAndAssertNoChanges(); } @Test public void testUpdateTicketInTarget_addCommentWithLinkToOtherComment() throws Exception { // given JiraIssue createdSourceIssue = createIssueInSource(); syncAndCheckResult(); JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getComment()).isNull(); // when clock.windForwardSeconds(30); jiraSource.addComment(createdSourceIssue.getKey(), "some comment"); clock.windForwardSeconds(30); syncAndCheckResult(); // then targetIssue = getSingleIssue(TARGET); List<JiraComment> comments = targetIssue.getFields().getComment().getComments(); assertThat(comments).hasSize(1); String linkToFirstComment = "https://localhost:" + port + "/SOURCE/browse/PROJECT_ONE-1?focusedCommentId=1_1&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-1_1"; assertThat(comments.get(0).getBody()).contains(linkToFirstComment); syncAndAssertNoChanges(); clock.windForwardSeconds(30); jiraSource.addComment(createdSourceIssue.getKey(), "see the [first comment|" + linkToFirstComment + "]"); syncAndCheckResult(); targetIssue = getSingleIssue(TARGET); comments = targetIssue.getFields().getComment().getComments(); assertThat(comments).hasSize(2); syncAndAssertNoChanges(); targetIssue = getSingleIssue(TARGET); comments = targetIssue.getFields().getComment().getComments(); assertThat(comments).hasSize(2); } private List<ProjectSyncResult> syncAndCheckResult() { List<ProjectSyncResult> results = syncTask.sync(); assertThat(results).extracting(ProjectSyncResult::hasFailed).containsExactly(false, false); return results; } private void syncAndAssertNoChanges() { List<ProjectSyncResult> results = syncAndCheckResult(); for (ProjectSyncResult result : results) { for (SyncResult syncResult : SyncResult.values()) { switch (syncResult) { case UNCHANGED: break; case UNCHANGED_WARNING: case CHANGED: case CHANGED_TRANSITION: case FAILED: case CREATED: assertThat(result.getCount(syncResult)).as("number of " + syncResult + " issues").isZero(); break; default: throw new IllegalArgumentException("Unknown syncResult: " + syncResult); } } } } @Test public void testUpdateTicketInTarget_updateCustomField() throws Exception { // given JiraIssue sourceIssue = new JiraIssue(null, null, "My first bug", SOURCE_STATUS_OPEN); sourceIssue.getFields().setProject(SOURCE_PROJECT); sourceIssue.getFields().setIssuetype(SOURCE_TYPE_BUG); sourceIssue.getFields().setPriority(SOURCE_PRIORITY_HIGH); sourceIssue.getFields().setOther(SOURCE_CUSTOM_FIELD_FOUND_IN_VERSION.getId(), Collections.singletonList("1.0")); JiraIssue createdSourceIssue = jiraSource.createIssue(sourceIssue); syncAndCheckResult(); JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getComment()).isNull(); // when clock.windForwardSeconds(30); jiraSource.updateIssue(createdSourceIssue.getKey(), fields -> { fields.setOther(SOURCE_CUSTOM_FIELD_FOUND_IN_VERSION.getId(), Arrays.asList("1.0", "1.1")); }); clock.windForwardSeconds(30); syncAndCheckResult(); // then targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getOther()).containsExactly(entry(TARGET_CUSTOM_FIELD_FOUND_IN_VERSION.getId(), Arrays.asList("1.0", "1.1"))); syncAndAssertNoChanges(); } @Test public void testUpdateCommentInSource() throws Exception { JiraIssue createdSourceIssue = createIssueInSource(); jiraSource.addComment(createdSourceIssue.getKey(), "first comment"); JiraComment secondComment = jiraSource.addComment(createdSourceIssue.getKey(), "second comment"); clock.windForwardSeconds(30); ZonedDateTime firstSyncTime = ZonedDateTime.now(clock); syncAndCheckResult(); clock.windForwardSeconds(30); JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getComment().getComments()).hasSize(2); jiraSource.updateComment(createdSourceIssue.getKey(), secondComment.getId(), "updated second comment"); clock.windForwardSeconds(30); ZonedDateTime secondSyncTime = ZonedDateTime.now(clock); syncAndCheckResult(); targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getComment().getComments()).hasSize(2); JiraComment comment = targetIssue.getFields().getComment().getComments().get(1); assertThat(comment.getCreated()).isEqualTo(firstSyncTime); assertThat(comment.getUpdated()).isEqualTo(secondSyncTime); assertThat(comment.getBody()).isEqualTo("{panel:title=my self - 2016-05-23 20:00:00 CEST (Updated: 2016-05-23 20:01:00 CEST)|titleBGColor=#dddddd|bgColor=#eeeeee}\n" + "updated second comment\n" + "~??[comment 1_2|https://localhost:" + port + "/SOURCE/browse/PROJECT_ONE-1?focusedCommentId=1_2&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-1_2]??~\n" + "{panel}"); syncAndAssertNoChanges(); } @Test public void testCreateTicketInTargetWithComment_UpdateDoesNotAddItAgain() throws Exception { // given JiraIssue createdSourceIssue = createIssueInSource(); jiraSource.addComment(createdSourceIssue.getKey(), "some comment"); syncAndCheckResult(); JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getComment().getComments()).hasSize(1); syncAndCheckResult(); // then targetIssue = getSingleIssue(TARGET); List<JiraComment> comments = targetIssue.getFields().getComment().getComments(); assertThat(comments).hasSize(1); syncAndAssertNoChanges(); } @Test public void testUpdateTicketInTarget_addCommentAfterCommentWasAddedInTarget() throws Exception { // given JiraIssue createdSourceIssue = createIssueInSource(); jiraSource.addComment(createdSourceIssue.getKey(), "first comment in source"); syncAndCheckResult(); JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getComment().getComments()).hasSize(1); clock.windForwardSeconds(30); jiraSource.addComment(createdSourceIssue.getKey(), "second comment in source"); clock.windForwardSeconds(30); jiraSource.addComment(createdSourceIssue.getKey(), "third comment in source"); clock.windForwardSeconds(30); jiraTarget.addComment(targetIssue.getKey(), "some comment in target"); // when clock.windForwardSeconds(30); syncAndCheckResult(); // then targetIssue = getSingleIssue(TARGET); List<JiraComment> comments = targetIssue.getFields().getComment().getComments(); assertThat(comments).hasSize(4); assertThat(comments.get(0).getBody()).contains("first comment in source").contains("2016-05-23 20:00:00 CEST|titleBGColor=#dddddd|bgColor=#eeeeee"); assertThat(comments.get(1).getBody()).contains("some comment in target"); assertThat(comments.get(2).getBody()) .contains("second comment in source") .contains("2016-05-23 20:00:30 CEST|titleBGColor=#cccccc|bgColor=#dddddd") .contains("This comment was added behind time. The order of comments might not represent the real order."); assertThat(comments.get(3).getBody()) .contains("third comment in source") .contains("2016-05-23 20:01:00 CEST|titleBGColor=#cccccc|bgColor=#dddddd") .contains("This comment was added behind time. The order of comments might not represent the real order."); syncAndAssertNoChanges(); } @Test public void testDoNotUpdateTicketInStatusResolvedOrClosed() throws Exception { // given JiraIssue createdSourceIssue = createIssueInSource(); JiraComment comment = jiraSource.addComment(createdSourceIssue.getKey(), "first comment in source"); syncAndCheckResult(); JiraIssue targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getComment().getComments()).hasSize(1); clock.windForwardSeconds(30); JiraTransition transition = findTransition(TARGET, targetIssue.getKey(), TARGET_STATUS_RESOLVED); JiraIssueUpdate update = new JiraIssueUpdate(); update.setTransition(transition); update.getOrCreateFields().setResolution(TARGET_RESOLUTION_DONE); update.getOrCreateFields().setFixVersions(newLinkedHashSet(TARGET_VERSION_10)); jiraDummyService.transitionIssue(TARGET, targetIssue.getKey(), update); jiraSource.updateComment(createdSourceIssue.getKey(), comment.getId(), "changed comment in source"); clock.windForwardSeconds(30); // when syncAndCheckResult(); // then targetIssue = getSingleIssue(TARGET); assertThat(targetIssue.getFields().getFixVersions()).containsExactly(TARGET_VERSION_10); List<JiraComment> comments = targetIssue.getFields().getComment().getComments(); assertThat(comments).hasSize(1); assertThat(comments.get(0).getBody()).contains("first comment in source"); syncAndAssertNoChanges(); } @Test public void testGetAllowedValuesForCustomField() { Map<String, Object> fields = jiraSource.getAllowedValuesForCustomField(SOURCE_PROJECT.getKey(), SOURCE_CUSTOM_FIELD_FIXED_IN_VERSION.getId()); assertThat(fields).isNotNull(); assertThat(fields.values().size()).isGreaterThanOrEqualTo(1); } @Test public void testDoNotResolveTicketInSourceWhenReopened() throws Exception { createIssueInSource(); syncAndCheckResult(); JiraIssue targetIssue = getSingleIssue(TARGET); transitionIssue(TARGET, targetIssue, TARGET_STATUS_CLOSED); syncAndCheckResult(); JiraIssue sourceIssue = getSingleIssue(SOURCE); assertThat(sourceIssue.getFields().getStatus()).isEqualTo(SOURCE_STATUS_RESOLVED); clock.windForwardSeconds(60); transitionIssue(SOURCE, sourceIssue, SOURCE_STATUS_REOPENED); transitionIssue(SOURCE, sourceIssue, SOURCE_STATUS_IN_PROGRESS); syncAndAssertNoChanges(); } }
package de.siegmar.logbackgelf; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.status.Status; public class XmlConfigurationTest { private LoggerContext context; @BeforeEach public void init() { context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.getStatusManager().clear(); context.reset(); } @Test public void udpConfiguration() throws IOException, JoranException { configure("/udp-config.xml"); assertEquals(Collections.emptyList(), filterWarningsErrors()); } @Test public void tcpConfiguration() throws IOException, JoranException { configure("/tcp-config.xml"); assertEquals(Collections.emptyList(), filterWarningsErrors()); } @Test public void tcpTlsConfiguration() throws IOException, JoranException { configure("/tcp_tls-config.xml"); assertEquals(Collections.emptyList(), filterWarningsErrors()); } private void configure(final String name) throws IOException, JoranException { final JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); try (InputStream config = XmlConfigurationTest.class.getResourceAsStream(name)) { configurator.doConfigure(config); } } private List<Status> filterWarningsErrors() { return context.getStatusManager().getCopyOfStatusList().stream() .filter(s -> s.getLevel() > Status.INFO) .collect(Collectors.toList()); } }
package hello.controllers; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.anonymous; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.handler; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.Collections; import javax.servlet.Filter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import hello.Hello; import hello.config.MessageConverterUtil; import hello.config.Security; import hello.dao.GreetingService; import hello.entities.Greeting; @RunWith(SpringRunner.class) @SpringBootTest(classes = Hello.class) @AutoConfigureMockMvc @ContextConfiguration(classes = Security.class) @ActiveProfiles("test") public class GreetingControllerApiTest { private MockMvc mvc; @Autowired private Filter springSecurityFilterChain; @Mock private Greeting greeting; @Mock private GreetingService greetingService; @InjectMocks private GreetingControllerApi greetingController; @Before public void setup() { MockitoAnnotations.initMocks(this); mvc = MockMvcBuilders.standaloneSetup(greetingController).apply(springSecurity(springSecurityFilterChain)) .setMessageConverters(MessageConverterUtil.getMessageConverters()).build(); } @Test public void getEmptyGreetingsList() throws Exception { when(greetingService.findAll()).thenReturn(Collections.<Greeting> emptyList()); mvc.perform(MockMvcRequestBuilders.get("/api/greeting").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andExpect(handler().methodName("list")) .andExpect(jsonPath("$.length()", equalTo(1))) .andExpect(jsonPath("$._links.self.href", endsWith("/api/greeting"))); } @Test public void getGreetingsList() throws Exception { Greeting g = new Greeting("%s"); when(greetingService.findAll()).thenReturn(Collections.<Greeting> singletonList(g)); mvc.perform(MockMvcRequestBuilders.get("/api/greeting").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andExpect(handler().methodName("list")) .andExpect(jsonPath("$.length()", equalTo(2))) .andExpect(jsonPath("$._links.self.href", endsWith("/api/greeting"))) .andExpect(jsonPath("$._embedded.greetings.length()", equalTo(1))); } @Test public void getGreeting() throws Exception { int id = 0; Greeting g = new Greeting("%s"); when(greetingService.findOne(id)).thenReturn(g); mvc.perform(MockMvcRequestBuilders.get("/api/greeting/{id}", id).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(handler().methodName("greeting")).andExpect(jsonPath("$.id", equalTo(id))) .andExpect(jsonPath("$.template", equalTo("%s"))) .andExpect(jsonPath("$._links.self.href", endsWith("" + id))); } @Test public void getNewGreeting() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/api/greeting/new").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotAcceptable()).andExpect(handler().methodName("newGreeting")); } @Test public void postGreetingNoAuth() throws Exception { mvc.perform(MockMvcRequestBuilders.post("/api/greeting").contentType(MediaType.APPLICATION_JSON) .content("{ \"template\": \"Howdy, %s!\" }").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isUnauthorized()); verify(greetingService, never()).save(greeting); } @Test public void postGreetingBadAuth() throws Exception { mvc.perform( MockMvcRequestBuilders.post("/api/greeting").with(anonymous()) .contentType(MediaType.APPLICATION_JSON).content("{ \"template\": \"Howdy, %s!\" }") .accept(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); verify(greetingService, never()).save(greeting); } @Test public void postGreeting() throws Exception { ArgumentCaptor<Greeting> arg = ArgumentCaptor.forClass(Greeting.class); mvc.perform( MockMvcRequestBuilders.post("/api/greeting").with(user("Rob")).contentType(MediaType.APPLICATION_JSON) .content("{ \"template\": \"Howdy, %s!\" }").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()).andExpect(content().string("")) .andExpect(header().string("Location", containsString("/api/greeting/"))) .andExpect(handler().methodName("createGreeting")); verify(greetingService).save(arg.capture()); assertThat("Howdy, %s!", equalTo(arg.getValue().getTemplate())); } @Test public void postBadGreeting() throws Exception { mvc.perform( MockMvcRequestBuilders.post("/api/greeting").with(user("Rob")).contentType(MediaType.APPLICATION_JSON) .content("{ \"template\": \"no placeholder\" }").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isUnprocessableEntity()).andExpect(content().string("")) .andExpect(handler().methodName("createGreeting")); verify(greetingService, never()).save(greeting); } @Test public void postLongGreeting() throws Exception { mvc.perform( MockMvcRequestBuilders.post("/api/greeting").with(user("Rob")).contentType(MediaType.APPLICATION_JSON) .content("{ \"template\": \"abcdefghij %s klmnopqrst uvwxyz\" }").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isUnprocessableEntity()).andExpect(content().string("")) .andExpect(handler().methodName("createGreeting")); verify(greetingService, never()).save(greeting); } @Test public void postEmptyGreeting() throws Exception { mvc.perform( MockMvcRequestBuilders.post("/api/greeting").with(user("Rob")).contentType(MediaType.APPLICATION_JSON) .content("{ \"template\": \"\" }").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isUnprocessableEntity()).andExpect(content().string("")) .andExpect(handler().methodName("createGreeting")); verify(greetingService, never()).save(greeting); } }
package com.iskrembilen.quasseldroid.gui; import java.util.ArrayList; import java.util.List; import java.util.Observable; import java.util.Observer; import android.annotation.TargetApi; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnMultiChoiceClickListener; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.Typeface; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.os.ResultReceiver; import android.preference.PreferenceManager; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.ViewGroup; import android.view.Window; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.Filter; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.MultiAutoCompleteTextView; import android.widget.TextView; import android.widget.Toast; import android.widget.TextView.OnEditorActionListener; import com.iskrembilen.quasseldroid.Buffer; import com.iskrembilen.quasseldroid.BufferInfo; import com.iskrembilen.quasseldroid.IrcMessage; import com.iskrembilen.quasseldroid.IrcUser; import com.iskrembilen.quasseldroid.UserCollection; import com.iskrembilen.quasseldroid.IrcMessage.Type; import com.iskrembilen.quasseldroid.R; import com.iskrembilen.quasseldroid.service.CoreConnService; import com.iskrembilen.quasseldroid.util.NickCompletionHelper; public class ChatActivity extends Activity{ public static final int MESSAGE_RECEIVED = 0; private static final String BUFFER_ID_EXTRA = "bufferid"; private static final String BUFFER_NAME_EXTRA = "buffername"; private BacklogAdapter adapter; private ListView backlogList; private int dynamicBacklogAmout; SharedPreferences preferences; private ResultReceiver statusReceiver; private NickCompletionHelper nickCompletionHelper; private static final String TAG = ChatActivity.class.getSimpleName(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chat_layout); initActionBar(); preferences = PreferenceManager.getDefaultSharedPreferences(this); adapter = new BacklogAdapter(this, null); backlogList = ((ListView)findViewById(R.id.chatBacklogList)); backlogList.setCacheColorHint(0xffffff); backlogList.setAdapter(adapter); backlogList.setOnScrollListener(new BacklogScrollListener(5)); backlogList.setDividerHeight(0); backlogList.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL); //View v = backlogList.getChildAt(backlogList.getChildCount()); backlogList.setSelection(backlogList.getChildCount()); ((ImageButton)findViewById(R.id.chat_auto_complete_button)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { EditText inputfield = (EditText)findViewById(R.id.ChatInputView); nickCompletionHelper.completeNick(inputfield); } }); ((EditText)findViewById(R.id.ChatInputView)).setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (event != null && event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { EditText inputfield = (EditText)findViewById(R.id.ChatInputView); String inputText = inputfield.getText().toString(); if (!"".equals(inputText)) { boundConnService.sendMessage(adapter.buffer.getInfo().id, inputText); inputfield.setText(""); } return true; } return false; } }); ((EditText)findViewById(R.id.ChatInputView)).setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_TAB && event.getAction() == KeyEvent.ACTION_DOWN) { onSearchRequested(); return true; } return false; } }); ((ListView) findViewById(R.id.chatBacklogList)).setCacheColorHint(0xffffff); //FIXME: why? statusReceiver = new ResultReceiver(null) { @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (resultCode==CoreConnService.CONNECTION_DISCONNECTED) finish(); super.onReceiveResult(resultCode, resultData); } }; } @TargetApi(14) private void initActionBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } } @Override public boolean onSearchRequested() { EditText inputfield = (EditText)findViewById(R.id.ChatInputView); nickCompletionHelper.completeNick(inputfield); return false; //Activity ate the request } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.chat_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent intent = new Intent(this, BufferActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); return true; case R.id.menu_preferences: Intent i = new Intent(ChatActivity.this, PreferenceView.class); startActivity(i); break; case R.id.menu_disconnect: this.boundConnService.disconnectFromCore(); finish(); break; case R.id.menu_hide_events: showDialog(R.id.DIALOG_HIDE_EVENTS); break; case R.id.menu_users_list: openNickList(adapter.buffer); break; } return super.onOptionsItemSelected(item); } @Override protected void onStart() { super.onStart(); dynamicBacklogAmout = Integer.parseInt(preferences.getString(getString(R.string.preference_dynamic_backlog), "10")); findViewById(R.id.chat_auto_complete_button).setEnabled(false); findViewById(R.id.ChatInputView).setEnabled(false); doBindService(); } @Override protected void onStop() { super.onStop(); if (adapter.buffer != null && boundConnService.isConnected()) { adapter.buffer.setDisplayed(false); //Dont save position if list is at bottom if (backlogList.getLastVisiblePosition()==adapter.getCount()-1) { adapter.buffer.setTopMessageShown(0); }else{ adapter.buffer.setTopMessageShown(adapter.getListTopMessageId()); } if (adapter.buffer.getUnfilteredSize()!= 0){ boundConnService.setLastSeen(adapter.getBufferId(), adapter.buffer.getUnfilteredBacklogEntry(adapter.buffer.getUnfilteredSize()-1).messageId); boundConnService.markBufferAsRead(adapter.getBufferId()); boundConnService.setMarkerLine(adapter.getBufferId(), adapter.buffer.getUnfilteredBacklogEntry(adapter.buffer.getUnfilteredSize()-1).messageId); } } doUnbindService(); } @Override protected Dialog onCreateDialog(int id) { //TODO: wtf rewrite this dialog in code creator shit, if it is possible, mabye it is an alert builder for a reason Dialog dialog; switch (id) { case R.id.DIALOG_HIDE_EVENTS: if(adapter.buffer == null) return null; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Hide Events"); String[] filterList = IrcMessage.Type.getFilterList(); boolean[] checked = new boolean[filterList.length]; ArrayList<IrcMessage.Type> filters = adapter.buffer.getFilters(); for (int i=0;i<checked.length;i++) { if(filters.contains(IrcMessage.Type.valueOf(filterList[i]))) { checked[i]=true; }else{ checked[i]=false; } } builder.setMultiChoiceItems(filterList, checked, new OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { IrcMessage.Type type = IrcMessage.Type.valueOf(IrcMessage.Type.getFilterList()[which]); if(isChecked) adapter.addFilter(type); else adapter.removeFilter(type); } }); dialog = builder.create(); break; default: dialog = null; break; } return dialog; } private void openNickList(Buffer buffer) { Intent i = new Intent(ChatActivity.this, NicksActivity.class); i.putExtra(BUFFER_ID_EXTRA, buffer.getInfo().id); i.putExtra(BUFFER_NAME_EXTRA, buffer.getInfo().name); startActivity(i); } public class BacklogAdapter extends BaseAdapter implements Observer { //private ArrayList<IrcMessage> backlog; private LayoutInflater inflater; private Buffer buffer; private ListView list = (ListView)findViewById(R.id.chatBacklogList); public BacklogAdapter(Context context, ArrayList<IrcMessage> backlog) { inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void setBuffer(Buffer buffer) { this.buffer = buffer; if ( buffer.getInfo().type == BufferInfo.Type.QueryBuffer ){ ((TextView)findViewById(R.id.chatNameView)).setText(buffer.getInfo().name); } else if ( buffer.getInfo().type == BufferInfo.Type.StatusBuffer ){ ((TextView)findViewById(R.id.chatNameView)).setText(buffer.getInfo().name); //TODO: Add which server we are connected to } else{ ((TextView)findViewById(R.id.chatNameView)).setText(buffer.getInfo().name + ": " + buffer.getTopic()); } notifyDataSetChanged(); list.scrollTo(list.getScrollX(), list.getScrollY()); } @Override public int getCount() { if (this.buffer==null) return 0; return buffer.getSize(); } @Override public IrcMessage getItem(int position) { //TODO: QriorityQueue is fucked, we dont want to convert to array here, so change later return (IrcMessage) buffer.getBacklogEntry(position); } @Override public long getItemId(int position) { return buffer.getBacklogEntry(position).messageId; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView==null) { convertView = inflater.inflate(R.layout.backlog_item, null); holder = new ViewHolder(); holder.timeView = (TextView)convertView.findViewById(R.id.backlog_time_view); holder.nickView = (TextView)convertView.findViewById(R.id.backlog_nick_view); holder.msgView = (TextView)convertView.findViewById(R.id.backlog_msg_view); holder.separatorView = (TextView)convertView.findViewById(R.id.backlog_list_separator); holder.item_layout = (LinearLayout)convertView.findViewById(R.id.backlog_item_linearlayout); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } //Set separator line here if (position != (getCount()-1) && (buffer.getMarkerLineMessage() == getItem(position).messageId || (buffer.isMarkerLineFiltered() && getItem(position).messageId<buffer.getMarkerLineMessage() && getItem(position+1).messageId>buffer.getMarkerLineMessage()))) { holder.separatorView.getLayoutParams().height = 1; } else { holder.separatorView.getLayoutParams().height = 0; } IrcMessage entry = this.getItem(position); holder.messageID = entry.messageId; holder.timeView.setText(entry.getTime()); switch (entry.type) { case Action: holder.nickView.setText("-*-"); holder.msgView.setTextColor(getResources().getColor(R.color.ircmessage_actionmessage_color)); holder.nickView.setTextColor(getResources().getColor(R.color.ircmessage_actionmessage_color)); holder.msgView.setText(entry.getNick()+" "+entry.content); break; case Server: holder.nickView.setText("*"); holder.msgView.setTextColor(getResources().getColor(R.color.ircmessage_servermessage_color)); holder.nickView.setTextColor(getResources().getColor(R.color.ircmessage_servermessage_color)); holder.msgView.setText(entry.content); break; case Join: holder.nickView.setText(" holder.msgView.setText(entry.getNick() + " has joined " + entry.content); holder.msgView.setTextColor(getResources().getColor(R.color.ircmessage_commandmessages_color)); holder.nickView.setTextColor(getResources().getColor(R.color.ircmessage_commandmessages_color)); break; case Part: holder.nickView.setText("< holder.msgView.setText(entry.getNick() + " has left (" + entry.content + ")"); holder.msgView.setTextColor(getResources().getColor(R.color.ircmessage_commandmessages_color)); holder.nickView.setTextColor(getResources().getColor(R.color.ircmessage_commandmessages_color)); break; case Quit: holder.nickView.setText("< holder.msgView.setText(entry.getNick() + " has quit (" + entry.content + ")"); holder.msgView.setTextColor(getResources().getColor(R.color.ircmessage_commandmessages_color)); holder.nickView.setTextColor(getResources().getColor(R.color.ircmessage_commandmessages_color)); break; //TODO: implement the rest case Kick: holder.nickView.setText("<-*"); int nickEnd = entry.content.toString().indexOf(" "); String nick = entry.content.toString().substring(0, nickEnd); String reason = entry.content.toString().substring(nickEnd+1); holder.msgView.setText(entry.getNick() + " has kicked " + nick + " from " + entry.bufferInfo.name + " (" + reason + ")"); holder.msgView.setTextColor(getResources().getColor(R.color.ircmessage_commandmessages_color)); holder.nickView.setTextColor(getResources().getColor(R.color.ircmessage_commandmessages_color)); break; case Mode: holder.nickView.setText("***"); holder.msgView.setText("Mode " + entry.content.toString() + " by " + entry.getNick()); holder.msgView.setTextColor(getResources().getColor(R.color.ircmessage_commandmessages_color)); holder.nickView.setTextColor(getResources().getColor(R.color.ircmessage_commandmessages_color)); break; case Nick: holder.nickView.setText("<->"); holder.msgView.setText(entry.getNick()+" is now known as " + entry.content.toString()); holder.msgView.setTextColor(getResources().getColor(R.color.ircmessage_commandmessages_color)); holder.nickView.setTextColor(getResources().getColor(R.color.ircmessage_commandmessages_color)); break; case Plain: default: if(entry.isSelf()) { holder.nickView.setTextColor(Color.BLACK); //TODO: probably move to color file, or somewhere else it needs to be, so user can select color them self }else{ int hashcode = entry.getNick().hashCode(); holder.nickView.setTextColor(Color.rgb(hashcode & 0xFF0000, hashcode & 0xFF00, hashcode & 0xFF)); } holder.msgView.setTextColor(0xff000000); holder.msgView.setTypeface(Typeface.DEFAULT); holder.nickView.setText("<" + entry.getNick() + ">"); holder.msgView.setText(entry.content); break; } if (entry.isHighlighted()) { holder.item_layout.setBackgroundResource(R.color.ircmessage_highlight_color); }else { holder.item_layout.setBackgroundResource(R.color.ircmessage_normal_color); } //Log.i(TAG, "CONTENT:" + entry.content); return convertView; } @Override public void update(Observable observable, Object data) { if (data==null) { notifyDataSetChanged(); return; } switch ((Integer)data) { case R.id.BUFFERUPDATE_NEWMESSAGE: notifyDataSetChanged(); break; case R.id.BUFFERUPDATE_BACKLOG: int topId = getListTopMessageId(); notifyDataSetChanged(); setListTopMessage(topId); break; default: notifyDataSetChanged(); } } /* * Returns the messageid for the ircmessage that is currently at the top of the screen */ public int getListTopMessageId() { int topId; if (list.getChildCount()==0) { topId = 0; }else { topId = ((ViewHolder)list.getChildAt(0).getTag()).messageID; } return topId; } /* * Sets what message from the adapter will be at the top of the visible screen */ public void setListTopMessage(int messageid) { for(int i=0;i<adapter.getCount();i++){ if (adapter.getItemId(i)==messageid){ list.setSelectionFromTop(i,5); break; } } } public void stopObserving() { if(buffer != null) buffer.deleteObserver(this); } public void clearBuffer() { buffer = null; } public int getBufferId() { return buffer.getInfo().id; } public void getMoreBacklog() { adapter.buffer.setBacklogPending(ChatActivity.this.dynamicBacklogAmout); boundConnService.getMoreBacklog(adapter.getBufferId(),ChatActivity.this.dynamicBacklogAmout); } public void removeFilter(Type type) { buffer.removeFilterType(type); } public void addFilter(Type type) { buffer.addFilterType(type); } } public static class ViewHolder { public TextView timeView; public TextView nickView; public TextView msgView; public TextView separatorView; public LinearLayout item_layout; public int messageID; } private class BacklogScrollListener implements OnScrollListener { private int visibleThreshold; private boolean loading = false; public BacklogScrollListener(int visibleThreshold) { this.visibleThreshold = visibleThreshold; } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (loading) { if (!adapter.buffer.hasPendingBacklog()) { loading = false; } } // Log.d(TAG, "loading: "+ Boolean.toString(loading) +"totalItemCount: "+totalItemCount+ "visibleItemCount: " +visibleItemCount+"firstVisibleItem: "+firstVisibleItem+ "visibleThreshold: "+visibleThreshold); if (!loading && (firstVisibleItem <= visibleThreshold)) { if (adapter.buffer!=null) { loading = true; ChatActivity.this.adapter.getMoreBacklog(); }else { Log.w(TAG, "Can't get backlog on null buffer"); } } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // Not interesting for us to use } } /** * Code for service binding: */ private CoreConnService boundConnService; private Boolean isBound; private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. Log.i(TAG, "BINDING ON SERVICE DONE"); boundConnService = ((CoreConnService.LocalBinder)service).getService(); Intent intent = getIntent(); //Testing to see if i can add item to adapter in service Buffer buffer = boundConnService.getBuffer(intent.getIntExtra(BufferActivity.BUFFER_ID_EXTRA, 0), adapter); adapter.setBuffer(buffer); nickCompletionHelper = new NickCompletionHelper(buffer.getUsers().getOperators(), buffer.getUsers().getVoiced(), buffer.getUsers().getUsers()); findViewById(R.id.chat_auto_complete_button).setEnabled(true); findViewById(R.id.ChatInputView).setEnabled(true); buffer.setDisplayed(true); boundConnService.onHighlightsRead(buffer.getInfo().id); //Move list to correect position if (adapter.buffer.getTopMessageShown() == 0) { backlogList.setSelection(adapter.getCount()-1); }else{ adapter.setListTopMessage(adapter.buffer.getTopMessageShown()); } boundConnService.registerStatusReceiver(statusReceiver); } public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. // Because it is running in our same process, we should never // see this happen. boundConnService = null; } }; void doBindService() { // Establish a connection with the service. We use an explicit // class name because we want a specific service implementation that // we know will be running in our own process (and thus won't be // supporting component replacement by other applications). bindService(new Intent(ChatActivity.this, CoreConnService.class), mConnection, Context.BIND_AUTO_CREATE); isBound = true; Log.i(TAG, "BINDING"); } void doUnbindService() { if (isBound) { Log.i(TAG, "Unbinding service"); // Detach our existing connection. adapter.stopObserving(); boundConnService.unregisterStatusReceiver(statusReceiver); unbindService(mConnection); isBound = false; } } }
package kuleuven.group2.policy; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.google.common.collect.ImmutableList; public class RoundRobinPolicyTest extends TestSortingPolicyTest { @Override public void correct_order_test() { } @Test public void correct_order_test_weight_readdedFixed() { List<kuleuven.group2.data.Test> list = ImmutableList.of(test1, test2, test3, test4); TestSortingPolicy policy = new LastFailureFirst(); FixedOrderPolicy fixed1 = new FixedOrderPolicy(list); RoundRobinPolicy rrp = new RoundRobinPolicy(); rrp.addLastWeightedPolicy(new WeightedPolicy(policy, 1)); rrp.addLastPolicy(fixed1); List<kuleuven.group2.data.Test> result = rrp.getSortedTests(super.testDatabase); assertTrue(result.get(0) == test3); assertTrue(result.get(1) == test1); assertTrue(result.get(2) == test2); assertTrue(result.get(3) == test4); } @Test public void correct_order_test_weight1() { List<kuleuven.group2.data.Test> list = ImmutableList.of(test1, test2, test3, test4); TestSortingPolicy policy = new LastFailureFirst(); FixedOrderPolicy fixed1 = new FixedOrderPolicy(list); FixedOrderPolicy fixed2 = new FixedOrderPolicy(list); FixedOrderPolicy fixed3 = new FixedOrderPolicy(list); RoundRobinPolicy rrp = new RoundRobinPolicy(); rrp.addLastWeightedPolicy(new WeightedPolicy(policy, 1)); rrp.addLastPolicy(fixed1); rrp.addLastPolicy(fixed2); rrp.addLastPolicy(fixed3); List<kuleuven.group2.data.Test> result = rrp.getSortedTests(super.testDatabase); assertTrue(result.get(0) == test3); assertTrue(result.get(1) == test1); assertTrue(result.get(2) == test2); assertTrue(result.get(3) == test4); } @Test public void correct_order_test_readded2() { List<kuleuven.group2.data.Test> list = ImmutableList.of(test4, test2, test3, test1); TestSortingPolicy policy = new LastFailureFirst(); FixedOrderPolicy fixed1 = new FixedOrderPolicy(list); FixedOrderPolicy fixed2 = new FixedOrderPolicy(list); FixedOrderPolicy fixed3 = new FixedOrderPolicy(list); RoundRobinPolicy rrp = new RoundRobinPolicy(); rrp.addLastPolicy(policy); rrp.addLastPolicy(policy); rrp.addLastPolicy(fixed1); rrp.addLastPolicy(fixed2); rrp.addLastPolicy(fixed3); List<kuleuven.group2.data.Test> result = rrp.getSortedTests(super.testDatabase); assertTrue(result.get(0) == test3); assertTrue(result.get(1) == test2); assertTrue(result.get(2) == test4); assertTrue(result.get(3) == test1); } @Test public void correct_order_test_weight2() { List<kuleuven.group2.data.Test> list = ImmutableList.of(test4, test2, test3, test1); TestSortingPolicy policy = new LastFailureFirst(); FixedOrderPolicy fixed1 = new FixedOrderPolicy(list); FixedOrderPolicy fixed2 = new FixedOrderPolicy(list); FixedOrderPolicy fixed3 = new FixedOrderPolicy(list); RoundRobinPolicy rrp = new RoundRobinPolicy(); rrp.addLastWeightedPolicy(new WeightedPolicy(policy, 2)); rrp.addLastPolicy(fixed1); rrp.addLastPolicy(fixed2); rrp.addLastPolicy(fixed3); List<kuleuven.group2.data.Test> result = rrp.getSortedTests(super.testDatabase); assertTrue(result.get(0) == test3); assertTrue(result.get(1) == test2); assertTrue(result.get(2) == test4); assertTrue(result.get(3) == test1); } @Test public void correct_order_test_readded3() { List<kuleuven.group2.data.Test> list = ImmutableList.of(test4, test2, test3, test1); TestSortingPolicy policy = new LastFailureFirst(); FixedOrderPolicy fixed1 = new FixedOrderPolicy(list); FixedOrderPolicy fixed2 = new FixedOrderPolicy(list); FixedOrderPolicy fixed3 = new FixedOrderPolicy(list); RoundRobinPolicy rrp = new RoundRobinPolicy(); rrp.addLastPolicy(policy); rrp.addLastPolicy(policy); rrp.addLastPolicy(policy); rrp.addLastPolicy(fixed1); rrp.addLastPolicy(fixed2); rrp.addLastPolicy(fixed3); List<kuleuven.group2.data.Test> result = rrp.getSortedTests(super.testDatabase); assertTrue(result.get(0) == test3); assertTrue(result.get(1) == test2); assertTrue(result.get(2) == test1); assertTrue(result.get(3) == test4); } @Test public void correct_order_test_weight3() { List<kuleuven.group2.data.Test> list = ImmutableList.of(test4, test2, test3, test1); TestSortingPolicy policy = new LastFailureFirst(); FixedOrderPolicy fixed1 = new FixedOrderPolicy(list); FixedOrderPolicy fixed2 = new FixedOrderPolicy(list); FixedOrderPolicy fixed3 = new FixedOrderPolicy(list); RoundRobinPolicy rrp = new RoundRobinPolicy(); rrp.addLastWeightedPolicy(new WeightedPolicy(policy, 3)); rrp.addLastPolicy(fixed1); rrp.addLastPolicy(fixed2); rrp.addLastPolicy(fixed3); List<kuleuven.group2.data.Test> result = rrp.getSortedTests(super.testDatabase); assertTrue(result.get(0) == test3); assertTrue(result.get(1) == test2); assertTrue(result.get(2) == test1); assertTrue(result.get(3) == test4); } @Test public void correct_order_test_selfDirectContaining() { List<kuleuven.group2.data.Test> list = ImmutableList.of(test1, test2, test3, test4); FixedOrderPolicy fixed1 = new FixedOrderPolicy(list); RoundRobinPolicy rrp_high = new RoundRobinPolicy(); rrp_high.addLastPolicy(fixed1); rrp_high.addLastPolicy(rrp_high); rrp_high.getSortedTests(super.testDatabase); } @Test public void correct_order_test_selfIndirectContaining() { List<kuleuven.group2.data.Test> list1 = ImmutableList.of(test1, test2, test3, test4); List<kuleuven.group2.data.Test> list2 = ImmutableList.of(test2, test3, test4, test1); FixedOrderPolicy fixed1 = new FixedOrderPolicy(list1); FixedOrderPolicy fixed2 = new FixedOrderPolicy(list2); RoundRobinPolicy rrp_high = new RoundRobinPolicy(); RoundRobinPolicy rrp_low = new RoundRobinPolicy(); rrp_high.addLastPolicy(fixed1); rrp_low.addLastPolicy(fixed2); rrp_high.addLastPolicy(rrp_low); rrp_low.addLastPolicy(rrp_high); rrp_high.getSortedTests(super.testDatabase); } @Test public void correct_order_test_multipleLevels() { List<kuleuven.group2.data.Test> list1 = ImmutableList.of(test1, test2, test3, test4); List<kuleuven.group2.data.Test> list2 = ImmutableList.of(test2, test3, test4, test1); TestSortingPolicy policy = new LastFailureFirst(); FixedOrderPolicy fixed1 = new FixedOrderPolicy(list1); FixedOrderPolicy fixed2 = new FixedOrderPolicy(list2); RoundRobinPolicy rrp_low = new RoundRobinPolicy(); rrp_low.addLastPolicy(fixed1); rrp_low.addLastPolicy(fixed2); RoundRobinPolicy rrp_high = new RoundRobinPolicy(); rrp_high.addLastPolicy(policy); rrp_high.addLastPolicy(rrp_low); List<kuleuven.group2.data.Test> result = rrp_high.getSortedTests(super.testDatabase); assertTrue(result.get(0) == test3); assertTrue(result.get(1) == test1); assertTrue(result.get(2) == test2); assertTrue(result.get(3) == test4); } @Test public void correct_order_test_noWeightedPolicies() { List<kuleuven.group2.data.Test> list = ImmutableList.of(test1, test2, test3, test4); RoundRobinPolicy rrp = new RoundRobinPolicy(); List<kuleuven.group2.data.Test> result = rrp.getSortedTests(super.testDatabase, list); assertTrue(result.get(0) == test1); assertTrue(result.get(1) == test2); assertTrue(result.get(2) == test3); assertTrue(result.get(3) == test4); } @Override @Test public void immutable_input_test() { List<kuleuven.group2.data.Test> list = ImmutableList.of(test1, test2, test3, test4); TestSortingPolicy policy = new LastFailureFirst(); FixedOrderPolicy fixed1 = new FixedOrderPolicy(list); FixedOrderPolicy fixed2 = new FixedOrderPolicy(list); FixedOrderPolicy fixed3 = new FixedOrderPolicy(list); RoundRobinPolicy rrp = new RoundRobinPolicy(); rrp.addLastWeightedPolicy(new WeightedPolicy(policy, 1)); rrp.addLastPolicy(fixed1); rrp.addLastPolicy(fixed2); rrp.addLastPolicy(fixed3); List<kuleuven.group2.data.Test> input = new ArrayList<kuleuven.group2.data.Test>(); input.add(test1); input.add(test2); input.add(test3); input.add(test4); rrp.getSortedTests(testDatabase, input); assertTrue(input.get(0) == test1); assertTrue(input.get(1) == test2); assertTrue(input.get(2) == test3); assertTrue(input.get(3) == test4); } }
package com.mantono.blink.importing; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Set; import com.mantono.blink.Bookmark; public class DeliciousImporter { private final File data; public DeliciousImporter(final File data) { this.data = data; } public static void main(String[] args) throws IOException, NoSuchAlgorithmException { DeliciousImporter di = new DeliciousImporter(new File("/home/anton/.blink/delicious.html")); System.out.println(di.importData()); } public int importData() throws IOException, NoSuchAlgorithmException { int imported = 0; List<String> lines = Files.readAllLines(data.toPath(), Charset.defaultCharset()); for(String line : lines) { if(!line.contains("A HREF=")) continue; line = line.replaceAll("(<DT><)|(>[^>]*</A>)", ""); final Bookmark bookmark = createBookmark(line); if(saveBookmark(bookmark)) { System.out.println(line); imported++; } } return imported; } private Bookmark createBookmark(String line) throws MalformedURLException { LineParser parser = new LineParser(line); final URL url = parser.getUrl(); final long timestamp = parser.getTimestamp(); final Set<String> labels = parser.getLabels(); return new Bookmark(url, timestamp, labels); } private boolean saveBookmark(Bookmark bookmark) throws NoSuchAlgorithmException, FileNotFoundException, IOException { final CharSequence hash = bookmark.getHash(); final String domain = bookmark.getDomain(); final File folder = new File(System.getProperty("user.home") + "/.blink/bookmarks/" + domain); if(!folder.exists()) Files.createDirectories(folder.toPath()); final File file = new File(folder.getAbsolutePath() + "/" + hash); if(file.exists()) return false; else file.createNewFile(); try(FileOutputStream fileStream = new FileOutputStream(file); PrintStream printStream = new PrintStream(fileStream);) { printStream.print(bookmark.getUrl().toString()+"\n"); printStream.print(bookmark.getTimestamp()+"\n"); for(String label : bookmark.getLabels()) printStream.print(label+"\n"); printStream.flush(); } return true; } }
package net.imagej.patcher; import static net.imagej.patcher.TestUtils.construct; import static net.imagej.patcher.TestUtils.invokeStatic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import ij.ImageJ; import java.awt.Frame; import java.awt.GraphicsEnvironment; import java.awt.Menu; import java.awt.MenuBar; import java.awt.MenuItem; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.Map; import javassist.ClassClassPath; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import net.imagej.patcher.LegacyInjector.Callback; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Tests whether the headless functionality is complete. * * @author Johannes Schindelin */ public class HeadlessCompletenessTest { static { try { LegacyInjector.preinit(); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException("Got exception (see error log)"); } } private File tmpDir; private String threadName; private ClassLoader threadLoader; @Before public void before() throws IOException { threadName = Thread.currentThread().getName(); threadLoader = Thread.currentThread().getContextClassLoader(); tmpDir = TestUtils.createTemporaryDirectory("legacy-"); } @After public void after() { if (threadName != null) Thread.currentThread().setName(threadName); if (threadLoader != null) Thread.currentThread().setContextClassLoader( threadLoader); if (tmpDir != null && tmpDir.isDirectory()) { TestUtils.deleteRecursively(tmpDir); } } @Test public void missingGenericDialogMethods() throws Exception { final ClassPool pool = new ClassPool(); pool.appendClassPath(new ClassClassPath(getClass())); final String originalName = "ij.gui.GenericDialog"; final CtClass original = pool.get(originalName); final String headlessName = HeadlessGenericDialog.class.getName(); final CtClass headless = pool.get(headlessName); final Map<String, CtMethod> methods = new HashMap<String, CtMethod>(); for (final CtMethod method : headless.getMethods()) { if (headless != method.getDeclaringClass()) continue; String name = method.getLongName(); assertTrue(name.startsWith(headlessName + ".")); name = name.substring(headlessName.length() + 1); methods.put(name, method); } // these do not need to be overridden for (final String name : new String[] { "actionPerformed(java.awt.event.ActionEvent)", "adjustmentValueChanged(java.awt.event.AdjustmentEvent)", "getInsets(int,int,int,int)", "getValue(java.lang.String)", "isMatch(java.lang.String,java.lang.String)", "itemStateChanged(java.awt.event.ItemEvent)", "keyPressed(java.awt.event.KeyEvent)", "keyReleased(java.awt.event.KeyEvent)", "keyTyped(java.awt.event.KeyEvent)", "paint(java.awt.Graphics)", "parseDouble(java.lang.String)", "setCancelLabel(java.lang.String)", "textValueChanged(java.awt.event.TextEvent)", "windowActivated(java.awt.event.WindowEvent)", "windowClosed(java.awt.event.WindowEvent)", "windowClosing(java.awt.event.WindowEvent)", "windowDeactivated(java.awt.event.WindowEvent)", "windowDeiconified(java.awt.event.WindowEvent)", "windowIconified(java.awt.event.WindowEvent)", "windowOpened(java.awt.event.WindowEvent)" }) { methods.put(name, null); } for (final CtMethod method : original.getMethods()) { if (original != method.getDeclaringClass()) continue; String name = method.getLongName(); assertTrue(name.startsWith(originalName + ".")); name = name.substring(originalName.length() + 1); assertTrue(name + " is not overridden", methods.containsKey(name)); } } /** * Verifies that the {@link LegacyInjector} adds dummy implementations for as * yet unhandled methods. * <p> * The previous test verifies that the current version of the * {@link HeadlessGenericDialog} has implementations for all of the methods * provided by the current ImageJ 1.x' {@link ij.gui.GenericDialog}. However, * to make things future-proof (i.e. to avoid errors when loading the headless * mode with a future ImageJ 1.x), we need to be extra careful to * auto-generate dummy methods for methods the {@code ij1-patcher} did not * encounter yet. * </p> * * @throws Exception */ @Test public void autogenerateDummyMethods() throws Exception { final LegacyInjector injector = new LegacyInjector(); injector.before.add(new Callback() { @Override public void call(CodeHacker hacker) { // simulate new method in the generic dialog hacker.insertNewMethod("ij.gui.GenericDialog", "public java.lang.String intentionalBreakage()", "throw new RuntimeException(\"This must be overridden\");"); // allow instantiating the headless generic dialog outside macros // hacker.replaceCallInMethod("net.imagej.patcher.HeadlessGenericDialog", // "public <init>()", "ij.Macro", "getOptions", "$_ = \"\";"); } }); final LegacyEnvironment ij1 = new LegacyEnvironment(null, true, injector); // pretend to be running inside a macro Thread.currentThread().setName("Run$_Aaaargh!"); ij1.setMacroOptions("Aaaaaaaaargh!!!"); final Object dialog = ij1.getClassLoader().loadClass("ij.gui.GenericDialog").getConstructor( String.class).newInstance("Hello"); final Object nextString = dialog.getClass().getMethod("intentionalBreakage").invoke(dialog); assertNull(nextString); } @Test public void testMenuStructure() throws Exception { assumeTrue(!GraphicsEnvironment.isHeadless()); final File jarFile = new File(tmpDir, "Set_Property.jar"); TestUtils.makeJar(jarFile, Set_Property.class.getName()); final LegacyEnvironment headlessIJ1 = TestUtils.getTestEnvironment(); headlessIJ1.addPluginClasspath(jarFile); headlessIJ1.runMacro("", ""); final Map<String, String> menuItems = new LinkedHashMap<String, String>(headlessIJ1.getMenuStructure()); assertTrue("does not have 'Set Property'", menuItems .containsKey("Plugins>Set Property")); final LegacyEnvironment ij1 = TestUtils.getTestEnvironment(false, false); ij1.addPluginClasspath(jarFile); final Frame ij1Frame = construct(ij1.getClassLoader(), "ij.ImageJ", ImageJ.NO_SHOW); final MenuBar menuBar = ij1Frame.getMenuBar(); final Hashtable<String, String> commands = invokeStatic(ij1.getClassLoader(), "ij.Menus", "getCommands"); for (int i = 0; i < menuBar.getMenuCount(); i++) { final Menu menu = menuBar.getMenu(i); assertMenuItems(menuItems, commands, menu.getLabel() + ">", menu); } assertTrue("Left-over menu items: " + menuItems.keySet(), menuItems.size() == 0); } private void assertMenuItems(final Map<String, String> menuItems, final Hashtable<String, String> commands, final String prefix, final Menu menu) { int separatorCounter = 0; for (int i = 0; i < menu.getItemCount(); i++) { final MenuItem item = menu.getItem(i); final String label = item.getLabel(); String menuPath = prefix + label; if (item instanceof Menu) { assertMenuItems(menuItems, commands, menuPath + ">", (Menu) item); } else if ("-".equals(label)) { final String menuPath2 = menuPath + ++separatorCounter; assertTrue("Not found: " + menuPath2, menuItems.containsKey(menuPath2)); menuItems.remove(menuPath2); } else if (!menuPath.startsWith("File>Open Recent>")) { assertTrue("Not found: " + menuPath, menuItems.containsKey(menuPath)); assertEquals("Command for menu path: " + menuPath, commands.get(label), menuItems.get(menuPath)); menuItems.remove(menuPath); } } } }
package com.opengamma.engine.security; import java.io.Serializable; import java.util.Collection; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import com.opengamma.id.DomainSpecificIdentifier; import com.opengamma.id.DomainSpecificIdentifiers; /** * A concrete, JavaBean-based implementation of {@link Security}. * * @author kirk */ public class DefaultSecurity implements Security, Serializable { private DomainSpecificIdentifiers _identifiers; private String _securityType; //private AnalyticValueDefinition<FudgeMsg> _marketDataDefinition; private DomainSpecificIdentifier _identityKey; private String _displayName; public DefaultSecurity() { _identifiers = new DomainSpecificIdentifiers(); } public DefaultSecurity(String securityType, Collection<? extends DomainSpecificIdentifier> identifiers) { setSecurityType(securityType); setIdentifiers(identifiers); } @Override public Collection<DomainSpecificIdentifier> getIdentifiers() { return _identifiers.getIdentifiers(); } /** * This will create a <em>copy</em> of the provided collection. * @param identifiers the identifiers to set */ public void setIdentifiers(Collection<? extends DomainSpecificIdentifier> identifiers) { _identifiers = new DomainSpecificIdentifiers(identifiers); } @Override public DomainSpecificIdentifier getIdentityKey() { return _identityKey; } public void setIdentityKey(String identityKey) { _identityKey = new DomainSpecificIdentifier(SECURITY_IDENTITY_KEY_DOMAIN, identityKey); } public void setIdentityKey(DomainSpecificIdentifier identityKey) { _identityKey = identityKey; } @Override public String getSecurityType() { return _securityType; } /** * @param securityType the securityType to set */ public void setSecurityType(String securityType) { _securityType = securityType; } @Override public boolean equals (final Object o) { return EqualsBuilder.reflectionEquals(this, o); } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } public void setDisplayName (final String displayName) { _displayName = displayName; } /** * Override this to supply a "default" display name if one hasn't been explicitly set. The default * here constructs one from the identity key or identifiers. */ protected String getDefaultDisplayName () { DomainSpecificIdentifier identifier = getIdentityKey (); if (identifier == null) { final Collection<DomainSpecificIdentifier> identifiers = getIdentifiers (); if ((identifiers == null) || identifiers.isEmpty ()) { return getClass ().getName (); } identifier = identifiers.iterator ().next (); } return identifier.getDomain ().getDomainName () + "/" + identifier.getValue (); } @Override public String getDisplayName () { if (_displayName != null) { return _displayName; } else { return getDefaultDisplayName (); } } }
package main; import io.IORobot; import java.awt.Point; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import javax.swing.SwingUtilities; import java.lang.InterruptedException; import java.lang.Thread; import move.AttackTransferMove; import move.MoveResult; import move.PlaceArmiesMove; import org.bson.types.ObjectId; import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBObject; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; public class RunGame { LinkedList<MoveResult> fullPlayedGame; LinkedList<MoveResult> player1PlayedGame; LinkedList<MoveResult> player2PlayedGame; int gameIndex = 1; String playerName1, playerName2; final String gameId, bot1Id, bot2Id, bot1Dir, bot2Dir; Engine engine; DB db; public static void main(String args[]) throws Exception { RunGame run = new RunGame(args); run.go(); } public RunGame(String args[]) { this.gameId = args[0]; this.bot1Id = args[1]; this.bot2Id = args[2]; this.bot1Dir = args[3]; this.bot2Dir = args[4]; this.playerName1 = "player1"; this.playerName2 = "player2"; } private void go() throws IOException, InterruptedException { System.out.println("starting game " + gameId); Map initMap, map; Player player1, player2; IORobot bot1, bot2; int startingArmies; db = new MongoClient("localhost", 27017).getDB("test"); // authentication // boolean auth = db.authenticate(<username>,<password>); //setup the bots bot1 = new IORobot("/opt/aigames/scripts/run_bot.sh aiplayer1 " + bot1Dir); bot2 = new IORobot("/opt/aigames/scripts/run_bot.sh aiplayer2 " + bot2Dir); startingArmies = 5; player1 = new Player(playerName1, bot1, startingArmies); player2 = new Player(playerName2, bot2, startingArmies); //setup the map initMap = makeInitMap(); map = setupMap(initMap); //start the engine this.engine = new Engine(map, player1, player2); //send the bots the info they need to start bot1.writeInfo("settings your_bot " + player1.getName()); bot1.writeInfo("settings opponent_bot " + player2.getName()); bot2.writeInfo("settings your_bot " + player2.getName()); bot2.writeInfo("settings opponent_bot " + player1.getName()); sendSetupMapInfo(player1.getBot(), initMap); sendSetupMapInfo(player2.getBot(), initMap); this.engine.distributeStartingRegions(); //decide the player's starting regions this.engine.recalculateStartingArmies(); //calculate how much armies the players get at the start of the round (depending on owned SuperRegions) this.engine.sendAllInfo(); //play the game while(this.engine.winningPlayer() == null && this.engine.getRoundNr() <= 100) { bot1.addToDump("Round " + this.engine.getRoundNr() + "\n"); bot2.addToDump("Round " + this.engine.getRoundNr() + "\n"); this.engine.playRound(); } fullPlayedGame = this.engine.getFullPlayedGame(); player1PlayedGame = this.engine.getPlayer1PlayedGame(); player2PlayedGame = this.engine.getPlayer2PlayedGame(); // String outputFile = this.writeOutputFile(this.gameId, this.engine.winningPlayer()); // this.saveGame(engine.winningPlayer().getName(), engine.getRoundNr(), outputFile); finish(bot1, bot2); } //aanpassen en een QPlayer class maken? met eigen finish private void finish(IORobot bot1, IORobot bot2) throws InterruptedException { bot1.finish(); Thread.sleep(200); bot2.finish(); Thread.sleep(200); Thread.sleep(200); // write everything // String outputFile = this.writeOutputFile(this.gameId, this.engine.winningPlayer()); this.saveGame(bot1, bot2); System.exit(0); } //tijdelijk handmatig invoeren private Map makeInitMap() { Map map = new Map(); SuperRegion northAmerica = new SuperRegion(1, 5); SuperRegion southAmerica = new SuperRegion(2, 2); SuperRegion europe = new SuperRegion(3, 5); SuperRegion afrika = new SuperRegion(4, 3); SuperRegion azia = new SuperRegion(5, 7); SuperRegion australia = new SuperRegion(6, 2); Region region1 = new Region(1, northAmerica); Region region2 = new Region(2, northAmerica); Region region3 = new Region(3, northAmerica); Region region4 = new Region(4, northAmerica); Region region5 = new Region(5, northAmerica); Region region6 = new Region(6, northAmerica); Region region7 = new Region(7, northAmerica); Region region8 = new Region(8, northAmerica); Region region9 = new Region(9, northAmerica); Region region10 = new Region(10, southAmerica); Region region11 = new Region(11, southAmerica); Region region12 = new Region(12, southAmerica); Region region13 = new Region(13, southAmerica); Region region14 = new Region(14, europe); Region region15 = new Region(15, europe); Region region16 = new Region(16, europe); Region region17 = new Region(17, europe); Region region18 = new Region(18, europe); Region region19 = new Region(19, europe); Region region20 = new Region(20, europe); Region region21 = new Region(21, afrika); Region region22 = new Region(22, afrika); Region region23 = new Region(23, afrika); Region region24 = new Region(24, afrika); Region region25 = new Region(25, afrika); Region region26 = new Region(26, afrika); Region region27 = new Region(27, azia); Region region28 = new Region(28, azia); Region region29 = new Region(29, azia); Region region30 = new Region(30, azia); Region region31 = new Region(31, azia); Region region32 = new Region(32, azia); Region region33 = new Region(33, azia); Region region34 = new Region(34, azia); Region region35 = new Region(35, azia); Region region36 = new Region(36, azia); Region region37 = new Region(37, azia); Region region38 = new Region(38, azia); Region region39 = new Region(39, australia); Region region40 = new Region(40, australia); Region region41 = new Region(41, australia); Region region42 = new Region(42, australia); region1.addNeighbor(region2); region1.addNeighbor(region4); region1.addNeighbor(region30); region2.addNeighbor(region4); region2.addNeighbor(region3); region2.addNeighbor(region5); region3.addNeighbor(region5); region3.addNeighbor(region6); region3.addNeighbor(region14); region4.addNeighbor(region5); region4.addNeighbor(region7); region5.addNeighbor(region6); region5.addNeighbor(region7); region5.addNeighbor(region8); region6.addNeighbor(region8); region7.addNeighbor(region8); region7.addNeighbor(region9); region8.addNeighbor(region9); region9.addNeighbor(region10); region10.addNeighbor(region11); region10.addNeighbor(region12); region11.addNeighbor(region12); region11.addNeighbor(region13); region12.addNeighbor(region13); region12.addNeighbor(region21); region14.addNeighbor(region15); region14.addNeighbor(region16); region15.addNeighbor(region16); region15.addNeighbor(region18); region15.addNeighbor(region19); region16.addNeighbor(region17); region17.addNeighbor(region19); region17.addNeighbor(region20); region17.addNeighbor(region27); region17.addNeighbor(region32); region17.addNeighbor(region36); region18.addNeighbor(region19); region18.addNeighbor(region20); region18.addNeighbor(region21); region19.addNeighbor(region20); region20.addNeighbor(region21); region20.addNeighbor(region22); region20.addNeighbor(region36); region21.addNeighbor(region22); region21.addNeighbor(region23); region21.addNeighbor(region24); region22.addNeighbor(region23); region22.addNeighbor(region36); region23.addNeighbor(region24); region23.addNeighbor(region25); region23.addNeighbor(region26); region23.addNeighbor(region36); region24.addNeighbor(region25); region25.addNeighbor(region26); region27.addNeighbor(region28); region27.addNeighbor(region32); region27.addNeighbor(region33); region28.addNeighbor(region29); region28.addNeighbor(region31); region28.addNeighbor(region33); region28.addNeighbor(region34); region29.addNeighbor(region30); region29.addNeighbor(region31); region30.addNeighbor(region31); region30.addNeighbor(region34); region30.addNeighbor(region35); region31.addNeighbor(region34); region32.addNeighbor(region33); region32.addNeighbor(region36); region32.addNeighbor(region37); region33.addNeighbor(region34); region33.addNeighbor(region37); region33.addNeighbor(region38); region34.addNeighbor(region35); region36.addNeighbor(region37); region37.addNeighbor(region38); region38.addNeighbor(region39); region39.addNeighbor(region40); region39.addNeighbor(region41); region40.addNeighbor(region41); region40.addNeighbor(region42); region41.addNeighbor(region42); map.add(region1); map.add(region2); map.add(region3); map.add(region4); map.add(region5); map.add(region6); map.add(region7); map.add(region8); map.add(region9); map.add(region10); map.add(region11); map.add(region12); map.add(region13); map.add(region14); map.add(region15); map.add(region16); map.add(region17); map.add(region18); map.add(region19); map.add(region20); map.add(region21); map.add(region22); map.add(region23); map.add(region24); map.add(region25); map.add(region26); map.add(region27); map.add(region28); map.add(region29); map.add(region30); map.add(region31); map.add(region32); map.add(region33); map.add(region34); map.add(region35); map.add(region36); map.add(region37); map.add(region38); map.add(region39); map.add(region40); map.add(region41); map.add(region42); map.add(northAmerica); map.add(southAmerica); map.add(europe); map.add(afrika); map.add(azia); map.add(australia); return map; } //Make every region neutral with 2 armies to start with private Map setupMap(Map initMap) { Map map = initMap; for(Region region : map.regions) { region.setPlayerName("neutral"); region.setArmies(2); } return map; } private void sendSetupMapInfo(Robot bot, Map initMap) { String setupSuperRegionsString, setupRegionsString, setupNeighborsString; setupSuperRegionsString = getSuperRegionsString(initMap); setupRegionsString = getRegionsString(initMap); setupNeighborsString = getNeighborsString(initMap); bot.writeInfo(setupSuperRegionsString); // System.out.println(setupSuperRegionsString); bot.writeInfo(setupRegionsString); // System.out.println(setupRegionsString); bot.writeInfo(setupNeighborsString); // System.out.println(setupNeighborsString); } private String getSuperRegionsString(Map map) { String superRegionsString = "setup_map super_regions"; for(SuperRegion superRegion : map.superRegions) { int id = superRegion.getId(); int reward = superRegion.getArmiesReward(); superRegionsString = superRegionsString.concat(" " + id + " " + reward); } return superRegionsString; } private String getRegionsString(Map map) { String regionsString = "setup_map regions"; for(Region region : map.regions) { int id = region.getId(); int superRegionId = region.getSuperRegion().getId(); regionsString = regionsString.concat(" " + id + " " + superRegionId); } return regionsString; } //beetje inefficiente methode, maar kan niet sneller wss private String getNeighborsString(Map map) { String neighborsString = "setup_map neighbors"; ArrayList<Point> doneList = new ArrayList<Point>(); for(Region region : map.regions) { int id = region.getId(); String neighbors = ""; for(Region neighbor : region.getNeighbors()) { if(checkDoneList(doneList, id, neighbor.getId())) { neighbors = neighbors.concat("," + neighbor.getId()); doneList.add(new Point(id,neighbor.getId())); } } if(neighbors.length() != 0) { neighbors = neighbors.replaceFirst(","," "); neighborsString = neighborsString.concat(" " + id + neighbors); } } return neighborsString; } private Boolean checkDoneList(ArrayList<Point> doneList, int regionId, int neighborId) { for(Point p : doneList) if((p.x == regionId && p.y == neighborId) || (p.x == neighborId && p.y == regionId)) return false; return true; } private String writeOutputFile(String gameId, Player winner) { try { //temp String fileString = "/home/jim/development/the-ai-games-website/public/games/gameOutputFile" + gameId + ".txt"; FileWriter fileStream = new FileWriter(fileString); BufferedWriter out = new BufferedWriter(fileStream); writePlayedGame(winner, out, "fullGame"); writePlayedGame(winner, out, "player1"); writePlayedGame(winner, out, "player2"); out.close(); return fileString; } catch(Exception e) { System.err.println("Error on creating output file: " + e.getMessage()); return null; } } private void writePlayedGame(Player winner, BufferedWriter out, String gameView) throws IOException { LinkedList<MoveResult> playedGame; if(gameView.equals("player1")) playedGame = player1PlayedGame; else if(gameView.equals("player2")) playedGame = player2PlayedGame; else playedGame = fullPlayedGame; playedGame.removeLast(); int roundNr = 2; out.write("map " + playedGame.getFirst().getMap().getMapString() + "\n"); out.write("round 1" + "\n"); for(MoveResult moveResult : playedGame) { if(moveResult != null) { if(moveResult.getMove() != null) { try { PlaceArmiesMove plMove = (PlaceArmiesMove) moveResult.getMove(); out.write(plMove.getString() + "\n"); } catch(Exception e) { AttackTransferMove atMove = (AttackTransferMove) moveResult.getMove(); out.write(atMove.getString() + "\n"); } out.write("map " + moveResult.getMap().getMapString() + "\n"); } } else { out.write("round " + roundNr + "\n"); roundNr++; } } if(winner != null) out.write(winner.getName() + " won\n"); else out.write("Nobody won\n"); } private String getPlayedGame(Player winner, String gameView) { StringBuffer out = new StringBuffer(); LinkedList<MoveResult> playedGame; if(gameView.equals("player1")) playedGame = player1PlayedGame; else if(gameView.equals("player2")) playedGame = player2PlayedGame; else playedGame = fullPlayedGame; playedGame.removeLast(); int roundNr = 2; out.append("map " + playedGame.getFirst().getMap().getMapString() + "\n"); out.append("round 1" + "\n"); for(MoveResult moveResult : playedGame) { if(moveResult != null) { if(moveResult.getMove() != null) { try { PlaceArmiesMove plMove = (PlaceArmiesMove) moveResult.getMove(); out.append(plMove.getString() + "\n"); } catch(Exception e) { AttackTransferMove atMove = (AttackTransferMove) moveResult.getMove(); out.append(atMove.getString() + "\n"); } out.append("map " + moveResult.getMap().getMapString() + "\n"); } } else { out.append("round " + roundNr + "\n"); roundNr++; } } if(winner != null) out.append(winner.getName() + " won\n"); else out.append("Nobody won\n"); return out.toString(); } /* * MongoDB connection functions */ public void saveGame(IORobot bot1, IORobot bot2) { System.out.println("starting saveGame"); Player winner = this.engine.winningPlayer(); int score = this.engine.getRoundNr(); DBCollection coll = db.getCollection("games"); DBObject queryDoc = new BasicDBObject() .append("_id", new ObjectId(gameId)); ObjectId bot1ObjectId = new ObjectId(bot1Id); ObjectId bot2ObjectId = new ObjectId(bot2Id); ObjectId winnerId = null; if(winner != null) { winnerId = winner.getName() == playerName1 ? bot1ObjectId : bot2ObjectId; } DBObject updateDoc = new BasicDBObject() .append("$set", new BasicDBObject() .append("winner", winnerId) .append("score", score) // .append("visualization", new BasicDBObject() // .append("fullGame", getPlayedGame(winner, "fullGame")) // .append("player1", getPlayedGame(winner, "player1")) // .append("player2", getPlayedGame(winner, "player2")) .append("visualization", getPlayedGame(winner, "fullGame") + getPlayedGame(winner, "player1") + getPlayedGame(winner, "player2") ) .append("output", new BasicDBObject() .append(bot1Id, bot1.getStdout()) .append(bot2Id, bot2.getStdout()) ) .append("input", new BasicDBObject() .append(bot1Id, bot1.getStdin()) .append(bot2Id, bot2.getStdin()) ) .append("errors", new BasicDBObject() .append(bot1Id, bot1.getStderr()) .append(bot2Id, bot2.getStderr()) ) .append("dump", new BasicDBObject() .append(bot1Id, bot1.getDump()) .append(bot2Id, bot2.getDump()) ) ); coll.findAndModify(queryDoc, updateDoc); // System.out.print("Game done... winner: " + winner.getName() + ", score: " + score); System.out.println("Savegame Done"); } }
package org.asteriskjava.manager.event; import java.util.TimeZone; import junit.framework.TestCase; public class TestCdrEvent extends TestCase { CdrEvent cdrEvent; TimeZone defaultTimeZone; @Override protected void setUp() throws Exception { cdrEvent = new CdrEvent(this); cdrEvent.setStartTime("2006-05-19 11:54:48"); defaultTimeZone = TimeZone.getDefault(); } @Override protected void tearDown() throws Exception { TimeZone.setDefault(defaultTimeZone); } public void testGetStartTimeAsDate() { TimeZone.setDefault(TimeZone.getTimeZone("GMT")); assertEquals(1137671688000L, cdrEvent.getStartTimeAsDate().getTime()); } public void testGetStartTimeAsDateWithTimeZone() { TimeZone tz = TimeZone.getTimeZone("GMT+2"); assertEquals(1137664488000L, cdrEvent.getStartTimeAsDate(tz).getTime()); } }
package nallar.patched.entity; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import nallar.patched.annotation.FakeExtend; import net.minecraft.entity.DataWatcher; import net.minecraft.entity.WatchableObject; import net.minecraft.item.ItemStack; import net.minecraft.network.packet.Packet; import net.minecraft.util.ChunkCoordinates; @FakeExtend public abstract class PatchDataWatcher extends DataWatcher { private boolean isBlank = true; private static final HashMap<Class, Integer> dataTypes = new HashMap<Class, Integer>(); private final WatchableObject[] watchedObjects = new WatchableObject[31]; /** * true if one or more object was changed */ private boolean objectChanged; static { dataTypes.put(Byte.class, 0); dataTypes.put(Short.class, 1); dataTypes.put(Integer.class, 2); dataTypes.put(Float.class, 3); dataTypes.put(String.class, 4); dataTypes.put(ItemStack.class, 5); dataTypes.put(ChunkCoordinates.class, 6); } /** * adds a new object to dataWatcher to watch, to update an already existing object see updateObject. Arguments: data * Value Id, Object to add */ @Override public void addObject(int par1, Object par2Obj) { Integer var3 = dataTypes.get(par2Obj.getClass()); if (var3 == null) { throw new IllegalArgumentException("Unknown data type: " + par2Obj.getClass()); } else if (par1 > 31) { throw new IllegalArgumentException("Data value id is too big with " + par1 + "! (Max is " + 31 + ')'); } else if (watchedObjects[par1] != null) { throw new IllegalArgumentException("Duplicate id value for " + par1 + '!'); } watchedObjects[par1] = new WatchableObject(var3, par1, par2Obj); isBlank = false; } /** * Add a new object for the DataWatcher to watch, using the specified data type. */ @Override public void addObjectByDataType(int par1, int par2) { WatchableObject var3 = new WatchableObject(par2, par1, null); watchedObjects[par1] = var3; isBlank = false; } /** * gets the bytevalue of a watchable object */ @Override public byte getWatchableObjectByte(int par1) { return (Byte) watchedObjects[par1].getObject(); } @Override public short getWatchableObjectShort(int par1) { return (Short) watchedObjects[par1].getObject(); } /** * gets a watchable object and returns it as a Integer */ @Override public int getWatchableObjectInt(int par1) { return (Integer) watchedObjects[par1].getObject(); } /** * gets a watchable object and returns it as a String */ @Override public String getWatchableObjectString(int par1) { return (String) watchedObjects[par1].getObject(); } /** * Get a watchable object as an ItemStack. */ @Override public ItemStack getWatchableObjectItemStack(int par1) { return (ItemStack) watchedObjects[par1].getObject(); } /** * updates an already existing object */ @Override public void updateObject(int par1, Object par2Obj) { WatchableObject var3 = watchedObjects[par1]; if (!par2Obj.equals(var3.getObject())) { var3.setObject(par2Obj); var3.setWatched(true); objectChanged = true; } } @Override public void setObjectWatched(int par1) { watchedObjects[par1].watched = true; objectChanged = true; } @Override public boolean hasChanges() { return objectChanged; } /** * writes every object in passed list to dataoutputstream, terminated by 0x7F */ public static void a(List par0List, DataOutputStream par1DataOutputStream) throws IOException { if (par0List != null) { for (final Object aPar0List : par0List) { WatchableObject watchableobject = (WatchableObject) aPar0List; a(par1DataOutputStream, watchableobject); } } par1DataOutputStream.writeByte(127); } @Override public List unwatchAndReturnAllWatched() { ArrayList arraylist = null; if (this.objectChanged) { for (WatchableObject watchableobject : watchedObjects) { if (watchableobject != null && watchableobject.isWatched()) { watchableobject.setWatched(false); if (arraylist == null) { arraylist = new ArrayList(); } arraylist.add(watchableobject); } } } this.objectChanged = false; return arraylist; } @Override public void writeWatchableObjects(DataOutput dataOutput) throws IOException { for (WatchableObject watchableobject : watchedObjects) { if (watchableobject != null) { a(dataOutput, watchableobject); } } dataOutput.writeByte(127); } @Override public List getAllWatched() { ArrayList arraylist = null; for (WatchableObject watchableobject : watchedObjects) { if (watchableobject == null) { continue; } if (arraylist == null) { arraylist = new ArrayList(); } arraylist.add(watchableobject); } return arraylist; } protected static void a(DataOutput dataOutput, WatchableObject par1WatchableObject) throws IOException { int i = (par1WatchableObject.getObjectType() << 5 | par1WatchableObject.getDataValueId() & 31) & 255; dataOutput.writeByte(i); switch (par1WatchableObject.getObjectType()) { case 0: dataOutput.writeByte((Byte) par1WatchableObject.getObject()); break; case 1: dataOutput.writeShort((Short) par1WatchableObject.getObject()); break; case 2: dataOutput.writeInt((Integer) par1WatchableObject.getObject()); break; case 3: dataOutput.writeFloat((Float) par1WatchableObject.getObject()); break; case 4: Packet.writeString((String) par1WatchableObject.getObject(), dataOutput); break; case 5: ItemStack itemstack = (ItemStack) par1WatchableObject.getObject(); Packet.writeItemStack(itemstack, dataOutput); break; case 6: ChunkCoordinates chunkcoordinates = (ChunkCoordinates) par1WatchableObject.getObject(); dataOutput.writeInt(chunkcoordinates.posX); dataOutput.writeInt(chunkcoordinates.posY); dataOutput.writeInt(chunkcoordinates.posZ); } } public static List a(DataInput dataInput) throws IOException { ArrayList arraylist = null; for (byte b0 = dataInput.readByte(); b0 != 127; b0 = dataInput.readByte()) { if (arraylist == null) { arraylist = new ArrayList(); } int i = (b0 & 224) >> 5; int j = b0 & 31; WatchableObject watchableobject = null; switch (i) { case 0: watchableobject = new WatchableObject(i, j, dataInput.readByte()); break; case 1: watchableobject = new WatchableObject(i, j, dataInput.readShort()); break; case 2: watchableobject = new WatchableObject(i, j, dataInput.readInt()); break; case 3: watchableobject = new WatchableObject(i, j, dataInput.readFloat()); break; case 4: watchableobject = new WatchableObject(i, j, Packet.readString(dataInput, 64)); break; case 5: watchableobject = new WatchableObject(i, j, Packet.readItemStack(dataInput)); break; case 6: int k = dataInput.readInt(); int l = dataInput.readInt(); int i1 = dataInput.readInt(); watchableobject = new WatchableObject(i, j, new ChunkCoordinates(k, l, i1)); } arraylist.add(watchableobject); } return arraylist; } @Override @SideOnly (Side.CLIENT) public void updateWatchedObjectsFromList(List par1List) { throw new UnsupportedOperationException(); } @Override public boolean getIsBlank() { return this.isBlank; } }
package org.mitre.synthea.export; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mitre.synthea.world.agents.Person.INCOME_LEVEL; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.time.Instant; import java.time.LocalDate; import java.time.Month; import java.time.ZoneId; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mitre.synthea.TestHelper; import org.mitre.synthea.engine.Generator; import org.mitre.synthea.export.BB2RIFExporter.CodeMapper; import org.mitre.synthea.export.BB2RIFExporter.HICN; import org.mitre.synthea.export.BB2RIFExporter.MBI; import org.mitre.synthea.export.BB2RIFExporter.StaticFieldConfig; import org.mitre.synthea.export.BB2RIFStructure.BENEFICIARY; import org.mitre.synthea.export.BB2RIFStructure.CARRIER; import org.mitre.synthea.export.BB2RIFStructure.DME; import org.mitre.synthea.export.BB2RIFStructure.INPATIENT; import org.mitre.synthea.helpers.Config; import org.mitre.synthea.helpers.DefaultRandomNumberGenerator; import org.mitre.synthea.helpers.RandomNumberGenerator; import org.mitre.synthea.helpers.SimpleCSV; import org.mitre.synthea.helpers.Utilities; import org.mitre.synthea.world.agents.Person; import org.mitre.synthea.world.concepts.Claim; public class BB2RIFExporterTest { /** * Temporary folder for any exported files, guaranteed to be deleted at the end of the test. */ @ClassRule public static TemporaryFolder tempFolder = new TemporaryFolder(); private static File exportDir; /** * Global setup for export tests. * @throws Exception if something goes wrong */ @BeforeClass public static void setUpExportDir() throws Exception { TestHelper.exportOff(); TestHelper.loadTestProperties(); Generator.DEFAULT_STATE = Config.get("test_state.default", "Massachusetts"); Config.set("exporter.bfd.export", "true"); Config.set("exporter.bfd.require_code_maps", "false"); Config.set("exporter.bfd.years_of_history", "10"); Config.set("generate.only_alive_patients", "true"); exportDir = tempFolder.newFolder(); Config.set("exporter.baseDirectory", exportDir.toString()); BB2RIFExporter.getInstance().prepareOutputFiles(); } @Test public void testBB2Export() throws Exception { int numberOfPeople = 10; Exporter.ExporterRuntimeOptions exportOpts = new Exporter.ExporterRuntimeOptions(); Generator.GeneratorOptions generatorOpts = new Generator.GeneratorOptions(); generatorOpts.population = numberOfPeople; generatorOpts.seed = 1010; RandomNumberGenerator rand = new DefaultRandomNumberGenerator(generatorOpts.seed); generatorOpts.minAge = 70; generatorOpts.maxAge = 80; generatorOpts.ageSpecified = true; generatorOpts.overflow = false; Generator generator = new Generator(generatorOpts, exportOpts); for (int i = 0; i < numberOfPeople; i++) { generator.generatePerson(i, rand.randLong()); } // Adding post completion exports to generate organizations and providers CSV files Exporter.runPostCompletionExports(generator, exportOpts); // if we get here we at least had no exceptions Path expectedExportPath = exportDir.toPath().resolve("bfd"); File expectedExportFolder = expectedExportPath.toFile(); assertTrue(expectedExportFolder.exists() && expectedExportFolder.isDirectory()); PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**/beneficiary_*.csv"); List<File> beneFiles = Files.list(expectedExportPath) .filter(Files::isRegularFile) .filter((path) -> matcher.matches(path)) .map(Path::toFile) .collect(Collectors.toList()); assertTrue("Expected at least one beneficiary file", beneFiles.size() > 0); for (File beneficiaryFile: beneFiles) { assertTrue(beneficiaryFile.exists() && beneficiaryFile.isFile()); String csvData = new String(Files.readAllBytes(beneficiaryFile.toPath())); // the BB2 exporter doesn't use the SimpleCSV class to write the data, // so we can use it here for a level of validation List<LinkedHashMap<String, String>> rows = SimpleCSV.parse(csvData, '|'); assertTrue( "Expected at least 1 row in the beneficiary file, found " + rows.size(), rows.size() >= 1); rows.forEach(row -> { assertTrue("Expected non-zero length surname", row.containsKey("BENE_SRNM_NAME") && row.get("BENE_SRNM_NAME").length() > 0); }); } // TODO: more meaningful testing of contents File beneficiaryHistoryFile = expectedExportFolder.toPath() .resolve("beneficiary_history.csv").toFile(); assertTrue(beneficiaryHistoryFile.exists() && beneficiaryHistoryFile.isFile()); // Check that other expected files are present but only if the corresponding code mapping files // are present, otherwise the files could be empty and in that case they aren't created. BB2RIFExporter bb2Exporter = BB2RIFExporter.getInstance(); if (bb2Exporter.conditionCodeMapper.hasMap() && bb2Exporter.hcpcsCodeMapper.hasMap()) { // TODO: more meaningful testing of contents (e.g. count of claims) File inpatientFile = expectedExportFolder.toPath().resolve("inpatient.csv").toFile(); assertTrue(inpatientFile.exists() && inpatientFile.isFile()); File outpatientFile = expectedExportFolder.toPath().resolve("outpatient.csv").toFile(); assertTrue(outpatientFile.exists() && outpatientFile.isFile()); File carrierFile = expectedExportFolder.toPath().resolve("carrier.csv").toFile(); assertTrue(carrierFile.exists() && carrierFile.isFile()); validateClaimTotals(carrierFile); } if (bb2Exporter.conditionCodeMapper.hasMap() && bb2Exporter.dmeCodeMapper.hasMap()) { // TODO: more meaningful testing of contents File dmeFile = expectedExportFolder.toPath().resolve("dme.csv").toFile(); assertTrue(dmeFile.exists() && dmeFile.isFile()); validateClaimTotals(dmeFile); } if (bb2Exporter.medicationCodeMapper.hasMap()) { File pdeFile = expectedExportFolder.toPath().resolve("pde.csv").toFile(); assertTrue(pdeFile.exists() && pdeFile.isFile()); validatePDETotals(pdeFile); } } private static class ClaimTotals { private final String claimID; private final BigDecimal claimPaymentAmount; private final BigDecimal claimAllowedAmount; private final BigDecimal claimBenePaymentAmount; private final BigDecimal claimBeneDDblAmount; private final BigDecimal claimProviderPaymentAmount; private BigDecimal linePaymentAmount; private BigDecimal linePaymentAmountTotal; private BigDecimal lineBenePaymentAmount; private BigDecimal lineBenePaymentAmountTotal; private BigDecimal lineBeneDDblAmountTotal; private BigDecimal lineProviderPaymentAmount; private BigDecimal lineProviderPaymentAmountTotal; ClaimTotals(LinkedHashMap<String, String> row) { claimID = row.get("CLM_ID"); claimPaymentAmount = new BigDecimal(row.get("CLM_PMT_AMT")).setScale(2); claimAllowedAmount = new BigDecimal(row.get("NCH_CARR_CLM_ALOWD_AMT")).setScale(2); claimBenePaymentAmount = new BigDecimal(row.get("NCH_CLM_BENE_PMT_AMT")).setScale(2); claimBeneDDblAmount = new BigDecimal(row.get("CARR_CLM_CASH_DDCTBL_APLD_AMT")).setScale(2); claimProviderPaymentAmount = new BigDecimal(row.get("NCH_CLM_PRVDR_PMT_AMT")).setScale(2); linePaymentAmountTotal = Claim.ZERO_CENTS; lineBenePaymentAmountTotal = Claim.ZERO_CENTS; lineProviderPaymentAmountTotal = Claim.ZERO_CENTS; lineBeneDDblAmountTotal = Claim.ZERO_CENTS; } void addLineItems(LinkedHashMap<String, String> row) { linePaymentAmount = new BigDecimal(row.get("LINE_NCH_PMT_AMT")).setScale(2); linePaymentAmountTotal = linePaymentAmountTotal.add(linePaymentAmount); lineBenePaymentAmount = new BigDecimal(row.get("LINE_BENE_PMT_AMT")).setScale(2); lineBenePaymentAmountTotal = lineBenePaymentAmountTotal.add(lineBenePaymentAmount); lineProviderPaymentAmount = new BigDecimal(row.get("LINE_PRVDR_PMT_AMT")).setScale(2); lineProviderPaymentAmountTotal = lineProviderPaymentAmountTotal .add(lineProviderPaymentAmount); lineBeneDDblAmountTotal = lineBeneDDblAmountTotal .add(new BigDecimal(row.get("LINE_BENE_PTB_DDCTBL_AMT")).setScale(2)); } } private void validateClaimTotals(File file) throws IOException { String csvData = new String(Files.readAllBytes(file.toPath())); // the BB2 exporter doesn't use the SimpleCSV class to write the data, // so we can use it here for a level of validation List<LinkedHashMap<String, String>> rows = SimpleCSV.parse(csvData, '|'); assertTrue( "Expected at least 1 row in the claim file, found " + rows.size(), rows.size() >= 1); Map<String, ClaimTotals> claims = new HashMap<>(); rows.forEach(row -> { assertTrue("Expected non-zero length claim ID", row.containsKey("CLM_ID") && row.get("CLM_ID").length() > 0); String claimID = row.get("CLM_ID"); if (!claims.containsKey(claimID)) { ClaimTotals claim = new ClaimTotals(row); claims.put(claimID, claim); } ClaimTotals claim = claims.get(claimID); claim.addLineItems(row); assertTrue(claim.linePaymentAmount.equals( claim.lineBenePaymentAmount.add(claim.lineProviderPaymentAmount))); }); claims.values().forEach(claim -> { assertTrue(claim.claimPaymentAmount.equals( claim.claimBenePaymentAmount.add(claim.claimProviderPaymentAmount))); assertTrue(claim.linePaymentAmountTotal.equals(claim.claimAllowedAmount)); assertTrue(claim.lineBenePaymentAmountTotal.equals(claim.claimBenePaymentAmount)); assertTrue(claim.lineProviderPaymentAmountTotal.equals(claim.claimProviderPaymentAmount)); assertTrue(claim.lineBeneDDblAmountTotal.equals(claim.claimBeneDDblAmount)); }); } private static class PDETotals { private final String pdeID; private BigDecimal lineTotalRxAmount; private BigDecimal linePatientAmount; private BigDecimal lineOtherPocketAmount; private BigDecimal lineSubsidizedAmount; private BigDecimal lineOtherInsuranceAmount; private BigDecimal linePartDCoveredAmount; private BigDecimal linePartDNotCoveredAmount; PDETotals(LinkedHashMap<String, String> row) { pdeID = row.get("PDE_ID"); lineTotalRxAmount = new BigDecimal(row.get("TOT_RX_CST_AMT")).setScale(2); linePatientAmount = new BigDecimal(row.get("PTNT_PAY_AMT")).setScale(2); lineOtherPocketAmount = new BigDecimal(row.get("OTHR_TROOP_AMT")).setScale(2); lineSubsidizedAmount = new BigDecimal(row.get("LICS_AMT")).setScale(2); lineOtherInsuranceAmount = new BigDecimal(row.get("PLRO_AMT")).setScale(2); linePartDCoveredAmount = new BigDecimal(row.get("CVRD_D_PLAN_PD_AMT")).setScale(2); linePartDNotCoveredAmount = new BigDecimal(row.get("NCVRD_PLAN_PD_AMT")).setScale(2); } boolean isValid() { BigDecimal sum = Claim.ZERO_CENTS; sum = sum.add(linePatientAmount).add(lineOtherPocketAmount).add(lineSubsidizedAmount); sum = sum.add(lineOtherInsuranceAmount).add(linePartDCoveredAmount); sum = sum.add(linePartDNotCoveredAmount); return (sum.compareTo(lineTotalRxAmount) == 0); } } private void validatePDETotals(File file) throws IOException { String csvData = new String(Files.readAllBytes(file.toPath())); // the BB2 exporter doesn't use the SimpleCSV class to write the data, // so we can use it here for a level of validation List<LinkedHashMap<String, String>> rows = SimpleCSV.parse(csvData, '|'); assertTrue( "Expected at least 1 row in the claim file, found " + rows.size(), rows.size() >= 1); Set<String> pdeIds = new HashSet<String>(); rows.forEach(row -> { assertTrue("Expected non-zero length PDE ID", row.containsKey("PDE_ID") && row.get("PDE_ID").length() > 0); String pdeId = row.get("PDE_ID"); assertFalse("PDE IDs should be unique.", pdeIds.contains(pdeId)); pdeIds.add(pdeId); PDETotals event = new PDETotals(row); assertTrue("PDE dollar amounts do not add up correctly.", event.isValid()); }); } @Test public void testCodeMapper() { // these tests depend on the presence of the code map file and will not be run in CI try { Utilities.readResource("condition_code_map.json"); } catch (IOException | IllegalArgumentException e) { return; } RandomNumberGenerator random = new DefaultRandomNumberGenerator(0); CodeMapper mapper = new CodeMapper("condition_code_map.json"); assertTrue(mapper.canMap("10509002")); assertEquals("J20.9", mapper.map("10509002", random)); assertEquals("J209", mapper.map("10509002", random, true)); assertFalse(mapper.canMap("not a code")); } @Test public void testMBI() { MBI mbi = new MBI(MBI.MIN_MBI); assertEquals("1S00A00AA00", mbi.toString()); mbi = new MBI(MBI.MAX_MBI); assertEquals("9SY9YY9YY99", mbi.toString()); mbi = MBI.parse("1S00A00AA00"); assertEquals("1S00A00AA00", mbi.toString()); mbi = MBI.parse("1S00-A00-AA00"); assertEquals("1S00A00AA00", mbi.toString()); mbi = MBI.parse("9SY9YY9YY99"); assertEquals("9SY9YY9YY99", mbi.toString()); mbi = MBI.parse("9SY9-YY9-YY99"); assertEquals("9SY9YY9YY99", mbi.toString()); } @Test public void testHICN() { HICN hicn = new HICN(HICN.MIN_HICN); assertEquals("T00000000A", hicn.toString()); hicn = new HICN(HICN.MAX_HICN); assertEquals("T99999999A", hicn.toString()); hicn = HICN.parse("T01001001A"); assertEquals("T01001001A", hicn.toString()); hicn = HICN.parse("T99999999A"); assertEquals("T99999999A", hicn.toString()); } @Test public void testStaticFieldConfig() throws IOException, NoSuchMethodException { RandomNumberGenerator rand = new Person(System.currentTimeMillis()); assertEquals("foo", StaticFieldConfig.processCell("foo", rand)); String randomVal = StaticFieldConfig.processCell("1, 2, 3", rand); assertTrue(randomVal.equalsIgnoreCase("1") || randomVal.equalsIgnoreCase("2") || randomVal.equalsIgnoreCase("3")); StaticFieldConfig config = new StaticFieldConfig(); assertEquals("INSERT", config.getValue("DML_IND", INPATIENT.class)); assertEquals("82 (DMEPOS)", config.getValue("NCH_CLM_TYPE_CD", DME.class)); assertEquals("71 (local carrier, non-DME)", config.getValue("NCH_CLM_TYPE_CD", CARRIER.class)); HashMap<BENEFICIARY, String> values = new HashMap<>(); config.setValues(values, BENEFICIARY.class, rand); assertEquals("INSERT", values.get(BENEFICIARY.DML_IND)); String sexIdent = values.get(BENEFICIARY.BENE_SEX_IDENT_CD); assertTrue(sexIdent.equals("1") || sexIdent.equals("2")); } @Test public void testPartDContractPeriod() { Person rand = new Person(System.currentTimeMillis()); rand.attributes.put(INCOME_LEVEL, "1.5"); LocalDate start = LocalDate.of(2020, Month.MARCH, 15); LocalDate end = LocalDate.of(2021, Month.JUNE, 15); BB2RIFExporter.PartDContractHistory history = new BB2RIFExporter.PartDContractHistory( rand, java.time.Instant.now().toEpochMilli(), 10); BB2RIFExporter.PartDContractHistory.ContractPeriod period = history.new ContractPeriod(start, end, null, (BB2RIFExporter.PlanBenefitPackageID)null); assertNull(period.getContractID()); assertFalse(period.coversYear(2019)); assertEquals(0, period.getCoveredMonths(2019).size()); assertTrue(period.coversYear(2020)); List<Integer> twentyTwentyMonths = period.getCoveredMonths(2020); assertEquals(10, twentyTwentyMonths.size()); assertFalse(twentyTwentyMonths.contains(1)); assertFalse(twentyTwentyMonths.contains(2)); assertTrue(twentyTwentyMonths.contains(3)); assertTrue(twentyTwentyMonths.contains(4)); assertTrue(twentyTwentyMonths.contains(5)); assertTrue(twentyTwentyMonths.contains(6)); assertTrue(twentyTwentyMonths.contains(7)); assertTrue(twentyTwentyMonths.contains(8)); assertTrue(twentyTwentyMonths.contains(9)); assertTrue(twentyTwentyMonths.contains(10)); assertTrue(twentyTwentyMonths.contains(11)); assertTrue(twentyTwentyMonths.contains(12)); assertTrue(period.coversYear(2021)); List<Integer> twentyTwentyOneMonths = period.getCoveredMonths(2021); assertEquals(6, twentyTwentyOneMonths.size()); assertTrue(twentyTwentyOneMonths.contains(1)); assertTrue(twentyTwentyOneMonths.contains(2)); assertTrue(twentyTwentyOneMonths.contains(3)); assertTrue(twentyTwentyOneMonths.contains(4)); assertTrue(twentyTwentyOneMonths.contains(5)); assertTrue(twentyTwentyOneMonths.contains(6)); assertFalse(twentyTwentyOneMonths.contains(7)); assertFalse(twentyTwentyOneMonths.contains(8)); assertFalse(twentyTwentyOneMonths.contains(9)); assertFalse(twentyTwentyOneMonths.contains(10)); assertFalse(twentyTwentyOneMonths.contains(11)); assertFalse(twentyTwentyOneMonths.contains(12)); assertFalse(period.coversYear(2022)); assertEquals(0, period.getCoveredMonths(2022).size()); LocalDate pointInTime = start; Instant instant = pointInTime.atStartOfDay(ZoneId.systemDefault()).toInstant(); long timeInMillis = instant.toEpochMilli(); assertTrue(period.covers(timeInMillis)); pointInTime = start.minusDays(1); // previous day (start is middle of month) instant = pointInTime.atStartOfDay(ZoneId.systemDefault()).toInstant(); timeInMillis = instant.toEpochMilli(); assertTrue(period.covers(timeInMillis)); pointInTime = start.minusDays(15); // previous month instant = pointInTime.atStartOfDay(ZoneId.systemDefault()).toInstant(); timeInMillis = instant.toEpochMilli(); assertFalse(period.covers(timeInMillis)); pointInTime = end; instant = pointInTime.atStartOfDay(ZoneId.systemDefault()).toInstant(); timeInMillis = instant.toEpochMilli(); assertTrue(period.covers(timeInMillis)); pointInTime = end.plusDays(1); // next day (end is middle of month) instant = pointInTime.atStartOfDay(ZoneId.systemDefault()).toInstant(); timeInMillis = instant.toEpochMilli(); assertTrue(period.covers(timeInMillis)); pointInTime = end.plusDays(16); // next month (end is middle of month) instant = pointInTime.atStartOfDay(ZoneId.systemDefault()).toInstant(); timeInMillis = instant.toEpochMilli(); assertFalse(period.covers(timeInMillis)); } }
package org.wyona.yanel.core.util; import org.apache.log4j.Category; import org.wyona.commons.io.Path; import org.wyona.yarep.core.Node; import org.wyona.yarep.core.NodeType; import org.wyona.yarep.core.Repository; import org.wyona.yarep.core.RepositoryException; /** * @deprecated Use org.wyona.yarep.util.YarepUtil */ public class YarepUtil { private static Category log = Category.getInstance(YarepUtil.class); /** * Creates the node named by this abstract pathname, including any necessary but nonexistent parent nodes (similar to java.io.File.mkdirs()). */ public static Node addNodes(Repository repo, String path, int nodeType) throws RepositoryException { if (repo.existsNode(path)) { return repo.getNode(path); } else { Path parentPath = new Path(path).getParent(); if (parentPath != null) { Node parentNode = null; if (repo.existsNode(parentPath.toString())) { parentNode = repo.getNode(parentPath.toString()); } else { parentNode = addNodes(repo, parentPath.toString(), org.wyona.yarep.core.NodeType.COLLECTION); } return parentNode.addNode(new Path(path).getName().toString(), nodeType); } else { throw new RepositoryException("Root node does not have a parent!"); } } } }
package org.myrobotlab.service; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Test; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.interfaces.ServiceInterface; import org.myrobotlab.framework.repo.ServiceData; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.service.meta.abstracts.MetaData; import org.myrobotlab.test.AbstractTest; import org.slf4j.Logger; public class ServiceInterfaceTest extends AbstractTest { public final static Logger log = LoggerFactory.getLogger(ServiceInterfaceTest.class); private boolean testWebPages = false; // FIXME - add to report at end of "all" testing ... private boolean serviceHasWebPage(String service) { String url = "http://myrobotlab.org/service/" + service; InputStream in = null; try { in = new URL(url).openStream(); } catch (MalformedURLException e) { // TODO Auto-generated catch block // e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); return false; } try { // read the page (we don't care about contents. (yet)) IOUtils.toString(in); } catch (IOException e) { // e.printStackTrace(); return false; } finally { IOUtils.closeQuietly(in); } return true; } private boolean serviceInterfaceTest(String service) throws IOException { // see if we can start/stop and release the service. ServiceInterface foo = Runtime.create(service.toLowerCase(), service); if (foo == null) { log.warn("Runtime Create returned a null service for {}", service); return false; } System.out.println("Service Test:" + service); System.out.flush(); // Assert.assertNotNull(foo.getCategories()); Assert.assertNotNull(foo.getDescription()); Assert.assertNotNull(foo.getName()); Assert.assertNotNull(foo.getSimpleName()); Assert.assertNotNull(foo.getType()); // TODO: add a bunch more tests here! foo.startService(); foo.stopService(); foo.startService(); foo.save(); foo.load(); foo.stopService(); foo.releaseService(); return true; } @Test public final void testAllServices() throws ClassNotFoundException, IOException { if (printMethods) System.out.println(String.format("Running %s.%s", getSimpleName(), getName())); ArrayList<String> servicesWithoutWebPages = new ArrayList<String>(); ArrayList<String> servicesWithoutScripts = new ArrayList<String>(); ArrayList<String> servicesThatDontStartProperly = new ArrayList<String>(); ArrayList<String> servicesNotInServiceDataJson = new ArrayList<String>(); HashSet<String> blacklist = new HashSet<String>(); blacklist.add("OpenNi"); blacklist.add("IntegratedMovement"); blacklist.add("VirtualDevice"); blacklist.add("GoogleAssistant"); blacklist.add("LeapMotion"); blacklist.add("Python"); // python's interpreter cannot be restarted cleanly blacklist.add("Runtime"); blacklist.add("WorkE"); blacklist.add("JMonkeyEngine"); blacklist.add("_TemplateService"); blacklist.add("Lloyd"); blacklist.add("Solr"); blacklist.add("Sphinx"); blacklist.add("SwingGui"); // This one just takes so darn long. blacklist.add("Deeplearning4j"); blacklist.add("OculusDiy"); // start up python so we have it available to do some testing with. Python python = (Python) Runtime.start("python", "Python"); Service.sleep(1000); ServiceData sd = ServiceData.getLocalInstance(); List<MetaData> sts = sd.getServiceTypes(); // there is also // sd.getAvailableServiceTypes(); int numServices = sts.size(); int numServicePages = 0; int numScripts = 0; int numScriptsWorky = 0; int numStartable = 0; log.info(" // FIXME - subscribe to all errors of all new services !!! - a prefix script // FIXME - must have different thread (prefix script) which runs a timer - // script REQUIRED to complete in 4 minutes ... or BOOM it fails // sts.clear(); // sts.add(sd.getServiceType("org.myrobotlab.service.InMoov")); for (MetaData serviceType : sts) { // test single service // serviceType = // sd.getServiceType("org.myrobotlab.service.VirtualDevice"); String service = serviceType.getSimpleName(); // System.out.println("SYSTEM TESTING " + service); // System.out.flush(); // service = "org.myrobotlab.service.EddieControlBoard"; if (blacklist.contains( service)/* || !serviceType.getSimpleName().equals("Emoji") */) { log.info("White listed testing of service {}", service); continue; } log.info("Testing Service: {}", service); MetaData st = ServiceData.getMetaData("org.myrobotlab.service." + service); if (st == null) { System.out.println("NO SERVICE TYPE FOUND!"); // perhaps this should // throw servicesNotInServiceDataJson.add(service); } if (testWebPages) { if (serviceHasWebPage(service)) { log.info("Service {} has a web page..", service); numServicePages++; } else { log.warn("Service {} does not have a web page..", service); servicesWithoutWebPages.add(service); } } if (serviceInterfaceTest(service)) { numStartable++; } else { servicesThatDontStartProperly.add(service); } String serviceScript = Service.getServiceScript(service); if (serviceScript != null) { log.info("Service Has a Script: {}", service); numScripts++; } else { log.warn("Missing Script for Service {}", service); servicesWithoutScripts.add(service); } if (testServiceScript(python, service)) { // log.info("Default script for {} executes ok!", service); numScriptsWorky++; } else { // log.warn("Default script for {} blows up!", service); // servicesWithoutWorkyScript(service); } // log.info("SERVICE TESTED WAS :" + service); log.info(" // CLEAN-UP !!! releaseServices(); // System.out.println("Next?"); // try { // System.in.read(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); } log.info(" log.info("Service Report"); log.info("Number of Services: {}", numServices); log.info("Number of Startable Services: {}", numStartable); log.info("Number of Services Pages {}", numServicePages); log.info("Number of Scripts: {}", numScripts); log.info("Number of Scripts Worky: {}", numScriptsWorky); log.info(" for (String s : servicesThatDontStartProperly) { log.warn("FAILED ON START:" + s); } for (String s : servicesWithoutWebPages) { log.warn("NO WEB PAGE :" + s); } for (String s : servicesWithoutScripts) { log.warn("NO SCRIPT :" + s); } for (String s : servicesNotInServiceDataJson) { log.info("NOT IN SERVICE DATA :" + s); } log.info("Done..."); } @Test public final void testInstallAllServices() throws ClassNotFoundException, ParseException, IOException { // TODO: this probably is going to take longer but it's worth while! ServiceData sd = ServiceData.getLocalInstance();// CodecUtils.fromJson(FileUtils.readFileToString(new // File("../repo/serviceData.json")), // ServiceData.class); for (MetaData st : sd.getServiceTypes()) { if (!st.isAvailable()) { log.info("Installing Service:" + st.getType()); Runtime.install(st.getType(), true); } else { log.info("already installed."); } } } private boolean testServiceScript(Python python, String serviceType) { String testScriptFile = Service.getServiceScript(serviceType); if (testScriptFile == null) { log.warn("No default script for Service {}", Service.getResource(serviceType, serviceType + ".py")); return false; } else { log.info("Default Script Exists for {}", serviceType); } return false; } }
package org.owasp.esapi.util; import static org.junit.Assert.*; import junit.framework.JUnit4TestAdapter; import org.junit.Test; import org.owasp.esapi.codecs.Hex; /** JUnit test for {@code ByteConversionUtil}. */ public class ByteConversionUtilTest { private static final String EOL = System.getProperty("line.separator", "\n"); private static final boolean VERBOSE = false; /** * Test conversion byte[] <--> short. */ @Test public void testShortConversion() { debug("========== testShortConversion() =========="); short[] testArray = { -1, 0, 1, Short.MIN_VALUE, Short.MAX_VALUE }; for(int i = 0; i < testArray.length; i++ ) { byte[] bytes = ByteConversionUtil.fromShort(testArray[i]); short n = ByteConversionUtil.toShort(bytes); debug("i: " + i + ", value: " + testArray[i]); debug("byte array: " + Hex.toHex(bytes, true)); debug("testArray[" + i + "]: " + Integer.toHexString(testArray[i])); debug("n: " + Integer.toHexString(n) + EOL + " assertEquals(testArray[i], n); } } /** * Test conversion byte[] <--> int. */ @Test public void testIntConversion() { debug("========== testIntConversion() =========="); int[] testArray = { -1, 0, 1, Integer.MIN_VALUE, Integer.MAX_VALUE }; for(int i = 0; i < testArray.length; i++ ) { byte[] bytes = ByteConversionUtil.fromInt(testArray[i]); int n = ByteConversionUtil.toInt(bytes); debug("i: " + i + ", value: " + testArray[i]); debug("byte array: " + Hex.toHex(bytes, true)); debug("testArray[" + i + "]: " + Integer.toHexString(testArray[i])); debug("n: " + Integer.toHexString(n) + EOL + " assertEquals(testArray[i], n); } } /** * Test conversion byte[] <--> long. */ @Test public void testLongConversion() { debug("========== testLongConversion() =========="); long[] testArray = { -1, 0, 1, Long.MIN_VALUE, Long.MAX_VALUE }; for(int i = 0; i < testArray.length; i++ ) { byte[] bytes = ByteConversionUtil.fromLong(testArray[i]); long n = ByteConversionUtil.toLong(bytes); debug("i: " + i + ", value: " + testArray[i]); debug("byte array: " + Hex.toHex(bytes, true)); debug("testArray[" + i + "]: " + Long.toHexString(testArray[i])); debug("n: " + Long.toHexString(n) + EOL + " assertEquals(testArray[i], n); } } /** * Run all the test cases in this suite. * This is to allow running from {@code org.owasp.esapi.AllTests} which * uses a JUnit 3 test runner. */ public static junit.framework.Test suite() { return new JUnit4TestAdapter(ByteConversionUtilTest.class); } private void debug(String msg) { if ( VERBOSE ) { System.err.println(msg); } } }
package org.threadly.concurrent; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.threadly.test.TestUtil; public class TaskDistributorTest { private static final int PARALLEL_LEVEL = 100; private static final int RUNNABLE_COUNT_PER_LEVEL = 5000; private volatile boolean ready; private PriorityScheduledExecutor scheduler; private Object agentLock; private TaskDistributor distributor; @Before public void setup() { scheduler = new PriorityScheduledExecutor(PARALLEL_LEVEL + 1, PARALLEL_LEVEL * 2, 1000 * 10, TaskPriority.High, PriorityScheduledExecutor.DEFAULT_LOW_PRIORITY_MAX_WAIT); agentLock = new Object(); distributor = new TaskDistributor(scheduler, agentLock); ready = false; } @After public void tearDown() { scheduler.shutdown(); scheduler = null; agentLock = null; distributor = null; ready = false; } @Test public void testGetExecutor() { assertTrue(scheduler == distributor.getExecutor()); } @Test public void testExecutes() { final List<TestRunnable> runs = new ArrayList<TestRunnable>(PARALLEL_LEVEL * RUNNABLE_COUNT_PER_LEVEL); scheduler.execute(new Runnable() { @Override public void run() { // hold agent lock to prevent execution till ready synchronized (agentLock) { for (int i = 0; i < PARALLEL_LEVEL; i++) { Object key = new Object(); ThreadContainer tc = new ThreadContainer(); for (int j = 0; j < RUNNABLE_COUNT_PER_LEVEL; j++) { TestRunnable tr = new TestRunnable(tc); runs.add(tr); distributor.addTask(key, tr); } } ready = true; } } }); while (! ready) { // spin } // sleep for a little time to give time for the runnables to execute TestUtil.sleep(100); Iterator<TestRunnable> it = runs.iterator(); while (it.hasNext()) { TestRunnable tr = it.next(); assertEquals(tr.ranCount, 1); assertTrue(tr.threadTracker.threadConsistent); } } private class TestRunnable implements Runnable { private final ThreadContainer threadTracker; private int ranCount = 0; private TestRunnable(ThreadContainer threadTracker) { this.threadTracker = threadTracker; } @Override public void run() { ranCount++; threadTracker.running(); } } private class ThreadContainer { private Thread runningThread = null; private boolean threadConsistent = true; public synchronized void running() { if (runningThread == null) { runningThread = Thread.currentThread(); } else { threadConsistent = threadConsistent && runningThread.equals(Thread.currentThread()); } } } }
package org.jdesktop.swingx.renderer; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.swing.AbstractAction; import javax.swing.AbstractListModel; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.DefaultListModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ListCellRenderer; import javax.swing.ListModel; import javax.swing.UIDefaults; import javax.swing.border.Border; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import org.jdesktop.swingx.EditorPaneLinkVisitor; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXEditorPaneTest; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXHyperlink; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.LinkModel; import org.jdesktop.swingx.LinkRenderer; import org.jdesktop.swingx.RolloverRenderer; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.action.LinkModelAction; import org.jdesktop.swingx.decorator.AlternateRowHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.AlternateRowHighlighter.UIAlternateRowHighlighter; import org.jdesktop.swingx.table.ColumnControlButton; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.test.AncientSwingTeam; /** * Visual check of extended Swingx renderers. * * @author Jeanette Winzenburg */ public class RendererVisualCheck extends InteractiveTestCase { public static void main(String[] args) { setSystemLF(true); RendererVisualCheck test = new RendererVisualCheck(); try { // test.runInteractiveTests(); test.runInteractiveTests(".*TextArea.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Quick example of using a JTextArea as rendering component. * */ public void interactiveTextAreaRenderer() { DefaultTableModel model = new DefaultTableModel(0, 1); model.addRow(new String[] {"some really, maybe really really long text - " + "wrappit .... where needed "}); model.addRow(new String[] {"another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"}); JXTable table = new JXTable(model); table.setVisibleRowCount(4); table.setColumnControlVisible(true); table.getColumnExt(0).setCellRenderer(new DefaultTableRenderer(new TextAreaProvider())); table.addHighlighter(new AlternateRowHighlighter()); JTextArea textArea = (JTextArea) table.prepareRenderer(table.getCellRenderer(0, 0), 0, 0); table.packColumn(0, -1); table.setRowHeight(textArea.getPreferredSize().height); showWithScrollingInFrame(table, "textArea as rendering comp"); } public static class TextAreaProvider extends ComponentProvider<JTextArea> { @Override protected void configureState(CellContext context) { // TODO Auto-generated method stub } @Override protected JTextArea createRendererComponent() { JTextArea area = new JTextArea(3, 20); area.setLineWrap(true); area.setWrapStyleWord(true); area.setOpaque(true); return area; } @Override protected void format(CellContext context) { rendererComponent.setText(getStringValue(context)); rendererComponent.revalidate(); } } /** * Check disabled appearance. * */ public void interactiveListDisabledIconRenderer() { final TableModel model = createTableModelWithDefaultTypes(); ListModel listModel = new AbstractListModel() { public Object getElementAt(int index) { if (index == 0) { return "dummy"; } return model.getValueAt(index - 1, 4); } public int getSize() { return model.getRowCount() + 1; } }; final JList standard = new JList(listModel); final JList enhanced = new JList(listModel); enhanced.setCellRenderer(new DefaultListRenderer()); AbstractAction action = new AbstractAction("toggle disabled") { public void actionPerformed(ActionEvent e) { standard.setEnabled(!standard.isEnabled()); enhanced.setEnabled(!enhanced.isEnabled()); } }; JXFrame frame = wrapWithScrollingInFrame(standard, enhanced, "Disabled - compare renderers: default <--> enhanced"); addAction(frame, action); frame.setVisible(true); } /** * Check disabled appearance for all renderers. * */ public void interactiveTableDefaultRenderers() { TableModel model = createTableModelWithDefaultTypes(); final JTable standard = new JTable(model); final JTable enhanced = new JTable(model) { @Override protected void createDefaultRenderers() { defaultRenderersByColumnClass = new UIDefaults(); setDefaultRenderer(Object.class, new DefaultTableRenderer()); LabelProvider controller = new LabelProvider(FormatStringValue.NUMBER_TO_STRING); controller.setHorizontalAlignment(JLabel.RIGHT); setDefaultRenderer(Number.class, new DefaultTableRenderer(controller)); setDefaultRenderer(Date.class, new DefaultTableRenderer( FormatStringValue.DATE_TO_STRING)); TableCellRenderer renderer = new DefaultTableRenderer(new LabelProvider(JLabel.CENTER)); setDefaultRenderer(Icon.class, renderer); setDefaultRenderer(ImageIcon.class, renderer); setDefaultRenderer(Boolean.class, new DefaultTableRenderer(new ButtonProvider())); } }; AbstractAction action = new AbstractAction("toggle disabled") { public void actionPerformed(ActionEvent e) { standard.setEnabled(!standard.isEnabled()); enhanced.setEnabled(!enhanced.isEnabled()); } }; JXFrame frame = wrapWithScrollingInFrame(standard, enhanced, "Disabled Compare renderers: default <--> enhanced"); addAction(frame, action); frame.setVisible(true); } /** * @return */ private TableModel createTableModelWithDefaultTypes() { String[] names = {"Object", "Number", "Double", "Date", "ImageIcon", "Boolean"}; final Class[] types = {Object.class, Number.class, Double.class, Date.class, ImageIcon.class, Boolean.class}; DefaultTableModel model = new DefaultTableModel(names, 0) { @Override public Class<?> getColumnClass(int columnIndex) { return types[columnIndex]; } }; Date today = new Date(); Icon icon = new ImageIcon(JXTable.class.getResource("resources/images/kleopatra.jpg")); for (int i = 0; i < 10; i++) { Object[] values = new Object[] {"row " + i, i, Math.random() * 100, new Date(today.getTime() + i * 1000000), icon, i % 2 == 0}; model.addRow(values); } return model; } /** * Compare core table using core default renderer vs. swingx default renderer.<p> * Unselected background of lead is different for editable/not-editable cells. */ public void interactiveTableCompareFocusedCellBackground() { TableModel model = new AncientSwingTeam() { public boolean isCellEditable(int row, int column) { return column != 0; } }; JTable xtable = new JTable(model); xtable.setBackground(Highlighter.notePadBackground.getBackground()); // ledger JTable table = new JTable(model); table.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger TableCellRenderer renderer = new DefaultTableRenderer(); table.setDefaultRenderer(Object.class, renderer); JXFrame frame = wrapWithScrollingInFrame(xtable, table, "JTable: Unselected focused background: core/ext renderer"); getStatusBar(frame).add(new JLabel("background for unselected lead: first column is not-editable")); frame.setVisible(true); } /** * Compare xtable using core default renderer vs. swingx default renderer.<p> * Obsolete - swingx renderers registered by default. * * Unselected background of lead is different for editable/not-editable cells. * With core renderer: can't because Highlighter hack jumps in. * */ public void interactiveXTableCompareFocusedCellBackground() { // TableModel model = new AncientSwingTeam() { // public boolean isCellEditable(int row, int column) { // return column != 0; // JXTable xtable = new JXTable(model); // xtable.setBackground(Highlighter.notePadBackground.getBackground()); // ledger // JXTable table = new JXTable(model) { // @Override // protected void createDefaultRenderers() { // defaultRenderersByColumnClass = new UIDefaults(); // setDefaultRenderer(Object.class, new DefaultTableRenderer()); // LabelProvider controller = new LabelProvider(FormatStringValue.NUMBER_TO_STRING); // controller.setHorizontalAlignment(JLabel.RIGHT); // setDefaultRenderer(Number.class, new DefaultTableRenderer(controller)); // setDefaultRenderer(Date.class, new DefaultTableRenderer( // FormatStringValue.DATE_TO_STRING)); // TableCellRenderer renderer = new DefaultTableRenderer(new LabelProvider(JLabel.CENTER)); // setDefaultRenderer(Icon.class, renderer); // setDefaultRenderer(ImageIcon.class, renderer); // setDefaultRenderer(Boolean.class, new DefaultTableRenderer(new ButtonProvider())); // table.setBackground(xtable.getBackground()); // ledger // JXFrame frame = wrapWithScrollingInFrame(xtable, table, "JXTable: Unselected focused background: core/ext renderer"); // getStatusBar(frame).add(new JLabel("different background for unselected lead: first column is not-editable")); // frame.pack(); // frame.setVisible(true); } /** * Issue #282-swingx: compare disabled appearance of * collection views. * Check if extended renderers behave correctly. Still open: header * renderer disabled. */ public void interactiveDisabledCollectionViews() { final JXTable table = new JXTable(new AncientSwingTeam()); // table.setDefaultRenderer(Object.class, new DefaultTableRenderer()); table.setEnabled(false); final JXList list = new JXList(new String[] {"one", "two", "and something longer"}); list.setEnabled(false); // list.setCellRenderer(new DefaultListRenderer()); final JXTree tree = new JXTree(new FileSystemModel()); tree.setEnabled(false); JComponent box = Box.createHorizontalBox(); box.add(new JScrollPane(table)); box.add(new JScrollPane(list)); box.add(new JScrollPane(tree)); JXFrame frame = wrapInFrame(box, "disabled collection views"); AbstractAction action = new AbstractAction("toggle disabled") { public void actionPerformed(ActionEvent e) { table.setEnabled(!table.isEnabled()); list.setEnabled(!list.isEnabled()); tree.setEnabled(!tree.isEnabled()); } }; addAction(frame, action); frame.setVisible(true); } /** * * Example for custom StringValue: bound to bean property. * * A column of xtable and the xlist share the same component controller.<p> * * */ public void interactiveTableAndListCustomRenderer() { final ListModel players = createPlayerModel(); TableModel tableModel = new AbstractTableModel() { String[] columnNames = {"Name", "Score", "Player.toString"}; public int getColumnCount() { return 3; } public int getRowCount() { return players.getSize(); } public Object getValueAt(int rowIndex, int columnIndex) { return players.getElementAt(rowIndex); } @Override public Class<?> getColumnClass(int columnIndex) { return Player.class; } @Override public String getColumnName(int column) { return columnNames[column]; } }; JXTable xtable = new JXTable(tableModel); PropertyStringValue converter = new PropertyStringValue("name"); LabelProvider nameController = new LabelProvider(converter); xtable.getColumn(0).setCellRenderer(new DefaultTableRenderer(nameController)); PropertyStringValue scoreConverter = new PropertyStringValue("score"); xtable.getColumn(1).setCellRenderer(new DefaultTableRenderer(scoreConverter)); xtable.packAll(); JXList list = new JXList(players); // we share the component controller between table and list list.setCellRenderer(new DefaultListRenderer(nameController)); showWithScrollingInFrame(xtable, list, "JXTable/JXList: Custom property renderer"); } /** * Simple example to bind a toStringConverter to a single property of the value. */ public static class PropertyStringValue implements StringValue { private String property; public PropertyStringValue(String property) { this.property = property; } /** * {@inheritDoc} <p> * Implemented to return the toString of the named property value. */ public String getString(Object value) { try { PropertyDescriptor desc = getPropertyDescriptor(value.getClass(), property); return TO_STRING.getString(getValue(value, desc)); } catch (Exception e) { // nothing much we can do here... } return ""; } } /** * Use custom converter for Dimension/Point (from demo) * */ public void interactiveTableCustomRenderer() { JXTable table = new JXTable(); StringValue converter = new StringValue() { public String getString(Object value) { if (value instanceof Point) { Point p = (Point) value; value = createString(p.x, p.y); } else if (value instanceof Dimension) { Dimension dim = (Dimension) value; value = createString(dim.width, dim.height); } return TO_STRING.getString(value); } private Object createString(int width, int height) { return "(" + width + ", " + height + ")"; } }; TableCellRenderer renderer = new DefaultTableRenderer(converter); table.setDefaultRenderer(Point.class, renderer); table.setDefaultRenderer(Dimension.class, renderer); JXFrame frame = showWithScrollingInFrame(table, "custom renderer (from demo) for Point/Dimension"); ComponentTreeTableModel model = new ComponentTreeTableModel(frame); JXTreeTable treeTable = new JXTreeTable(model); treeTable.expandAll(); table.setModel(treeTable.getModel()); } /** * extended link renderer in table. * */ public void interactiveTestTableLinkRenderer() { EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); JXTable table = new JXTable(createModelWithLinks()); LinkModelAction action = new LinkModelAction<LinkModel>(visitor); ComponentProvider<JXHyperlink> controller = new HyperlinkProvider(action, LinkModel.class); table.setDefaultRenderer(LinkModel.class, new DefaultTableRenderer(controller)); LinkModelAction action2 = new LinkModelAction<LinkModel>(visitor); // TODO: obsolete - need to think about what to do with editable link cells? table.setDefaultEditor(LinkModel.class, new LinkRenderer(action2, LinkModel.class)); JFrame frame = wrapWithScrollingInFrame(table, visitor.getOutputComponent(), "show link renderer in table"); frame.setVisible(true); } /** * extended link renderer in list. * */ public void interactiveTestListLinkRenderer() { EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); JXList list = new JXList(createListModelWithLinks(20)); list.setRolloverEnabled(true); LinkModelAction action = new LinkModelAction(visitor); ComponentProvider<JXHyperlink> context = new HyperlinkProvider(action, LinkModel.class); list.setCellRenderer(new DefaultListRenderer(context)); JFrame frame = wrapWithScrollingInFrame(list, visitor.getOutputComponent(), "show link renderer in list"); frame.setVisible(true); } /** * extended link renderer in tree. * */ public void interactiveTestTreeLinkRenderer() { EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); JXTree tree = new JXTree(createTreeModelWithLinks(20)); tree.setRolloverEnabled(true); LinkModelAction action = new LinkModelAction(visitor); ComponentProvider<JXHyperlink> context = new HyperlinkProvider(action, LinkModel.class); tree.setCellRenderer(new DefaultTreeRenderer(new WrappingProvider(context))); JFrame frame = wrapWithScrollingInFrame(tree, visitor.getOutputComponent(), "show link renderer in list"); frame.setVisible(true); } /** * Use a custom button controller to show both checkbox icon and text to * render Actions in a JXList. */ public void interactiveTableWithRolloverListColumnControl() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); JXList list = new JXList(); // quick-fill and hook to table columns' visibility state configureList(list, table, true); // a custom rendering button controller showing both checkbox and text ButtonProvider wrapper = new RolloverRenderingButtonController(); list.setCellRenderer(new DefaultListRenderer(wrapper)); JXFrame frame = showWithScrollingInFrame(table, list, "rollover checkbox list-renderer"); addStatusMessage(frame, "fake editable list: use rollover renderer - not really working"); frame.pack(); } /** * * Naive implementation: toggle the selected status of the last * stored action. Doesn't work reliably.... requires to leave the * item before the next click updates the action. * */ public static class RolloverRenderingButtonController extends ButtonProvider implements RolloverRenderer { private AbstractActionExt actionExt; public RolloverRenderingButtonController() { setHorizontalAlignment(JLabel.LEADING); } @Override protected void format(CellContext context) { if (!(context.getValue() instanceof AbstractActionExt)) { super.format(context); return; } actionExt = (AbstractActionExt) context.getValue(); rendererComponent.setAction(actionExt); rendererComponent.setSelected(actionExt.isSelected()); // rendererComponent.setText(((AbstractActionExt) context.getValue()).getName()); } public void doClick() { boolean selected = !actionExt.isSelected(); rendererComponent.doClick(0); // actionExt.setSelected(rendererComponent.isSelected()); actionExt.setSelected(selected); // rendererComponent.setSelected(selected); } public boolean isEnabled() { // TODO Auto-generated method stub return true; } } /** * Use a custom button controller to show both checkbox icon and text to * render Actions in a JXList. */ public void interactiveTableWithListColumnControl() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); JXList list = new JXList(); Highlighter highlighter = new UIAlternateRowHighlighter(); table.addHighlighter(highlighter); list.addHighlighter(highlighter); // quick-fill and hook to table columns' visibility state configureList(list, table, false); // a custom rendering button controller showing both checkbox and text ButtonProvider wrapper = new ButtonProvider() { @Override protected void format(CellContext context) { if (!(context.getValue() instanceof AbstractActionExt)) { super.format(context); return; } // rendererComponent.setAction((AbstractActionExt) context.getValue()); rendererComponent.setSelected(((AbstractActionExt) context.getValue()).isSelected()); rendererComponent.setText(((AbstractActionExt) context.getValue()).getName()); } }; wrapper.setHorizontalAlignment(JLabel.LEADING); list.setCellRenderer(new DefaultListRenderer(wrapper)); JXFrame frame = showWithScrollingInFrame(table, list, "checkbox list-renderer"); addStatusMessage(frame, "fake editable list: space/doubleclick on selected item toggles column visibility"); frame.pack(); } /** * Fills the list with a collection of actions (as returned from the * table's column control). Binds space and double-click to toggle * the action's selected state. * * note: this is just an example to show-off the button renderer in a list! * ... it's very dirty!! * * @param list * @param table */ private void configureList(final JXList list, final JXTable table, boolean useRollover) { final List<Action> actions = new ArrayList<Action>(); ColumnControlButton columnControl = new ColumnControlButton(table, null) { @Override protected void addVisibilityActionItems() { actions.addAll(Collections .unmodifiableList(getColumnVisibilityActions())); } }; list.setModel(createListeningListModel(actions)); // action toggling selected state of selected list item final Action toggleSelected = new AbstractActionExt( "toggle column visibility") { public void actionPerformed(ActionEvent e) { if (list.isSelectionEmpty()) return; AbstractActionExt selectedItem = (AbstractActionExt) list .getSelectedValue(); selectedItem.setSelected(!selectedItem.isSelected()); } }; if (useRollover) { list.setRolloverEnabled(true); } else { // bind action to space list.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "toggleSelectedActionState"); } list.getActionMap().put("toggleSelectedActionState", toggleSelected); // bind action to double-click MouseAdapter adapter = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { toggleSelected.actionPerformed(null); } } }; list.addMouseListener(adapter); } /** * Creates and returns a ListModel containing the given actions. * Registers a PropertyChangeListener with each action to get * notified and fire ListEvents. * * @param actions the actions to add into the model. * @return the filled model. */ private ListModel createListeningListModel(final List<Action> actions) { final DefaultListModel model = new DefaultListModel() { DefaultListModel reallyThis = this; @Override public void addElement(Object obj) { super.addElement(obj); ((Action) obj).addPropertyChangeListener(l); } PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { int index = indexOf(evt.getSource()); if (index >= 0) { fireContentsChanged(reallyThis, index, index); } } }; }; for (Action action : actions) { model.addElement(action); } return model; } /** * Compare xtable using custom color renderer - standard vs. ext.<p> * */ public void interactiveTableCustomColorRenderer() { TableModel model = new AncientSwingTeam(); JXTable xtable = new JXTable(model); xtable.setDefaultRenderer(Color.class, new ColorRenderer(true)); JXTable table = new JXTable(model); TableCellRenderer renderer = createColorRendererExt(); table.setDefaultRenderer(Color.class, renderer); showWithScrollingInFrame(xtable, table, "JXTable: Custom color renderer - standard/ext"); } /** * Compare xtable using custom color renderer - standard vs. ext.<p> * Adds highlighter ... running amok. */ public void interactiveTableCustomColorRendererWithHighlighter() { TableModel model = new AncientSwingTeam(); JXTable xtable = new JXTable(model); xtable.addHighlighter(AlternateRowHighlighter.genericGrey); xtable.setDefaultRenderer(Color.class, new ColorRenderer(true)); JXTable table = new JXTable(model); table.addHighlighter(AlternateRowHighlighter.genericGrey); TableCellRenderer renderer = createColorRendererExt(); table.setDefaultRenderer(Color.class, renderer); JXFrame frame = wrapWithScrollingInFrame(xtable, table, "JXTable/highlighter: Custom color renderer - standard/ext"); addStatusMessage(frame, "Highlighter hide custom color renderer background for unselected"); frame.setVisible(true); } /** * Compare xtable using custom color renderer - standard vs. ext.<p> * Adds highlighter which respects renderer's dont touch. */ public void interactiveTableCustomColorRendererWithHighlighterDontTouch() { TableModel model = new AncientSwingTeam(); JXTable xtable = new JXTable(model); Highlighter highlighter = createPropertyRespectingHighlighter(AlternateRowHighlighter.genericGrey); xtable.addHighlighter(highlighter); xtable.setDefaultRenderer(Color.class, new ColorRenderer(true)); JXTable table = new JXTable(model); table.addHighlighter(highlighter); TableCellRenderer renderer = createColorRendererExt(); table.setDefaultRenderer(Color.class, renderer); JXFrame frame = wrapWithScrollingInFrame(xtable, table, "JXTable/highlighter dont-touch: Custom color renderer - standard/ext"); addStatusMessage(frame, "Highlighter doesn't touch custom color renderer visual properties"); frame.setVisible(true); } /** * Creates and returns a Highlighter which does nothing if the * rendererComponent has the dont-touch property set. Otherwise * delegates highlighting to the delegate. * * @param delegate * @return */ private Highlighter createPropertyRespectingHighlighter(final Highlighter delegate) { Highlighter highlighter = new Highlighter() { @Override public Component highlight(Component renderer, ComponentAdapter adapter) { if (((JComponent) renderer).getClientProperty("renderer-dont-touch") != null) return renderer; return delegate.highlight(renderer, adapter); } }; return highlighter; } /** * xtable/xlist using the same custom component controller.<p> * */ public void interactiveTableAndListCustomColorRenderingController() { TableModel tableModel = new AncientSwingTeam(); ComponentProvider<JLabel> controller = createColorRenderingLabelController(); JXTable xtable = new JXTable(tableModel); xtable.setDefaultRenderer(Color.class, new DefaultTableRenderer(controller)); ListModel model = createListColorModel(); JXList list = new JXList(model); ListCellRenderer renderer = new DefaultListRenderer(controller); list.setCellRenderer(renderer); showWithScrollingInFrame(xtable, list, "JXTable/JXList: Custom color renderer - sharing the component controller"); } /** * xtable/xlist using the same custom component controller.<p> * */ public void interactiveTableAndTreeCustomColorRenderingController() { TableModel tableModel = new AncientSwingTeam(); ComponentProvider<JLabel> controller = createColorRenderingLabelController(); JXTable xtable = new JXTable(tableModel); xtable.setDefaultRenderer(Color.class, new DefaultTableRenderer(controller)); TreeModel model = createTreeColorModel(); JTree tree = new JTree(model); ComponentProvider wrapper = new WrappingProvider(createColorRenderingLabelController()); TreeCellRenderer renderer = new DefaultTreeRenderer(wrapper); tree.setCellRenderer(renderer); showWithScrollingInFrame(xtable, tree, "JXTable/JXTree: Custom color renderer - sharing the component controller"); } /** * creates and returns a color ext renderer. * @return */ protected TableCellRenderer createColorRendererExt() { ComponentProvider<JLabel> context = createColorRenderingLabelController(); TableCellRenderer renderer = new DefaultTableRenderer(context); return renderer; } /** * creates and returns a color ext renderer. * @return */ protected ListCellRenderer createListColorRendererExt() { ComponentProvider<JLabel> context = createColorRenderingLabelController(); ListCellRenderer renderer = new DefaultListRenderer(context); return renderer; } /** * Creates and returns a component controller specialized on Color values. <p> * Note: this implementation set's the tooltip * @return */ private ComponentProvider<JLabel> createColorRenderingLabelController() { ComponentProvider<JLabel> context = new LabelProvider() { Border selectedBorder; @Override protected void format(CellContext context) { super.format(context); Object value = context.getValue(); if (value instanceof Color) { rendererComponent.setBackground((Color) value); rendererComponent.putClientProperty("renderer-dont-touch", "color"); } else { rendererComponent.putClientProperty("renderer-dont-touch", null); } } /** * * @param context */ @Override protected void configureState(CellContext context) { Object value = context.getValue(); if (value instanceof Color) { Color newColor = (Color) value; rendererComponent.setToolTipText("RGB value: " + newColor.getRed() + ", " + newColor.getGreen() + ", " + newColor.getBlue()); } else { rendererComponent.setToolTipText(null); } if (context.isSelected()) { selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, context.getSelectionBackground()); } else { selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, context.getBackground()); } rendererComponent.setBorder(selectedBorder); } }; return context; } private ListModel createListModelWithLinks(int count) { DefaultListModel model = new DefaultListModel(); for (int i = 0; i < count; i++) { try { LinkModel link = new LinkModel("a link text " + i, null, new URL("http://some.dummy.url" + i)); if (i == 1) { URL url = JXEditorPaneTest.class.getResource("resources/test.html"); link = new LinkModel("a link text " + i, null, url); } model.addElement(link); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return model; } private TreeModel createTreeModelWithLinks(int count) { DefaultMutableTreeNode root = new DefaultMutableTreeNode("Links"); for (int i = 0; i < count; i++) { try { LinkModel link = new LinkModel("a link text " + i, null, new URL("http://some.dummy.url" + i)); if (i == 1) { URL url = JXEditorPaneTest.class.getResource("resources/test.html"); link = new LinkModel("a link text " + i, null, url); } root.add(new DefaultMutableTreeNode(link)); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return new DefaultTreeModel(root); } private TableModel createModelWithLinks() { String[] columnNames = { "text only", "Link editable", "Link not-editable", "Bool editable", "Bool not-editable" }; DefaultTableModel model = new DefaultTableModel(columnNames, 0) { @Override public Class<?> getColumnClass(int columnIndex) { return getValueAt(0, columnIndex).getClass(); } @Override public boolean isCellEditable(int row, int column) { return !getColumnName(column).contains("not"); } }; for (int i = 0; i < 4; i++) { try { LinkModel link = new LinkModel("a link text " + i, null, new URL("http://some.dummy.url" + i)); if (i == 1) { URL url = JXEditorPaneTest.class .getResource("resources/test.html"); link = new LinkModel("a link text " + i, null, url); } model.addRow(new Object[] { "text only " + i, link, link, Boolean.TRUE, Boolean.TRUE }); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return model; } /** * * @return a ListModel wrapped around the AncientSwingTeam's Color column. */ private ListModel createListColorModel() { AncientSwingTeam tableModel = new AncientSwingTeam(); int colorColumn = 2; DefaultListModel model = new DefaultListModel(); for (int i = 0; i < tableModel.getRowCount(); i++) { model.addElement(tableModel.getValueAt(i, colorColumn)); } return model; } /** * @return a TreeModel with tree nodes of type Color. */ private TreeModel createTreeColorModel() { final AncientSwingTeam tableModel = new AncientSwingTeam(); final int colorColumn = 2; DefaultMutableTreeNode root = new DefaultMutableTreeNode("Colors"); for (int row = 0; row < tableModel.getRowCount(); row++) { root.add(new DefaultMutableTreeNode(tableModel.getValueAt(row, colorColumn))); } return new DefaultTreeModel(root); } /** * copied from sun's tutorial. */ public static class ColorRenderer extends JLabel implements TableCellRenderer { Border unselectedBorder = null; Border selectedBorder = null; boolean isBordered = true; public ColorRenderer(boolean isBordered) { this.isBordered = isBordered; setOpaque(true); // MUST do this for background to show up. putClientProperty("renderer-dont-touch", "color"); } public Component getTableCellRendererComponent(JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) { Color newColor = (Color) color; setBackground(newColor); if (isBordered) { if (isSelected) { if (selectedBorder == null) { selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, table.getSelectionBackground()); } setBorder(selectedBorder); } else { if (unselectedBorder == null) { unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, table.getBackground()); } setBorder(unselectedBorder); } } setToolTipText("RGB value: " + newColor.getRed() + ", " + newColor.getGreen() + ", " + newColor.getBlue()); return this; } } public static class Player { String name; int score; public Player(String name, int score) { this.name = name; this.score = score; } @Override public String toString() { return name + " has score: " + score; } public String getName() { return name; } public int getScore() { return score; } } /** * create and returns a ListModel containing Players. * @return */ private ListModel createPlayerModel() { DefaultListModel model = new DefaultListModel(); model.addElement(new Player("Henry", 10)); model.addElement(new Player("Berta", 112)); model.addElement(new Player("Dave", 20)); return model; } /** * c&p'd from JGoodies BeanUtils. * * Looks up and returns a <code>PropertyDescriptor</code> for the * given Java Bean class and property name using the standard * Java Bean introspection behavior. * * @param beanClass the type of the bean that holds the property * @param propertyName the name of the Bean property * @return the <code>PropertyDescriptor</code> associated with the given * bean and property name as returned by the Bean introspection * * @throws IntrospectionException if an exception occurs during * introspection. * @throws NullPointerException if the beanClass or propertyName is <code>null</code> * * @since 1.1.1 */ public static PropertyDescriptor getPropertyDescriptor( Class beanClass, String propertyName) throws IntrospectionException { BeanInfo info = Introspector.getBeanInfo(beanClass); PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); for (int i = 0; i < descriptors.length; i++) { if (propertyName.equals(descriptors[i].getName())) return descriptors[i]; } throw new IntrospectionException( "Property '" + propertyName + "' not found in bean " + beanClass); } /** * c&p'd from JGoodies BeanUtils. * * Returns the value of the specified property of the given non-null bean. * This operation is unsupported if the bean property is read-only.<p> * * If the read access fails, a PropertyAccessException is thrown * that provides the Throwable that caused the failure. * * @param bean the bean to read the value from * @param propertyDescriptor describes the property to be read * @return the bean's property value * * @throws NullPointerException if the bean is <code>null</code> * @throws UnsupportedOperationException if the bean property is write-only * @throws PropertyAccessException if the new value could not be read */ public static Object getValue(Object bean, PropertyDescriptor propertyDescriptor) { if (bean == null) throw new NullPointerException("The bean must not be null."); Method getter = propertyDescriptor.getReadMethod(); if (getter == null) { throw new UnsupportedOperationException( "The property '" + propertyDescriptor.getName() + "' is write-only."); } try { return getter.invoke(bean); } catch (Exception e) { throw new RuntimeException("can't access property: " + propertyDescriptor.getName()); } // throw PropertyAccessException.createWriteAccessException( // bean, newValue, propertyDescriptor, e); // throw PropertyAccessException.createWriteAccessException( // bean, newValue, propertyDescriptor, e); } }
package de.gurkenlabs.utiLITI.Components; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Path2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import de.gurkenlabs.litiengine.Game; import de.gurkenlabs.litiengine.SpriteSheetInfo; import de.gurkenlabs.litiengine.entities.CollisionEntity; import de.gurkenlabs.litiengine.entities.IEntity; import de.gurkenlabs.litiengine.entities.CollisionEntity.CollisionAlign; import de.gurkenlabs.litiengine.entities.CollisionEntity.CollisionValign; import de.gurkenlabs.litiengine.entities.DecorMob.MovementBehaviour; import de.gurkenlabs.litiengine.environment.Environment; import de.gurkenlabs.litiengine.environment.tilemap.IImageLayer; import de.gurkenlabs.litiengine.environment.tilemap.IMap; import de.gurkenlabs.litiengine.environment.tilemap.IMapLoader; import de.gurkenlabs.litiengine.environment.tilemap.IMapObject; import de.gurkenlabs.litiengine.environment.tilemap.IMapObjectLayer; import de.gurkenlabs.litiengine.environment.tilemap.ITileset; import de.gurkenlabs.litiengine.environment.tilemap.MapObjectProperties; import de.gurkenlabs.litiengine.environment.tilemap.MapObjectType; import de.gurkenlabs.litiengine.environment.tilemap.MapUtilities; import de.gurkenlabs.litiengine.environment.tilemap.OrthogonalMapRenderer; import de.gurkenlabs.litiengine.environment.tilemap.TmxMapLoader; import de.gurkenlabs.litiengine.environment.tilemap.xml.Map; import de.gurkenlabs.litiengine.environment.tilemap.xml.MapObject; import de.gurkenlabs.litiengine.graphics.ImageCache; import de.gurkenlabs.litiengine.graphics.LightSource; import de.gurkenlabs.litiengine.graphics.RenderEngine; import de.gurkenlabs.litiengine.graphics.Spritesheet; import de.gurkenlabs.litiengine.gui.GuiComponent; import de.gurkenlabs.litiengine.input.Input; import de.gurkenlabs.utiLITI.EditorScreen; import de.gurkenlabs.utiLITI.Program; import de.gurkenlabs.utiLITI.UndoManager; import de.gurkenlabs.util.MathUtilities; import de.gurkenlabs.util.geom.GeometricUtilities; import de.gurkenlabs.util.io.FileUtilities; import de.gurkenlabs.util.io.ImageSerializer; public class MapComponent extends EditorComponent { public enum TransformType { UP, DOWN, LEFT, RIGHT, UPLEFT, UPRIGHT, DOWNLEFT, DOWNRIGHT, NONE } private static final int TRANSFORM_RECT_SIZE = 6; private static final int BASE_SCROLL_SPEED = 50; private double currentTransformRectSize = TRANSFORM_RECT_SIZE; private final java.util.Map<TransformType, Rectangle2D> transformRects; private TransformType currentTransform; public static final int EDITMODE_CREATE = 0; public static final int EDITMODE_EDIT = 1; public static final int EDITMODE_MOVE = 2; private final List<Consumer<Integer>> editModeChangedConsumer; private final List<Consumer<IMapObject>> focusChangedConsumer; private final List<Consumer<Map>> mapLoadedConsumer; private int currentEditMode = EDITMODE_EDIT; private static final float[] zooms = new float[] { 0.1f, 0.25f, 0.5f, 1, 1.5f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f, 16f, 32f, 50f, 80f, 100f }; private int currentZoomIndex = 7; private final java.util.Map<String, Point2D> cameraFocus; private final java.util.Map<String, IMapObject> focusedObjects; private final List<Map> maps; private float scrollSpeed = BASE_SCROLL_SPEED; private Point2D startPoint; private Point2D dragPoint; private Point2D dragLocationMapObject; private boolean isMoving; private boolean isTransforming; private Dimension dragSizeMapObject; private Rectangle2D newObject; private IMapObject copiedMapObject; private int gridSize; public boolean snapToGrid = true; public boolean renderGrid = false; public boolean renderCollisionBoxes = true; private final EditorScreen screen; private boolean isLoading; public MapComponent(final EditorScreen screen) { super(ComponentType.MAP); this.editModeChangedConsumer = new CopyOnWriteArrayList<>(); this.focusChangedConsumer = new CopyOnWriteArrayList<>(); this.mapLoadedConsumer = new CopyOnWriteArrayList<>(); this.focusedObjects = new ConcurrentHashMap<>(); this.maps = new ArrayList<>(); this.cameraFocus = new ConcurrentHashMap<>(); this.transformRects = new ConcurrentHashMap<>(); this.screen = screen; Game.getScreenManager().getCamera().onZoomChanged(zoom -> { this.currentTransformRectSize = TRANSFORM_RECT_SIZE / zoom; this.updateTransformControls(); }); this.gridSize = Program.USER_PREFERNCES.getGridSize(); } public void onEditModeChanged(Consumer<Integer> cons) { this.editModeChangedConsumer.add(cons); } public void onFocusChanged(Consumer<IMapObject> cons) { this.focusChangedConsumer.add(cons); } public void onMapLoaded(Consumer<Map> cons) { this.mapLoadedConsumer.add(cons); } @Override public void render(Graphics2D g) { Color COLOR_BOUNDING_BOX_FILL = new Color(0, 0, 0, 35); Color COLOR_NAME_FILL = new Color(0, 0, 0, 60); Color COLOR_BOUNDING_BOX_BORDER = new Color(0, 0, 0, 150); final Color COLOR_FOCUS_FILL = new Color(0, 0, 0, 50); final Color COLOR_FOCUS_BORDER = Color.BLACK; final Color COLOR_COLLISION_FILL = new Color(255, 0, 0, 15); final Color COLOR_NOCOLLISION_FILL = new Color(255, 100, 0, 15); final Color COLOR_COLLISION_BORDER = Color.RED; final Color COLOR_NOCOLLISION_BORDER = Color.ORANGE; final Color COLOR_SPAWNPOINT = Color.GREEN; final Color COLOR_LANE = Color.YELLOW; final Color COLOR_NEWOBJECT_FILL = new Color(0, 255, 0, 50); final Color COLOR_NEWOBJECT_BORDER = Color.GREEN.darker(); final Color COLOR_TRANSFORM_RECT_FILL = new Color(255, 255, 255, 100); final Color COLOR_SHADOW_FILL = new Color(85, 130, 200, 15); final Color COLOR_SHADOW_BORDER = new Color(30, 85, 170); if (this.renderCollisionBoxes) { // render all entities for (final IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) { if (layer == null) { continue; } if (!EditorScreen.instance().getMapSelectionPanel().isSelectedMapObjectLayer(layer.getName())) { continue; } if (layer.getColor() != null) { COLOR_BOUNDING_BOX_BORDER = layer.getColor(); COLOR_BOUNDING_BOX_FILL = new Color(layer.getColor().getRed(), layer.getColor().getGreen(), layer.getColor().getBlue(), 15); } else { COLOR_BOUNDING_BOX_BORDER = new Color(0, 0, 0, 150); COLOR_BOUNDING_BOX_FILL = new Color(0, 0, 0, 35); } for (final IMapObject mapObject : layer.getMapObjects()) { if (mapObject == null) { continue; } String objectName = mapObject.getName(); if (objectName != null && !objectName.isEmpty()) { Rectangle2D nameBackground = new Rectangle2D.Double(mapObject.getX(), mapObject.getBoundingBox().getMaxY() - 3, mapObject.getDimension().getWidth(), 3); g.setColor(COLOR_NAME_FILL); RenderEngine.fillShape(g, nameBackground); } MapObjectType type = MapObjectType.get(mapObject.getType()); // render spawn points if (type == MapObjectType.SPAWNPOINT) { g.setColor(COLOR_SPAWNPOINT); RenderEngine.fillShape(g, new Rectangle2D.Double(mapObject.getBoundingBox().getCenterX() - 1, mapObject.getBoundingBox().getCenterY() - 1, 2, 2)); RenderEngine.drawShape(g, mapObject.getBoundingBox()); } else if (type == MapObjectType.COLLISIONBOX) { g.setColor(COLOR_COLLISION_FILL); RenderEngine.fillShape(g, mapObject.getBoundingBox()); g.setColor(COLOR_COLLISION_BORDER); RenderEngine.drawShape(g, mapObject.getBoundingBox()); } else if (type == MapObjectType.STATICSHADOW) { g.setColor(COLOR_SHADOW_FILL); RenderEngine.fillShape(g, mapObject.getBoundingBox()); g.setColor(COLOR_SHADOW_BORDER); RenderEngine.drawShape(g, mapObject.getBoundingBox()); } else if (type == MapObjectType.LANE) { // render lane if (mapObject.getPolyline() == null || mapObject.getPolyline().getPoints().size() == 0) { continue; } // found the path for the rat final Path2D path = MapUtilities.convertPolylineToPath(mapObject); if (path == null) { continue; } g.setColor(COLOR_LANE); RenderEngine.drawShape(g, path); Point2D start = new Point2D.Double(mapObject.getLocation().getX(), mapObject.getLocation().getY()); RenderEngine.fillShape(g, new Ellipse2D.Double(start.getX() - 1, start.getY() - 1, 3, 3)); RenderEngine.drawMapText(g, "#" + mapObject.getId() + "(" + mapObject.getName() + ")", start.getX(), start.getY() - 5); } // render bounding boxes final IMapObject focusedMapObject = this.getFocusedMapObject(); if (focusedMapObject == null || mapObject.getId() != focusedMapObject.getId()) { g.setColor(COLOR_BOUNDING_BOX_FILL); // don't fill rect for lightsource because it is important to judge // the color if (type != MapObjectType.LIGHTSOURCE) { if (type == MapObjectType.TRIGGER) { g.setColor(COLOR_NOCOLLISION_FILL); } RenderEngine.fillShape(g, mapObject.getBoundingBox()); } if (type == MapObjectType.TRIGGER) { g.setColor(COLOR_NOCOLLISION_BORDER); } RenderEngine.drawShape(g, mapObject.getBoundingBox()); } // render collision boxes String coll = mapObject.getCustomProperty(MapObjectProperties.COLLISION); final String collisionBoxWidthFactor = mapObject.getCustomProperty(MapObjectProperties.COLLISIONBOXWIDTH); final String collisionBoxHeightFactor = mapObject.getCustomProperty(MapObjectProperties.COLLISIONBOXHEIGHT); final CollisionAlign align = CollisionAlign.get(mapObject.getCustomProperty(MapObjectProperties.COLLISIONALGIN)); final CollisionValign valign = CollisionValign.get(mapObject.getCustomProperty(MapObjectProperties.COLLISIONVALGIN)); if (coll != null && collisionBoxWidthFactor != null && collisionBoxHeightFactor != null) { boolean collision = Boolean.valueOf(coll); final Color collisionColor = collision ? COLOR_COLLISION_FILL : COLOR_NOCOLLISION_FILL; final Color collisionShapeColor = collision ? COLOR_COLLISION_BORDER : COLOR_NOCOLLISION_BORDER; float collisionBoxWidth = 0, collisionBoxHeight = 0; try { collisionBoxWidth = Float.parseFloat(collisionBoxWidthFactor); collisionBoxHeight = Float.parseFloat(collisionBoxHeightFactor); } catch (NumberFormatException | NullPointerException e) { e.printStackTrace(); } g.setColor(collisionColor); Rectangle2D collisionBox = CollisionEntity.getCollisionBox(mapObject.getLocation(), mapObject.getDimension().getWidth(), mapObject.getDimension().getHeight(), collisionBoxWidth, collisionBoxHeight, align, valign); RenderEngine.fillShape(g, collisionBox); g.setColor(collisionShapeColor); RenderEngine.drawShape(g, collisionBox); } g.setColor(Color.WHITE); float textSize = 3 * zooms[this.currentZoomIndex]; g.setFont(Program.TEXT_FONT.deriveFont(textSize)); RenderEngine.drawMapText(g, objectName, mapObject.getX() + 1, mapObject.getBoundingBox().getMaxY()); } } } switch (this.currentEditMode) { case EDITMODE_CREATE: if (newObject != null) { g.setColor(COLOR_NEWOBJECT_FILL); RenderEngine.fillShape(g, newObject); g.setColor(COLOR_NEWOBJECT_BORDER); RenderEngine.drawShape(g, newObject); g.setFont(g.getFont().deriveFont(Font.BOLD)); RenderEngine.drawMapText(g, newObject.getWidth() + "", newObject.getX() + newObject.getWidth() / 2 - 3, newObject.getY() - 5); RenderEngine.drawMapText(g, newObject.getHeight() + "", newObject.getX() - 10, newObject.getY() + newObject.getHeight() / 2); } break; case EDITMODE_EDIT: // draw selection final Point2D start = this.startPoint; if (start != null && !Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { Rectangle2D rect = this.getCurrentMouseSelectionArea(); g.setColor(new Color(0, 130, 152, 30)); RenderEngine.fillShape(g, rect); if (rect.getWidth() > 0 || rect.getHeight() > 0) { g.setColor(new Color(0, 130, 152, 255)); g.setFont(g.getFont().deriveFont(Font.BOLD)); RenderEngine.drawMapText(g, rect.getWidth() + "", rect.getX() + rect.getWidth() / 2 - 3, rect.getY() - 5); RenderEngine.drawMapText(g, rect.getHeight() + "", rect.getX() - 10, rect.getY() + rect.getHeight() / 2); } g.setColor(new Color(0, 130, 152, 150)); RenderEngine.drawShape(g, rect, new BasicStroke(2 / Game.getInfo().getRenderScale(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 1 }, 0)); } break; } // render the focus and the transform rects final Rectangle2D focus = this.getFocus(); final IMapObject focusedMapObject = this.getFocusedMapObject(); if (focus != null && focusedMapObject != null) { Stroke stroke = new BasicStroke(2 / Game.getInfo().getRenderScale(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 1f }, 0); if (MapObjectType.get(focusedMapObject.getType()) != MapObjectType.LIGHTSOURCE) { g.setColor(COLOR_FOCUS_FILL); RenderEngine.fillShape(g, focus); } g.setColor(COLOR_FOCUS_BORDER); RenderEngine.drawShape(g, focus, stroke); // render transform rects if (!Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { Stroke transStroke = new BasicStroke(1 / Game.getInfo().getRenderScale()); for (Rectangle2D trans : this.transformRects.values()) { g.setColor(COLOR_TRANSFORM_RECT_FILL); RenderEngine.fillShape(g, trans); g.setColor(COLOR_FOCUS_BORDER); RenderEngine.drawShape(g, trans, transStroke); } } } if (focusedMapObject != null) { Point2D loc = Game.getScreenManager().getCamera() .getViewPortLocation(new Point2D.Double(focusedMapObject.getX() + focusedMapObject.getDimension().getWidth() / 2, focusedMapObject.getY())); g.setFont(Program.TEXT_FONT.deriveFont(Font.BOLD, 15f)); g.setColor(COLOR_FOCUS_BORDER); String id = "#" + focusedMapObject.getId(); RenderEngine.drawText(g, id, loc.getX() * Game.getInfo().getRenderScale() - g.getFontMetrics().stringWidth(id) / 2, loc.getY() * Game.getInfo().getRenderScale() - (5 * this.currentTransformRectSize)); if (MapObjectType.get(focusedMapObject.getType()) == MapObjectType.TRIGGER) { g.setColor(COLOR_NOCOLLISION_BORDER); g.setFont(Program.TEXT_FONT.deriveFont(11f)); RenderEngine.drawMapText(g, focusedMapObject.getName(), focusedMapObject.getX() + 2, focusedMapObject.getY() + 5); } } // render the grid if (this.renderGrid && Game.getInfo().getRenderScale() >= 1) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(new Color(255, 255, 255, 100)); Stroke stroke = new BasicStroke(1 / Game.getInfo().getRenderScale(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 0.5f }, 0); final double viewPortX = Math.max(0, Game.getScreenManager().getCamera().getViewPort().getX()); final double viewPortMaxX = Math.min(Game.getEnvironment().getMap().getSizeInPixels().getWidth(), Game.getScreenManager().getCamera().getViewPort().getMaxX()); final double viewPortY = Math.max(0, Game.getScreenManager().getCamera().getViewPort().getY()); final double viewPortMaxY = Math.min(Game.getEnvironment().getMap().getSizeInPixels().getHeight(), Game.getScreenManager().getCamera().getViewPort().getMaxY()); final int startX = Math.max(0, (int) (viewPortX / gridSize) * gridSize); final int startY = Math.max(0, (int) (viewPortY / gridSize) * gridSize); for (int x = startX; x <= viewPortMaxX; x += gridSize) { RenderEngine.drawShape(g, new Line2D.Double(x, viewPortY, x, viewPortMaxY), stroke); } for (int y = startY; y <= viewPortMaxY; y += gridSize) { RenderEngine.drawShape(g, new Line2D.Double(viewPortX, y, viewPortMaxX, y), stroke); } g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } super.render(g); } public void loadMaps(String projectPath) { final List<String> files = FileUtilities.findFiles(new ArrayList<>(), Paths.get(projectPath), "tmx"); System.out.println(files.size() + " maps found in folder " + projectPath); final List<Map> maps = new ArrayList<>(); for (final String mapFile : files) { final IMapLoader tmxLoader = new TmxMapLoader(); Map map = (Map) tmxLoader.loadMap(mapFile); maps.add(map); System.out.println("map found: " + map.getFileName()); } this.loadMaps(maps); } public void loadMaps(List<Map> maps) { EditorScreen.instance().getMapObjectPanel().bind(null); this.setFocus(null); this.getMaps().clear(); maps.sort(new Comparator<Map>() { @Override public int compare(Map arg0, Map arg1) { // TODO Auto-generated method stub return arg0.getName().compareTo(arg1.getName()); } }); this.getMaps().addAll(maps); EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps()); } public List<Map> getMaps() { return this.maps; } public int getGridSize() { return this.gridSize; } @Override public void prepare() { Game.getScreenManager().getCamera().setZoom(zooms[this.currentZoomIndex], 0); Program.horizontalScroll.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { if (isLoading) { return; } Point2D cameraFocus = new Point2D.Double(Program.horizontalScroll.getValue(), Game.getScreenManager().getCamera().getFocus().getY()); Game.getScreenManager().getCamera().setFocus(cameraFocus); } }); Program.verticalScroll.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { if (isLoading) { return; } Point2D cameraFocus = new Point2D.Double(Game.getScreenManager().getCamera().getFocus().getX(), Program.verticalScroll.getValue()); Game.getScreenManager().getCamera().setFocus(cameraFocus); } }); Game.getScreenManager().getRenderComponent().addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { startPoint = null; } @Override public void focusGained(FocusEvent e) { } }); this.setupControls(); super.prepare(); this.onMouseMoved(e -> { if (this.getFocus() == null || this.currentEditMode != EDITMODE_EDIT) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0); currentTransform = TransformType.NONE; return; } boolean hovered = false; if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { return; } for (TransformType type : this.transformRects.keySet()) { Rectangle2D rect = this.transformRects.get(type); Rectangle2D hoverrect = new Rectangle2D.Double(rect.getX() - rect.getWidth() * 2, rect.getY() - rect.getHeight() * 2, rect.getWidth() * 4, rect.getHeight() * 4); if (hoverrect.contains(Input.mouse().getMapLocation())) { hovered = true; if (type == TransformType.DOWN || type == TransformType.UP) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_VERTICAL, 0, 0); } else if (type == TransformType.UPLEFT || type == TransformType.DOWNRIGHT) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_DIAGONAL_LEFT, 0, 0); } else if (type == TransformType.UPRIGHT || type == TransformType.DOWNLEFT) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_DIAGONAL_RIGHT, 0, 0); } else { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_HORIZONTAL, 0, 0); } currentTransform = type; break; } } if (!hovered) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0); currentTransform = TransformType.NONE; } }); this.onMousePressed(e -> { if (!this.hasFocus()) { return; } switch (this.currentEditMode) { case EDITMODE_CREATE: this.startPoint = Input.mouse().getMapLocation(); break; case EDITMODE_MOVE: break; case EDITMODE_EDIT: if (this.currentTransform != TransformType.NONE) { return; } final Point2D mouse = Input.mouse().getMapLocation(); this.startPoint = mouse; boolean somethingIsFocused = false; boolean currentObjectFocused = false; for (IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) { if (layer == null) { continue; } if (somethingIsFocused) { break; } if (!EditorScreen.instance().getMapSelectionPanel().isSelectedMapObjectLayer(layer.getName())) { continue; } for (IMapObject mapObject : layer.getMapObjects()) { if (mapObject == null) { continue; } MapObjectType type = MapObjectType.get(mapObject.getType()); if (type == MapObjectType.LANE) { continue; } if (mapObject.getBoundingBox().contains(mouse)) { if (this.getFocusedMapObject() != null && mapObject.getId() == this.getFocusedMapObject().getId()) { currentObjectFocused = true; continue; } this.setFocus(mapObject); EditorScreen.instance().getMapObjectPanel().bind(mapObject); somethingIsFocused = true; break; } } } if (!somethingIsFocused && !currentObjectFocused) { this.setFocus(null); EditorScreen.instance().getMapObjectPanel().bind(null); } break; } }); this.onMouseDragged(e -> { if (!this.hasFocus()) { return; } switch (this.currentEditMode) { case EDITMODE_CREATE: if (startPoint == null) { return; } newObject = this.getCurrentMouseSelectionArea(); break; case EDITMODE_EDIT: if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { if (!this.isMoving) { this.isMoving = true; UndoManager.instance().mapObjectChanging(this.getFocusedMapObject()); } this.handleEntityDrag(); return; } else if (this.currentTransform != TransformType.NONE) { if (!this.isTransforming) { this.isTransforming = true; UndoManager.instance().mapObjectChanging(this.getFocusedMapObject()); } this.handleTransform(); return; } break; case EDITMODE_MOVE: if (!this.isMoving) { this.isMoving = true; UndoManager.instance().mapObjectChanging(this.getFocusedMapObject()); } break; } }); this.onMouseReleased(e -> { if (!this.hasFocus()) { return; } this.dragPoint = null; this.dragLocationMapObject = null; this.dragSizeMapObject = null; switch (this.currentEditMode) { case EDITMODE_CREATE: if (this.newObject == null) { break; } IMapObject mo = this.createNewMapObject(EditorScreen.instance().getMapObjectPanel().getObjectType()); this.newObject = null; this.setFocus(mo); EditorScreen.instance().getMapObjectPanel().bind(mo); this.setEditMode(EDITMODE_EDIT); break; case EDITMODE_MOVE: break; case EDITMODE_EDIT: if (this.isMoving || this.isTransforming) { this.isMoving = false; this.isTransforming = false; UndoManager.instance().mapObjectChanged(this.getFocusedMapObject()); } if (this.startPoint == null) { return; } Rectangle2D rect = this.getCurrentMouseSelectionArea(); if (rect.getHeight() > 0 && rect.getWidth() > 0) { boolean somethingIsFocused = false; for (IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) { if (layer == null) { continue; } if (!EditorScreen.instance().getMapSelectionPanel().isSelectedMapObjectLayer(layer.getName())) { continue; } for (IMapObject mapObject : layer.getMapObjects()) { if (mapObject == null) { continue; } MapObjectType type = MapObjectType.get(mapObject.getType()); if (type == MapObjectType.LANE) { continue; } if (!GeometricUtilities.intersects(rect, mapObject.getBoundingBox())) { continue; } this.setFocus(mapObject); if (mapObject.equals(this.getFocusedMapObject())) { somethingIsFocused = true; continue; } EditorScreen.instance().getMapObjectPanel().bind(mapObject); somethingIsFocused = true; break; } } if (!somethingIsFocused) { this.setFocus(null); EditorScreen.instance().getMapObjectPanel().bind(null); } } break; } this.startPoint = null; }); } public void loadEnvironment(Map map) { this.isLoading = true; try { if (Game.getEnvironment() != null && Game.getEnvironment().getMap() != null) { double x = Game.getScreenManager().getCamera().getFocus().getX(); double y = Game.getScreenManager().getCamera().getFocus().getY(); Point2D newPoint = new Point2D.Double(x, y); this.cameraFocus.put(Game.getEnvironment().getMap().getFileName(), newPoint); } Point2D newFocus = null; if (this.cameraFocus.containsKey(map.getFileName())) { newFocus = this.cameraFocus.get(map.getFileName()); } else { newFocus = new Point2D.Double(map.getSizeInPixels().getWidth() / 2, map.getSizeInPixels().getHeight() / 2); this.cameraFocus.put(map.getFileName(), newFocus); } Game.getScreenManager().getCamera().setFocus(new Point2D.Double(newFocus.getX(), newFocus.getY())); this.ensureUniqueIds(map); Environment env = new Environment(map); env.init(); Game.loadEnvironment(env); this.updateScrollBars(); EditorScreen.instance().getMapSelectionPanel().setSelection(map.getFileName()); EditorScreen.instance().getMapObjectPanel().bind(this.getFocusedMapObject()); for (Consumer<Map> cons : this.mapLoadedConsumer) { cons.accept(map); } } finally { this.isLoading = false; } } private void ensureUniqueIds(IMap map) { int maxMapId = MapUtilities.getMaxMapId(map); List<Integer> usedIds = new ArrayList<>(); for (IMapObject obj : map.getMapObjects()) { if (usedIds.contains(obj.getId())) { obj.setId(++maxMapId); } usedIds.add(obj.getId()); } } public void add(IMapObject mapObject, IMapObjectLayer layer) { layer.addMapObject(mapObject); Game.getEnvironment().loadFromMap(mapObject.getId()); if (MapObjectType.get(mapObject.getType()) == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } this.setFocus(mapObject); EditorScreen.instance().getMapObjectPanel().bind(mapObject); this.setEditMode(EDITMODE_EDIT); } public void copy() { if (this.currentEditMode != EDITMODE_EDIT) { return; } this.copiedMapObject = this.getFocusedMapObject(); } public void paste() { if (this.copiedMapObject != null) { int x = (int) Input.mouse().getMapLocation().getX(); int y = (int) Input.mouse().getMapLocation().getY(); this.newObject = new Rectangle(x, y, (int) this.copiedMapObject.getDimension().getWidth(), (int) this.copiedMapObject.getDimension().getHeight()); this.copyMapObject(this.copiedMapObject); } } public void cut() { if (this.currentEditMode != EDITMODE_EDIT) { return; } this.copiedMapObject = this.getFocusedMapObject(); UndoManager.instance().mapObjectDeleting(this.getFocusedMapObject()); this.delete(this.getFocusedMapObject()); } public void delete() { if (this.getFocusedMapObject() == null) { return; } int n = JOptionPane.showConfirmDialog( null, "Do you really want to delete the entity [" + this.getFocusedMapObject().getId() + "]", "Delete Entity?", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.OK_OPTION) { UndoManager.instance().mapObjectDeleting(this.getFocusedMapObject()); this.delete(this.getFocusedMapObject()); } } public void delete(final IMapObject mapObject) { if (mapObject == null) { return; } MapObjectType type = MapObjectType.valueOf(mapObject.getType()); Game.getEnvironment().getMap().removeMapObject(mapObject.getId()); Game.getEnvironment().remove(mapObject.getId()); if (type == MapObjectType.STATICSHADOW || type == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } EditorScreen.instance().getMapObjectPanel().bind(null); this.setFocus(null); } public void setEditMode(int editMode) { if (editMode == this.currentEditMode) { return; } switch (editMode) { case EDITMODE_CREATE: this.setFocus(null); EditorScreen.instance().getMapObjectPanel().bind(null); break; case EDITMODE_EDIT: break; case EDITMODE_MOVE: break; } this.currentEditMode = editMode; for (Consumer<Integer> cons : this.editModeChangedConsumer) { cons.accept(this.currentEditMode); } } public void setFocus(IMapObject mapObject) { if (mapObject != null && mapObject.equals(this.getFocusedMapObject()) || mapObject == null && this.getFocusedMapObject() == null) { return; } if (Game.getEnvironment() == null || Game.getEnvironment().getMap() == null) { return; } if (this.isMoving || this.isTransforming) { return; } if (mapObject == null) { this.focusedObjects.remove(Game.getEnvironment().getMap().getFileName()); } else { this.focusedObjects.put(Game.getEnvironment().getMap().getFileName(), mapObject); } for (Consumer<IMapObject> cons : this.focusChangedConsumer) { cons.accept(this.getFocusedMapObject()); } this.updateTransformControls(); } public void setGridSize(int gridSize) { Program.USER_PREFERNCES.setGridSize(gridSize); this.gridSize = gridSize; } public void updateTransformControls() { final Rectangle2D focus = this.getFocus(); if (focus == null) { this.transformRects.clear(); return; } for (TransformType trans : TransformType.values()) { if (trans == TransformType.NONE) { continue; } Rectangle2D transRect = new Rectangle2D.Double(this.getTransX(trans, focus), this.getTransY(trans, focus), this.currentTransformRectSize, this.currentTransformRectSize); this.transformRects.put(trans, transRect); } } public void deleteMap() { if (this.getMaps() == null || this.getMaps().size() == 0) { return; } if (Game.getEnvironment() == null && Game.getEnvironment().getMap() == null) { return; } this.getMaps().removeIf(x -> x.getFileName().equals(Game.getEnvironment().getMap().getFileName())); EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps()); if (this.maps.size() > 0) { this.loadEnvironment(this.maps.get(0)); } else { this.loadEnvironment(null); } } public void importMap() { if (this.getMaps() == null || this.getMaps().size() == 0) { return; } JFileChooser chooser; try { String defaultPath = EditorScreen.instance().getProjectPath() != null ? EditorScreen.instance().getProjectPath() : new File(".").getCanonicalPath(); chooser = new JFileChooser(defaultPath); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setDialogType(JFileChooser.OPEN_DIALOG); chooser.setDialogTitle("Import Map"); FileFilter filter = new FileNameExtensionFilter("tmx - Tilemap XML", Map.FILE_EXTENSION); chooser.setFileFilter(filter); chooser.addChoosableFileFilter(filter); int result = chooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { final IMapLoader tmxLoader = new TmxMapLoader(); Map map = (Map) tmxLoader.loadMap(chooser.getSelectedFile().toString()); if (map == null) { System.out.println("could not load map from file '" + chooser.getSelectedFile().toString() + "'"); return; } Optional<Map> current = this.maps.stream().filter(x -> x.getFileName().equals(map.getFileName())).findFirst(); if (current.isPresent()) { int n = JOptionPane.showConfirmDialog( null, "Do you really want to replace the existing map '" + map.getFileName() + "' ?", "Replace Map", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { this.getMaps().remove(current.get()); ImageCache.MAPS.clear("^(" + OrthogonalMapRenderer.getCacheKey(map) + ").*(static)$"); } else { return; } } this.getMaps().add(map); EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps()); // remove old spritesheets for (ITileset tileSet : map.getTilesets()) { Spritesheet sprite = Spritesheet.find(tileSet.getImage().getSource()); if (sprite != null) { Spritesheet.remove(sprite.getName()); this.screen.getGameFile().getTileSets().removeIf(x -> x.getName().equals(sprite.getName())); } } for (ITileset tileSet : map.getTilesets()) { Spritesheet sprite = Spritesheet.load(tileSet); this.screen.getGameFile().getTileSets().add(new SpriteSheetInfo(sprite)); } for (IImageLayer imageLayer : map.getImageLayers()) { BufferedImage img = RenderEngine.getImage(imageLayer.getImage().getAbsoluteSourcePath(), true); Spritesheet sprite = Spritesheet.load(img, imageLayer.getImage().getSource(), img.getWidth(), img.getHeight()); this.screen.getGameFile().getTileSets().add(new SpriteSheetInfo(sprite)); } this.loadEnvironment(map); System.out.println("imported map '" + map.getFileName() + "'"); } } catch (IOException e1) { e1.printStackTrace(); } } public void exportMap() { if (this.getMaps() == null || this.getMaps().size() == 0) { return; } Map map = (Map) Game.getEnvironment().getMap(); if (map == null) { return; } JFileChooser chooser; try { String source = EditorScreen.instance().getProjectPath(); chooser = new JFileChooser(source != null ? source : new File(".").getCanonicalPath()); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setDialogType(JFileChooser.SAVE_DIALOG); chooser.setDialogTitle("Export Map"); FileFilter filter = new FileNameExtensionFilter("tmx - Tilemap XML", Map.FILE_EXTENSION); chooser.setFileFilter(filter); chooser.addChoosableFileFilter(filter); chooser.setSelectedFile(new File(map.getFileName() + "." + Map.FILE_EXTENSION)); int result = chooser.showSaveDialog(null); if (result == JFileChooser.APPROVE_OPTION) { String newFile = map.save(chooser.getSelectedFile().toString()); // save all tilesets manually because a map has a relative reference to // the tilesets String dir = FileUtilities.getParentDirPath(newFile); for (ITileset tileSet : map.getTilesets()) { ImageSerializer.saveImage(Paths.get(dir, tileSet.getImage().getSource()).toString(), Spritesheet.find(tileSet.getImage().getSource()).getImage()); } System.out.println("exported " + map.getFileName() + " to " + newFile); } } catch (IOException e1) { e1.printStackTrace(); } } public void createNewMap() { } public void zoomIn() { if (this.currentZoomIndex < zooms.length - 1) { this.currentZoomIndex++; } this.setCurrentZoom(); this.updateScrollSpeed(); } public void zoomOut() { if (this.currentZoomIndex > 0) { this.currentZoomIndex } this.setCurrentZoom(); this.updateScrollSpeed(); } private void updateScrollSpeed() { this.scrollSpeed = BASE_SCROLL_SPEED / this.zooms[this.currentZoomIndex]; } private IMapObject copyMapObject(IMapObject obj) { IMapObject mo = new MapObject(); mo.setType(obj.getType()); mo.setX(this.snapX(this.newObject.getX())); mo.setY(this.snapY(this.newObject.getY())); mo.setWidth((int) obj.getDimension().getWidth()); mo.setHeight((int) obj.getDimension().getHeight()); mo.setId(Game.getEnvironment().getNextMapId()); mo.setName(obj.getName()); mo.setCustomProperties(obj.getAllCustomProperties()); this.add(mo, getCurrentLayer()); UndoManager.instance().mapObjectAdded(mo); return mo; } private static IMapObjectLayer getCurrentLayer() { int layerIndex = EditorScreen.instance().getMapSelectionPanel().getSelectedLayerIndex(); if (layerIndex < 0 || layerIndex >= Game.getEnvironment().getMap().getMapObjectLayers().size()) { layerIndex = 0; } return Game.getEnvironment().getMap().getMapObjectLayers().get(layerIndex); } private IMapObject createNewMapObject(MapObjectType type) { IMapObject mo = new MapObject(); mo.setType(type.toString()); mo.setX((int) this.newObject.getX()); mo.setY((int) this.newObject.getY()); mo.setWidth((int) this.newObject.getWidth()); mo.setHeight((int) this.newObject.getHeight()); mo.setId(Game.getEnvironment().getNextMapId()); mo.setName(""); switch (type) { case PROP: mo.setCustomProperty(MapObjectProperties.COLLISIONBOXWIDTH, (this.newObject.getWidth() * 0.4) + ""); mo.setCustomProperty(MapObjectProperties.COLLISIONBOXHEIGHT, (this.newObject.getHeight() * 0.4) + ""); mo.setCustomProperty(MapObjectProperties.COLLISION, "true"); mo.setCustomProperty(MapObjectProperties.INDESTRUCTIBLE, "false"); break; case DECORMOB: mo.setCustomProperty(MapObjectProperties.COLLISIONBOXWIDTH, (this.newObject.getWidth() * 0.4) + ""); mo.setCustomProperty(MapObjectProperties.COLLISIONBOXHEIGHT, (this.newObject.getHeight() * 0.4) + ""); mo.setCustomProperty(MapObjectProperties.COLLISION, "false"); mo.setCustomProperty(MapObjectProperties.DECORMOB_VELOCITY, "2"); mo.setCustomProperty(MapObjectProperties.DECORMOB_BEHAVIOUR, MovementBehaviour.IDLE.toString()); break; case LIGHTSOURCE: mo.setCustomProperty(MapObjectProperties.LIGHTBRIGHTNESS, "180"); mo.setCustomProperty(MapObjectProperties.LIGHTCOLOR, "#ffffff"); mo.setCustomProperty(MapObjectProperties.LIGHTSHAPE, LightSource.ELLIPSE); break; case SPAWNPOINT: mo.setWidth(3); mo.setHeight(3); default: break; } this.add(mo, getCurrentLayer()); UndoManager.instance().mapObjectAdded(mo); return mo; } private Rectangle2D getCurrentMouseSelectionArea() { final Point2D startPoint = this.startPoint; if (startPoint == null) { return null; } final Point2D endPoint = Input.mouse().getMapLocation(); double minX = this.snapX(Math.min(startPoint.getX(), endPoint.getX())); double maxX = this.snapX(Math.max(startPoint.getX(), endPoint.getX())); double minY = this.snapY(Math.min(startPoint.getY(), endPoint.getY())); double maxY = this.snapY(Math.max(startPoint.getY(), endPoint.getY())); double width = Math.abs(minX - maxX); double height = Math.abs(minY - maxY); return new Rectangle2D.Double(minX, minY, width, height); } private Rectangle2D getFocus() { if (this.getFocusedMapObject() != null) { return this.getFocusedMapObject().getBoundingBox(); } return null; } private IMapObject getFocusedMapObject() { if (Game.getEnvironment() != null && Game.getEnvironment().getMap() != null) { return this.focusedObjects.get(Game.getEnvironment().getMap().getFileName()); } return null; } private double getTransX(TransformType type, Rectangle2D focus) { switch (type) { case DOWN: case UP: return focus.getCenterX() - this.currentTransformRectSize / 2; case LEFT: case DOWNLEFT: case UPLEFT: return focus.getX() - this.currentTransformRectSize; case RIGHT: case DOWNRIGHT: case UPRIGHT: return focus.getMaxX(); default: return 0; } } private double getTransY(TransformType type, Rectangle2D focus) { switch (type) { case DOWN: case DOWNLEFT: case DOWNRIGHT: return focus.getMaxY(); case UP: case UPLEFT: case UPRIGHT: return focus.getY() - this.currentTransformRectSize; case LEFT: case RIGHT: return focus.getCenterY() - this.currentTransformRectSize / 2; default: return 0; } } private void handleTransform() { if (this.getFocusedMapObject() == null || this.currentEditMode != EDITMODE_EDIT || currentTransform == TransformType.NONE) { return; } if (this.dragPoint == null) { this.dragPoint = Input.mouse().getMapLocation(); this.dragLocationMapObject = new Point2D.Double(this.getFocusedMapObject().getX(), this.getFocusedMapObject().getY()); this.dragSizeMapObject = new Dimension(this.getFocusedMapObject().getDimension()); return; } double deltaX = Input.mouse().getMapLocation().getX() - this.dragPoint.getX(); double deltaY = Input.mouse().getMapLocation().getY() - this.dragPoint.getY(); double newWidth = this.dragSizeMapObject.getWidth(); double newHeight = this.dragSizeMapObject.getHeight(); double newX = this.snapX(this.dragLocationMapObject.getX()); double newY = this.snapY(this.dragLocationMapObject.getY()); switch (this.currentTransform) { case DOWN: newHeight += deltaY; break; case DOWNRIGHT: newHeight += deltaY; newWidth += deltaX; break; case DOWNLEFT: newHeight += deltaY; newWidth -= deltaX; newX += deltaX; newX = MathUtilities.clamp(newX, 0, this.dragLocationMapObject.getX() + this.dragSizeMapObject.getWidth()); break; case LEFT: newWidth -= deltaX; newX += deltaX; newX = MathUtilities.clamp(newX, 0, this.dragLocationMapObject.getX() + this.dragSizeMapObject.getWidth()); break; case RIGHT: newWidth += deltaX; break; case UP: newHeight -= deltaY; newY += deltaY; newY = MathUtilities.clamp(newY, 0, this.dragLocationMapObject.getY() + this.dragSizeMapObject.getHeight()); break; case UPLEFT: newHeight -= deltaY; newY += deltaY; newY = MathUtilities.clamp(newY, 0, this.dragLocationMapObject.getY() + this.dragSizeMapObject.getHeight()); newWidth -= deltaX; newX += deltaX; newX = MathUtilities.clamp(newX, 0, this.dragLocationMapObject.getX() + this.dragSizeMapObject.getWidth()); break; case UPRIGHT: newHeight -= deltaY; newY += deltaY; newY = MathUtilities.clamp(newY, 0, this.dragLocationMapObject.getY() + this.dragSizeMapObject.getHeight()); newWidth += deltaX; break; default: return; } this.getFocusedMapObject().setWidth(this.snapX(newWidth)); this.getFocusedMapObject().setHeight(this.snapY(newHeight)); this.getFocusedMapObject().setX(this.snapX(newX)); this.getFocusedMapObject().setY(this.snapY(newY)); Game.getEnvironment().reloadFromMap(this.getFocusedMapObject().getId()); if (MapObjectType.get(this.getFocusedMapObject().getType()) == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } EditorScreen.instance().getMapObjectPanel().bind(this.getFocusedMapObject()); this.updateTransformControls(); } private void handleEntityDrag() { // only handle drag i if (this.getFocusedMapObject() == null || (!Input.keyboard().isPressed(KeyEvent.VK_CONTROL) && this.currentEditMode != EDITMODE_MOVE)) { return; } if (this.dragPoint == null) { this.dragPoint = Input.mouse().getMapLocation(); this.dragLocationMapObject = new Point2D.Double(this.getFocusedMapObject().getX(), this.getFocusedMapObject().getY()); return; } double deltaX = Input.mouse().getMapLocation().getX() - this.dragPoint.getX(); double deltaY = Input.mouse().getMapLocation().getY() - this.dragPoint.getY(); double newX = this.snapX(this.dragLocationMapObject.getX() + deltaX); double newY = this.snapY(this.dragLocationMapObject.getY() + deltaY); this.getFocusedMapObject().setX((int) newX); this.getFocusedMapObject().setY((int) newY); Game.getEnvironment().reloadFromMap(this.getFocusedMapObject().getId()); if (MapObjectType.get(this.getFocusedMapObject().getType()) == MapObjectType.STATICSHADOW || MapObjectType.get(this.getFocusedMapObject().getType()) == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } EditorScreen.instance().getMapObjectPanel().bind(this.getFocusedMapObject()); this.updateTransformControls(); } private void setCurrentZoom() { Game.getScreenManager().getCamera().setZoom(zooms[this.currentZoomIndex], 0); } private void setupControls() { Input.keyboard().onKeyReleased(KeyEvent.VK_ADD, e -> { if (this.isSuspended() || !this.isVisible()) { return; } if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { this.zoomIn(); } }); Input.keyboard().onKeyReleased(KeyEvent.VK_SUBTRACT, e -> { if (this.isSuspended() || !this.isVisible()) { return; } if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { this.zoomOut(); } }); Input.keyboard().onKeyPressed(KeyEvent.VK_SPACE, e -> { if (this.getFocusedMapObject() != null) { Game.getScreenManager().getCamera().setFocus(new Point2D.Double(this.getFocus().getCenterX(), this.getFocus().getCenterY())); } }); Input.keyboard().onKeyPressed(KeyEvent.VK_CONTROL, e -> { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_MOVE, 0, 0); }); Input.keyboard().onKeyReleased(KeyEvent.VK_CONTROL, e -> { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0); }); Input.keyboard().onKeyReleased(KeyEvent.VK_Z, e -> { if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { UndoManager.instance().undo(); } }); Input.keyboard().onKeyReleased(KeyEvent.VK_Y, e -> { if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { UndoManager.instance().redo(); } }); Input.keyboard().onKeyPressed(KeyEvent.VK_DELETE, e -> { if (this.isSuspended() || !this.isVisible() || this.getFocusedMapObject() == null) { return; } if (Game.getScreenManager().getRenderComponent().hasFocus()) { if (this.currentEditMode == EDITMODE_EDIT) { this.delete(); } } }); Input.mouse().onWheelMoved(e -> { if (!this.hasFocus()) { return; } // horizontal scrolling if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL) && this.dragPoint == null) { if (e.getWheelRotation() < 0) { Point2D cameraFocus = Game.getScreenManager().getCamera().getFocus(); Point2D newFocus = new Point2D.Double(cameraFocus.getX() - this.scrollSpeed, cameraFocus.getY()); Game.getScreenManager().getCamera().setFocus(newFocus); } else { Point2D cameraFocus = Game.getScreenManager().getCamera().getFocus(); Point2D newFocus = new Point2D.Double(cameraFocus.getX() + this.scrollSpeed, cameraFocus.getY()); Game.getScreenManager().getCamera().setFocus(newFocus); } Program.horizontalScroll.setValue((int) Game.getScreenManager().getCamera().getViewPort().getCenterX()); return; } if (Input.keyboard().isPressed(KeyEvent.VK_ALT)) { if (e.getWheelRotation() < 0) { this.zoomIn(); } else { this.zoomOut(); } return; } if (e.getWheelRotation() < 0) { Point2D cameraFocus = Game.getScreenManager().getCamera().getFocus(); Point2D newFocus = new Point2D.Double(cameraFocus.getX(), cameraFocus.getY() - this.scrollSpeed); Game.getScreenManager().getCamera().setFocus(newFocus); } else { Point2D cameraFocus = Game.getScreenManager().getCamera().getFocus(); Point2D newFocus = new Point2D.Double(cameraFocus.getX(), cameraFocus.getY() + this.scrollSpeed); Game.getScreenManager().getCamera().setFocus(newFocus); } Program.verticalScroll.setValue((int) Game.getScreenManager().getCamera().getViewPort().getCenterY()); }); Input.mouse().onClicked(e -> { if (this.isSuspended() || !this.isVisible()) { return; } }); } private int snapX(double x) { if (!this.snapToGrid) { return MathUtilities.clamp((int) Math.round(x), 0, (int) Game.getEnvironment().getMap().getSizeInPixels().getWidth()); } double snapped = ((int) (x / this.gridSize) * this.gridSize); return (int) Math.round(Math.min(Math.max(snapped, 0), Game.getEnvironment().getMap().getSizeInPixels().getWidth())); } private int snapY(double y) { if (!this.snapToGrid) { return MathUtilities.clamp((int) Math.round(y), 0, (int) Game.getEnvironment().getMap().getSizeInPixels().getHeight()); } double snapped = (int) (y / this.gridSize) * this.gridSize; return (int) Math.round(Math.min(Math.max(snapped, 0), Game.getEnvironment().getMap().getSizeInPixels().getHeight())); } private void updateScrollBars() { Program.horizontalScroll.setMinimum(0); Program.horizontalScroll.setMaximum(Game.getEnvironment().getMap().getSizeInPixels().width); Program.verticalScroll.setMinimum(0); Program.verticalScroll.setMaximum(Game.getEnvironment().getMap().getSizeInPixels().height); Program.horizontalScroll.setValue((int) Game.getScreenManager().getCamera().getViewPort().getCenterX()); Program.verticalScroll.setValue((int) Game.getScreenManager().getCamera().getViewPort().getCenterY()); } private boolean hasFocus() { if (this.isSuspended() || !this.isVisible()) { return false; } for (GuiComponent comp : this.getComponents()) { if (comp.isHovered() && !comp.isSuspended()) { return false; } } return true; } }
package dr.evomodel.continuous; import dr.evolution.tree.MultivariateTraitTree; import dr.evolution.tree.NodeRef; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.DiscretizedBranchRates; import dr.evomodel.tree.TreeModel; import dr.evomodel.tree.TreeStatistic; import dr.geo.math.SphericalPolarCoordinates; import dr.inference.model.Statistic; import dr.math.distributions.MultivariateNormalDistribution; import dr.stats.DiscreteStatistics; import dr.xml.*; import java.util.ArrayList; import java.util.List; /** * @author Marc Suchard * @author Philippe Lemey * @author Andrew Rambaut */ public class DiffusionRateStatistic extends Statistic.Abstract { public static final String DIFFUSION_RATE_STATISTIC = "diffusionRateStatistic"; public static final String TREE_DISPERSION_STATISTIC = "treeDispersionStatistic"; public static final String BOOLEAN_DIS_OPTION = "greatCircleDistance"; public static final String MODE = "mode"; public static final String MEDIAN = "median"; public static final String AVERAGE = "average"; // average over all branches public static final String WEIGHTED_AVERAGE = "weightedAverage"; // weighted average (=total distance/total time) public static final String COEFFICIENT_OF_VARIATION = "coefficientOfVariation"; // weighted average (=total distance/total time) public static final String STATISTIC = "statistic"; public static final String DIFFUSION_RATE = "diffusionRate"; // weighted average (=total distance/total time) public static final String WAVEFRONT_DISTANCE = "wavefrontDistance"; // weighted average (=total distance/total time) public static final String WAVEFRONT_RATE = "wavefrontRate"; // weighted average (=total distance/total time) public static final String DIFFUSION_COEFFICIENT = "diffusionCoefficient"; // public static final String DIFFUSIONCOEFFICIENT = "diffusionCoefficient"; // weighted average (=total distance/total time) // public static final String BOOLEAN_DC_OPTION = "diffusionCoefficient"; public static final String HEIGHT_UPPER = "heightUpper"; public static final String HEIGHT_LOWER = "heightLower"; public DiffusionRateStatistic(String name, List<AbstractMultivariateTraitLikelihood> traitLikelihoods, boolean option, Mode mode, summaryStatistic statistic, double heightUpper, double heightLower) { super(name); this.traitLikelihoods = traitLikelihoods; this.useGreatCircleDistances = option; summaryMode = mode; summaryStat = statistic; this.heightUpper = heightUpper; this.heightLower = heightLower; } public int getDimension() { return 1; } public double getStatisticValue(int dim) { String traitName = traitLikelihoods.get(0).getTraitName(); double treelength = 0; double treeDistance = 0; double maxDistanceFromRoot = 0; double maxDistanceOverTimeFromRoot = 0; //double[] rates = null; List<Double> rates = new ArrayList<Double>(); //double[] diffusionCoefficients = null; List<Double> diffusionCoefficients = new ArrayList<Double>(); double waDiffusionCoefficient = 0; for (AbstractMultivariateTraitLikelihood traitLikelihood : traitLikelihoods) { MultivariateTraitTree tree = traitLikelihood.getTreeModel(); BranchRateModel branchRates = traitLikelihood.getBranchRateModel(); for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); if (node != tree.getRoot()) { NodeRef parentNode = tree.getParent(node); if ((tree.getNodeHeight(parentNode) > heightLower) && (tree.getNodeHeight(node) < heightUpper)) { double[] trait = traitLikelihood.getTraitForNode(tree, node, traitName); double[] parentTrait = traitLikelihood.getTraitForNode(tree, parentNode, traitName); double[] traitUp = parentTrait; double[] traitLow = trait; double timeUp = tree.getNodeHeight(parentNode); double timeLow = tree.getNodeHeight(node); double rate = (branchRates != null ? branchRates.getBranchRate(tree, node) : 1.0); MultivariateDiffusionModel diffModel = traitLikelihood.diffusionModel; double[] precision = diffModel.getPrecisionParameter().getParameterValues(); if (tree.getNodeHeight(parentNode) > heightUpper) { timeUp = heightUpper; //TODO: implement TrueNoise?? traitUp = imputeValue(trait, parentTrait, heightUpper, tree.getNodeHeight(node), tree.getNodeHeight(parentNode), precision, rate, false); } if (tree.getNodeHeight(node) < heightLower) { timeLow = heightLower; traitLow = imputeValue(trait, parentTrait, heightLower, tree.getNodeHeight(node), tree.getNodeHeight(parentNode), precision, rate, false); } double time = timeUp - timeLow; treelength += time; double[] rootTrait = traitLikelihood.getTraitForNode(tree, tree.getRoot(), traitName); if (useGreatCircleDistances && (trait.length == 2)) { // Great Circle distance SphericalPolarCoordinates coord1 = new SphericalPolarCoordinates(traitLow[0], traitLow[1]); SphericalPolarCoordinates coord2 = new SphericalPolarCoordinates(traitUp[0], traitUp[1]); double distance = coord1.distance(coord2); treeDistance += distance; double dc = Math.pow(distance,2)/(4*time); diffusionCoefficients.add(dc); waDiffusionCoefficient += dc*time; rates.add(distance/time); SphericalPolarCoordinates rootCoord = new SphericalPolarCoordinates(rootTrait[0], rootTrait[1]); double tempDistanceFromRoot = rootCoord.distance(coord2); if (tempDistanceFromRoot > maxDistanceFromRoot){ maxDistanceFromRoot = tempDistanceFromRoot; maxDistanceOverTimeFromRoot = tempDistanceFromRoot/(tree.getNodeHeight(tree.getRoot()) - timeLow); //distance between traitLow and traitUp for maxDistanceFromRoot if (timeUp == heightUpper) { maxDistanceFromRoot = distance; maxDistanceOverTimeFromRoot = distance/time; } } } else { double distance = getNativeDistance(traitLow, traitLow); treeDistance += distance; double dc = Math.pow(distance,2)/(4*time); diffusionCoefficients.add(dc); waDiffusionCoefficient += dc*time; rates.add(distance/time); double tempDistanceFromRoot = getNativeDistance(traitLow, rootTrait); if (tempDistanceFromRoot > maxDistanceFromRoot){ maxDistanceFromRoot = tempDistanceFromRoot; maxDistanceOverTimeFromRoot = tempDistanceFromRoot/(tree.getNodeHeight(tree.getRoot()) - timeLow); //distance between traitLow and traitUp for maxDistanceFromRoot if (timeUp == heightUpper) { maxDistanceFromRoot = distance; maxDistanceOverTimeFromRoot = distance/time; } } } } } } } if (summaryStat == summaryStatistic.DIFFUSION_RATE){ if (summaryMode == Mode.AVERAGE) { return DiscreteStatistics.mean(toArray(rates)); } else if (summaryMode == Mode.MEDIAN) { return DiscreteStatistics.median(toArray(rates)); } else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) { // don't compute mean twice final double mean = DiscreteStatistics.mean(toArray(rates)); return Math.sqrt(DiscreteStatistics.variance(toArray(rates), mean)) / mean; } else { return treeDistance / treelength; } } else if (summaryStat == summaryStatistic.DIFFUSION_COEFFICIENT) { if (summaryMode == Mode.AVERAGE) { return DiscreteStatistics.mean(toArray(diffusionCoefficients)); } else if (summaryMode == Mode.MEDIAN) { return DiscreteStatistics.median(toArray(diffusionCoefficients)); } else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) { // don't compute mean twice final double mean = DiscreteStatistics.mean(toArray(diffusionCoefficients)); return Math.sqrt(DiscreteStatistics.variance(toArray(diffusionCoefficients), mean)) / mean; } else { return waDiffusionCoefficient/treelength; } } else if (summaryStat == summaryStatistic.WAVEFRONT_DISTANCE) { return maxDistanceFromRoot; } else { return maxDistanceOverTimeFromRoot; } } // private double getNativeDistance(double[] location1, double[] location2) { // return Math.sqrt(Math.pow((location2[0] - location1[0]), 2.0) + Math.pow((location2[1] - location1[1]), 2.0)); private double getNativeDistance(double[] location1, double[] location2) { int traitDimension = location1.length; double sum = 0; for (int i = 0; i < traitDimension; i++) { sum += Math.pow((location2[i] - location1[i]),2); } return Math.sqrt(sum); } private double[] toArray(List<Double> list) { double[] returnArray = new double[list.size()]; for (int i = 0; i < list.size(); i++) { returnArray[i] = Double.valueOf(list.get(i).toString()); } return returnArray; } private double[] imputeValue(double[] nodeValue, double[] parentValue, double time, double nodeHeight, double parentHeight, double[] precisionArray, double rate, boolean trueNoise) { final double scaledTimeChild = (time - nodeHeight) * rate; final double scaledTimeParent = (parentHeight - time) * rate; final double scaledWeightTotal = 1.0 / scaledTimeChild + 1.0 / scaledTimeParent; final int dim = nodeValue.length; double[][] precision = new double[dim][dim]; int counter = 0; for (int a = 0; a < dim; a++){ for (int b = 0; b < dim; b++){ precision[a][b] = precisionArray[counter]; counter++ ; } } if (scaledTimeChild == 0) return nodeValue; if (scaledTimeParent == 0) return parentValue; // Find mean value, weighted average double[] mean = new double[dim]; double[][] scaledPrecision = new double[dim][dim]; for (int i = 0; i < dim; i++) { mean[i] = (nodeValue[i] / scaledTimeChild + parentValue[i] / scaledTimeParent) / scaledWeightTotal; if (trueNoise) { for (int j = i; j < dim; j++) scaledPrecision[j][i] = scaledPrecision[i][j] = precision[i][j] * scaledWeightTotal; } } // System.out.print(time+"\t"+nodeHeight+"\t"+parentHeight+"\t"+scaledTimeChild+"\t"+scaledTimeParent+"\t"+scaledWeightTotal+"\t"+mean[0]+"\t"+mean[1]+"\t"+scaledPrecision[0][0]+"\t"+scaledPrecision[0][1]+"\t"+scaledPrecision[1][0]+"\t"+scaledPrecision[1][1]); if (trueNoise) { mean = MultivariateNormalDistribution.nextMultivariateNormalPrecision(mean, scaledPrecision); } // System.out.println("\t"+mean[0]+"\t"+mean[1]+"\r"); double[] result = new double[dim]; for (int i = 0; i < dim; i++) result[i] = mean[i]; return result; } enum Mode { AVERAGE, WEIGHTED_AVERAGE, MEDIAN, COEFFICIENT_OF_VARIATION } enum summaryStatistic { DIFFUSION_RATE, DIFFUSION_COEFFICIENT, WAVEFRONT_DISTANCE, WAVEFRONT_RATE, } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return DIFFUSION_RATE_STATISTIC; } @Override public String[] getParserNames() { return new String[]{getParserName(), TREE_DISPERSION_STATISTIC}; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { String name = xo.getAttribute(NAME, xo.getId()); boolean option = xo.getAttribute(BOOLEAN_DIS_OPTION, false); // Default value is false Mode averageMode; String mode = xo.getAttribute(MODE, WEIGHTED_AVERAGE); if (mode.equals(AVERAGE)) { averageMode = Mode.AVERAGE; } else if (mode.equals(MEDIAN)) { averageMode = Mode.MEDIAN; } else if (mode.equals(COEFFICIENT_OF_VARIATION)) { averageMode = Mode.COEFFICIENT_OF_VARIATION; } else if (mode.equals(WEIGHTED_AVERAGE)) { averageMode = Mode.WEIGHTED_AVERAGE; } else { System.err.println("Unknown mode: "+mode+". Reverting to weighted average"); averageMode = Mode.WEIGHTED_AVERAGE; } // boolean diffCoeff = xo.getAttribute(BOOLEAN_DC_OPTION, false); // Default value is false summaryStatistic summaryStat; String statistic = xo.getAttribute(STATISTIC, DIFFUSION_RATE); if (statistic.equals(DIFFUSION_RATE)) { summaryStat = summaryStatistic.DIFFUSION_RATE; } else if (statistic.equals(WAVEFRONT_DISTANCE)) { summaryStat = summaryStatistic.WAVEFRONT_DISTANCE; } else if (statistic.equals(WAVEFRONT_RATE)) { summaryStat = summaryStatistic.WAVEFRONT_RATE; } else if (statistic.equals(DIFFUSION_COEFFICIENT)) { summaryStat = summaryStatistic.DIFFUSION_COEFFICIENT; } else { System.err.println("Unknown statistic: "+statistic+". Reverting to diffusion rate"); summaryStat = summaryStatistic.DIFFUSION_COEFFICIENT; } final double upperHeight = xo.getAttribute(HEIGHT_UPPER, Double.MAX_VALUE); final double lowerHeight = xo.getAttribute(HEIGHT_LOWER, 0.0); List<AbstractMultivariateTraitLikelihood> traitLikelihoods = new ArrayList<AbstractMultivariateTraitLikelihood>(); for (int i = 0; i < xo.getChildCount(); i++) { if (xo.getChild(i) instanceof AbstractMultivariateTraitLikelihood) { AbstractMultivariateTraitLikelihood amtl = (AbstractMultivariateTraitLikelihood) xo.getChild(i); traitLikelihoods.add(amtl); } } return new DiffusionRateStatistic(name, traitLikelihoods, option, averageMode, summaryStat, upperHeight, lowerHeight); }