answer
stringlengths
17
10.2M
package tests.examples; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.HashMap; import org.junit.Test; import jsystem.framework.ParameterProperties; import jsystem.framework.TestProperties; import jsystem.framework.report.Reporter; import jsystem.framework.scenario.Parameter; import jsystem.framework.scenario.UseProvider; import junit.framework.SystemTestCase4; public class TestsExamples extends SystemTestCase4 { public enum HarryPotterBook { Philosophers_Stone, Chamber_of_Secrets, Prisoner_of_Azkaban, Goblet_of_Fire, Order_of_the_Phoenix, Half_Blood_Prince, Deathly_Hallows } // Test parameters can also have default values private File file = new File("."); private String str = "Some string"; private int i = 5; private Date date = new Date(); private String[] strArr; private Account account; private Account[] accountArr; private HarryPotterBook book = HarryPotterBook.Chamber_of_Secrets; private String[] books; // Parameters in sections. See the @ParameterProperties of each of the // parameters setters private int intInSection9; private String strInSection9; private File fileInSection9; // Parameters for showing how to control parameter properties - see // handleUiEvent method private boolean setEditable; private boolean setVisible; private String canYouSeeMe; private String canYouEditMe; /** * Test with success report */ @Test @TestProperties(name = "Report Success", paramsInclude = { "" }) public void reportSuccess() { report.report("Success"); } /** * Test with failure report */ @Test @TestProperties(name = "Report Failure", paramsInclude = { "" }) public void reportFailure() { report.report("Failure", false); } /** * Test with error report * * @throws Exception */ @Test @TestProperties(name = "Report Error", paramsInclude = { "" }) public void reportError() throws Exception { report.report("Error"); throw new Exception("Error"); } /** * Test with warning report */ @Test @TestProperties(name = "Report Warning", paramsInclude = { "" }) public void reportWarning() { report.report("Warning", Reporter.WARNING); } /** * Test with different parameters */ @Test @TestProperties(name = "Test with file '${file}' string '${str}' integer ${i} date ${date}", paramsInclude = { "file", "str", "i", "date", "strArr", "book", "intInSection9", "strInSection9", "fileInSection9","books" }) public void testWithParameters() { report.report("File: " + file.getAbsolutePath()); report.report("Date: " + date.toString()); report.report("String: " + str); report.report("Integer: " + i); } /** * Test with levels * * @throws IOException */ @Test @TestProperties(name = "Report With Levels", paramsInclude = { "" }) public void reportWithLevels() throws IOException { report.startLevel("Starting level", 2); try { report.report("Inside level"); report.report("Inside level"); report.startLevel("Starting level", 2); try { report.report("Inside level"); } finally { report.stopLevel(); } report.report("Inside level"); } finally { // We would like it in a finally block in case an exception is // thrown before the stop level happens. report.stopLevel(); } } /** * Test with parameter provider */ @Test @TestProperties(name = "Test with parameter provider", paramsInclude = { "account", "accountArr" }) public void testWithParameterProvider() { } /** * Use JSystem handleUiEvent method to control the <b>visibility</b> and * <b>editability</b> of parameters. To see the effect, change the values of * the setEditable and setVisible parameters. * */ @Test @TestProperties(name = "Control different parametrs attributes", paramsInclude = { "setEditable", "setVisible", "canYouSeeMe", "canYouEditMe" }) public void controlParametersAttributes() { report.report("Using handle UI event for controlling parameters attibutes"); } @Override public void handleUIEvent(HashMap<String, Parameter> map, String methodName) throws Exception { // Making sure that the event is only for the correct building block if (methodName.equals("controlParametersAttributes")) { Parameter setEditableParam = map.get("SetEditable"); if (setEditableParam.getValue().toString().equals("true")) { map.get("CanYouEditMe").setEditable(true); } else { map.get("CanYouEditMe").setEditable(false); } Parameter setVisibleParam = map.get("SetVisible"); if (setVisibleParam.getValue().toString().equals("true")) { map.get("CanYouSeeMe").setVisible(true); } else { map.get("CanYouSeeMe").setVisible(false); } } } public boolean isSetEditable() { return setEditable; } public void setSetEditable(boolean setEditable) { this.setEditable = setEditable; } public boolean isSetVisible() { return setVisible; } public void setSetVisible(boolean setVisible) { this.setVisible = setVisible; } public File getFile() { return file; } @ParameterProperties(description = "File Parameter") public void setFile(File file) { this.file = file; } public String getStr() { return str; } @ParameterProperties(description = "String Parameter") public void setStr(String str) { this.str = str; } public int getI() { return i; } @ParameterProperties(description = "Integer Parameter") public void setI(int i) { this.i = i; } public Date getDate() { return date; } @ParameterProperties(description = "Java Date Parameter") public void setDate(Date date) { this.date = date; } public String[] getStrArr() { return strArr; } @ParameterProperties(description = "String Array Parameter") public void setStrArr(String[] strArr) { this.strArr = strArr; } public Account getAccount() { return account; } @ParameterProperties(description = "Provider that exposes bean") @UseProvider(provider = jsystem.extensions.paramproviders.GenericObjectParameterProvider.class) public void setAccount(Account account) { this.account = account; } public Account[] getAccountArr() { return accountArr; } @ParameterProperties(description = "Provider that exposes bean array") @UseProvider(provider = jsystem.extensions.paramproviders.ObjectArrayParameterProvider.class) public void setAccountArr(Account[] accountArr) { this.accountArr = accountArr; } public HarryPotterBook getBook() { return book; } @ParameterProperties(description = "Harry Potter Book") public void setBook(HarryPotterBook book) { this.book = book; } public String getCanYouSeeMe() { return canYouSeeMe; } public void setCanYouSeeMe(String canYouSeeMe) { this.canYouSeeMe = canYouSeeMe; } public String getCanYouEditMe() { return canYouEditMe; } public void setCanYouEditMe(String canYouEditMe) { this.canYouEditMe = canYouEditMe; } public int getIntInSection9() { return intInSection9; } @ParameterProperties(section = "Section9") public void setIntInSection9(int intInSection9) { this.intInSection9 = intInSection9; } public String getStrInSection9() { return strInSection9; } @ParameterProperties(section = "Section9") public void setStrInSection9(String strInSection9) { this.strInSection9 = strInSection9; } public File getFileInSection9() { return fileInSection9; } @ParameterProperties(section = "Section9") public void setFileInSection9(File fileInSection9) { this.fileInSection9 = fileInSection9; } /** * @see getBooksOptions * @return */ public String[] getBooks() { return books; } @ParameterProperties(description = "Multiple selection example") public void setBooks(String[] books) { this.books = books; } public String[] getBooksOptions() { return new String[] { HarryPotterBook.Chamber_of_Secrets.name(), HarryPotterBook.Deathly_Hallows.name(), HarryPotterBook.Half_Blood_Prince.name(), HarryPotterBook.Goblet_of_Fire.name(), HarryPotterBook.Order_of_the_Phoenix.name(), HarryPotterBook.Philosophers_Stone.name(), HarryPotterBook.Prisoner_of_Azkaban.name() }; } }
// Nexus Core - a framework for developing distributed applications package com.samskivert.nexus.util; /** * Handles logging for the Nexus code. */ public class Log { /** A level of indirection that allows us to plug in Java or GWT-based logging. */ public interface Logger { /** Logs an info level message, with the supplied arguments and optional Throwable cause in * final position. For example: * {@code log.info("Thing happened", "info", data, "also", moredata);} */ void info (String message, Object... args); /** Logs a warning level message, with the supplied arguments and optional Throwable cause * in final position. For example: * {@code log.info("Bad thing happened", "info", data, cause);} */ void warning (String message, Object... args); /** Implementation detail that's easier to expose here; please ignore. */ void log (Object level, String message, Throwable cause); /** Disables info logging, shows only warnings and above. */ void setWarnOnly (); } // TODO: some secret static initialization that wires up either a Java logger or GWT depending // on where we're running /** Dispatch log messages through this instance. */ public static final Logger log = new JavaLogger("nexus"); private Log () {} // no constructsky protected static void format (Logger logger, Object level, String message, Object... args) { StringBuilder sb = new StringBuilder(); sb.append(message); if (args.length > 1) { sb.append(" ["); for (int ii = 0, ll = args.length/2; ii < ll; ii++) { if (ii > 0) { sb.append(", "); } sb.append(args[2*ii]).append("=").append(args[2*ii+1]); } sb.append("]"); } Object last = (args.length % 2 == 1) ? args[args.length-1] : null; Throwable cause = (last instanceof Throwable) ? (Throwable)last : null; logger.log(level, sb.toString(), cause); } protected static class JavaLogger implements Logger { public JavaLogger (String name) { _impl = java.util.logging.Logger.getLogger(name); } public void info (String message, Object... args) { if (_impl.isLoggable(java.util.logging.Level.INFO)) { format(this, java.util.logging.Level.INFO, message, args); } } public void warning (String message, Object... args) { if (_impl.isLoggable(java.util.logging.Level.WARNING)) { format(this, java.util.logging.Level.WARNING, message, args); } } public void log (Object level, String message, Throwable cause) { _impl.log((java.util.logging.Level)level, message, cause); } public void setWarnOnly () { _impl.setLevel(java.util.logging.Level.WARNING); } protected final java.util.logging.Logger _impl; } }
package hudson.tasks.junit; import hudson.model.AbstractBuild; import hudson.util.IOException2; import hudson.*; import org.apache.tools.ant.DirectoryScanner; import org.dom4j.DocumentException; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.export.Exported; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * Root of all the test results for one build. * * @author Kohsuke Kawaguchi */ public final class TestResult extends MetaTabulatedResult { /** * List of all {@link SuiteResult}s in this test. * This is the core data structure to be persisted in the disk. */ private final List<SuiteResult> suites = new ArrayList<SuiteResult>(); /** * {@link #suites} keyed by their names for faster lookup. */ private transient Map<String,SuiteResult> suitesByName; /** * Results tabulated by package. */ private transient Map<String,PackageResult> byPackages; // set during the freeze phase private transient TestResultAction parent; /** * Number of all tests. */ private transient int totalTests; private transient int skippedTests; private float duration; /** * Number of failed/error tests. */ private transient List<CaseResult> failedTests; /** * Creates an empty result. */ TestResult() { } /** * Collect reports from the given {@link DirectoryScanner}, while * filtering out all files that were created before the given time. */ public TestResult(long buildTime, DirectoryScanner results) throws IOException { parse(buildTime, results); } /** * Collect reports from the given {@link DirectoryScanner}, while * filtering out all files that were created before the given time. */ public void parse(long buildTime, DirectoryScanner results) throws IOException { String[] includedFiles = results.getIncludedFiles(); File baseDir = results.getBasedir(); boolean parsed=false; for (String value : includedFiles) { File reportFile = new File(baseDir, value); // only count files that were actually updated during this build if(buildTime-1000/*error margin*/ <= reportFile.lastModified()) { if(reportFile.length()==0) { // this is a typical problem when JVM quits abnormally, like OutOfMemoryError during a test. SuiteResult sr = new SuiteResult(reportFile.getName(), "", ""); sr.addCase(new CaseResult(sr,"<init>","Test report file "+reportFile.getAbsolutePath()+" was length 0")); add(sr); } else { parse(reportFile); } parsed = true; } } if(!parsed) { long localTime = System.currentTimeMillis(); if(localTime < buildTime-1000) /*margin*/ // build time is in the the future. clock on this slave must be running behind throw new AbortException( "Clock on this slave is out of sync with the master, and therefore \n" + "I can't figure out what test results are new and what are old.\n" + "Please keep the slave clock in sync with the master."); File f = new File(baseDir,includedFiles[0]); throw new AbortException( String.format( "Test reports were found but none of them are new. Did tests run? \n"+ "For example, %s is %s old\n", f, Util.getTimeSpanString(buildTime-f.lastModified()))); } } private void add(SuiteResult sr) { for (SuiteResult s : suites) { // a common problem is that people parse TEST-*.xml as well as TESTS-TestSuite.xml if(s.getName().equals(sr.getName()) && eq(s.getTimestamp(),sr.getTimestamp())) return; // duplicate } suites.add(sr); duration += sr.getDuration(); } private boolean eq(Object lhs, Object rhs) { return lhs != null && rhs != null && lhs.equals(rhs); } /** * Parses an additional report file. */ public void parse(File reportFile) throws IOException { try { for( SuiteResult suiteResult : SuiteResult.parse(reportFile) ) add(suiteResult); } catch (RuntimeException e) { throw new IOException2("Failed to read "+reportFile,e); } catch (DocumentException e) { if(!reportFile.getPath().endsWith(".xml")) throw new IOException2("Failed to read "+reportFile+"\n"+ "Is this really a JUnit report file? Your configuration must be matching too many files",e); else throw new IOException2("Failed to read "+reportFile,e); } } public String getDisplayName() { return "Test Result"; } public AbstractBuild<?,?> getOwner() { return parent.owner; } @Override public TestResult getPreviousResult() { TestResultAction p = parent.getPreviousResult(); if(p!=null) return p.getResult(); else return null; } public String getTitle() { return Messages.TestResult_getTitle(); } public String getChildTitle() { return Messages.TestResult_getChildTitle(); } // TODO once stapler 1.60 is released: @Exported public float getDuration() { return duration; } @Exported(visibility=999) @Override public int getPassCount() { return totalTests-getFailCount()-getSkipCount(); } @Exported(visibility=999) @Override public int getFailCount() { return failedTests.size(); } @Exported @Override public int getSkipCount() { return skippedTests; } @Override public List<CaseResult> getFailedTests() { return failedTests; } @Override @Exported(name="child",inline=true) public Collection<PackageResult> getChildren() { return byPackages.values(); } public PackageResult getDynamic(String packageName, StaplerRequest req, StaplerResponse rsp) { return byPackage(packageName); } public PackageResult byPackage(String packageName) { return byPackages.get(packageName); } public SuiteResult getSuite(String name) { return suitesByName.get(name); } /** * Builds up the transient part of the data structure * from results {@link #parse(File) parsed} so far. * * <p> * After the data is frozen, more files can be parsed * and then freeze can be called again. */ public void freeze(TestResultAction parent) { this.parent = parent; if(suitesByName==null) { // freeze for the first time suitesByName = new HashMap<String,SuiteResult>(); totalTests = 0; failedTests = new ArrayList<CaseResult>(); byPackages = new TreeMap<String,PackageResult>(); } for (SuiteResult s : suites) { if(!s.freeze(this)) continue; suitesByName.put(s.getName(),s); totalTests += s.getCases().size(); for(CaseResult cr : s.getCases()) { if(cr.isSkipped()) skippedTests++; else if(!cr.isPassed()) failedTests.add(cr); String pkg = cr.getPackageName(); PackageResult pr = byPackage(pkg); if(pr==null) byPackages.put(pkg,pr=new PackageResult(this,pkg)); pr.add(cr); } } Collections.sort(failedTests,CaseResult.BY_AGE); for (PackageResult pr : byPackages.values()) pr.freeze(); } private static final long serialVersionUID = 1L; }
package io.bisq.core.btc; import io.bisq.core.app.BisqEnvironment; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class BitcoinNodes { public enum BitcoinNodesOption { PROVIDED, CUSTOM, PUBLIC } // For other base currencies or testnet we ignore provided nodes public List<BtcNode> getProvidedBtcNodes() { return useProvidedBtcNodes() ? Arrays.asList( BtcNode.fromHostNameAndAddress("bitcoin.christophatteneder.com", "174.138.35.229", "https://github.com/ripcurlx"), BtcNode.fromHostName("btc.beams.io", "https://github.com/cbeams"), // 62.178.187.80 BtcNode.fromHostNameAndAddress("kirsche.emzy.de", "78.47.61.83", "https://github.com/emzy"), BtcNode.fromHostName("poyvpdt762gllauu.onion", "https://github.com/emzy"), BtcNode.fromHostName("3r44ddzjitznyahw.onion", "https://github.com/sqrrm"), BtcNode.fromHostName("i3a5xtzfm4xwtybd.onion", "https://github.com/sqrrm"), BtcNode.fromHostName("r3dsojfhwcm7x7p6.onion", "https://github.com/alexej996"), BtcNode.fromHostName("vlf5i3grro3wux24.onion", "https://github.com/alexej996"), BtcNode.fromHostNameAndAddress("bcwat.ch", "5.189.166.193", "https://github.com/sgeisler"), BtcNode.fromHostNameAndAddress("btc.jochen-hoenicke.de", "37.221.198.57", "https://github.com/jhoenicke"), BtcNode.fromHostNameAndAddress("btc.vante.me", "138.68.117.247", "https://github.com/mrosseel"), BtcNode.fromHostName("mxdtrjhe2yfsx3pg.onion", "https://github.com/mrosseel"), BtcNode.fromHostNameAndAddress("bitcoin4-fullnode.csg.uzh.ch", "192.41.136.217", "https://github.com/tbocek") ) : new ArrayList<>(); } public boolean useProvidedBtcNodes() { return BisqEnvironment.getBaseCurrencyNetwork().isBitcoin() && BisqEnvironment.getBaseCurrencyNetwork().isMainnet(); } @Getter @ToString public static class BtcNode { @Nullable private final String hostName; @Nullable private final String operator; // null in case the user provides a list of custom btc nodes @Nullable private final String address; // IPv4 address private int port = BisqEnvironment.getParameters().getPort(); /** * @param fullAddress [hostName:port | IPv4 address:port] * @return BtcNode instance */ public static BtcNode fromFullAddress(String fullAddress) { String[] parts = fullAddress.split(":"); checkArgument(parts.length > 0); if (parts.length == 1) { return BtcNode.fromHostName(parts[0], null); } else { checkArgument(parts.length == 2); return BtcNode.fromHostNameAndPort(parts[0], Integer.valueOf(parts[1]), null); } } public static BtcNode fromHostName(String hostName, @Nullable String operator) { return new BtcNode(hostName, null, operator); } public static BtcNode fromAddress(String address, @Nullable String operator) { return new BtcNode(null, address, operator); } public static BtcNode fromHostNameAndPort(String hostName, int port, @Nullable String operator) { return new BtcNode(hostName, null, port, operator); } public static BtcNode fromHostNameAndAddress(String hostName, String address, @Nullable String operator) { return new BtcNode(hostName, address, operator); } private BtcNode(@Nullable String hostName, @Nullable String address, int port, @Nullable String operator) { this.hostName = hostName; this.address = address; this.port = port; this.operator = operator; if (address == null) checkNotNull(hostName, "hostName must not be null if address is null"); else if (hostName == null) checkNotNull(address, "address must not be null if hostName is null"); } private BtcNode(@Nullable String hostName, @Nullable String address, @Nullable String operator) { this.hostName = hostName; this.address = address; this.operator = operator; if (address == null) checkNotNull(hostName, "hostName must not be null if address is null"); else if (hostName == null) checkNotNull(address, "address must not be null if hostName is null"); } public boolean isHiddenService() { return hostName != null && hostName.endsWith("onion"); } public String getHostAddressOrHostName() { if (address != null) return address; else return hostName; } } }
package org.kohsuke.stapler; import net.sf.json.JSONArray; import org.apache.commons.io.IOUtils; import org.kohsuke.stapler.bind.JavaScriptMethod; import org.kohsuke.stapler.lang.Klass; import org.kohsuke.stapler.lang.MethodRef; import javax.annotation.PostConstruct; import javax.servlet.ServletException; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import static javax.servlet.http.HttpServletResponse.*; public class MetaClass extends TearOffSupport { /** * This meta class wraps this class * * @deprecated as of 1.177 * Use {@link #klass}. If you really want the Java class representation, use {@code klass.toJavaClass()}. */ public final Class clazz; public final Klass<?> klass; /** * {@link MetaClassLoader} that wraps {@code clazz.getClassLoader()}. * Null if the class is loaded by the bootstrap classloader. */ public final MetaClassLoader classLoader; public final List<Dispatcher> dispatchers = new ArrayList<Dispatcher>(); /** * Base metaclass. * Note that <tt>baseClass.clazz==clazz.getSuperClass()</tt> */ public final MetaClass baseClass; /** * {@link WebApp} that owns this meta class. */ public final WebApp webApp; /** * If there's a method annotated with @PostConstruct, that {@link MethodRef} object, linked * to the list of the base class. */ private volatile SingleLinkedList<MethodRef> postConstructMethods; /*package*/ MetaClass(WebApp webApp, Klass<?> klass) { this.clazz = klass.toJavaClass(); this.klass = klass; this.webApp = webApp; this.baseClass = webApp.getMetaClass(klass.getSuperClass()); this.classLoader = MetaClassLoader.get(clazz.getClassLoader()); buildDispatchers(); } /** * Build {@link #dispatchers}. * * <p> * This is the meat of URL dispatching. It looks at the class * via reflection and figures out what URLs are handled by who. */ /*package*/ void buildDispatchers() { this.dispatchers.clear(); ClassDescriptor node = new ClassDescriptor(clazz,null/*TODO:support wrappers*/); // check action <obj>.do<token>(...) for( final Function f : node.methods.prefix("do") ) { WebMethod a = f.getAnnotation(WebMethod.class); String[] names; if(a!=null && a.name().length>0) names=a.name(); else names=new String[]{camelize(f.getName().substring(2))}; // 'doFoo' -> 'foo' for (String name : names) { dispatchers.add(new NameBasedDispatcher(name,0) { public boolean doDispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IllegalAccessException, InvocationTargetException, ServletException, IOException { if(traceable()) trace(req,rsp,"-> <%s>.%s(...)",node,f.getName()); return f.bindAndInvokeAndServeResponse(node, req, rsp); } public String toString() { return f.getQualifiedName()+"(...) for url=/"+name+"/..."; } }); } } // JavaScript proxy method invocations for <obj>js<token> // reacts only to a specific content type for( final Function f : node.methods.prefix("js") ) { String name = camelize(f.getName().substring(2)); // jsXyz -> xyz dispatchers.add(new JavaScriptProxyMethodDispatcher(name, f)); } // JavaScript proxy method with @JavaScriptMethod // reacts only to a specific content type for( final Function f : node.methods.annotated(JavaScriptMethod.class) ) { JavaScriptMethod a = f.getAnnotation(JavaScriptMethod.class); String[] names; if(a!=null && a.name().length>0) names=a.name(); else names=new String[]{f.getName()}; for (String name : names) dispatchers.add(new JavaScriptProxyMethodDispatcher(name,f)); } for (Facet f : webApp.facets) f.buildViewDispatchers(this, dispatchers); // check action <obj>.doIndex(...) for( final Function f : node.methods.name("doIndex") ) { dispatchers.add(new Dispatcher() { public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IllegalAccessException, InvocationTargetException, ServletException, IOException { if(req.tokens.hasMore()) return false; // applicable only when there's no more token if(traceable()) trace(req,rsp,"-> <%s>.doIndex(...)",node); return f.bindAndInvokeAndServeResponse(node,req,rsp); } public String toString() { return f.getQualifiedName()+"(StaplerRequest,StaplerResponse) for url=/"; } }); } // check public properties of the form NODE.TOKEN for (final Field f : node.fields) { dispatchers.add(new NameBasedDispatcher(f.getName()) { final String role = getProtectedRole(f); public boolean doDispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException, IllegalAccessException { if(role!=null && !req.isUserInRole(role)) throw new IllegalAccessException("Needs to be in role "+role); if(traceable()) traceEval(req,rsp,node,f.getName()); req.getStapler().invoke(req, rsp, f.get(node)); return true; } public String toString() { return String.format("%1$s.%2$s for url=/%2$s/...",f.getDeclaringClass().getName(),f.getName()); } }); } FunctionList getMethods = node.methods.prefix("get"); // check public selector methods of the form NODE.getTOKEN() for( final Function f : getMethods.signature() ) { if(f.getName().length()<=3) continue; WebMethod a = f.getAnnotation(WebMethod.class); String[] names; if(a!=null && a.name().length>0) names=a.name(); else names=new String[]{camelize(f.getName().substring(3))}; // 'getFoo' -> 'foo' for (String name : names) { dispatchers.add(new NameBasedDispatcher(name) { public boolean doDispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException, IllegalAccessException, InvocationTargetException { if(traceable()) traceEval(req,rsp,node,f.getName()+"()"); req.getStapler().invoke(req,rsp, f.invoke(req, rsp, node)); return true; } public String toString() { return String.format("%1$s() for url=/%2$s/...",f.getQualifiedName(),name); } }); } } // check public selector methods of the form static NODE.getTOKEN(StaplerRequest) for( final Function f : getMethods.signature(StaplerRequest.class) ) { if(f.getName().length()<=3) continue; String name = camelize(f.getName().substring(3)); // 'getFoo' -> 'foo' dispatchers.add(new NameBasedDispatcher(name) { public boolean doDispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException, IllegalAccessException, InvocationTargetException { if(traceable()) traceEval(req,rsp,node,f.getName()+"(...)"); req.getStapler().invoke(req,rsp, f.invoke(req, rsp, node, req)); return true; } public String toString() { return String.format("%1$s(StaplerRequest) for url=/%2$s/...",f.getQualifiedName(),name); } }); } // check public selector methods <obj>.get<Token>(String) for( final Function f : getMethods.signature(String.class) ) { if(f.getName().length()<=3) continue; String name = camelize(f.getName().substring(3)); // 'getFoo' -> 'foo' dispatchers.add(new NameBasedDispatcher(name,1) { public boolean doDispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException, IllegalAccessException, InvocationTargetException { String token = req.tokens.next(); if(traceable()) traceEval(req,rsp,node,f.getName()+"(\""+token+"\")"); req.getStapler().invoke(req,rsp, f.invoke(req, rsp, node,token)); return true; } public String toString() { return String.format("%1$s(String) for url=/%2$s/TOKEN/...",f.getQualifiedName(),name); } }); } // check public selector methods <obj>.get<Token>(int) for( final Function f : getMethods.signature(int.class) ) { if(f.getName().length()<=3) continue; String name = camelize(f.getName().substring(3)); // 'getFoo' -> 'foo' dispatchers.add(new NameBasedDispatcher(name,1) { public boolean doDispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException, IllegalAccessException, InvocationTargetException { int idx = req.tokens.nextAsInt(); if(traceable()) traceEval(req,rsp,node,f.getName()+"("+idx+")"); req.getStapler().invoke(req,rsp, f.invoke(req, rsp, node,idx)); return true; } public String toString() { return String.format("%1$s(int) for url=/%2$s/N/...",f.getQualifiedName(),name); } }); } if(node.clazz.isArray()) { dispatchers.add(new Dispatcher() { public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException { if(!req.tokens.hasMore()) return false; try { int index = req.tokens.nextAsInt(); if(traceable()) traceEval(req,rsp,node,"((Object[])",")["+index+"]"); req.getStapler().invoke(req,rsp, ((Object[]) node)[index]); return true; } catch (NumberFormatException e) { return false; // try next } } public String toString() { return "Array look-up for url=/N/..."; } }); } if(List.class.isAssignableFrom(node.clazz)) { dispatchers.add(new Dispatcher() { public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException { if(!req.tokens.hasMore()) return false; try { int index = req.tokens.nextAsInt(); if(traceable()) traceEval(req,rsp,node,"((List)",").get("+index+")"); List list = (List) node; if (0<=index && index<list.size()) req.getStapler().invoke(req,rsp, list.get(index)); else { if(traceable()) trace(req,rsp,"-> IndexOutOfRange [0,%d)",list.size()); rsp.sendError(SC_NOT_FOUND); } return true; } catch (NumberFormatException e) { return false; // try next } } public String toString() { return "List.get(int) look-up for url=/N/..."; } }); } if(Map.class.isAssignableFrom(node.clazz)) { dispatchers.add(new Dispatcher() { public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IOException, ServletException { if(!req.tokens.hasMore()) return false; try { String key = req.tokens.peek(); if(traceable()) traceEval(req,rsp,"((Map)",").get(\""+key+"\")"); Object item = ((Map)node).get(key); if(item!=null) { req.tokens.next(); req.getStapler().invoke(req,rsp,item); return true; } else { // otherwise just fall through if(traceable()) trace(req,rsp,"Map.get(\""+key+"\")==null. Back tracking."); return false; } } catch (NumberFormatException e) { return false; // try next } } public String toString() { return "Map.get(String) look-up for url=/TOKEN/..."; } }); } // TODO: check if we can route to static resources // which directory shall we look up a resource from? for (Facet f : webApp.facets) f.buildFallbackDispatchers(this, dispatchers); // check action <obj>.doDynamic(...) for( final Function f : node.methods.name("doDynamic") ) { dispatchers.add(new Dispatcher() { public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IllegalAccessException, InvocationTargetException, ServletException, IOException { if(traceable()) trace(req,rsp,"-> <%s>.doDynamic(...)",node); return f.bindAndInvokeAndServeResponse(node,req,rsp); } public String toString() { return String.format("%s(StaplerRequest,StaplerResponse) for any URL",f.getQualifiedName()); } }); } // check public selector methods <obj>.getDynamic(<token>,...) for( final Function f : getMethods.signatureStartsWith(String.class).name("getDynamic")) { dispatchers.add(new Dispatcher() { public boolean dispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IllegalAccessException, InvocationTargetException, IOException, ServletException { if(!req.tokens.hasMore()) return false; String token = req.tokens.next(); if(traceable()) traceEval(req,rsp,node,"getDynamic(\""+token+"\",...)"); Object target = f.bindAndInvoke(node, req,rsp, token); if(target!=null) { req.getStapler().invoke(req,rsp, target); return true; } else { if(traceable()) // indent: "-> evaluate( trace(req,rsp," %s.getDynamic(\"%s\",...)==null. Back tracking.",node,token); req.tokens.prev(); // cancel the next effect return false; } } public String toString() { return String.format("%s(String,StaplerRequest,StaplerResponse) for url=/TOKEN/...",f.getQualifiedName()); } }); } } /** * Returns all the methods in the ancestory chain annotated with {@link PostConstruct} * from those defined in the derived type toward those defined in the base type. * * Normally invocation requires visiting the list in the reverse order. * @since 1.220 */ public SingleLinkedList<MethodRef> getPostConstructMethods() { if (postConstructMethods ==null) { SingleLinkedList<MethodRef> l = baseClass==null ? SingleLinkedList.<MethodRef>empty() : baseClass.getPostConstructMethods(); for (MethodRef mr : klass.getDeclaredMethods()) { if (mr.hasAnnotation(PostConstruct.class)) { l = l.grow(mr); } } postConstructMethods = l; } return postConstructMethods; } private String getProtectedRole(Field f) { try { LimitedTo a = f.getAnnotation(LimitedTo.class); return (a!=null)?a.value():null; } catch (LinkageError e) { return null; // running in JDK 1.4 } } private static String camelize(String name) { return Character.toLowerCase(name.charAt(0))+name.substring(1); } private static class JavaScriptProxyMethodDispatcher extends NameBasedDispatcher { private final Function f; public JavaScriptProxyMethodDispatcher(String name, Function f) { super(name, 0); this.f = f; } public boolean doDispatch(RequestImpl req, ResponseImpl rsp, Object node) throws IllegalAccessException, InvocationTargetException, ServletException, IOException { if (!req.isJavaScriptProxyCall()) return false; req.stapler.getWebApp().getCrumbIssuer().validateCrumb(req,req.getHeader("Crumb")); if(traceable()) trace(req,rsp,"-> <%s>.%s(...)",node, f.getName()); JSONArray jsargs = JSONArray.fromObject(IOUtils.toString(req.getReader())); Object[] args = new Object[jsargs.size()]; Class[] types = f.getParameterTypes(); Type[] genericTypes = f.getGenericParameterTypes(); if (args.length != types.length) { throw new IllegalArgumentException("argument count mismatch between " + jsargs + " and " + Arrays.toString(genericTypes)); } for (int i=0; i<args.length; i++) args[i] = req.bindJSON(genericTypes[i],types[i],jsargs.get(i)); return f.bindAndInvokeAndServeResponse(node,req,rsp,args); } public String toString() { return f.getQualifiedName()+"(...) for url=/"+name+"/..."; } } /** * Don't cache anything in memory, so that any change * will take effect instantly. */ public static boolean NO_CACHE = false; static { try { NO_CACHE = Boolean.getBoolean("stapler.jelly.noCache"); } catch (SecurityException e) { // ignore. } } private static final Object NONE = "none"; }
package org.radargun.config; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Stack; import org.radargun.logging.Log; import org.radargun.logging.LogFactory; import org.radargun.utils.Tokenizer; /** * Class with only static methods used for evaluation of expressions. Does: * - replace ${property.name} with the actual property value (from System.getProperty()) * - replace ${property.name : default.value} with property value or default.value if the property is not defined * - evaluate infix expressions inside #{ expression } block, available operators are: * '+' (addition), '-' (subtraction), '*' (multiplying), '/' (division), '%' (modulo operation), * '..' (range generation), ',' (adding to list), '(' and ')' as usual parentheses. * * Examples: * #{ 1..3,5 } -> 1,2,3,5 * #{ ( ${x} + 5 ) * 6 } with -Dx=2 -> 42 * foo${y}bar with -Dy=goo -> foogoobar * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class Evaluator { private final static Log log = LogFactory.getLog(Evaluator.class); /** * Parse string possibly containing expressions and properties and convert the value to integer. */ public static int parseInt(String string) { return Integer.parseInt(parseString(string)); } /** * Parse string possibly containing expressions and properties. */ public static String parseString(String string) { if (string == null) return null; StringBuilder sb = new StringBuilder(); int currentIndex = 0; while (currentIndex < string.length()) { int propertyIndex = string.indexOf("${", currentIndex); int expressionIndex = string.indexOf("#{", currentIndex); int nextIndex = propertyIndex < 0 ? (expressionIndex < 0 ? string.length() : expressionIndex) : (expressionIndex < 0 ? propertyIndex : Math.min(expressionIndex, propertyIndex)); sb.append(string.substring(currentIndex, nextIndex)); currentIndex = nextIndex + 2; if (nextIndex == propertyIndex) { nextIndex = string.indexOf('}', currentIndex); if (nextIndex < 0) { throw new IllegalArgumentException(string); } sb.append(evalProperty(string, currentIndex, nextIndex)); currentIndex = nextIndex + 1; } else if (nextIndex == expressionIndex) { Stack<Operator> operators = new Stack<>(); Stack<Value> operands = new Stack<>(); Tokenizer tokenizer = new Tokenizer(string, Operator.symbols(), true, false, currentIndex); boolean closed = false; // we set this to true because if '-' is on the beginning, is interpreted as sign boolean lastTokenIsOperator = true; boolean negativeSign = false; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); Operator op = Operator.from(token); if (op == null) { operands.push(new Value(negativeSign ? "-" + token : token)); lastTokenIsOperator = false; continue; } else if (op.isWhite()) { // do not set lastTokenIsOperator continue; } else if (op == Operator.OPENVAR) { if (!tokenizer.hasMoreTokens()) throw new IllegalArgumentException(string); StringBuilder var = new StringBuilder(); while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if ((op = Operator.from(token)) == null || op.isWhite()) { var.append(token); } else { break; } } if (op != Operator.CLOSEVAR) { throw new IllegalArgumentException("Expected '}' but found " + token + " in " + string); } operands.push(evalProperty(var.toString(), 0, var.length())); lastTokenIsOperator = false; continue; } else if (op == Operator.CLOSEVAR) { // end of expression to be evaluated closed = true; break; } else if (op.isFunction()) { operators.push(op); } else if (op == Operator.OPENPAR) { operators.push(op); } else if (op == Operator.CLOSEPAR) { while ((op = operators.pop()) != Operator.OPENPAR) { op.exec(operands); } } else if (op == Operator.MINUS && lastTokenIsOperator) { negativeSign = true; } else { while (true) { if (operators.isEmpty() || operators.peek() == Operator.OPENPAR || operators.peek().precedence() < op.precedence()) { operators.push(op); break; } operators.pop().exec(operands); } } lastTokenIsOperator = true; } if (!closed) { throw new IllegalArgumentException("Expression is missing closing '}': " + string); } while (!operators.empty()) { operators.pop().exec(operands); } sb.append(operands.pop()); if (!operands.empty()) { throw new IllegalArgumentException(operands.size() + " operands not processed: top=" + operands.pop() + " all=" + operands); } currentIndex = tokenizer.getPosition(); } } return sb.toString(); } private static Value evalProperty(String string, int startIndex, int endIndex) { int colonIndex = string.indexOf(':', startIndex); String property; Value value = null, def = null; if (colonIndex < 0 || colonIndex > endIndex) { property = string.substring(startIndex, endIndex).trim(); } else { property = string.substring(startIndex, colonIndex).trim(); def = new Value(string.substring(colonIndex + 1, endIndex).trim()); } String strValue = System.getProperty(property); if (strValue != null && !strValue.isEmpty()) { value = new Value(strValue.trim()); } else { if (property.startsWith("env.")) { String env = System.getenv(property.substring(4)); if (env != null && !env.isEmpty()) { value = new Value(env.trim()); } } else if (property.startsWith("random.")) { value = random(property); } } if (value != null) { return value; } else if (def != null) { return def; } else { throw new IllegalArgumentException("Property " + property + " not defined!"); } } private static Value random(String type) { Random random = new Random(); if (type.equals("random.int")) { return new Value(random.nextInt() & Integer.MAX_VALUE); } else if (type.equals("random.long")) { return new Value(random.nextLong() & Long.MAX_VALUE); } else if (type.equals("random.double")) { return new Value(random.nextDouble()); } else if (type.equals("random.boolean")) { return new Value(String.valueOf(random.nextBoolean())); } else { return null; } } private static Value range(Value first, Value second) { if (first.type.canBeLong() && second.type.canBeLong()) { long from = first.getLong(); long to = second.getLong(); List<Value> values = new ArrayList((int) Math.abs(from - to)); long inc = from <= to ? 1 : -1; for (long i = from; from <= to ? i <= to : i >= to; i += inc) values.add(new Value(i)); return new Value(values); } else { throw new IllegalArgumentException(first + " .. " + second); } } private static Value multiply(Value first, Value second) { if (first.type.canBeLong() && second.type.canBeLong()) { return new Value(first.getLong() * second.getLong()); } else if (first.type.canBeDouble() && second.type.canBeDouble()) { return new Value(first.getDouble() * second.getDouble()); } else { throw new IllegalArgumentException(first + " * " + second); } } private static Value minus(Value first, Value second) { if (first.type.canBeLong() && second.type.canBeLong()) { return new Value(first.getLong() - second.getLong()); } else if (first.type.canBeDouble() && second.type.canBeDouble()) { return new Value(first.getDouble() - second.getDouble()); } else { throw new IllegalArgumentException(first + " - " + second); } } private static Value plus(Value first, Value second) { if (first.type.canBeLong() && second.type.canBeLong()) { return new Value(first.getLong() + second.getLong()); } else if (first.type.canBeDouble() && second.type.canBeDouble()) { return new Value(first.getDouble() + second.getDouble()); } else { throw new IllegalArgumentException(first + " + " + second); } } private static Value div(Value first, Value second) { if (first.type.canBeLong() && second.type.canBeLong()) { return new Value(first.getLong() / second.getLong()); } else if (first.type.canBeDouble() && second.type.canBeDouble()) { return new Value(first.getDouble() / second.getDouble()); } else { throw new IllegalArgumentException(first + " / " + second); } } private static Value modulo(Value first, Value second) { if (first.type.canBeLong() && second.type.canBeLong()) { return new Value(first.getLong() % second.getLong()); } else { throw new IllegalArgumentException(first + " % " + second); } } private static Value power(Value first, Value second) { if (first.type.canBeLong() && second.type.canBeLong()) { long base = first.getLong(); long power = second.getLong(); long value = 1; if (power < 0) { return new Value(Math.pow(base, power)); } for (long i = power; i > 0; --i) { value *= base; } return new Value(value); } else if (first.type.canBeDouble() && second.type.canBeDouble()) { return new Value(Math.pow(first.getDouble(), second.getDouble())); } else { throw new IllegalArgumentException(first + "^" + second); } } private static Value concat(Value first, Value second) { List<Value> list = new ArrayList(); if (first.type == ValueType.LIST) { list.addAll(first.getList()); } else { list.add(first); } if (second.type == ValueType.LIST) { list.addAll(second.getList()); } else { list.add(second); } return new Value(list); } private static Value max(Value value) { if (value.type == ValueType.LIST) { Value max = null; for (Value v : value.getList()) { if (max == null) { max = v; } else if (max.type.canBeLong() && v.type.canBeLong()) { max = max.getLong() >= v.getLong() ? max : v; } else if (max.type.canBeDouble() && v.type.canBeDouble()) { max = max.getDouble() >= v.getDouble() ? max : v; } else { throw new IllegalArgumentException("max(" + value + ")"); } } if (max == null) { throw new IllegalArgumentException("max of 0 values"); } return max; } else { log.warn("Computing max from single value"); return value; } } private static Value min(Value value) { if (value.type == ValueType.LIST) { Value min = null; for (Value v : value.getList()) { if (min == null) { min = v; } else if (min.type.canBeLong() && v.type.canBeLong()) { min = min.getLong() <= v.getLong() ? min : v; } else if (min.type.canBeDouble() && v.type.canBeDouble()) { min = min.getDouble() <= v.getDouble() ? min : v; } else { throw new IllegalArgumentException("min(" + value + ")"); } } if (min == null) { throw new IllegalArgumentException("min of 0 values"); } return min; } else { log.warn("Computing min from single value"); return value; } } private static Value floor(Value value) { if (value.type.canBeLong()) { return value; } else if (value.type.canBeDouble()) { return new Value((long) Math.floor(value.getDouble())); } else { throw new IllegalArgumentException("floor(" + value + ")"); } } private static Value ceil(Value value) { if (value.type.canBeLong()) { return value; } else if (value.type.canBeDouble()) { return new Value((long) Math.ceil(value.getDouble())); } else { throw new IllegalArgumentException("abs(" + value + ")"); } } private static Value abs(Value value) { if (value.type.canBeLong()) { return new Value(Math.abs(value.getLong())); } else if (value.type.canBeDouble()) { return new Value(Math.abs(value.getDouble())); } else { throw new IllegalArgumentException("abs(" + value + ")"); } } private enum ValueType { STRING(false, false), LONG(true, true), DOUBLE(false, true), LIST(false, false); private final boolean canBeLong; private final boolean canBeDouble; ValueType(boolean canBeLong, boolean canBeDouble) { this.canBeLong = canBeLong; this.canBeDouble = canBeDouble; } public boolean canBeLong() { return canBeLong; } public boolean canBeDouble() { return canBeDouble; } } private static class Value { public final ValueType type; private final double doubleValue; private final long longValue; private final Object objectValue; private Value(long longValue) { this.type = ValueType.LONG; this.doubleValue = longValue; this.longValue = longValue; this.objectValue = String.valueOf(longValue); } private Value(double doubleValue) { this.type = ValueType.DOUBLE; this.doubleValue = doubleValue; this.longValue = 0; this.objectValue = String.valueOf(doubleValue); } private Value(String string) { ValueType t = ValueType.STRING; double d = 0; long l = 0; Object o = string; try { d = l = Long.parseLong(string); o = l; t = ValueType.LONG; } catch (NumberFormatException e) { try { o = d = Double.parseDouble(string); t = ValueType.DOUBLE; } catch (NumberFormatException e2) { } } type = t; doubleValue = d; longValue = l; objectValue = o; } public Value(List<Value> values) { type = ValueType.LIST; doubleValue = 0; longValue = 0; objectValue = values; } public long getLong() { return longValue; } public double getDouble() { return doubleValue; } public List<Value> getList() { return (List<Value>) objectValue; } @Override public String toString() { if (type == ValueType.LIST) { StringBuilder sb = new StringBuilder(); for (Value v : (List<Value>) objectValue) { if (sb.length() != 0) sb.append(", "); // inner lists would require special treatment if (v.type == ValueType.LIST) { sb.append("[").append(v).append("]"); } else { sb.append(v); } } return sb.toString(); } else { return String.valueOf(objectValue); } } } private static interface OneArgFunctor { Value exec(Value value); } private static interface TwoArgFunctor { Value exec(Value first, Value second); } private enum Operator { SPACE(" ", 0, true, false, null, null), TAB("\t", 0, true, false, null, null), NEWLINE("\n", 0, true, false, null, null), CR("\r", 0, true, false, null, null), PLUS("+", 100, false, false, null, new TwoArgFunctor() { @Override public Value exec(Value first, Value second) { return plus(first, second); } }), MINUS("-", 100, false, false, null, new TwoArgFunctor() { @Override public Value exec(Value first, Value second) { return minus(first, second); } }), MULTIPLY("*", 200, false, false, null, new TwoArgFunctor() { @Override public Value exec(Value first, Value second) { return multiply(first, second); } }), DIVIDE("/", 200, false, false, null, new TwoArgFunctor() { @Override public Value exec(Value first, Value second) { return div(first, second); } }), MODULO("%", 200, false, false, null, new TwoArgFunctor() { @Override public Value exec(Value first, Value second) { return modulo(first, second); } }), POWER("^", 300, false, false, null, new TwoArgFunctor() { @Override public Value exec(Value first, Value second) { return power(first, second); } }), RANGE("..", 50, false, false, null, new TwoArgFunctor() { @Override public Value exec(Value first, Value second) { return range(first, second); } }), COMMA(",", 10, false, false, null, new TwoArgFunctor() { @Override public Value exec(Value first, Value second) { return concat(first, second); } }), OPENPAR("(", 0, false, false, null, null), CLOSEPAR(")", 0, false, false, null, null), OPENVAR("${", 0, false, false, null, null), CLOSEVAR("}", 0, false, false, null, null), MAX("max", 0, false, true, new OneArgFunctor() { @Override public Value exec(Value value) { return max(value); } }, null), MIN("min", 0, false, true, new OneArgFunctor() { @Override public Value exec(Value value) { return min(value); } }, null), FLOOR("floor", 0, false, true, new OneArgFunctor() { @Override public Value exec(Value value) { return floor(value); } }, null), CEIL("ceil", 0, false, true, new OneArgFunctor() { @Override public Value exec(Value value) { return ceil(value); } }, null), ABS("abs", 0, false, true, new OneArgFunctor() { @Override public Value exec(Value value) { return abs(value); } }, null), ; private static Map<String, Operator> symbolMap = new HashMap<String, Operator>(); private String symbol; private int precedence; private boolean isWhite; private boolean isFunction; private OneArgFunctor functor1; private TwoArgFunctor functor2; static { for (Operator op : values()) { symbolMap.put(op.symbol, op); } } Operator(String symbol, int precedence, boolean isWhite, boolean isFunction, OneArgFunctor functor1, TwoArgFunctor functor2) { this.symbol = symbol; this.precedence = precedence; this.isWhite = isWhite; this.isFunction = isFunction; this.functor1 = functor1; this.functor2 = functor2; } /** * @return Symbols that don't belong to functions */ public static String[] symbols() { Operator[] values = values(); ArrayList<String> symbols = new ArrayList<>(values.length); for (int i = 0; i < values.length; ++i) { if (!values[i].isFunction()) { symbols.add(values[i].symbol); } } return symbols.toArray(new String[symbols.size()]); } public static Operator from(String symbol) { return symbolMap.get(symbol); } public int precedence() { return precedence; } public boolean isWhite() { return isWhite; } public boolean isFunction() { return isFunction; } public void exec(Stack<Value> operands) { if (functor1 != null) { operands.push(functor1.exec(operands.pop())); } else if (functor2 != null) { Value second = operands.pop(); Value first = operands.pop(); operands.push(functor2.exec(first, second)); } else { throw new IllegalStateException("This operator cannot be executed."); } } } }
// FILE: c:/projects/jetel/org/jetel/graph/Node.java package org.jetel.graph; import java.io.IOException; import java.nio.ByteBuffer; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.TreeMap; import org.jetel.data.DataRecord; import org.jetel.enums.EnabledEnum; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.TransformException; import org.jetel.exception.XMLConfigurationException; import org.jetel.exception.ConfigurationStatus.Priority; import org.jetel.exception.ConfigurationStatus.Severity; import org.jetel.graph.runtime.CloverRuntime; import org.jetel.graph.runtime.ErrorMsgBody; import org.jetel.graph.runtime.Message; import org.jetel.metadata.DataRecordMetadata; import org.w3c.dom.Element; /** * A class that represents atomic transformation task. It is a base class for * all kinds of transformation components. * *@author D.Pavlis *@created January 31, 2003 *@since April 2, 2002 *@see org.jetel.component *@revision $Revision$ */ public abstract class Node extends GraphElement implements Runnable { public enum Result{ RUNNING(0,"RUNNING"), OK(1,"OK"), ERROR(-1,"ERROR"), ABORTED(-2,"ABORTED"); private final int code; private final String message; Result(int _code,String msg){ code=_code; message=msg; } public int code(){return code;} public String message(){return message;} } protected Thread nodeThread; protected EnabledEnum enabled; protected int passThroughInputPort; protected int passThroughOutputPort; protected TreeMap outPorts; protected TreeMap inPorts; protected OutputPort logPort; protected volatile boolean runIt = true; protected Result runResult; protected Throwable resultException; protected Phase phase; // buffered values protected List outPortList; protected OutputPort[] outPortsArray; protected int outPortsSize; /** * Various PORT kinds identifiers * *@since August 13, 2002 */ public final static char OUTPUT_PORT = 'O'; /** Description of the Field */ public final static char INPUT_PORT = 'I'; /** Description of the Field */ public final static char LOG_PORT = 'L'; /** * XML attributes of every cloverETL component */ public final static String XML_TYPE_ATTRIBUTE="type"; public final static String XML_ENABLED_ATTRIBUTE="enabled"; /** * Standard constructor. * *@param id Unique ID of the Node *@since April 4, 2002 */ public Node(String id, TransformationGraph graph) { super(id,graph); outPorts = new TreeMap(); inPorts = new TreeMap(); logPort = null; phase = null; } /** * Standard constructor. * *@param id Unique ID of the Node *@since April 4, 2002 */ public Node(String id){ this(id,null); } /** * Sets the EOF for particular output port. EOF indicates that no more data * will be sent throught the output port. * *@param portNum The new EOF value *@since April 18, 2002 */ public void setEOF(int portNum) { try { ((OutputPort) outPorts.get(new Integer(portNum))).close(); } catch (IndexOutOfBoundsException ex) { ex.printStackTrace(); } } /** * Returns the type of this Node (subclasses/Components should override * this method to return appropriate type). * *@return The Type value *@since April 4, 2002 */ public abstract String getType(); /** * Returns True if this Node is Leaf Node - i.e. only consumes data (has only * input ports connected to it) * *@return True if Node is a Leaf *@since April 4, 2002 */ public boolean isLeaf() { if (outPorts.size() == 0) { return true; } else { return false; } } /** * Returns True if this Node is Phase Leaf Node - i.e. only consumes data within * phase it belongs to (has only input ports connected or any connected output ports * connects this Node with Node in different phase) * * @return True if this Node is Phase Leaf */ public boolean isPhaseLeaf(){ Iterator iterator=getOutPorts().iterator(); while(iterator.hasNext()){ if (phase!=((OutputPort)(iterator.next())).getReader().getPhase()) return true; } return false; } /** * Returns True if this node is Root Node - i.e. it produces data (has only output ports * connected to id). * *@return True if Node is a Root *@since April 4, 2002 */ public boolean isRoot() { if (inPorts.size() == 0) { return true; } else { return false; } } /** * Sets the processing phase of the Node object.<br> * Default is 0 (ZERO). * *@param phase The new phase number */ public void setPhase(Phase phase) { this.phase = phase; } /** * Gets the processing phase of the Node object * *@return The phase value */ public Phase getPhase() { return phase; } public int getPhaseNum(){ return phase.getPhaseNum(); } /** * Gets the OutPorts attribute of the Node object * *@return Collection of OutPorts *@since April 18, 2002 */ public Collection getOutPorts() { return outPorts.values(); } /** * Gets the InPorts attribute of the Node object * *@return Collection of InPorts *@since April 18, 2002 */ public Collection getInPorts() { return inPorts.values(); } /** * Gets the metadata on output ports of the Node object * *@return Collection of output ports metadata */ public Collection<DataRecordMetadata> getOutMetadata() { List<DataRecordMetadata> ret = new ArrayList<DataRecordMetadata>(outPorts.size()); for(Iterator it = getOutPorts().iterator(); it.hasNext();) { ret.add(((OutputPort) (it.next())).getMetadata()); } return ret; } /** * Gets the metadata on input ports of the Node object * *@return Collection of input ports metadata */ public Collection getInMetadata() { List ret = new ArrayList(inPorts.size()); for(Iterator it = getInPorts().iterator(); it.hasNext();) { ret.add(((InputPort) (it.next())).getMetadata()); } return ret; } /** * Gets the number of records passed through specified port type and number * *@param portType Port type (IN, OUT, LOG) *@param portNum port number (0...) *@return The RecordCount value *@since May 17, 2002 */ public int getRecordCount(char portType, int portNum) { int count; // Integer used as key to TreeMap containing ports Integer port = new Integer(portNum); try { switch (portType) { case OUTPUT_PORT: count = ((OutputPort) outPorts.get(port)).getRecordCounter(); break; case INPUT_PORT: count = ((InputPort) inPorts.get(port)).getRecordCounter(); break; case LOG_PORT: if (logPort != null) { count = logPort.getRecordCounter(); } else { count = -1; } break; default: count = -1; } } catch (Exception ex) { count = -1; } return count; } /** * Gets the result code of finished Node.<br> * Zero (0) indicates Success, any other number indicates error. * *@return The ResultCode value *@since July 29, 2002 */ public Result getResultCode() { return runResult; } /** * Gets the ResultMsg of finished Node.<br> * This message briefly describes what caused and error (if there was any). * *@return The ResultMsg value *@since July 29, 2002 */ public String getResultMsg() { return runResult!=null ? runResult.message() : null; } /** * Gets exception which caused Node to fail execution - if * there was such failure. * * @return * @since 13.12.2006 */ public Throwable getResultException(){ return resultException; } // Operations /** * main execution method of Node (calls in turn execute()) * *@since April 2, 2002 */ public void run() { runResult=Result.RUNNING; // set running result, so we know run() method was started try { runResult = execute(); } catch (IOException ex) { // may be handled differently later runResult=Result.ERROR; resultException = ex; Message msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), runResult.message(), ex)); getCloverRuntime().sendMessage(msg); return; } catch (InterruptedException ex) { runResult=Result.ABORTED; return; } catch (TransformException ex){ runResult=Result.ERROR; resultException = ex; Message msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), "Error occurred in nested transformation: " + runResult.message(), ex)); getCloverRuntime().sendMessage(msg); return; } catch (SQLException ex){ runResult=Result.ERROR; resultException = ex; Message msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), runResult.message(), ex)); getCloverRuntime().sendMessage(msg); return; } catch (Exception ex) { // may be handled differently later runResult=Result.ERROR; resultException = ex; Message msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), runResult.message(), ex)); getCloverRuntime().sendMessage(msg); return; } } public abstract Result execute() throws Exception; /** * Abort execution of Node - brutal force * *@since April 4, 2002 */ public void abort() { runIt = false; try { Thread.sleep(50); } catch (InterruptedException e) { //EMPTY INTENTIONALLY } if (runResult==Result.RUNNING){ runResult = Result.ABORTED; getNodeThread().interrupt(); } } /** * @return thread of running node; <b>null</b> if node does not runnig */ public Thread getNodeThread() { if(nodeThread == null) { ThreadGroup defaultThreadGroup = Thread.currentThread().getThreadGroup(); Thread[] activeThreads = new Thread[defaultThreadGroup.activeCount() * 2]; int numThreads = defaultThreadGroup.enumerate(activeThreads, false); for(int i = 0; i < numThreads; i++) { if(activeThreads[i].getName().equals(getId())) { nodeThread = activeThreads[i]; } } } return nodeThread; } /** * Sets actual thread in which this node current running. * @param nodeThread */ public void setNodeThread(Thread nodeThread) { this.nodeThread = nodeThread; } /** * End execution of Node - let Node finish gracefully * *@since April 4, 2002 */ public void end() { runIt = false; } /** * Provides CloverRuntime - object providing * various run-time services * * @return * @since 13.12.2006 */ public CloverRuntime getCloverRuntime(){ return getGraph().getRuntime(); } /** * An operation that adds port to list of all InputPorts * *@param port Port (Input connection) to be added *@since April 2, 2002 *@deprecated Use the other method which takes 2 arguments (portNum, port) */ public void addInputPort(InputPort port) { Integer portNum; int keyVal; try { portNum = (Integer) inPorts.lastKey(); keyVal = portNum.intValue() + 1; } catch (NoSuchElementException ex) { keyVal = 0; } inPorts.put(new Integer(keyVal), port); port.connectReader(this, keyVal); } /** * An operation that adds port to list of all InputPorts * *@param portNum Number to be associated with this port *@param port Port (Input connection) to be added *@since April 2, 2002 */ public void addInputPort(int portNum, InputPort port) { inPorts.put(new Integer(portNum), port); port.connectReader(this, portNum); } /** * An operation that adds port to list of all OutputPorts * *@param port Port (Output connection) to be added *@since April 4, 2002 *@deprecated Use the other method which takes 2 arguments (portNum, port) */ public void addOutputPort(OutputPort port) { Integer portNum; int keyVal; try { portNum = (Integer) inPorts.lastKey(); keyVal = portNum.intValue() + 1; } catch (NoSuchElementException ex) { keyVal = 0; } outPorts.put(new Integer(keyVal), port); port.connectWriter(this, keyVal); resetBufferedValues(); } /** * An operation that adds port to list of all OutputPorts * *@param portNum Number to be associated with this port *@param port The feature to be added to the OutputPort attribute *@since April 4, 2002 */ public void addOutputPort(int portNum, OutputPort port) { outPorts.put(new Integer(portNum), port); port.connectWriter(this, portNum); resetBufferedValues(); } /** * Gets the port which has associated the num specified * *@param portNum number associated with the port *@return The outputPort */ public OutputPort getOutputPort(int portNum) { Object outPort=outPorts.get(new Integer(portNum)); if (outPort instanceof OutputPort) { return (OutputPort)outPort ; }else if (outPort==null) { return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement OutputPort interface "+outPort.getClass().getName()); } /** * Gets the port which has associated the num specified * *@param portNum number associated with the port *@return The outputPort */ public OutputPortDirect getOutputPortDirect(int portNum) { Object outPort=outPorts.get(new Integer(portNum)); if (outPort instanceof OutputPortDirect) { return (OutputPortDirect)outPort ; }else if (outPort==null) { return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement OutputPortDirect interface"); } /** * Gets the port which has associated the num specified * *@param portNum portNum number associated with the port *@return The inputPort */ public InputPort getInputPort(int portNum) { Object inPort=inPorts.get(new Integer(portNum)); if (inPort instanceof InputPort) { return (InputPort)inPort ; }else if (inPort==null){ return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement InputPort interface"); } /** * Gets the port which has associated the num specified * *@param portNum portNum number associated with the port *@return The inputPort */ public InputPortDirect getInputPortDirect(int portNum) { Object inPort=inPorts.get(new Integer(portNum)); if (inPort instanceof InputPortDirect) { return (InputPortDirect)inPort ; }else if (inPort==null){ return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement InputPortDirect interface"); } /** * Removes input port. * @param inputPort */ public void removeInputPort(InputPort inputPort) { inPorts.remove(new Integer(inputPort.getInputPortNumber())); } /** * Removes output port. * @param outputPort */ public void removeOutputPort(OutputPort outputPort) { outPorts.remove(new Integer(outputPort.getOutputPortNumber())); resetBufferedValues(); } /** * Adds a feature to the LogPort attribute of the Node object * *@param port The feature to be added to the LogPort attribute *@since April 4, 2002 */ public void addLogPort(OutputPort port) { logPort = port; port.connectWriter(this, -1); } /** * An operation that does removes/unregisteres por<br> * Not yet implemented. * *@param _portNum Description of Parameter *@param _portType Description of Parameter *@since April 2, 2002 */ public void deletePort(int _portNum, char _portType) { throw new UnsupportedOperationException("Deleting port is not supported !"); } /** * An operation that writes one record through specified output port.<br> * As this operation gets the Port object from TreeMap, don't use it in loops * or when time is critical. Instead obtain the Port object directly and * use it's writeRecord() method. * *@param _portNum Description of Parameter *@param _record Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public void writeRecord(int _portNum, DataRecord _record) throws IOException, InterruptedException { ((OutputPort) outPorts.get(new Integer(_portNum))).writeRecord(_record); } /** * An operation that reads one record through specified input port.<br> * As this operation gets the Port object from TreeMap, don't use it in loops * or when time is critical. Instead obtain the Port object directly and * use it's readRecord() method. * *@param _portNum Description of Parameter *@param record Description of Parameter *@return Description of the Returned Value *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public DataRecord readRecord(int _portNum, DataRecord record) throws IOException, InterruptedException { return ((InputPort) inPorts.get(new Integer(_portNum))).readRecord(record); } /** * An operation that writes record to Log port * *@param record Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public void writeLogRecord(DataRecord record) throws IOException, InterruptedException { logPort.writeRecord(record); } /** * An operation that does ... * *@param record Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public void writeRecordBroadcast(DataRecord record) throws IOException, InterruptedException { if (outPortsArray == null) { refreshBufferedValues(); } for(int i=0;i<outPortsSize;i++){ outPortsArray[i].writeRecord(record); } } /** * Converts the collection of ports into List (ArrayList)<br> * This is auxiliary method which "caches" list of ports for faster access * when we need to go through all ports sequentially. Namely in * RecordBroadcast situations * *@param ports Collection of Ports *@return List (LinkedList) of ports */ private List getPortList(Collection ports) { List portList = new ArrayList(); portList.addAll(ports); return portList; } /** * Description of the Method * *@param recordBuffer Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since August 13, 2002 */ public void writeRecordBroadcastDirect(ByteBuffer recordBuffer) throws IOException, InterruptedException { if (outPortsArray == null) { refreshBufferedValues(); } for(int i=0;i<outPortsSize;i++){ ((OutputPortDirect) outPortsArray[i]).writeRecordDirect(recordBuffer); recordBuffer.rewind(); } } /** * Closes all output ports - sends EOF signal to them. * *@since April 11, 2002 */ public void closeAllOutputPorts() { Iterator iterator = getOutPorts().iterator(); OutputPort port; while (iterator.hasNext()) { port = (OutputPort) iterator.next(); port.close(); } } /** * Send EOF (no more data) to all connected output ports * *@since April 18, 2002 */ public void broadcastEOF() { closeAllOutputPorts(); } /** * Closes specified output port - sends EOF signal. * *@param portNum Which port to close *@since April 11, 2002 */ public void closeOutputPort(int portNum) { OutputPort port = (OutputPort) outPorts.get(new Integer(portNum)); if (port == null) { throw new RuntimeException(this.getId()+" - can't close output port \"" + portNum + "\" - does not exists!"); } port.close(); } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#free() */ public void free() { //EMPTY } /** * Compares this Node to specified Object * *@param obj Node to compare with *@return True if obj represents node with the same ID *@since April 18, 2002 */ @Override public boolean equals(Object obj) { if (getId().equals(((Node) obj).getId())) { return true; } else { return false; } } @Override public int hashCode(){ return getId().hashCode(); } /** * Description of the Method * *@return Description of the Returned Value *@since May 21, 2002 */ public void toXML(Element xmlElement) { // set basic XML attributes of all graph components xmlElement.setAttribute(XML_ID_ATTRIBUTE, getId()); xmlElement.setAttribute(XML_TYPE_ATTRIBUTE, getType()); } /** * Description of the Method * *@param nodeXML Description of Parameter *@return Description of the Returned Value *@since May 21, 2002 */ public static Node fromXML(TransformationGraph graph, Element xmlElement)throws XMLConfigurationException { throw new UnsupportedOperationException("not implemented in org.jetel.graph.Node"); } /** * @return <b>true</b> if node is enabled; <b>false</b> else */ public EnabledEnum getEnabled() { return enabled; } /** * @param enabled whether node is enabled */ public void setEnabled(String enabledStr) { enabled = EnabledEnum.fromString(enabledStr); } /** * @return index of "pass through" input port */ public int getPassThroughInputPort() { return passThroughInputPort; } /** * Sets "pass through" input port. * @param passThroughInputPort */ public void setPassThroughInputPort(int passThroughInputPort) { this.passThroughInputPort = passThroughInputPort; } /** * @return index of "pass through" output port */ public int getPassThroughOutputPort() { return passThroughOutputPort; } /** * Sets "pass through" output port * @param passThroughOutputPort */ public void setPassThroughOutputPort(int passThroughOutputPort) { this.passThroughOutputPort = passThroughOutputPort; } protected void resetBufferedValues(){ outPortList = null; outPortsArray=null; outPortsSize=0; } protected void refreshBufferedValues(){ Collection op = getOutPorts(); outPortsArray = (OutputPort[]) op.toArray(new OutputPort[op.size()]); outPortsSize = outPortsArray.length; } protected ConfigurationStatus checkInputPorts(ConfigurationStatus status, int min, int max) { if(getInPorts().size() < min) { status.add(new ConfigurationProblem("At least " + min + " input port can be defined!", Severity.ERROR, this, Priority.NORMAL)); } if(getInPorts().size() > max) { status.add(new ConfigurationProblem("At most " + max + " input ports can be defined!", Severity.ERROR, this, Priority.NORMAL)); } return status; } protected ConfigurationStatus checkOutputPorts(ConfigurationStatus status, int min, int max) { if(getOutPorts().size() < min) { status.add(new ConfigurationProblem("At least " + min + " output port can be defined!", Severity.ERROR, this, Priority.NORMAL)); } if(getOutPorts().size() > max) { status.add(new ConfigurationProblem("At most " + max + " output ports can be defined!", Severity.ERROR, this, Priority.NORMAL)); } return status; } } /* * end class Node */
import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import Sharing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class GUIframe implements Engine.EngineClient { BufferedImage image; String suffices[]; private JFrame window; private JPanel canvas; private Engine engine; private JButton startFilter; private JButton pauseFilter; private boolean showImage; private BufferedImage dotImage; public GUIframe(int width, int height) throws IOException { showImage = true; window = new JFrame("Dot Vinci"); window.setSize(width, height); // add canvasPanel objects canvas = new MyCanvas(); canvas.setPreferredSize(new Dimension(width, height)); canvas.setBackground(Color.WHITE); // intialize engine engine = new Engine(); engine.setEngineClient(this); // add buttonsPanel objects // - add buttons JButton openImage = new JButton("Open Image"); startFilter = new JButton("Draw"); pauseFilter = new JButton("Pause"); JButton resetFilter = new JButton("Re-draw"); JButton immediateFilter = new JButton("Quick Draw"); JButton saveImage = new JButton("Save Image"); JButton shareImage = new JButton("Share Image"); shareImage.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { BufferedImage bi = new BufferedImage( canvas.getWidth(), canvas.getHeight(), BufferedImage.TYPE_INT_RGB); canvas.paint(bi.getGraphics()); try{ ImageIO.write(bi,"png",new File(".temp.png")); String to_email = (String)JOptionPane.showInputDialog( "Email to share to( Works best with gmail to gmail):" ); /* System.out.println(to_email); String from_email = (String)JOptionPane.showInputDialog( "Gmail Full Email (Ex: bill@gmail.com ):" ); System.out.println(from_email); String from_pass = (String)JOptionPane.showInputDialog( "Gmail Password:" ); */ JLabel from_email_label = new JLabel("Email ID:"); JTextField from_email= new JTextField(); JLabel from_pass_label = new JLabel("Password"); JTextField from_pass = new JPasswordField(); Object[] ob = {from_email_label, from_email, from_pass_label,from_pass }; int result = JOptionPane.showConfirmDialog(null, ob, "Gmail Sign In", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { //Here is some validation code GmailShare email = new GmailShare(to_email, from_email.getText(), from_pass.getText(), "Check out my drawing on DotVinci!", ".temp.png"); email.share(); } } catch(Exception e1) { System.out.println(e.toString()); } } }); openImage.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (engine.isTimerRunning()) { // Pause drawing on canvas to load image for (ActionListener a : pauseFilter.getActionListeners()) { a.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null) { }); } } // open a JFilesChooser when the open button is clicked JFileChooser chooser = new JFileChooser(); // Get array of available formats (only once) if (suffices == null) { suffices = ImageIO.getReaderFileSuffixes(); // Add a file filter for each one for (String suffice : suffices) { FileNameExtensionFilter filter = new FileNameExtensionFilter( suffice.toUpperCase(), suffice); chooser.addChoosableFileFilter(filter); } } chooser.setFileFilter(new AllImagesFilter()); chooser.setAcceptAllFileFilterUsed(false); int ret = chooser.showDialog(null, "Open file"); if (ret == JFileChooser.APPROVE_OPTION) { // add the selected file to the canvas File file = chooser.getSelectedFile(); try { image = ImageIO.read(new FileInputStream(file .toString())); LoadImage(image); } catch (IOException e1) { e1.printStackTrace(); } if (Main.DEBUG) { System.out.println(file); } } } }); //Save action listener saveImage.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (image == null) { JOptionPane.showMessageDialog(window, "No image to save, please load one first"); return; } if (engine.isTimerRunning()) { // Pause drawing on canvas to save image for (ActionListener a : pauseFilter.getActionListeners()) { a.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null) { }); } } /* * TODO: Add save code here */ // open a JFilesChooser when the save button is clicked JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(new SaveImageFilter("BMP")); chooser.addChoosableFileFilter(new SaveImageFilter("JPG")); chooser.addChoosableFileFilter(new SaveImageFilter("WBMP")); chooser.addChoosableFileFilter(new SaveImageFilter("PNG")); chooser.addChoosableFileFilter(new SaveImageFilter("GIF")); chooser.setFileFilter(new SaveImageFilter("JPEG")); chooser.setAcceptAllFileFilterUsed(false); int ret = chooser.showDialog(null, "Save file"); if (ret == JFileChooser.APPROVE_OPTION) { // get selected file File file = chooser.getSelectedFile(); //add extension String ext=""; String extension=chooser.getFileFilter().getDescription(); if(extension.equals("JPG")) ext=".jpg"; if(extension.equals("PNG")) ext=".png"; if(extension.equals("GIF")) ext=".gif"; if(extension.equals("WBMP")) ext=".wbmp"; if(extension.equals("JPEG")) ext=".jpeg"; if(extension.equals("BMP")) ext=".bmp"; String fileName; //fixes imageFile.jpeg.jpeg bug if(! (file.toString().contains("."))) { fileName = file.toString() + ext; } else { String parts[] = file.toString().split("\\."); fileName = parts[0] + ext; } //creating new file with modified file name File newFile = new File(fileName); System.out.println(fileName + "\t\t" + newFile.toString()); try { // save image BufferedImage bi = new BufferedImage( canvas.getWidth(), canvas.getHeight(), BufferedImage.TYPE_INT_RGB); canvas.paint(bi.getGraphics()); System.out.println("ext = " + ext); String format = ext.substring(1); System.out.println("format = " + format); ImageIO.write(bi, format , newFile); } catch (IOException e1) { e1.printStackTrace(); } } } }); // - add filters JLabel filterText = new JLabel("Filters:"); final JRadioButton noFilter = new JRadioButton("None"); noFilter.setSelected(true); final JRadioButton sepiaFilter = new JRadioButton("Sepia"); final JRadioButton grayscaleFilter = new JRadioButton("Gray Scale"); final JRadioButton negativeFilter = new JRadioButton("Negative"); //prevent user from unchecking a radio button noFilter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (!noFilter.isSelected()) { noFilter.setSelected(true); } } }); sepiaFilter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (!sepiaFilter.isSelected()) { sepiaFilter.setSelected(true); } } }); negativeFilter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (!negativeFilter.isSelected()) { negativeFilter.setSelected(true); } } }); grayscaleFilter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (!grayscaleFilter.isSelected()) { grayscaleFilter.setSelected(true); } } }); //uncheck all other radio buttons when the user checks a radio button noFilter.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (noFilter.isSelected()) { sepiaFilter.setSelected(false); grayscaleFilter.setSelected(false); negativeFilter.setSelected(false); engine.setFilter(Engine.Filter.NORMAL); } if (Main.DEBUG) { System.out.println("NORMAL"); System.out.println(engine.getFilter()); } } }); sepiaFilter.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (sepiaFilter.isSelected()) { noFilter.setSelected(false); grayscaleFilter.setSelected(false); negativeFilter.setSelected(false); engine.setFilter(Engine.Filter.SEPIA); } if (Main.DEBUG) { System.out.println("SEPIA"); System.out.println(engine.getFilter()); } } }); negativeFilter.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (negativeFilter.isSelected()) { sepiaFilter.setSelected(false); grayscaleFilter.setSelected(false); noFilter.setSelected(false); engine.setFilter(Engine.Filter.NEGATIVE); } if (Main.DEBUG) { System.out.println("NEGATIVE"); System.out.println(engine.getFilter()); } } }); grayscaleFilter.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (grayscaleFilter.isSelected()) { sepiaFilter.setSelected(false); noFilter.setSelected(false); negativeFilter.setSelected(false); engine.setFilter(Engine.Filter.GRAYSCALE); } if (Main.DEBUG) { System.out.println("GRAYSCALE"); System.out.println(engine.getFilter()); } } }); // - add render speed slider JLabel renderSpeedText = new JLabel("Render Speed:"); final JSlider renderSpeed_slider = new JSlider(1, 100); final JTextField renderSpeed_value = new JTextField(3); Dimension dim = new Dimension(40, 30); renderSpeed_slider.setValue(100); renderSpeed_value.setSize(20, 20); renderSpeed_value.setMaximumSize(dim); renderSpeed_value.setText("100%"); renderSpeed_slider.addMouseListener(new MouseListener() { public void mouseReleased(MouseEvent arg0) { renderSpeed_value.setText(String.valueOf(renderSpeed_slider .getValue() + "%")); if (engine.isTimerRunning()) { pauseFilter.doClick(); startFilter.doClick(); } } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } }); // - add dot size slider JLabel dotSizeText = new JLabel("Pixel Size:"); final JSlider dotSize_slider = new JSlider(1, 50); final JTextField dotSize_value = new JTextField(3); Dimension dim2 = new Dimension(40, 30); dotSize_slider.setValue(100); dotSize_slider.setValue(6); dotSize_value.setSize(20, 20); dotSize_value.setMaximumSize(dim2); dotSize_value.setText("6 px"); dotSize_slider.addMouseListener(new MouseListener() { public void mouseReleased(MouseEvent arg0) { dotSize_value.setText(String.valueOf(dotSize_slider .getValue() + " px")); engine.setPixelSize(dotSize_slider.getValue()); if (engine.isTimerRunning()) { pauseFilter.doClick(); startFilter.doClick(); } } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } }); // - add dot shape options JLabel dotShapeText = new JLabel("Pixel Shape:"); final JRadioButton circleShape = new JRadioButton("Circle"); noFilter.setSelected(true); final JRadioButton squareShape = new JRadioButton("Square"); //prevent user from unchecking a radio button circleShape.setSelected(true); circleShape.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (!circleShape.isSelected()) { circleShape.setSelected(true); squareShape.setSelected(false); } } }); squareShape.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (!squareShape.isSelected()) { squareShape.setSelected(true); circleShape.setSelected(false); } } }); //uncheck all other radio buttons when the user checks a radio button circleShape.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (circleShape.isSelected()) { engine.setShape(Engine.Shape.Circle); squareShape.setSelected(false); } if (Main.DEBUG) { System.out.println("CIRCLE SHAPE"); } } }); squareShape.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (squareShape.isSelected()) { engine.setShape(Engine.Shape.Square); circleShape.setSelected(false); } if (Main.DEBUG) { System.out.println("SQUARE SHAPE"); } } }); // setup the panels JPanel mainPanel = new JPanel(); JPanel canvasPanel = new JPanel(); JPanel buttonsPanel = new JPanel(); JPanel tweakablesPanel = new JPanel(); buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS)); tweakablesPanel.setLayout(new BoxLayout(tweakablesPanel, BoxLayout.X_AXIS)); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); // setup the button panel @SuppressWarnings("unused") Container contentPane = window.getContentPane(); buttonsPanel.add(Box.createRigidArea(new Dimension(5, 10))); buttonsPanel.add(openImage); buttonsPanel.add(Box.createRigidArea(new Dimension(5, 10))); buttonsPanel.add(saveImage); buttonsPanel.add(Box.createRigidArea(new Dimension(5, 10))); buttonsPanel.add(shareImage); buttonsPanel.add(Box.createHorizontalGlue()); JPanel filterPanel = new JPanel(); filterPanel.add(filterText); filterPanel.add(Box.createRigidArea(new Dimension(5, 10))); filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.X_AXIS)); filterPanel.add(Box.createRigidArea(new Dimension(10, 20))); filterPanel.add(filterText); filterPanel.add(Box.createRigidArea(new Dimension(10, 20))); filterPanel.add(noFilter); filterPanel.add(sepiaFilter); filterPanel.add(grayscaleFilter); filterPanel.add(negativeFilter); tweakablesPanel.add(filterPanel); tweakablesPanel.add(Box.createRigidArea(new Dimension(5, 10))); tweakablesPanel.add(renderSpeedText); tweakablesPanel.add(Box.createRigidArea(new Dimension(5, 10))); tweakablesPanel.add(renderSpeed_slider); tweakablesPanel.add(Box.createRigidArea(new Dimension(5, 10))); // tweakablesPanel.add(renderSpeed_value); JPanel shapePanel = new JPanel(); shapePanel.setLayout(new BoxLayout(shapePanel, BoxLayout.X_AXIS)); shapePanel.add(Box.createRigidArea(new Dimension(10, 20))); shapePanel.add(dotShapeText); shapePanel.add(Box.createRigidArea(new Dimension(10, 20))); shapePanel.add(circleShape); shapePanel.add(squareShape); tweakablesPanel.add(shapePanel); tweakablesPanel.add(Box.createRigidArea(new Dimension(5, 10))); tweakablesPanel.add(dotSizeText); tweakablesPanel.add(Box.createRigidArea(new Dimension(5, 10))); tweakablesPanel.add(dotSize_slider); tweakablesPanel.add(Box.createRigidArea(new Dimension(5, 10))); // tweakablesPanel.add(dotSize_value); // buttonsPanel.add(Box.createRigidArea(new Dimension(800, 10))); buttonsPanel.add(startFilter); startFilter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (image == null) { JOptionPane.showMessageDialog(window, "Cannot start timer without an image open"); return; } engine.startTimer(renderSpeed_slider.getValue()); if (showImage) { clearDotImage(); } showImage = false; pauseFilter.setVisible(true); startFilter.setVisible(false); } }); buttonsPanel.add(pauseFilter); pauseFilter.setVisible(false); startFilter.setVisible(true); pauseFilter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pauseFilter.setVisible(false); startFilter.setVisible(true); engine.stopTimer(); } }); buttonsPanel.add(Box.createRigidArea(new Dimension(5, 10))); buttonsPanel.add(resetFilter); resetFilter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean interrupt = false; if (engine.isTimerRunning()) { // Pause drawing pauseFilter.doClick(); if (!showImage) { interrupt = true; } } int confirmation = JOptionPane.showConfirmDialog(null, "Are you sure you want to reset to the starting image?", "Choose", JOptionPane.YES_NO_OPTION ); if (confirmation == JOptionPane.YES_OPTION) { if (Main.DEBUG) { System.out.println("YES"); } // Reset canvas to original image engine.setImage(image); showImage = false; clearDotImage(); canvas.repaint(); if (interrupt) { startFilter.doClick(); } else { showImage = true; } } else { if (Main.DEBUG) { System.out.println("NO"); } if (interrupt) { // Continue draw operation startFilter.doClick(); } } } }); buttonsPanel.add(Box.createRigidArea(new Dimension(5, 10))); buttonsPanel.add(immediateFilter); immediateFilter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { engine.stopTimer(); pauseFilter.doClick(); if (!engine.isTimerRunning()) { clearDotImage(); canvas.repaint(); showImage = false; engine.drawOutputFast(dotImage.getGraphics()); } } }); buttonsPanel.add(Box.createRigidArea(new Dimension(5, 10))); canvasPanel.add(canvas); mainPanel.add(Box.createRigidArea(new Dimension(5, 5))); mainPanel.add(buttonsPanel); mainPanel.add(tweakablesPanel); mainPanel.add(canvasPanel); // add the main panel to the window window.add(mainPanel); window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); window.setResizable(true); window.setVisible(true); if (Main.DEBUG) { image = ImageIO.read(new FileInputStream("sample.jpg")); LoadImage(image); System.out.println(String.format("Size is width: %d height: %d", image.getWidth(), image.getHeight())); } } private void LoadImage(BufferedImage image) { canvas.setSize(image.getWidth(), image.getHeight()); canvas.setPreferredSize(new Dimension(image.getWidth(), image.getHeight())); engine.setImage(image); dotImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); startFilter.doClick(); pauseFilter.doClick(); showImage = true; clearDotImage(); canvas.repaint(); } public void onTimerTick() { canvas.repaint(); } public void forceRedraw() { canvas.repaint(); } private void clearDotImage() { dotImage.getGraphics().setColor(Color.WHITE); dotImage.getGraphics().fillRect(0, 0, dotImage.getWidth(), dotImage.getHeight()); } class MyCanvas extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); if (dotImage != null) { Graphics gImg = dotImage.getGraphics(); if (showImage) { engine.drawImage(gImg); } else { engine.updateOutput(gImg); } g.drawImage(dotImage, 0, 0, null); } } } }
package com.sandwell.JavaSimulation3D; import com.sandwell.JavaSimulation.Entity; import com.sandwell.JavaSimulation.Input; import com.sandwell.JavaSimulation.IntegerVector; import com.sandwell.JavaSimulation.Util; import com.sandwell.JavaSimulation.Vector; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.MouseInputListener; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; /** * Class to display information about model objects. <br> * displays the results of getInfo for an object */ public class PropertyBox extends FrameBox { private static PropertyBox myInstance; // only one instance allowed to be open private Entity currentEntity; private int presentPage; private final IntegerVector presentLineByPage = new IntegerVector(); private final JTabbedPane jTabbedFrame = new JTabbedPane(); private boolean ignoreStateChange = false; public PropertyBox() { super( "Property Viewer" ); setDefaultCloseOperation(FrameBox.HIDE_ON_CLOSE); jTabbedFrame.setPreferredSize( new Dimension( 800, 400 ) ); jTabbedFrame.setBackground( INACTIVE_TAB_COLOR ); // Register a change listener jTabbedFrame.addChangeListener(new ChangeListener() { // This method is called whenever the selected tab changes public void stateChanged(ChangeEvent evt) { if( ! ignoreStateChange ) { jTabbedFrame.setBackgroundAt( presentPage, INACTIVE_TAB_COLOR ); presentPage = jTabbedFrame.getSelectedIndex(); jTabbedFrame.setBackgroundAt( presentPage, ACTIVE_TAB_COLOR ); updateValues(); } } }); getContentPane().add( jTabbedFrame ); setSize( 300, 150 ); setLocation(0, 110); pack(); } private static Entity getEntityWithName( String key ) { Entity ent = Input.tryParseEntity(key, Entity.class); if (ent != null) return ent; // if the object is not in the namedEntityHashMap, check the Entity List String regionName = null; String entName = null; // check if region is part of name if (key.indexOf("/") > -1) { String[] itemArray = key.split("/"); regionName = itemArray[0]; entName = itemArray[1]; } else { entName = key; } for (int i = 0; i < Entity.getAll().size(); i++) { Entity each = null; try { each = Entity.getAll().get(i); } catch (IndexOutOfBoundsException e) {} // Check the name matches if (!each.getName().equalsIgnoreCase(entName)) continue; // If no region given, return the first matching name if (regionName == null) return each; // Otherwise Check the region name matches if (each instanceof DisplayEntity) { if (((DisplayEntity)each).getCurrentRegion().getName().equalsIgnoreCase(regionName)) return each; } if (each instanceof Display2DEntity) { if (((Display2DEntity)each).getCurrentRegion().getName().equalsIgnoreCase(regionName)) return each; } } return null; } private JScrollPane getPropTable() { final JTable propTable = new AjustToLastColumnTable(0, 3); int totalWidth = jTabbedFrame.getWidth(); propTable.getColumnModel().getColumn( 2 ).setWidth( totalWidth / 2 ); propTable.getColumnModel().getColumn( 1 ).setWidth( totalWidth / 5 ); propTable.getColumnModel().getColumn( 0 ).setWidth( 3 * totalWidth / 10 ); propTable.getColumnModel().getColumn( 0 ).setHeaderValue( "Property" ); propTable.getColumnModel().getColumn( 1 ).setHeaderValue( "Type" ); propTable.getColumnModel().getColumn( 2 ).setHeaderValue( "Value" ); propTable.getTableHeader().setBackground( HEADER_COLOR ); propTable.getTableHeader().setFont(propTable.getFont().deriveFont(Font.BOLD)); propTable.getTableHeader().setReorderingAllowed(false); propTable.addMouseListener( new MouseInputListener() { public void mouseEntered( MouseEvent e ) { } public void mouseClicked( MouseEvent e ) { // Left double click if( e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1 ) { // Get the index of the row the user has clicked on int row = propTable.getSelectedRow(); int column = propTable.getSelectedColumn(); String name = propTable.getValueAt(row, column).toString(); // Remove HTML name = name.replaceAll( "<html>", "").replace( "<p>", "" ).replace( "<align=top>", "" ).replace("<br>", "" ).trim(); Entity entity = PropertyBox.getEntityWithName(name); // An Entity Name if( entity != null ) { FrameBox.setSelectedEntity(entity); } } } public void mouseReleased(MouseEvent e) {} public void mouseMoved(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseDragged(MouseEvent e) {} public void mousePressed( MouseEvent e ) { // Right Mouse Button if( e.getButton() == MouseEvent.BUTTON3 ) { // get the coordinates of the mouse click Point p = e.getPoint(); // get the row index that contains that coordinate int row = propTable.rowAtPoint( p ); // Not get focused on the cell if( row < 0 ) { return; } String type = propTable.getValueAt(row, 1).toString(); // Remove HTML type = type.replaceAll( "<html>", "").replaceAll( "<p>", "" ).replaceAll( "<align=top>", "" ).replaceAll("<br>", "" ).trim(); // A list of entities if( type.equalsIgnoreCase("Vector") || type.equalsIgnoreCase("ArrayList")) { // Define a popup menu JPopupMenu popupMenu = new JPopupMenu( ); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { Entity entity = PropertyBox.getEntityWithName(e.getActionCommand()); FrameBox.setSelectedEntity(entity); } }; // Split the values in the list String value = propTable.getValueAt(row, 2).toString(); value = value.replaceAll( "<html>", "").replaceAll( "<p>", "" ).replaceAll( "<align=top>", "" ).replaceAll("<br>", "" ).trim(); String[] items = value.split( " " ); for( int i = 0; i < items.length; i++ ) { String each = items[ i ].replace( ",", ""); each = each.replace("[", ""); each = each.replace("]", ""); Entity entity = PropertyBox.getEntityWithName(each); // This item is an entity if( entity != null ) { // Add the entity to the popup menu JMenuItem item = new JMenuItem( entity.getName() ); item.addActionListener( actionListener ); popupMenu.add( item ); } } // Show the popup menu if it has items if( popupMenu.getComponentCount() > 0 ) { popupMenu.show( e.getComponent(), e.getX(), e.getY() ); } } } } }); JScrollPane jScrollPane = new JScrollPane(propTable); return jScrollPane; } public void setEntity( Entity entity ) { if(currentEntity == entity || ! this.isVisible()) return; // Prevent stateChanged() method of jTabbedFrame to reenter this method if( ignoreStateChange ) { return; } ignoreStateChange = true; Vector propertiesBySuperClass = null; if(entity != null) { // All the properties of the super classes propertiesBySuperClass = Util.getPropertiesBySuperClassesOf( entity ); } else { setTitle("Property Viewer"); presentPage = 0; currentEntity = entity; jTabbedFrame.removeAll(); ignoreStateChange = false; return; } // A different class has been selected, or no previous value for currentEntity if(currentEntity == null || currentEntity.getClass() != entity.getClass()) { presentPage = 0; presentLineByPage.clear(); // Remove the tabs for new selected entity jTabbedFrame.removeAll(); } currentEntity = entity; // Create tabs if they do not exist yet if( jTabbedFrame.getTabCount() == 0 ) { for( int i = 0; i < propertiesBySuperClass.size(); i++ ) { jTabbedFrame.addTab( ((Vector)propertiesBySuperClass.get( i )).get( 0 ).toString() , getPropTable() ); // The properties in the current page Vector info = (Vector) propertiesBySuperClass.get( i ); // The first one is the super class name info.remove( 0 ); JTable propTable = (JTable)(((JScrollPane)jTabbedFrame.getComponentAt(i)).getViewport().getComponent(0)); // Add new rows if it is required while( propTable.getRowCount() < info.size() ) { ((javax.swing.table.DefaultTableModel) propTable.getModel()).addRow( new Object[] {"","",""}); } // populate property and type columns for this propTable for( int j = 0; j < info.size(); j++ ) { String[] record = ((String)info.get( j )).split( "\t" ); // Property column propTable.setValueAt( "<html>" + record[0], j, 0 ); if( record.length > 1 ) { // Type column propTable.setValueAt( record[1], j, 1 ); } } } } ignoreStateChange = false; updateValues(); } public void updateValues() { if(currentEntity == null || ! this.isVisible()) return; setTitle(String.format("Property Viewer - %s", currentEntity)); Vector propertiesBySuperClass = Util.getPropertiesBySuperClassesOf( currentEntity ); // The properties in the current page Vector info = (Vector) propertiesBySuperClass.get( presentPage ); // The first one is the super class name info.remove( 0 ); JTable propTable = (JTable)(((JScrollPane)jTabbedFrame.getComponentAt(presentPage)).getViewport().getComponent(0)); // Print value column for current page for( int i = 0; i < info.size(); i++ ) { String[] record = ((String)info.get( i )).split( "\t" ); // Value column if( record.length > 2 ) { // Number of items for an appendable property int numberOfItems = 1; for( int l = 0; l < record[2].length() - 1 ; l++ ) { // Items are separated by "}," if( record[2].substring( l, l + 2 ).equalsIgnoreCase( "},") ) { numberOfItems++; } } // If the property is not appendable, then check for word wrapping if( numberOfItems == 1 ) { // Set the row height for this entry int stringLengthInPixel = Util.getPixelWidthOfString_ForFont( record[2].trim(), propTable.getFont() ); double lines = (double) stringLengthInPixel / ((double) propTable.getColumnModel().getColumn( 2 ).getWidth() ); // Adjustment if( lines > 1 ){ lines *= 1.1 ; } int numberOfLines = (int) Math.ceil( lines ); String lineBreaks = ""; // Only if there are not too many lines if( numberOfLines < 10 ) { int height = (numberOfLines - 1 ) * (int) (propTable.getRowHeight() * 0.9) + propTable.getRowHeight(); // text height is about 90% of the row height propTable.setRowHeight( i, height ); // Add extra line breaks to the end of the string to shift the entry to the top of the row // (Jtable should do this with <align=top>, but this does not work) for( int j = 0; j < numberOfLines; j++ ) { lineBreaks = lineBreaks + "<br>"; } // Set the value String value = "null"; if( ! record[2].equalsIgnoreCase( "<null>" ) ) { value = record[2]; } propTable.setValueAt( "<html> <p> <align=top>" + " " + value + lineBreaks, i, 2 ); } else { propTable.setValueAt( numberOfLines + " rows is too large to be displayed!", i, 2 ); } } // If the property is appendable, then add line breaks after each item else if( numberOfItems <= 50 ) { // Set the row height for this entry int height = (numberOfItems - 1 ) * (int) (propTable.getRowHeight() * 0.9) + propTable.getRowHeight(); // text height is about 90% of the row height propTable.setRowHeight( i, height ); // Set the entry String str = record[2].replaceAll( "},", "}<br>" ); // Replace the brace and comma with a brace and line break propTable.setValueAt( "<html>" + str, i, 2 ); } // Do not print an appendable entry that requires too many rows else { propTable.setValueAt( numberOfItems + " rows is too large to be displayed!", i, 2 ); } } } } /** * Returns the only instance of the property box */ public synchronized static PropertyBox getInstance() { if (myInstance == null) myInstance = new PropertyBox(); return myInstance; } public void dispose() { myInstance = null; super.dispose(); } }
package net.katsuster.ememu.generic; /** * SD Card * * : SD Specifications Part 1 Physical Layer * Simplified Specification Version 6.00 * August 29, 2018 */ public class SDCard extends AbstractParentCore { public static final int REG_IO = 0x00; private SDCardState st; public SDCard(String n) { super(n); setSlaveCore(new SDCardSlave()); st = new CmdState(); } class SDCardState { public SDCardState() { } public int readData() { return 0; } public void writeData(int b) { } } class CmdStateCommon extends SDCardState { protected int cmd = 0; protected int arg = 0; protected int crc = 0; protected int resp = 0xff; protected int pos = 0; public CmdStateCommon() { } public void reset() { cmd = 0; arg = 0; crc = 0; resp = 0xff; pos = 0; } public void recvCommand() { int[] dat; //Do not support dat = new int[1]; dat[0] = 0x3; st = new RespState(dat, new CmdState()); } @Override public int readData() { return resp; } @Override public void writeData(int b) { if (pos == 0 && b == 0xff) { resp = 0xff; return; } resp = 0xff; switch (pos) { case 0: cmd = b & 0x3f; break; case 1: arg |= (b & 0xff) << 24; break; case 2: arg |= (b & 0xff) << 16; break; case 3: arg |= (b & 0xff) << 8; break; case 4: arg |= b & 0xff; break; case 5: crc = b >> 1; break; case 7: recvCommand(); break; } pos++; } } class CmdState extends CmdStateCommon { public CmdState() { } @Override public void recvCommand() { int[] dat; switch (cmd) { case 0x00: //CMD 0: GO_IDLE_STATE dat = new int[1]; dat[0] = 0x1; st = new RespState(dat, new CmdState()); break; case 0x08: //CMD 8: SEND_EXT_CSD dat = new int[5]; dat[0] = 0x01; dat[1] = 0x00; dat[2] = 0x00; //voltage accepted: 2.6-3.7V dat[3] = 0x01; //echo back dat[4] = arg & 0xff; st = new RespState(dat, new CmdState()); break; case 0x37: //CMD 55: APP_CMD dat = new int[1]; dat[0] = 0x1; st = new RespState(dat, new AcmdState()); break; default: //Do not support super.recvCommand(); break; } } } class AcmdState extends CmdStateCommon { public AcmdState() { } @Override public void recvCommand() { int[] dat; switch (cmd) { case 0x29: //ACMD 41: SD_SEND_OP_COND dat = new int[1]; dat[0] = 0x1; st = new RespState(dat, new CmdState()); break; default: //Do not support super.recvCommand(); break; } } } class RespState extends SDCardState { private int[] resp; private SDCardState nextState; private int pos; public RespState(int[] r, SDCardState n) { resp = r; nextState = n; pos = 0; } @Override public int readData() { if (pos >= resp.length) { st = nextState; return 0xff; } else { int result = resp[pos]; pos++; return result; } } @Override public void writeData(int b) { } } class SDCardSlave extends Controller32 { public SDCardSlave() { addReg(REG_IO, "IO", 0x00000000); } @Override public int readWord(BusMaster64 m, long addr) { int result = st.readData() & 0xff; return result; } @Override public void writeWord(BusMaster64 m, long addr, int data) { st.writeData(data & 0xff); } } }
package org.codehaus.plexus.component.configurator.converters.special; import org.codehaus.classworlds.ClassRealmAdapter; import org.codehaus.classworlds.ClassRealmReverseAdapter; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; public final class ClassRealmConverter extends AbstractConfigurationConverter { private final ClassRealm realm; public ClassRealmConverter( final ClassRealm realm ) { this.realm = realm; } public ClassRealmConverter( final org.codehaus.classworlds.ClassRealm realm ) { this.realm = ClassRealmReverseAdapter.getInstance( realm ); } public boolean canConvert( final Class<?> type ) { return ClassRealm.class.isAssignableFrom( type ) || org.codehaus.classworlds.ClassRealm.class.isAssignableFrom( type ); } public Object fromConfiguration( final ConverterLookup lookup, final PlexusConfiguration configuration, final Class<?> type, final Class<?> enclosingType, final ClassLoader loader, final ExpressionEvaluator evaluator, final ConfigurationListener listener ) throws ComponentConfigurationException { Object result = fromExpression( configuration, evaluator, type ); if ( null == result ) { result = realm; } if ( !ClassRealm.class.isAssignableFrom( type ) && result instanceof ClassRealm ) { result = ClassRealmAdapter.getInstance( (ClassRealm) result ); } return result; } }
package org.devgateway.toolkit.persistence.mongo.spring; import java.math.BigDecimal; import java.util.Arrays; import org.devgateway.ocvn.persistence.mongo.ocds.BigDecimal2; import org.devgateway.toolkit.persistence.mongo.repository.ReleaseRepository; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; import org.springframework.core.convert.converter.Converter; import org.springframework.data.mongodb.config.EnableMongoAuditing; import org.springframework.data.mongodb.core.convert.CustomConversions; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; /** * Run this application only when you need access to Spring Data JPA but without * Wicket frontend * * @author mpostelnicu * */ @SpringBootApplication @ComponentScan("org.devgateway.toolkit") @PropertySource("classpath:/org/devgateway/toolkit/persistence/mongo/application.properties") @EnableMongoRepositories(basePackageClasses = ReleaseRepository.class) @EnableMongoAuditing public class MongoPersistenceApplication { public static void main(final String[] args) { SpringApplication.run(MongoPersistenceApplication.class, args); } public enum BigDecimal2ToDoubleConverter implements Converter<BigDecimal2, Double> { INSTANCE; @Override public Double convert(BigDecimal2 source) { return source == null ? null : source.doubleValue(); } } public enum DoubleToBigDecimal2Converter implements Converter<Double, BigDecimal2> { INSTANCE; @Override public BigDecimal2 convert(Double source) { return source != null ? new BigDecimal2(source) : null; } } public enum BigDecimalToDoubleConverter implements Converter<BigDecimal, Double> { INSTANCE; @Override public Double convert(BigDecimal source) { return source == null ? null : source.doubleValue(); } } public enum DoubleToBigDecimalConverter implements Converter<Double, BigDecimal> { INSTANCE; @Override public BigDecimal convert(Double source) { return source != null ? new BigDecimal(source) : null; } } @Bean public CustomConversions customConversions() { return new CustomConversions(Arrays .asList(new Object[] { BigDecimal2ToDoubleConverter.INSTANCE, DoubleToBigDecimal2Converter.INSTANCE, BigDecimalToDoubleConverter.INSTANCE, DoubleToBigDecimalConverter.INSTANCE })); } }
package org.project.openbaton.clients.interfaces; import org.project.openbaton.catalogue.mano.common.DeploymentFlavour; import org.project.openbaton.catalogue.nfvo.*; import org.project.openbaton.clients.exceptions.VimDriverException; import java.io.InputStream; import java.util.List; import java.util.Set; public interface ClientInterfaces { /** * This version must match the version of the plugin... */ String interfaceVersion = "1.0"; Server launchInstance(VimInstance vimInstance, String name, String image, String flavor, String keypair, Set<String> network, Set<String> secGroup, String userData); // void init(VimInstance vimInstance); List<NFVImage> listImages(VimInstance vimInstance); List<Server> listServer(VimInstance vimInstance); List<Network> listNetworks(VimInstance vimInstance); List<DeploymentFlavour> listFlavors(VimInstance vimInstance); Server launchInstanceAndWait(VimInstance vimInstance, String hostname, String image, String extId, String keyPair, Set<String> networks, Set<String> securityGroups, String s) throws VimDriverException; void deleteServerByIdAndWait(VimInstance vimInstance, String id); Network createNetwork(VimInstance vimInstance, Network network); DeploymentFlavour addFlavor(VimInstance vimInstance, DeploymentFlavour deploymentFlavour); NFVImage addImage(VimInstance vimInstance, NFVImage image, InputStream inputStream); NFVImage updateImage(VimInstance vimInstance, NFVImage image); NFVImage copyImage(VimInstance vimInstance, NFVImage image, InputStream inputStream); boolean deleteImage(VimInstance vimInstance, NFVImage image); DeploymentFlavour updateFlavor(VimInstance vimInstance, DeploymentFlavour deploymentFlavour) throws VimDriverException; boolean deleteFlavor(VimInstance vimInstance, String extId); Subnet createSubnet(VimInstance vimInstance, Network createdNetwork, Subnet subnet); Network updateNetwork(VimInstance vimInstance, Network network); Subnet updateSubnet(VimInstance vimInstance, Network updatedNetwork, Subnet subnet); List<String> getSubnetsExtIds(VimInstance vimInstance, String network_extId); boolean deleteSubnet(VimInstance vimInstance, String existingSubnetExtId); boolean deleteNetwork(VimInstance vimInstance, String extId); Network getNetworkById(VimInstance vimInstance, String id); Quota getQuota(VimInstance vimInstance); String getType(VimInstance vimInstance); }
package com.opengamma.masterdb.exchange; import static org.junit.Assert.assertEquals; import java.util.TimeZone; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.id.Identifier; import com.opengamma.id.IdentifierBundle; import com.opengamma.master.exchange.ExchangeSearchRequest; import com.opengamma.master.exchange.ExchangeSearchResult; import com.opengamma.util.db.PagingRequest; /** * Tests QueryExchangeDbExchangeMasterWorker. */ public class QueryExchangeDbExchangeMasterWorkerSearchTest extends AbstractDbExchangeMasterWorkerTest { // superclass sets up dummy database private static final Logger s_logger = LoggerFactory.getLogger(QueryExchangeDbExchangeMasterWorkerSearchTest.class); private DbExchangeMasterWorker _worker; public QueryExchangeDbExchangeMasterWorkerSearchTest(String databaseType, String databaseVersion) { super(databaseType, databaseVersion); s_logger.info("running testcases for {}", databaseType); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); } @Before public void setUp() throws Exception { super.setUp(); _worker = new QueryExchangeDbExchangeMasterWorker(); _worker.init(_exgMaster); } @After public void tearDown() throws Exception { super.tearDown(); _worker = null; } @Test public void test_search_documents() { ExchangeSearchRequest request = new ExchangeSearchRequest(); ExchangeSearchResult test = _worker.search(request); assertEquals(1, test.getPaging().getFirstItem()); assertEquals(Integer.MAX_VALUE, test.getPaging().getPagingSize()); assertEquals(_totalExchanges, test.getPaging().getTotalItems()); assertEquals(_totalExchanges, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert102(test.getDocuments().get(1)); assert202(test.getDocuments().get(2)); } @Test public void test_search_pageOne() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.setPagingRequest(new PagingRequest(1, 2)); ExchangeSearchResult test = _worker.search(request); assertEquals(1, test.getPaging().getFirstItem()); assertEquals(2, test.getPaging().getPagingSize()); assertEquals(_totalExchanges, test.getPaging().getTotalItems()); assertEquals(2, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert102(test.getDocuments().get(1)); } @Test public void test_search_pageTwo() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.setPagingRequest(new PagingRequest(2, 2)); ExchangeSearchResult test = _worker.search(request); assertEquals(3, test.getPaging().getFirstItem()); assertEquals(2, test.getPaging().getPagingSize()); assertEquals(_totalExchanges, test.getPaging().getTotalItems()); assertEquals(1, test.getDocuments().size()); assert202(test.getDocuments().get(0)); } @Test public void test_search_name_noMatch() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.setName("FooBar"); ExchangeSearchResult test = _worker.search(request); assertEquals(0, test.getDocuments().size()); } @Test public void test_search_name() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.setName("TestExchange102"); ExchangeSearchResult test = _worker.search(request); assertEquals(1, test.getDocuments().size()); assert102(test.getDocuments().get(0)); } @Test public void test_search_name_case() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.setName("TESTExchange102"); ExchangeSearchResult test = _worker.search(request); assertEquals(1, test.getDocuments().size()); assert102(test.getDocuments().get(0)); } @Test public void test_search_name_wildcard() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.setName("TestExchange1*"); ExchangeSearchResult test = _worker.search(request); assertEquals(2, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert102(test.getDocuments().get(1)); } @Test public void test_search_name_wildcardCase() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.setName("TESTExchange1*"); ExchangeSearchResult test = _worker.search(request); assertEquals(2, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert102(test.getDocuments().get(1)); } @Test public void test_search_oneId_AB() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(Identifier.of("A", "B")); ExchangeSearchResult test = _worker.search(request); assertEquals(2, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert102(test.getDocuments().get(1)); } @Test public void test_search_oneId_CD() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(Identifier.of("C", "D")); ExchangeSearchResult test = _worker.search(request); assertEquals(3, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert102(test.getDocuments().get(1)); assert202(test.getDocuments().get(2)); } @Test public void test_search_oneId_EF() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(Identifier.of("E", "F")); ExchangeSearchResult test = _worker.search(request); assertEquals(2, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert202(test.getDocuments().get(1)); } @Test public void test_search_oneId_GH() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(Identifier.of("G", "H")); ExchangeSearchResult test = _worker.search(request); assertEquals(1, test.getDocuments().size()); assert102(test.getDocuments().get(0)); } @Test public void test_search_oneId_noMatch() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(Identifier.of("A", "H")); ExchangeSearchResult test = _worker.search(request); assertEquals(0, test.getDocuments().size()); } @Test public void test_search_twoIds_AB_CD() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(IdentifierBundle.of(Identifier.of("A", "B"), Identifier.of("C", "D"))); ExchangeSearchResult test = _worker.search(request); assertEquals(2, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert102(test.getDocuments().get(1)); } @Test public void test_search_twoIds_CD_EF() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(IdentifierBundle.of(Identifier.of("C", "D"), Identifier.of("E", "F"))); ExchangeSearchResult test = _worker.search(request); assertEquals(2, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert202(test.getDocuments().get(1)); } @Test public void test_search_twoIds_noMatch() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(IdentifierBundle.of(Identifier.of("C", "D"), Identifier.of("E", "H"))); ExchangeSearchResult test = _worker.search(request); assertEquals(0, test.getDocuments().size()); } @Test public void test_search_threeIds_AB_CD_EF() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(IdentifierBundle.of(Identifier.of("A", "B"), Identifier.of("C", "D"), Identifier.of("E", "F"))); ExchangeSearchResult test = _worker.search(request); assertEquals(1, test.getDocuments().size()); assert101(test.getDocuments().get(0)); } @Test public void test_search_threeIds_AB_CD_GH() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(IdentifierBundle.of(Identifier.of("A", "B"), Identifier.of("C", "D"), Identifier.of("G", "H"))); ExchangeSearchResult test = _worker.search(request); assertEquals(1, test.getDocuments().size()); assert102(test.getDocuments().get(0)); } @Test public void test_search_threeIds_noMatch() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(IdentifierBundle.of(Identifier.of("C", "D"), Identifier.of("E", "F"), Identifier.of("A", "H"))); ExchangeSearchResult test = _worker.search(request); assertEquals(0, test.getDocuments().size()); } @Test public void test_search_ids_AB_or_CD() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(Identifier.of("A", "B")); request.addIdentifierBundle(Identifier.of("C", "D")); ExchangeSearchResult test = _worker.search(request); assertEquals(3, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert102(test.getDocuments().get(1)); assert202(test.getDocuments().get(2)); } @Test public void test_search_ids_EF_or_GH() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(Identifier.of("E", "F")); request.addIdentifierBundle(Identifier.of("G", "H")); ExchangeSearchResult test = _worker.search(request); assertEquals(3, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert102(test.getDocuments().get(1)); assert202(test.getDocuments().get(2)); } @Test public void test_search_ids_or_noMatch() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.addIdentifierBundle(Identifier.of("E", "H")); request.addIdentifierBundle(Identifier.of("A", "D")); ExchangeSearchResult test = _worker.search(request); assertEquals(0, test.getDocuments().size()); } @Test public void test_search_versionAsOf_below() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.setVersionAsOfInstant(_version1Instant.minusSeconds(5)); ExchangeSearchResult test = _worker.search(request); assertEquals(0, test.getDocuments().size()); } @Test public void test_search_versionAsOf_mid() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.setVersionAsOfInstant(_version1Instant.plusSeconds(5)); ExchangeSearchResult test = _worker.search(request); assertEquals(3, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert102(test.getDocuments().get(1)); assert201(test.getDocuments().get(2)); // old version } @Test public void test_search_versionAsOf_above() { ExchangeSearchRequest request = new ExchangeSearchRequest(); request.setVersionAsOfInstant(_version2Instant.plusSeconds(5)); ExchangeSearchResult test = _worker.search(request); assertEquals(3, test.getDocuments().size()); assert101(test.getDocuments().get(0)); assert102(test.getDocuments().get(1)); assert202(test.getDocuments().get(2)); // new version } @Test public void test_toString() { assertEquals(_worker.getClass().getSimpleName() + "[DbExg]", _worker.toString()); } }
package com.oracle.truffle.llvm.nodes.impl.func; import java.util.ArrayList; import java.util.List; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.source.SourceSection; import com.oracle.truffle.llvm.nodes.base.LLVMExpressionNode; import com.oracle.truffle.llvm.nodes.base.LLVMNode; import com.oracle.truffle.llvm.nodes.base.LLVMStackFrameNuller; import com.oracle.truffle.llvm.nodes.impl.base.LLVMLanguage; public class LLVMFunctionStartNode extends RootNode { @Child private LLVMExpressionNode node; @Children private final LLVMNode[] beforeFunction; @Children private final LLVMNode[] afterFunction; private final String functionName; @CompilationFinal private LLVMStackFrameNuller[] nullers; public LLVMFunctionStartNode(LLVMExpressionNode node, LLVMNode[] beforeFunction, LLVMNode[] afterFunction, SourceSection sourceSection, FrameDescriptor frameDescriptor, String functionName) { super(LLVMLanguage.class, sourceSection, frameDescriptor); this.node = node; this.beforeFunction = beforeFunction; this.afterFunction = afterFunction; this.functionName = functionName; getInitNullers(frameDescriptor); } /** * Initializes the tags of the frame. */ private void getInitNullers(FrameDescriptor frameDescriptor) throws AssertionError { List<LLVMStackFrameNuller> initNullers = new ArrayList<>(); for (FrameSlot slot : frameDescriptor.getSlots()) { switch (slot.getKind()) { case Boolean: initNullers.add(new LLVMStackFrameNuller.LLVMBooleanNuller(slot)); break; case Byte: initNullers.add(new LLVMStackFrameNuller.LLVMByteNuller(slot)); break; case Int: initNullers.add(new LLVMStackFrameNuller.LLVMIntNuller(slot)); break; case Long: initNullers.add(new LLVMStackFrameNuller.LLVMLongNuller(slot)); break; case Float: initNullers.add(new LLVMStackFrameNuller.LLVMFloatNuller(slot)); break; case Double: initNullers.add(new LLVMStackFrameNuller.LLVMDoubleNuller(slot)); break; case Object: initNullers.add(new LLVMStackFrameNuller.LLVMAddressNuller(slot)); break; case Illegal: break; default: throw new AssertionError(slot); } } this.nullers = initNullers.toArray(new LLVMStackFrameNuller[initNullers.size()]); } @Override @ExplodeLoop public Object execute(VirtualFrame frame) { for (LLVMStackFrameNuller nuller : nullers) { nuller.nullifySlot(frame); } CompilerAsserts.compilationConstant(beforeFunction); for (LLVMNode before : beforeFunction) { before.executeVoid(frame); } Object result = node.executeGeneric(frame); CompilerAsserts.compilationConstant(afterFunction); for (LLVMNode after : afterFunction) { after.executeVoid(frame); } return result; } @Override public String toString() { return functionName; } public String getFunctionName() { return functionName; } @Override public String getName() { return functionName; } }
package gov.nih.nci.integration.catissue.client; import edu.wustl.catissuecore.domain.AbstractSpecimen; import edu.wustl.catissuecore.domain.CollectionProtocol; import edu.wustl.catissuecore.domain.ConsentTier; import edu.wustl.catissuecore.domain.ConsentTierStatus; import edu.wustl.catissuecore.domain.Participant; import edu.wustl.catissuecore.domain.Specimen; import gov.nih.nci.integration.catissue.domain.ConsentData; import gov.nih.nci.integration.catissue.domain.ConsentDetail; import gov.nih.nci.integration.catissue.domain.Consents; import gov.nih.nci.system.applicationservice.ApplicationException; import java.io.StringReader; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.StaxDriver; /** * This is the Client class to perform Consent Status Update Related Operations (RegisterConsent, RollbackConsent etc). * * @author Rohit Gupta */ public class CaTissueConsentClient { private static final Logger LOG = LoggerFactory.getLogger(CaTissueConsentClient.class); private CaTissueAPIClientWithRegularAuthentication caTissueAPIClient; private final XStream xStream = new XStream(new StaxDriver()); /** * Constructor * * @param loginName - loginName for the API authentication * @param password - password for the API authentication * @throws MalformedURLException - MalformedURLException * @throws BeansException - BeansException */ public CaTissueConsentClient(String loginName, String password) throws BeansException, MalformedURLException { super(); Thread.currentThread().setContextClassLoader(CaTissueConsentClient.class.getClassLoader()); this.caTissueAPIClient = new CaTissueAPIClientWithRegularAuthentication(loginName, password); xStream.alias("consents", Consents.class); xStream.alias("participant", Participant.class); xStream.alias("consentDetails", ConsentDetail.class); xStream.alias("consentData", ConsentData.class); xStream.alias("collectionProtocol", CollectionProtocol.class); xStream.alias("consentTierStatus", ConsentTierStatus.class); xStream.alias("consentTier", ConsentTier.class); xStream.addImplicitCollection(ConsentData.class, "consentTierStatusSet"); xStream.addImplicitCollection(Consents.class, "consentDetailsList"); } /** * This method is used to fetch the existing Consents * * @param consentsListXMLStr - XMLString containing the list of consents for which data is to be fetched * @return String - XMLString representation of the retrieved data * @throws ApplicationException - if any exception occurred during data retrieval */ public String getExistingConsents(String consentsListXMLStr) throws ApplicationException { // Parse the incoming XML String. The returned object will contain data // from the incoming consents XML final Consents incomingConsents = parseConsentsListXML(consentsListXMLStr); // Fetch the existing Consents final Consents exitingConsents = fetchExistingConsents(incomingConsents); return xStream.toXML(exitingConsents); } /** * This method is used Register the Consents * * @param consentsListXMLStr - XMLString containing the list of consents for which registration has to be done * @return String - currently returning null * @throws ApplicationException - if any exception occurred during data insertion */ public String registerConsents(String consentsListXMLStr) throws ApplicationException { // Parse the incoming XML String. The returned object will contain data // from the incoming specimens XML final Consents incomingConsents = parseConsentsListXML(consentsListXMLStr); // perform the actual logic to register the Consents.. Also do the // rollback, if required performRegisterConsents(incomingConsents); // Returning NULL at the moment. return null; } /** * This method is used to Rollback the Consents * * @param consentsListXMLStr - XMLString containing the specimens/consents to be rollback * @throws ApplicationException - if any exception occurred during rollback itself */ public void rollbackConsentRegistration(String consentsListXMLStr) throws ApplicationException { // Parse the incoming XML String. The returned object will contain data // from the incoming specimens XML final Consents incomingConsents = parseConsentsListXML(consentsListXMLStr); // rollback the consents performRollbackConsentRegistration(incomingConsents); } /** * This method will fetch the existing consents which will be used incase of rollback * * @param incomingConsents * @return * @throws ApplicationException */ private Consents fetchExistingConsents(Consents incomingConsents) throws ApplicationException { final Consents existingConsents = new Consents(); final List<ConsentDetail> exitingConsentDetailsList = new ArrayList<ConsentDetail>(); final Iterator<ConsentDetail> incomingConsentDetailItr = incomingConsents.getConsentsDetailsList().iterator(); while (incomingConsentDetailItr.hasNext()) { final ConsentDetail consentDetail = incomingConsentDetailItr.next(); final ConsentDetail existingConsentDetail = new ConsentDetail(); final String specimenLabel = consentDetail.getConsentData().getSpecimenLabel().trim(); final Specimen existingSpecimen = getExistingSpecimen(specimenLabel); if (existingSpecimen == null) { LOG.error("Specimen for given LABEL " + specimenLabel + " doesn't exist."); throw new ApplicationException("Specimen for given LABEL doesn't exist"); } existingConsentDetail.setConsentData(getConsentData(existingSpecimen)); exitingConsentDetailsList.add(existingConsentDetail); } existingConsents.setConsentsDetailsList(exitingConsentDetailsList); return existingConsents; } /** * This method will register the Consents in caTissue * * @param consents * @throws ApplicationException */ private void performRegisterConsents(Consents consents) throws ApplicationException { final List<ConsentDetail> consentDetailList = consents.getConsentsDetailsList(); Iterator<ConsentDetail> consentDetailItr = null; Specimen existingSpecimen = null; try { for (consentDetailItr = consentDetailList.iterator(); consentDetailItr.hasNext();) { ConsentDetail consentDetail = consentDetailItr.next(); existingSpecimen = getExistingSpecimen(consentDetail.getConsentData().getSpecimenLabel().trim()); // populate the tierId for given 'statement' inside consentDetail consentDetail = populateConsentTierId(consentDetail, existingSpecimen); // set the ConsentTierStatusCollection to main/parent specimen existingSpecimen.setConsentTierStatusCollection(consentDetail.getConsentData() .getConsentTierStatusSet()); // set the consentTierCollection for child specimens populateConsentTierStatusCollectionforChildSpecimens(existingSpecimen, consentDetail); // and then update the specimen updateSpecimen(existingSpecimen); // Currently the consent status of only parent specimen is updated and not child specimen(s). This is a } } catch (ApplicationException ae) { LOG.error("Register Consent Failed for Specimen" + existingSpecimen.getLabel(), ae); throw new ApplicationException("Register Consent Failed for Specimen" + existingSpecimen.getLabel() + " and exception is " + ae.getCause() + ae.getMessage(), ae); } } /** * This method is used to set the consentTierStatusCollection to the child specimens of the given parent specimen */ private void populateConsentTierStatusCollectionforChildSpecimens(Specimen parentSpecimen, ConsentDetail consentDetail) throws ApplicationException { final Collection<AbstractSpecimen> childSpecimenCollection = parentSpecimen.getChildSpecimenCollection(); if (childSpecimenCollection != null) { final Iterator<AbstractSpecimen> itrChildSpecimen = childSpecimenCollection.iterator(); while (itrChildSpecimen.hasNext()) { final Specimen childSpecimen = (Specimen) itrChildSpecimen.next(); childSpecimen.setConsentTierStatusCollection(consentDetail.getConsentData().getConsentTierStatusSet()); populateConsentTierStatusCollectionforChildSpecimens(childSpecimen, consentDetail); } } } /** * This method is used to populate the 'consent_tier_id' based on the 'Statement' * * @param consentDetail * @existingSpecimen existingSpecimen * @return * @throws ApplicationException */ private ConsentDetail populateConsentTierId(ConsentDetail consentDetail, Specimen existingSpecimen) throws ApplicationException { final Set<ConsentTierStatus> conTierStatusSet = consentDetail.getConsentData().getConsentTierStatusSet(); final Iterator<ConsentTierStatus> itrTierStatus = conTierStatusSet.iterator(); // iterate thru all the consentTierStatus's statement while (itrTierStatus.hasNext()) { boolean isTierIdFound = false; final ConsentTierStatus tierStatus = itrTierStatus.next(); final String stmt = tierStatus.getConsentTier().getStatement(); final CollectionProtocol cp = existingSpecimen.getSpecimenCollectionGroup().getCollectionProtocolEvent() .getCollectionProtocol(); final Collection<ConsentTier> consentTierCollection = cp.getConsentTierCollection(); if (consentTierCollection != null) { final Iterator<ConsentTier> itrConsentTier = consentTierCollection.iterator(); // iterate thru each consentTier and compare for the statement.. // if it matches- get its corresponding Id while (itrConsentTier.hasNext()) { final ConsentTier consentTier = itrConsentTier.next(); if (stmt.equalsIgnoreCase(consentTier.getStatement())) { tierStatus.getConsentTier().setId(consentTier.getId()); isTierIdFound = true; break; } } } if (!isTierIdFound) { // i.e tierId not found for given CollectionProtocol & Statement // combination LOG.error("populateConsentTierId failed as ConsentTier Statement was not found for given CollectionProtocol " + consentDetail.getCollectionProtocol().getShortTitle() + "in caTissue."); throw new ApplicationException( "ConsentTier Statement was not found for given CollectionProtocol in caTissue"); } } return consentDetail; } /** * This method will rollback the Consents * * @param consents * @throws ApplicationException */ private void performRollbackConsentRegistration(Consents consents) throws ApplicationException { final List<ConsentDetail> consentDetailList = consents.getConsentsDetailsList(); Iterator<ConsentDetail> consentDetailItr = null; Specimen existingSpecimen = null; ConsentDetail consentDetail = null; try { for (consentDetailItr = consentDetailList.iterator(); consentDetailItr.hasNext();) { consentDetail = consentDetailItr.next(); existingSpecimen = getExistingSpecimen(consentDetail.getConsentData().getSpecimenLabel()); existingSpecimen.setConsentTierStatusCollection(consentDetail.getConsentData() .getConsentTierStatusSet()); // set the consentTierCollection for child specimens populateConsentTierStatusCollectionforChildSpecimens(existingSpecimen, consentDetail); // and then update the specimen updateSpecimen(existingSpecimen); } } catch (ApplicationException ae) { // code for handling the exception LOG.error("Exception During Rollback of Consent with SpecimenLabel as " + consentDetail.getConsentData().getSpecimenLabel(), ae); throw new ApplicationException("Error occurred : Unable to rollback. Please check the logs.", ae); } } /** * This method is used to parse the incoming XML string and populate the 'Consents' object * * @param specimenListXMLStr * @return */ private Consents parseConsentsListXML(String consentsListXMLStr) { return (Consents) xStream.fromXML(new StringReader(consentsListXMLStr)); } /** * This method is used to fetch the ConsentData for given Specimen * * @param existingSpecimen * @return */ private ConsentData getConsentData(Specimen existingSpecimen) { final ConsentData existingConsentData = new ConsentData(); final Set<ConsentTierStatus> existingTierStatusCollection = new LinkedHashSet<ConsentTierStatus>(); final Collection<ConsentTierStatus> consentTierStatusCollection = existingSpecimen .getConsentTierStatusCollection(); if (consentTierStatusCollection != null) { final Iterator<ConsentTierStatus> itr = consentTierStatusCollection.iterator(); while (itr.hasNext()) { final ConsentTierStatus tierStatus = itr.next(); final ConsentTierStatus exitingTierStatus = new ConsentTierStatus(); exitingTierStatus.setStatus(tierStatus.getStatus()); final ConsentTier exitingConsentTier = new ConsentTier(); exitingConsentTier.setId(tierStatus.getConsentTier().getId()); exitingConsentTier.setStatement(tierStatus.getConsentTier().getStatement()); exitingTierStatus.setConsentTier(exitingConsentTier); existingTierStatusCollection.add(exitingTierStatus); } existingConsentData.setConsentTierStatusSet(existingTierStatusCollection); existingConsentData.setSpecimenLabel(existingSpecimen.getLabel()); } return existingConsentData; } private Specimen updateSpecimen(Specimen specimen) throws ApplicationException { return caTissueAPIClient.update(specimen); } /** * This method is used to get a specimen on the basis of the Label * * @param label * @return * @throws ApplicationException */ private Specimen getExistingSpecimen(String label) throws ApplicationException { Specimen specimen = new Specimen(); specimen.setLabel(label);// set the cdmsSpecimenId // get the specimen, corresponding to the cdmsSpecimenId specimen = caTissueAPIClient.searchById(Specimen.class, specimen); return specimen; } /** * * @param caTissueAPIClient CaTissueAPIClientWithRegularAuthentication */ public void setCaTissueAPIClient(CaTissueAPIClientWithRegularAuthentication caTissueAPIClient) { this.caTissueAPIClient = caTissueAPIClient; } }
package moodprofile.controller; import foodprofile.view.FoodUI; import java.sql.Connection; import moodprofile.model.Mood; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.GregorianCalendar; import moodprofile.model.MoodList; import moodprofile.view.MoodListUI; import moodprofile.view.MoodUI; import userprofile.model.User; /** * * @author Michael Kramer */ public class MoodController { private MoodList moodList; private Connection theConnection; private Statement theStatement; public MoodController(User currentUser){ } /** * This sets the MoodList for the current user * @param moodList the moodList to set */ public void setMoodList(MoodList moodList) { this.moodList = moodList; } /** * Adds a Mood to the current user's FoodList * @param mood the mood to add */ public void addMood(Mood mood){ moodList.addMoodProfile(mood); } /** * This updates a mood, using the id stored within the mood class. Also updates linkages * @param mood the mood to update */ public void updateMood(Mood mood){ } /** * This deletes the mood from the current user's MoodList * @param moodID the mood to delete */ public void deleteMood(int moodID){ } /** * Deletes a mood from the current user's MoodList and the linkages of all foods it was linked to * @param mood the mood to delete */ public void deleteMood(Mood mood){ moodList.removeMoodProfile(mood); } /** * Links foods and moods based on the time the food was consumed * @param moodID the ID of the mood * @param time time the mood was entered */ public void addLinkedFoodsToMood(int moodID, GregorianCalendar time){ } public void readMoods(){ System.out.println("Reading moods"); try{ Class.forName("org.sqlite.JDBC"); theConnection = DriverManager.getConnection("jdbc:sqlite:foodmood.db"); theStatement = theConnection.createStatement(); ResultSet set = theStatement.executeQuery("SELECT * FROM mood"); ArrayList<Mood> moods = new ArrayList(); while(set.next()){ int id = set.getInt("id"); String name = set.getString("name"); int score = set.getInt("score"); Mood mood = new Mood(); mood.setId(id); mood.setName(name); mood.setMoodScore(score); moods.add(mood); } moodList = new MoodList(moods); theStatement.close(); theConnection.close(); }catch(Exception e){ e.printStackTrace(); System.exit(0); } } public void goListView(){ MoodListUI moodListUI = new MoodListUI(this); moodListUI.setVisible(true); } public void addMood(String name, GregorianCalendar time){ if(moodList==null){ moodList = new MoodList(); } moodList.add(name, time); } public MoodList getMoodList(){ if(moodList == null){ moodList = new MoodList(); } return moodList; } public void newMood(){ MoodUI moodUI = new MoodUI(this); moodUI.setVisible(true); } public void viewMood(Mood mood){ MoodUI moodUI = new MoodUI(this, mood); moodUI.setVisible(true); } }
package net.acomputerdog.ircbot.security; import com.sorcix.sirc.structure.User; import com.sorcix.sirc.util.Chattable; import net.acomputerdog.core.logger.CLogger; import net.acomputerdog.ircbot.config.Config; import net.acomputerdog.ircbot.main.IrcBot; import java.util.HashMap; import java.util.Map; public class Auth { private final IrcBot bot; private final CLogger LOGGER; private final Map<User, Long> authenticatedAdmins = new HashMap<>(); private final Map<User, Integer> loginAttempts = new HashMap<>(); private final Map<User, Long> authFailedTimeouts = new HashMap<>(); private final Map<User, Long> reauthWaitingAdmins = new HashMap<>(); private final Map<User, String> verifyWaitingPass = new HashMap<>(); private final Map<User, Long> verifyWaitingTimeout = new HashMap<>(); private final Map<User, Chattable> loginReplyTarget = new HashMap<>(); public Auth(IrcBot bot) { this.bot = bot; LOGGER = bot.getLogManager().getLogger("Auth"); } public void requestAuthentication(User user, Chattable target, String pass) { verifyWaitingPass.put(user, pass); verifyWaitingTimeout.put(user, System.currentTimeMillis() + 60000); loginReplyTarget.put(user, target); bot.getNickServ().send("ACC " + user.getNick()); } private boolean authenticate(User user, String pass) { if (loginAttempts.get(user) == null) { loginAttempts.put(user, 0); } int attempts = loginAttempts.get(user) + 1; loginAttempts.put(user, attempts); if (attempts < Config.MAX_AUTH_ATTEMPTS) { if (bot.getAdmins().isAdmin(user)) { if (pass.equals(Config.ADMIN_PASS)) { LOGGER.logInfo("Admin " + getUserName(user) + " has been authenticated."); loginReplyTarget.get(user).send("You have now been logged in! Remember that if you log out for more than " + (Config.AUTH_TIMEOUT / 60000) + " minutes your session will expire!"); authenticatedAdmins.put(user, System.currentTimeMillis() + Config.AUTH_TIMEOUT); loginAttempts.put(user, 0); authFailedTimeouts.remove(user); return true; } else { loginReplyTarget.get(user).send("Incorrect password, please try again!"); logFailedAuth(user, "Incorrect password.", pass); } } else { loginReplyTarget.get(user).send("You are not an AcomputerBot admin!"); logFailedAuth(user, "Not an admin.", pass); } } else { loginReplyTarget.get(user).send("You have too many failed login attempts! Please try again in " + (Config.LOGIN_ATTEMPT_TIMEOUT / 60000) + " minutes."); authFailedTimeouts.put(user, System.currentTimeMillis() + Config.LOGIN_ATTEMPT_TIMEOUT); logFailedAuth(user, "Too many login attempts.", pass); } return false; } private void logFailedAuth(User user, String reason, String pass) { LOGGER.logWarning("User " + getUserName(user) + " failed authentication!"); LOGGER.logWarning(" Reason: " + reason); LOGGER.logWarning(" Password used: \"" + pass + "\"."); } private String getUserName(User user) { return user.getNick() + "@" + user.getHostName(); } public boolean isAuthenticated(User user) { return authenticatedAdmins.containsKey(user); } public void tick() { for (User user : authFailedTimeouts.keySet()) { long time = authFailedTimeouts.get(user); if (time <= System.currentTimeMillis()) { authFailedTimeouts.remove(user); loginAttempts.put(user, 0); } } for (User user : authenticatedAdmins.keySet()) { if (authenticatedAdmins.get(user) <= System.currentTimeMillis()) { bot.getNickServ().send("ACC " + user.getNick()); reauthWaitingAdmins.put(user, System.currentTimeMillis() + 60000); } } for (User user : reauthWaitingAdmins.keySet()) { if (reauthWaitingAdmins.get(user) <= System.currentTimeMillis()) { deauthenticate(user); user.send("Your admin session has expired, you must reauthenticate to perform admin commands!"); LOGGER.logWarning("Authentication expired for admin " + user.getNick() + "."); } } for (User user : verifyWaitingTimeout.keySet()) { if (verifyWaitingTimeout.get(user) <= System.currentTimeMillis()) { verifyWaitingTimeout.remove(user); verifyWaitingPass.remove(user); loginReplyTarget.get(user).send("AcomputerBot was unable to verify your login status with NickServ! This is a bug, please try logging in again!"); LOGGER.logWarning("Unable to verify NickServ status for \"" + user.getNick() + "\"!"); } } } public boolean deauthenticate(User user) { loginAttempts.remove(user); authFailedTimeouts.remove(user); reauthWaitingAdmins.remove(user); verifyWaitingTimeout.remove(user); verifyWaitingPass.remove(user); loginReplyTarget.remove(user); if (!authenticatedAdmins.containsKey(user)) { return false; } authenticatedAdmins.remove(user); LOGGER.logInfo("Admin " + getUserName(user) + " has been deauthenticated."); return true; } void onUserVerified(User user) { if (verifyWaitingPass.containsKey(user)) { authenticate(user, verifyWaitingPass.get(user)); verifyWaitingPass.remove(user); verifyWaitingTimeout.remove(user); } if (authenticatedAdmins.containsKey(user)) { authenticatedAdmins.put(user, authenticatedAdmins.get(user) + Config.AUTH_TIMEOUT); reauthWaitingAdmins.remove(user); loginAttempts.put(user, 0); authFailedTimeouts.remove(user); } } void onUserUnverified(User user) { if (verifyWaitingPass.containsKey(user)) { logFailedAuth(user, "Not logged in to nickserv.", verifyWaitingPass.get(user)); user.send("You must be logged into NickServ to log in as an AcomputerBot admin!"); } if (reauthWaitingAdmins.containsKey(user)) { user.send("You have logged out of NickServ, and your admin session has expired! You must log in again to perform admin commands."); LOGGER.logWarning("Admin " + user.getNick() + " has logged out of NickServ and lost authentication."); } deauthenticate(user); } }
/** * @author dgeorge * * $Id: AnimalModelManagerImpl.java,v 1.72 2006-08-17 18:34:25 pandyas Exp $ * * $Log: not supported by cvs2svn $ * Revision 1.71 2006/05/23 17:00:31 pandyas * fixed comments - cut and paste from other section * * Revision 1.70 2006/05/03 20:04:21 pandyas * Modified to add Morpholino object data to application * * Revision 1.69 2006/04/27 15:03:54 pandyas * Removed unused import statement * * Revision 1.68 2006/04/20 19:18:53 pandyas * Moved save Assoc Met from AnimalModel to the Histopathology * * Revision 1.67 2006/04/20 18:11:31 pandyas * Cleaned up Species or Strain save of Other in DB * * Revision 1.66 2006/04/19 17:39:57 pandyas * Cleaned up e-mail - removed save of 'Other' to DB * * Revision 1.65 2006/04/18 16:19:32 pandyas * modified debug command from debug to info to display messages * * Revision 1.64 2006/04/17 19:11:06 pandyas * caMod 2.1 OM changes * * Revision 1.63 2006/01/18 14:24:23 georgeda * TT# 376 - Updated to use new Java 1.5 features * * Revision 1.62 2005/12/21 15:40:29 georgeda * Defect #288 - error when submitting an other strain * * Revision 1.61 2005/12/01 13:43:36 georgeda * Defect #226, reuse Taxon objects and do not delete them from Database * * Revision 1.60 2005/11/16 15:31:05 georgeda * Defect #41. Clean up of email functionality * * Revision 1.59 2005/11/14 14:17:57 georgeda * Cleanup * * Revision 1.58 2005/11/08 16:48:24 georgeda * Changes for images * * Revision 1.57 2005/11/07 19:15:17 pandyas * modified for clinical marker screen * * Revision 1.56 2005/11/04 14:44:25 georgeda * Cleaned up histopathology/assoc metastasis * * Revision 1.55 2005/11/03 18:57:13 pandyas * Modified for histopathology screens * * Revision 1.54 2005/11/03 18:11:04 georgeda * Fix old vocab problem * * Revision 1.53 2005/11/03 17:22:35 schroedn * Changed how Associated Expression for Genetic Description were coded, cleaned up * * Revision 1.52 2005/11/03 17:01:30 georgeda * Change taxon creation strat. * * Revision 1.51 2005/11/02 21:46:09 georgeda * Fixed creation of sex distribution * * Revision 1.50 2005/11/02 20:56:04 schroedn * Added Staining to Image submission * * Revision 1.49 2005/11/02 19:02:55 pandyas * Added e-mail functionality * * Revision 1.48 2005/10/27 17:15:22 schroedn * Updated addAssociatedExpression for all Genetic Descriptions * * Revision 1.45 2005/10/26 20:42:52 schroedn * merged changes, Added AssocExpression to EngineeredTransgene submission page * * Revision 1.44 2005/10/26 20:16:57 pandyas * implemented model availability * * Revision 1.43 2005/10/24 21:00:17 schroedn * addImage added * * Revision 1.42 2005/10/24 18:05:36 georgeda * Show the modified date in the returned models * * Revision 1.41 2005/10/24 17:10:39 georgeda * First pass at duplicate * * Revision 1.40 2005/10/24 13:28:06 georgeda * Cleanup changes * * Revision 1.39 2005/10/21 19:38:37 schroedn * Added caImage ftp capabilities for EngineeredTransgene, GenomicSegment and TargetedModification * * Revision 1.38 2005/10/21 16:07:26 pandyas * implementation of animal availability * * Revision 1.37 2005/10/20 20:39:50 stewardd * modified to use constant value instead of a hard coded string in messageKeys * * Revision 1.36 2005/10/20 18:55:38 stewardd * Employs new EmailUtil API supporting e-mail content built from ResourceBundle-stored templates with support for variables (via Velocity API) * * Revision 1.35 2005/10/19 19:26:35 pandyas * added admin route to growth factor * * Revision 1.34 2005/10/18 16:23:31 georgeda * Changed getModelsByUser to return models where the PI is the user as well * * Revision 1.33 2005/10/13 20:47:25 georgeda * Correctly handle the PI * * Revision 1.32 2005/10/12 15:55:16 georgeda * Do not reuse taxon since it has an uncontolled vocab * * Revision 1.31 2005/10/11 20:52:51 schroedn * EngineeredTransgene and GenomicSegment edit/save works, not image * * EngineeredTransgene - 'Other' Species not working * * Revision 1.30 2005/10/10 20:05:19 pandyas * removed animalmodel reference in populate method * * Revision 1.29 2005/10/10 14:08:02 georgeda * Performance improvement * * Revision 1.28 2005/10/07 16:27:54 georgeda * Implemented paganation * * Revision 1.27 2005/10/06 20:43:45 schroedn * Fixed missing reference * * Revision 1.26 2005/10/06 20:41:51 schroedn * InducedMutation, TargetedMutation, GenomicSegment changes * * Revision 1.25 2005/10/06 19:33:10 pandyas * modified for Therapy screen * * Revision 1.24 2005/10/06 13:36:09 georgeda * Changed ModelCharacteristics interface to be consistent w/ the rest of the interfaces * * Revision 1.23 2005/10/05 15:17:48 schroedn * SpontaneousMutation create and edit now working * * Revision 1.22 2005/10/04 20:12:52 schroedn * Added Spontaneous Mutation, InducedMutation, Histopathology, TargetedModification and GenomicSegment * * Revision 1.21 2005/10/03 13:51:36 georgeda * Search changes * * Revision 1.20 2005/09/30 18:59:06 pandyas * modified for cell line * * Revision 1.19 2005/09/28 21:20:02 georgeda * Finished up converting to new manager * * Revision 1.18 2005/09/28 15:12:29 schroedn * Added GeneDelivery and Xenograft/Transplant, businass logic in Managers * * Revision 1.17 2005/09/28 14:14:00 schroedn * Added saveXenograft and saveGeneDelivery * * Revision 1.16 2005/09/28 12:46:12 georgeda * Cleanup of animal manager * * Revision 1.15 2005/09/27 19:17:16 georgeda * Refactor of CI managers * * Revision 1.14 2005/09/27 16:44:49 georgeda * Added ChemicalDrug handling * Revision 1.13 2005/09/26 14:04:36 georgeda * Cleanup for cascade fix and common manager code * * Revision 1.12 2005/09/23 14:55:19 georgeda * Made SexDistribution a reference table * * Revision 1.11 2005/09/22 18:55:53 georgeda * Get coordinator from user in properties file * * Revision 1.10 2005/09/19 18:13:51 georgeda * Changed boolean to Boolean * * Revision 1.9 2005/09/19 12:55:24 georgeda * Handle empty sex distribution table * * Revision 1.8 2005/09/16 15:52:57 georgeda * Changes due to manager re-write * * */ package gov.nih.nci.camod.service.impl; import gov.nih.nci.camod.Constants; import gov.nih.nci.camod.domain.AnimalAvailability; import gov.nih.nci.camod.domain.AnimalModel; import gov.nih.nci.camod.domain.AnimalModelSearchResult; import gov.nih.nci.camod.domain.Availability; import gov.nih.nci.camod.domain.CarcinogenExposure; import gov.nih.nci.camod.domain.CellLine; import gov.nih.nci.camod.domain.EngineeredGene; import gov.nih.nci.camod.domain.GeneDelivery; import gov.nih.nci.camod.domain.GenomicSegment; import gov.nih.nci.camod.domain.Histopathology; import gov.nih.nci.camod.domain.Image; import gov.nih.nci.camod.domain.InducedMutation; import gov.nih.nci.camod.domain.Log; import gov.nih.nci.camod.domain.Morpholino; import gov.nih.nci.camod.domain.Person; import gov.nih.nci.camod.domain.Phenotype; import gov.nih.nci.camod.domain.Publication; import gov.nih.nci.camod.domain.SexDistribution; import gov.nih.nci.camod.domain.SpontaneousMutation; import gov.nih.nci.camod.domain.Strain; import gov.nih.nci.camod.domain.TargetedModification; import gov.nih.nci.camod.domain.Therapy; import gov.nih.nci.camod.domain.Transgene; import gov.nih.nci.camod.domain.Xenograft; import gov.nih.nci.camod.service.AnimalModelManager; import gov.nih.nci.camod.util.DuplicateUtil; import gov.nih.nci.camod.util.MailUtil; import gov.nih.nci.camod.webapp.form.AssociatedExpressionData; import gov.nih.nci.camod.webapp.form.AvailabilityData; import gov.nih.nci.camod.webapp.form.CellLineData; import gov.nih.nci.camod.webapp.form.ChemicalDrugData; import gov.nih.nci.camod.webapp.form.ClinicalMarkerData; import gov.nih.nci.camod.webapp.form.EngineeredTransgeneData; import gov.nih.nci.camod.webapp.form.EnvironmentalFactorData; import gov.nih.nci.camod.webapp.form.GeneDeliveryData; import gov.nih.nci.camod.webapp.form.GenomicSegmentData; import gov.nih.nci.camod.webapp.form.GrowthFactorData; import gov.nih.nci.camod.webapp.form.HistopathologyData; import gov.nih.nci.camod.webapp.form.HormoneData; import gov.nih.nci.camod.webapp.form.ImageData; import gov.nih.nci.camod.webapp.form.InducedMutationData; import gov.nih.nci.camod.webapp.form.ModelCharacteristicsData; import gov.nih.nci.camod.webapp.form.MorpholinoData; import gov.nih.nci.camod.webapp.form.NutritionalFactorData; import gov.nih.nci.camod.webapp.form.PublicationData; import gov.nih.nci.camod.webapp.form.RadiationData; import gov.nih.nci.camod.webapp.form.SearchData; import gov.nih.nci.camod.webapp.form.SpontaneousMutationData; import gov.nih.nci.camod.webapp.form.SurgeryData; import gov.nih.nci.camod.webapp.form.TargetedModificationData; import gov.nih.nci.camod.webapp.form.TherapyData; import gov.nih.nci.camod.webapp.form.ViralTreatmentData; import gov.nih.nci.camod.webapp.form.XenograftData; import gov.nih.nci.common.persistence.Persist; import gov.nih.nci.common.persistence.Search; import gov.nih.nci.common.persistence.exception.PersistenceException; import gov.nih.nci.common.persistence.hibernate.HibernateUtil; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import java.util.TreeMap; import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; /** * Manages fetching/saving/updating of animal models */ public class AnimalModelManagerImpl extends BaseManager implements AnimalModelManager { /** * Get all of the animal models in the DB * * @return the list of all animal models * * @exception throws * an Exception if an error occurred */ public List getAll() throws Exception { log.debug("In AnimalModelManagerImpl.getAll"); return super.getAll(AnimalModel.class); } /** * Get all of the animal models submitted by a username * * @param inUsername * the username the models are submitted by * * @return the list of animal models * * @exception throws * an Exception if an error occurred */ public List getAllByUser(String inUsername) throws Exception { log.debug("In AnimalModelManagerImpl.getAllByUser"); return QueryManagerSingleton.instance().getModelsByUser(inUsername); } /** * Get all of the animal models of a specific state * * @param inState * the state to query for * * @return the list of animal models * * @exception Exception * if an error occurred */ public List getAllByState(String inState) throws Exception { log.info("Entering AnimalModelManagerImpl.getAllByState"); // The list of AnimalModels to be returned List theAnimalModels = new ArrayList(); // The following two objects are needed for eQBE. AnimalModel theAnimalModel = new AnimalModel(); theAnimalModel.setState(inState); try { theAnimalModels = Search.query(theAnimalModel); } catch (Exception e) { log.error("Exception occurred in getAllByState", e); throw e; } log.info("Exiting AnimalModelManagerImpl.getAllByState"); return theAnimalModels; } /** * Get all of the models of a specific state * * @param inState * the state to query for * * @return the list of models * * @exception Exception * if an error occurred */ public List getAllByStateForPerson(String inState, Person inPerson) throws Exception { log.info("In CommentsManagerImpl.getAllByStateForPerson"); return QueryManagerSingleton.instance().getModelsByStateForPerson( inState, inPerson); } /** * Get a specific animal model * * @param id * The unique id for the model * * @return the animal model if found, null otherwise * @throws Exception * * @exception Exception * if an error occurred */ public AnimalModel get(String id) throws Exception { log.debug("In AnimalModelManagerImpl.get"); AnimalModel theAnimalModel = (AnimalModel) super.get(id, AnimalModel.class); // Set the modified date in case we save a change theAnimalModel.getAvailability().setModifiedDate(new Date()); return theAnimalModel; } /** * Save an animal model * * @param id * The unique id for the model * * @exception Exception * if an error occurred */ public void save(AnimalModel inAnimalModel) throws Exception { log.info("In AnimalModelManagerImpl.save"); super.save(inAnimalModel); } /** * Do a deep copy of the passed in animal model * * @return the list of all animal models * * @exception throws * an Exception if an error occurred */ public AnimalModel duplicate(AnimalModel inAnimalModel) throws Exception { log.info("In AnimalModelManagerImpl.duplicate"); AnimalModel theDuplicatedModel = (AnimalModel) DuplicateUtil .duplicateBean(inAnimalModel); String theNewModelDescriptor = theDuplicatedModel.getModelDescriptor() + " (Copy) "; theDuplicatedModel.setModelDescriptor(theNewModelDescriptor); theDuplicatedModel.getAvailability().setModifiedDate(null); theDuplicatedModel.getAvailability().setEnteredDate(new Date()); save(theDuplicatedModel); return theDuplicatedModel; } /** * Update an animal model and create an associated log entry * * @param id * The unique id for the model * @throws Exception * * @exception Exception * if an error occurred */ public void updateAndAddLog(AnimalModel inAnimalModel, Log inLog) throws Exception { log.info("Entering updateAndAddLog"); try { // Make sure they get saved together HibernateUtil.beginTransaction(); Persist.save(inAnimalModel); Persist.save(inLog); HibernateUtil.commitTransaction(); } catch (PersistenceException pe) { HibernateUtil.rollbackTransaction(); log.error("PersistenceException in save", pe); throw pe; } catch (Exception e) { HibernateUtil.rollbackTransaction(); log.error("Exception in save", e); throw e; } log.info("Exiting updateAndAddLog"); } /** * Create a new/unsaved animal model * * @param inModelCharacteristicsData * The values for the model and associated objects * * @param inUsername * The submitter * * @return the created and unsaved AnimalModel * @throws Exception */ public AnimalModel create( ModelCharacteristicsData inModelCharacteristicsData, String inUsername) throws Exception { log.info("Entering AnimalModelManagerImpl.create"); AnimalModel theAnimalModel = new AnimalModel(); log.info("Exiting AnimalModelManagerImpl.create"); return populateAnimalModel(inModelCharacteristicsData, inUsername, theAnimalModel); } /** * Update the animal model w/ the new characteristics and save * * @param inModelCharacteristicsData * The new values for the model and associated objects * * @param inAnimalModel * The animal model to update */ public void update(ModelCharacteristicsData inModelCharacteristicsData, AnimalModel inAnimalModel) throws Exception { log.info("Entering AnimalModelManagerImpl.update"); log.debug("Updating animal model: " + inAnimalModel.getId()); // Populate w/ the new values and save inAnimalModel = populateAnimalModel(inModelCharacteristicsData, null, inAnimalModel); save(inAnimalModel); log.info("Exiting AnimalModelManagerImpl.update"); } /** * Remove the animal model from the system. Should remove all associated * data as well * * @param id * The unique id of the animal model to delete * * @throws Exception * An error occurred when attempting to delete the model */ public void remove(String id) throws Exception { log.info("In AnimalModelManagerImpl.remove"); super.remove(id, AnimalModel.class); } /** * Search for animal models based on: - modelName - piName - siteOfTumor - * speciesName * * Note: This method is currently a dummy search method and simply returns * all the animal model objects in the database. Searching using eQBE needs * to be done. * * @throws Exception */ public List<AnimalModelSearchResult> search(SearchData inSearchData) throws Exception { log.info("In search"); List theAnimalModels = QueryManagerSingleton.instance() .searchForAnimalModels(inSearchData); List<AnimalModelSearchResult> theDisplayList = new ArrayList<AnimalModelSearchResult>(); // Add AnimalModel DTO's so that the paganation works quickly for (int i = 0, j = theAnimalModels.size(); i < j; i++) { AnimalModel theAnimalModel = (AnimalModel) theAnimalModels.get(i); theDisplayList.add(new AnimalModelSearchResult(theAnimalModel)); } return theDisplayList; } // Populate the model based on the model characteristics form passed in. private AnimalModel populateAnimalModel( ModelCharacteristicsData inModelCharacteristicsData, String inUsername, AnimalModel inAnimalModel) throws Exception { log.info("Entering populateAnimalModel"); // Handle the person information if (inUsername != null) { Person theSubmitter = PersonManagerSingleton.instance() .getByUsername(inUsername); if (theSubmitter == null) { throw new IllegalArgumentException("Unknown user: " + inUsername); } inAnimalModel.setSubmitter(theSubmitter); } Person thePI = PersonManagerSingleton.instance().getByUsername( inModelCharacteristicsData.getPrincipalInvestigator()); if (thePI == null) { throw new IllegalArgumentException( "Unknown principal investigator: " + inUsername); } inAnimalModel.setPrincipalInvestigator(thePI); // Set the animal model information boolean isToolStrain = inModelCharacteristicsData.getIsToolStrain() .equals("yes") ? true : false; inAnimalModel.setIsToolStrain(new Boolean(isToolStrain)); inAnimalModel.setUrl(inModelCharacteristicsData.getUrl()); inAnimalModel.setModelDescriptor(inModelCharacteristicsData .getModelDescriptor()); inAnimalModel.setExperimentDesign(inModelCharacteristicsData .getExperimentDesign()); // Create/reuse the strain object - This method does not set strain when // 'other' is selected (lookup) Strain theNewStrain = StrainManagerSingleton.instance().getOrCreate( inModelCharacteristicsData.getEthinicityStrain(), inModelCharacteristicsData.getOtherEthnicityStrain(), inModelCharacteristicsData.getScientificName()); log.info("\n theNewStrain: " + theNewStrain.getName() + ": " + theNewStrain.getNameUnctrlVocab()); // other option selected if (inModelCharacteristicsData.getEthinicityStrain().equals( Constants.Dropdowns.OTHER_OPTION)) { // Object is returned with uncontrolled vocab set, do not save // 'Other' in DB, send e-mail inAnimalModel.setStrain(theNewStrain); sendEmail(inAnimalModel, inModelCharacteristicsData .getOtherEthnicityStrain(), "EthinicityStrain"); } else { // used to setSpecies in AnimalModel now used to setStrain in 2.1 inAnimalModel.setStrain(theNewStrain); } Phenotype thePhenotype = inAnimalModel.getPhenotype(); if (thePhenotype == null) { thePhenotype = new Phenotype(); } // Get/create the sex distribution if (inModelCharacteristicsData.getType() != null) { SexDistribution theSexDistribution = SexDistributionManagerSingleton .instance().getByType(inModelCharacteristicsData.getType()); thePhenotype.setSexDistribution(theSexDistribution); } // Create the phenotype thePhenotype .setDescription(inModelCharacteristicsData.getDescription()); thePhenotype.setBreedingNotes(inModelCharacteristicsData .getBreedingNotes()); // Get the availability Availability theAvailability = inAnimalModel.getAvailability(); // When the model was created if (theAvailability == null) { theAvailability = new Availability(); } else { theAvailability.setModifiedDate(new Date()); } theAvailability.setEnteredDate(new Date()); // Convert the date Date theDate = new Date(); if (!inModelCharacteristicsData.getReleaseDate().equals("immediately")) { // Convert the string to a date. Default to "now" if there are any // errors DateFormat theDateFormat = new SimpleDateFormat("MM/dd/yyyy"); try { theDate = theDateFormat.parse(inModelCharacteristicsData .getCalendarReleaseDate()); } catch (Exception e) { log.error("Error parsing release date, defaulting to now", e); } } theAvailability.setReleaseDate(theDate); // Associated the created objects inAnimalModel.setAvailability(theAvailability); inAnimalModel.setPhenotype(thePhenotype); log.info("Exiting populateAnimalModel"); return inAnimalModel; } public void addXenograft(AnimalModel inAnimalModel, XenograftData inXenograftData) throws Exception { System.out .println("<AnimalModelManagerImpl populate> Entering addXenograft() "); log.info("Entering saveXenograft"); Xenograft theXenograft = XenograftManagerSingleton.instance().create( inXenograftData, inAnimalModel); inAnimalModel.addXenograft(theXenograft); save(inAnimalModel); System.out .println("<AnimalModelManagerImpl populate> Exiting addXenograft() "); log.info("Exiting saveXenograft"); } /** * Add a gene delivery * * @param inAnimalModel * the animal model that has the therapy * @param inGeneDeliveryData * the gene delivery * @throws Exception */ public void addGeneDelivery(AnimalModel inAnimalModel, GeneDeliveryData inGeneDeliveryData) throws Exception { log.info("<AnimalModelManagerImpl> Entering addGeneDelivery"); GeneDelivery theGeneDelivery = GeneDeliveryManagerSingleton.instance() .create(inAnimalModel, inGeneDeliveryData); inAnimalModel.addGeneDelivery(theGeneDelivery); save(inAnimalModel); log.info("<AnimalModelManagerImpl> Exiting addGeneDelivery"); } /** * Add a chemical/drug therapy * * @param inAnimalModel * the animal model that has the addCarcinogenExposure * @param inChemicalDrugData * the new chemical drug data * @throws Exception */ public void addCarcinogenExposure(AnimalModel inAnimalModel, ChemicalDrugData inChemicalDrugData) throws Exception { log .info("Entering AnimalModelManagerImpl.addCarcinogenExposure (chemical/drug)"); CarcinogenExposure theCarcinogenExposure = CarcinogenExposureManagerSingleton .instance().create(inAnimalModel, inChemicalDrugData); inAnimalModel.addCarcinogenExposure(theCarcinogenExposure); save(inAnimalModel); log .info("Exiting AnimalModelManagerImpl.addCarcinogenExposure (chemical/drug)"); } /** * Add an environmental factor CarcinogenExposure * * @param inAnimalModel * the animal model that has the CarcinogenExposure * @param inEnvironmentalFactorData * the data * @throws Exception */ public void addCarcinogenExposure(AnimalModel inAnimalModel, EnvironmentalFactorData inEnvironmentalFactorData) throws Exception { log.info("Entering AnimalModelManagerImpl.addCarcinogenExposure (EF)"); CarcinogenExposure theCarcinogenExposure = CarcinogenExposureManagerSingleton .instance().create(inAnimalModel, inEnvironmentalFactorData); inAnimalModel.addCarcinogenExposure(theCarcinogenExposure); save(inAnimalModel); log.info("Exiting AnimalModelManagerImpl.addCarcinogenExposure (EF)"); } /** * Add an Radiation * * @param inAnimalModel * the animal model that has the CarcinogenExposure * @param inRadiationData * the new radiation data * @throws Exception */ public void addCarcinogenExposure(AnimalModel inAnimalModel, RadiationData inRadiationData) throws Exception { log .info("Entering AnimalModelManagerImpl.addCarcinogenExposure (Radiation)"); CarcinogenExposure theCarcinogenExposure = CarcinogenExposureManagerSingleton .instance().create(inAnimalModel, inRadiationData); inAnimalModel.addCarcinogenExposure(theCarcinogenExposure); save(inAnimalModel); log .info("Exiting AnimalModelManagerImpl.addCarcinogenExposure (Radiation)"); } /** * Add an ViralTreatment * * @param inAnimalModel * the animal model that has the CarcinogenExposure * @param inViralTreatmentData * the new viral treatment data * @throws Exception */ public void addCarcinogenExposure(AnimalModel inAnimalModel, ViralTreatmentData inViralTreatmentData) throws Exception { log .info("Entering AnimalModelManagerImpl.addCarcinogenExposure (ViralTreatment)"); CarcinogenExposure theCarcinogenExposure = CarcinogenExposureManagerSingleton .instance().create(inAnimalModel, inViralTreatmentData); inAnimalModel.addCarcinogenExposure(theCarcinogenExposure); save(inAnimalModel); log .info("Exiting AnimalModelManagerImpl.addCarcinogenExposure (ViralTreatment)"); } /** * Add a growth factor * * @param inAnimalModel * the animal model that has the CarcinogenExposure * @param inGrowthFactorData * the new growth factor data * @throws Exception */ public void addCarcinogenExposure(AnimalModel inAnimalModel, GrowthFactorData inGrowthFactorData) throws Exception { log .info("Entering AnimalModelManagerImpl.addCarcinogenExposure (growth factor)"); CarcinogenExposure theCarcinogenExposure = CarcinogenExposureManagerSingleton .instance().create(inAnimalModel, inGrowthFactorData); inAnimalModel.addCarcinogenExposure(theCarcinogenExposure); save(inAnimalModel); log .info("Exiting AnimalModelManagerImpl.addCarcinogenExposure (growth factor)"); } /** * Add a hormone * * @param inAnimalModel * the animal model that has the addCarcinogenExposure * @param inHormoneData * the new growth factor data * @throws Exception */ public void addCarcinogenExposure(AnimalModel inAnimalModel, HormoneData inHormoneData) throws Exception { log .info("Entering AnimalModelManagerImpl.addCarcinogenExposure (hormone)"); CarcinogenExposure theCarcinogenExposure = CarcinogenExposureManagerSingleton .instance().create(inAnimalModel, inHormoneData); inAnimalModel.addCarcinogenExposure(theCarcinogenExposure); save(inAnimalModel); log .info("Exiting AnimalModelManagerImpl.addCarcinogenExposure (hormone) "); } /** * Add a nutritional factor * * @param inAnimalModel * the animal model that has the CarcinogenExposure * @param inNutritionalFactorData * the new nutrional factor data * @throws Exception */ public void addCarcinogenExposure(AnimalModel inAnimalModel, NutritionalFactorData inNutritionalFactorData) throws Exception { log .info("Entering AnimalModelManagerImpl.addCarcinogenExposure (nutritional)"); CarcinogenExposure theCarcinogenExposure = CarcinogenExposureManagerSingleton .instance().create(inAnimalModel, inNutritionalFactorData); inAnimalModel.addCarcinogenExposure(theCarcinogenExposure); save(inAnimalModel); log .info("Exiting AnimalModelManagerImpl.addCarcinogenExposure (nutritional)"); } /** * Add a surgery/other * * @param inAnimalModel * the animal model that has the CarcinogenExposure * @param inSurgeryData * the new CarcinogenExposure data * @throws Exception */ public void addCarcinogenExposure(AnimalModel inAnimalModel, SurgeryData inSurgeryData) throws Exception { log .info("Entering AnimalModelManagerImpl.addCarcinogenExposure (surgery/other)"); CarcinogenExposure theCarcinogenExposure = CarcinogenExposureManagerSingleton .instance().create(inAnimalModel, inSurgeryData); inAnimalModel.addCarcinogenExposure(theCarcinogenExposure); save(inAnimalModel); log .info("Exiting AnimalModelManagerImpl.addCarcinogenExposure (surgery/other)"); } /** * Add a cell line * * @param inAnimalModel * the animal model that has the cell line * @param inSurgeryData * the new cell line data * @throws Exception */ public void addCellLine(AnimalModel inAnimalModel, CellLineData inCellLineData) throws Exception { log.debug("<AnimalModelManagerImpl> Entering addCellLine"); CellLine theCellLine = CellLineManagerSingleton.instance().create( inCellLineData); inAnimalModel.addCellLine(theCellLine); save(inAnimalModel); log.debug("<AnimalModelManagerImpl> Exiting addCellLine"); } /** * Add a SpontaneousMutation */ public void addGeneticDescription(AnimalModel inAnimalModel, SpontaneousMutationData inSpontaneousMutationData) throws Exception { log .info("<AnimalModelManagerImpl> Entering addGeneticDescription (spontaneousMutation)"); SpontaneousMutation theSpontaneousMutation = SpontaneousMutationManagerSingleton .instance().create(inSpontaneousMutationData); // System.out.println(theSpontaneousMutation.getName()); inAnimalModel.addSpontaneousMutation(theSpontaneousMutation); save(inAnimalModel); log .info("<AnimalModelManagerImpl> Exiting addGeneticDescription (spontaneousMutation)"); } /** * Add a InducedMutation */ public void addGeneticDescription(AnimalModel inAnimalModel, InducedMutationData inInducedMutationData) throws Exception { log.info("Entering addGeneticDescription (inducedMutation)"); InducedMutation theInducedMutation = InducedMutationManagerSingleton .instance().create(inAnimalModel, inInducedMutationData); inAnimalModel.addEngineeredGene(theInducedMutation); save(inAnimalModel); log.info("Exiting addGeneticDescription (inducedMutation)"); } /** * Add a TargetedModification */ public void addGeneticDescription(AnimalModel inAnimalModel, TargetedModificationData inTargetedModificationData, HttpServletRequest request) throws Exception { log.info("Entering addGeneticDescription (TargetedModification)"); TargetedModification theTargetedModification = TargetedModificationManagerSingleton .instance().create(inAnimalModel, inTargetedModificationData, request); // System.out.println(theGene.getName() ); inAnimalModel.addEngineeredGene(theTargetedModification); save(inAnimalModel); log.info("Exiting addGeneticDescription (TargetedModification)"); } public void addGeneticDescription(AnimalModel inAnimalModel, GenomicSegmentData inGenomicSegmentData, HttpServletRequest request) throws Exception { log.info("Entering addGeneticDescription (GenomicSegment)"); GenomicSegment theGenomicSegment = GenomicSegmentManagerSingleton .instance() .create(inAnimalModel, inGenomicSegmentData, request); // System.out.println(theGenomicSegment.getName() ); inAnimalModel.addEngineeredGene(theGenomicSegment); save(inAnimalModel); log.info("Exiting addGeneticDescription (GenomicSegment)"); } public void addGeneticDescription(AnimalModel inAnimalModel, EngineeredTransgeneData inEngineeredTransgeneData, HttpServletRequest request) throws Exception { log.info("Entering addGeneticDescription (EngineeredTransgene)"); Transgene theEngineeredTransgene = EngineeredTransgeneManagerSingleton .instance().create(inEngineeredTransgeneData, request); // System.out.println(theGenomicSegment.getName() ); inAnimalModel.addEngineeredGene(theEngineeredTransgene); save(inAnimalModel); log.info("Exiting addGeneticDescription (EngineeredTransgene)"); } public void addImage(AnimalModel inAnimalModel, ImageData inImageData, String inPath) throws Exception { log.info("Entering addImage (Image)"); Image theImage = ImageManagerSingleton.instance() .create(inAnimalModel, inImageData, inPath, Constants.CaImage.FTPMODELSTORAGEDIRECTORY); inAnimalModel.addImage(theImage); save(inAnimalModel); log.info("Exiting addImage (Image)"); } /** * Add a therapy * * @param inAnimalModel * the animal model that has the therapy * @param inChemicalDrugData * the new therapy data * @throws Exception */ public void addTherapy(AnimalModel inAnimalModel, TherapyData inTherapyData) throws Exception { System.out.println("<AnimalModelManagerImpl addTherapy>"); log.info("Entering AnimalModelManagerImpl.addTherapy"); Therapy theTherapy = TherapyManagerSingleton.instance().create( inAnimalModel, inTherapyData); inAnimalModel.addTherapy(theTherapy); save(inAnimalModel); log.info("Exiting AnimalModelManagerImpl.addTherapy"); } /** * Add an Availability * * @param inAnimalModel * the animal model that has the Availability * @param inAvailabilityData * the new therapy data * @throws Exception */ public void addAvailability(AnimalModel inAnimalModel, AvailabilityData inAvailabilityData) throws Exception { System.out.println("<AnimalModelManagerImpl addAvailability>"); log.info("Entering AnimalModelManagerImpl.addAvailability"); AnimalAvailability theAvailability = AvailabilityManagerSingleton .instance().create(inAvailabilityData); inAnimalModel.addAnimalAvailability(theAvailability); save(inAnimalModel); log.info("Exiting AnimalModelManagerImpl.addAvailability"); } /** * Add an Availability * * @param inAnimalModel * the animal model that has the Availability * @param inAvailabilityData * the new therapy data * @throws Exception */ public void addInvestigatorAvailability(AnimalModel inAnimalModel, AvailabilityData inAvailabilityData) throws Exception { System.out .println("<AnimalModelManagerImpl addInvestigatorAvailability>"); log.info("Entering AnimalModelManagerImpl.addInvestigatorAvailability"); AnimalAvailability theAvailability = AvailabilityManagerSingleton .instance().createInvestigator(inAvailabilityData); inAnimalModel.addAnimalAvailability(theAvailability); save(inAnimalModel); log.info("Exiting AnimalModelManagerImpl.addInvestigatorAvailability"); } public void addAssociatedExpression(AnimalModel inAnimalModel, EngineeredGene inEngineeredGene, AssociatedExpressionData inAssociatedExpressionData) throws Exception { System.out.println("<AnimalModelManagerImpl addAssociatedExpression>"); log.info("Entering AnimalModelManagerImpl.addAssociatedExpression"); // addAssociatedExpression (ExpressionFeature) EngineeredTransgeneManagerSingleton.instance().createAssocExpression( inAssociatedExpressionData, inEngineeredGene); save(inAnimalModel); log.info("Exiting AnimalModelManagerImpl.addAssociatedExpression"); } public void addPublication(AnimalModel inAnimalModel, PublicationData inPublicationData) throws Exception { log.info("Entering AnimalModelManagerImpl.addPublication"); // addAssociatedExpression (ExpressionFeature Publication thePublication = PublicationManagerSingleton.instance() .create(inPublicationData); inAnimalModel.addPublication(thePublication); save(inAnimalModel); log.info("Exiting AnimalModelManagerImpl.addAssociatedExpression"); } public void addHistopathology(AnimalModel inAnimalModel, HistopathologyData inHistopathologyData) throws Exception { log.info("Entering AnimalModelManagerImpl.addHistopathology_1"); Histopathology theHistopathology = HistopathologyManagerSingleton .instance().createHistopathology(inHistopathologyData); inAnimalModel.addHistopathology(theHistopathology); save(inAnimalModel); log.info("Exiting AnimalModelManagerImpl.addHistopathology"); } public void addClinicalMarker(AnimalModel inAnimalModel, Histopathology inHistopathology, ClinicalMarkerData inClinicalMarkerData) throws Exception { log .info("Entering AnimalModelManagerImpl.addHistopathology to inClinicalMarkerData"); ClinicalMarkerManagerSingleton.instance().create(inClinicalMarkerData, inHistopathology); save(inAnimalModel); log .info("Exiting AnimalModelManagerImpl.addHistopathology to inClinicalMarkerData"); } /** * Add a Morpholino * * @param inAnimalModel * the animal model that has the Morpholino * @param inMorpholinoData * the new Morpholino data * @throws Exception */ public void addMorpholino(AnimalModel inAnimalModel, MorpholinoData inMorpholinoData) throws Exception { log.info("Entering AnimalModelManagerImpl.addMorpholino"); Morpholino theMorpholino = MorpholinoManagerSingleton.instance().create(inAnimalModel, inMorpholinoData); inAnimalModel.addMorpholino(theMorpholino); save(inAnimalModel); log.info("Exiting AnimalModelManagerImpl.addMorpholino"); } private void sendEmail(AnimalModel inAnimalModel, String theUncontrolledVocab, String inType) { // Get the e-mail resource Properties camodProperties = new Properties(); String camodPropertiesFileName = null; camodPropertiesFileName = System .getProperty("gov.nih.nci.camod.camodProperties"); try { FileInputStream in = new FileInputStream(camodPropertiesFileName); camodProperties.load(in); } catch (FileNotFoundException e) { log.error("Caught exception finding file for properties: ", e); e.printStackTrace(); } catch (IOException e) { log.error("Caught exception finding file for properties: ", e); e.printStackTrace(); } // String recipients = // theBundle.getString(Constants.BundleKeys.NEW_UNCONTROLLED_VOCAB_NOTIFY_KEY); String recipients = UserManagerSingleton.instance() .getEmailForCoordinator(); StringTokenizer st = new StringTokenizer(recipients, ","); String inRecipients[] = new String[st.countTokens()]; for (int i = 0; i < inRecipients.length; i++) { inRecipients[i] = st.nextToken(); } // String inSubject = // theBundle.getString(Constants.BundleKeys.NEW_UNCONTROLLED_VOCAB_SUBJECT_KEY); String inSubject = camodProperties .getProperty("model.new_unctrl_vocab_subject"); String inFrom = inAnimalModel.getSubmitter().getEmailAddress(); // gather message keys and variable values to build the e-mail String[] messageKeys = { Constants.Admin.NONCONTROLLED_VOCABULARY }; Map<String, Object> values = new TreeMap<String, Object>(); values.put("type", inType); values.put("value", theUncontrolledVocab); values.put("submitter", inAnimalModel.getSubmitter()); values.put("model", inAnimalModel.getModelDescriptor()); values.put("modelstate", inAnimalModel.getState()); // Send the email try { MailUtil.sendMail(inRecipients, inSubject, "", inFrom, messageKeys, values); } catch (MessagingException e) { log.error("Caught exception sending mail: ", e); e.printStackTrace(); } } }
package net.bolbat.kit.cache.guava; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import com.google.common.cache.CacheBuilder; import net.bolbat.kit.cache.Cache; import net.bolbat.kit.cache.LoadFunction; import org.configureme.annotations.AfterConfiguration; import org.configureme.annotations.Configure; import org.configureme.annotations.ConfigureMe; /** * {@link Cache} implementation for guava. * * @param <K> * key * @param <V> * value * @author ivanbatura */ @ConfigureMe (allfields = false) public class GuavaCache<K, V> implements Cache<K, V> { /** * {@link com.google.common.cache.Cache}. */ private com.google.common.cache.Cache<K, V> originalCache; /** * Initial capacity for cache. */ @Configure private int initiateCapacity; /** * Maximum capacity for cache. */ @Configure private long maximumCapacity; /** * Expiration time after last access in {@code expireAfterAccessTimeUnit}. */ @Configure private Long expireAfterAccess; /** * {@link TimeUnit} for {@code expireAfterAccess}. */ @Configure private TimeUnit expireAfterAccessTimeUnit; /** * Expiration time after last write in {@code expireAfterWriteTimeUnit}. */ @Configure private Long expireAfterWrite; /** * {@link TimeUnit} for {@code expireAfterWrite}. */ @Configure private TimeUnit expireAfterWriteTimeUnit; /** * {@link net.bolbat.kit.cache.LoadFunction} to load elements. */ private LoadFunction<K, V> functionLoad; /** * Constructor. * * @param aInitiateCapacity * Initial capacity * @param aMaximumCapacity * Maximum capacity * @param aExpireAfterAccess * Expiration time after last access * @param aExpireAfterAccessTimeUnit * {@link TimeUnit} for access expiration * @param aExpireAfterWrite * Expiration time after last write * @param aExpireAfterWriteTimeUnit * {@link TimeUnit} for write expiration * @param aFunctionLoad * {@link net.bolbat.kit.cache.LoadFunction} */ protected GuavaCache(final int aInitiateCapacity, final long aMaximumCapacity, final Long aExpireAfterAccess, final TimeUnit aExpireAfterAccessTimeUnit, final Long aExpireAfterWrite, TimeUnit aExpireAfterWriteTimeUnit, final LoadFunction<K, V> aFunctionLoad) { this.initiateCapacity = aInitiateCapacity; this.maximumCapacity = aMaximumCapacity; this.expireAfterAccess = aExpireAfterAccess; this.expireAfterAccessTimeUnit = aExpireAfterAccessTimeUnit; this.expireAfterWrite = aExpireAfterWrite; this.expireAfterWriteTimeUnit = aExpireAfterWriteTimeUnit; this.functionLoad = aFunctionLoad; //configure cache configureCache(); } public void setOriginalCache(com.google.common.cache.Cache<K, V> originalCache) { this.originalCache = originalCache; } public void setInitiateCapacity(int initiateCapacity) { this.initiateCapacity = initiateCapacity; } public void setMaximumCapacity(long maximumCapacity) { this.maximumCapacity = maximumCapacity; } public void setExpireAfterAccess(Long expireAfterAccess) { this.expireAfterAccess = expireAfterAccess; } public void setExpireAfterAccessTimeUnit(TimeUnit expireAfterAccessTimeUnit) { this.expireAfterAccessTimeUnit = expireAfterAccessTimeUnit; } public void setExpireAfterWrite(Long expireAfterWrite) { this.expireAfterWrite = expireAfterWrite; } public void setExpireAfterWriteTimeUnit(TimeUnit expireAfterWriteTimeUnit) { this.expireAfterWriteTimeUnit = expireAfterWriteTimeUnit; } /** * Cache configuration. */ @AfterConfiguration public void configureCache() { //save old cache data Map<K, V> oldCache = null; if (originalCache != null && originalCache.size() > 0) oldCache = new HashMap<K, V>(originalCache.asMap()); final CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); if (initiateCapacity > 0) cacheBuilder.initialCapacity(initiateCapacity); if (maximumCapacity > 0) cacheBuilder.maximumSize(maximumCapacity); if (expireAfterAccess != null) cacheBuilder.expireAfterAccess(expireAfterAccess, expireAfterAccessTimeUnit); if (expireAfterWrite != null) cacheBuilder.expireAfterWrite(expireAfterWrite, expireAfterWriteTimeUnit); originalCache = cacheBuilder.build(); //restore old data to new cache if (oldCache != null) originalCache.putAll(oldCache); } @Override public V get(K key) { V result = originalCache.getIfPresent(key); if (functionLoad != null && result == null) { result = functionLoad.load(key); if (result != null) put(key, result); } return result; } @Override public void put(K key, V value) { originalCache.put(key, value); } @Override public void invalidate(K key) { originalCache.invalidate(key); } @Override public Collection<V> get(Iterable<? extends K> keys) { return originalCache.getAllPresent(keys).values(); } @Override public Collection<V> getAll() { return originalCache.asMap().values(); } @Override public Map<K, V> getAllAsMap() { return originalCache.asMap(); } @Override public void put(Map<K, V> elements) { originalCache.putAll(elements); } @Override public void invalidate(Iterable<? extends K> keys) { originalCache.invalidateAll(keys); } @Override public void invalidateAll() { originalCache.invalidateAll(); } @Override public long size() { return originalCache.size(); } @Override public void cleanUp() { originalCache.cleanUp(); } @Override public boolean isEmpty() { return originalCache == null || originalCache.size() == 0; } }
// $Id: DirectionalEdge.java,v 1.3 2001/08/24 22:13:10 shaper Exp $ package com.threerings.nodemap.direction; import java.awt.*; import com.threerings.nodemap.*; /** * A directional edge extends the {@link Edge} object to allow * associating a direction with the edge and rendering the edge to the * screen. The edge direction must be one of the directional * constants detailed in the {@link Directions} object. */ public class DirectionalEdge extends Edge { /** The edge direction as a {@link Directions} constant. */ public int dir; /** * Construct a directional edge. * * @param src the source node. * @param dst the destination node. * @param dir the edge direction. */ public DirectionalEdge (Node src, Node dst, int dir) { super(src, dst); this.dir = dir; } /** * Render the edge to the given graphics context. * * @param g the graphics context. */ public void paint (Graphics g) { g.setColor(Color.black); int sx = src.getX(), sy = src.getY(); int dx = dst.getX(), dy = dst.getY(); int csx = sx + (src.getWidth() / 2); int csy = sy + (src.getHeight() / 2); int cdx = dx + (dst.getWidth() / 2); int cdy = dy + (dst.getHeight() / 2); g.drawLine(csx, csy, cdx, cdy); } public void toString (StringBuffer buf) { super.toString(buf); buf.append(", dir=").append(dir); } }
package org.apache.commons.collections; import java.util.Collection; public interface BoundedCollection extends Collection { /** * Returns true if this collection is full and no new elements can be added. * * @return <code>true</code> if the collection is full */ boolean isFull(); /** * Gets the maximum size of the collection (the bound). * * @return the maximum number of elements the collection can hold */ int maxSize(); }
package org.jivesoftware.openfire.keystore; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.net.DNSUtil; import org.jivesoftware.util.CertificateManager; import org.jivesoftware.util.JiveGlobals; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.KeyManagerFactory; import java.io.IOException; import java.security.*; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * A wrapper class for a store of certificates, its metadata (password, location) and related functionality that is * used to <em>provide</em> credentials (that represent this Openfire instance), an <em>identity store</em> * * An identity store should contain private keys, each associated with its certificate chain. * * Having the root certificate of the Certificate Authority that signed the certificates in this identity store should * be in a corresponding trust store, although this is not strictly required. The reasoning here is that when you trust * a Certificate Authority to verify your identity, you're likely to trust the same Certificate Authority to verify the * identities of others. * * Note that in Java terminology, an identity store is commonly referred to as a 'key store', while the same name is * also used to identify the generic certificate store. To have clear distinction between common denominator and each of * the specific types, this implementation uses the terms "certificate store", "identity store" and "trust store". * * @author Guus der Kinderen, guus.der.kinderen@gmail.com */ public class IdentityStore extends CertificateStore { private static final Logger Log = LoggerFactory.getLogger( IdentityStore.class ); public IdentityStore( CertificateStoreConfiguration configuration, boolean createIfAbsent ) throws CertificateStoreConfigException { super( configuration, createIfAbsent ); try { final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() ); keyManagerFactory.init( this.getStore(), configuration.getPassword() ); } catch ( NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException ex ) { throw new CertificateStoreConfigException( "Unable to initialize identity store (a common cause: the password for a key is different from the password of the entire store).", ex ); } } /** * Creates a Certificate Signing Request based on the private key and certificate identified by the provided alias. * * When the alias does not identify a private key and/or certificate, this method will throw an exception. * * The certificate that is identified by the provided alias can be an unsigned certificate, but also a certificate * that is already signed. The latter implies that the generated request is a request for certificate renewal. * * An invocation of this method does not change the state of the underlying store. * * @param alias An identifier for a private key / certificate in this store (cannot be null). * @return A PEM-encoded Certificate Signing Request (never null). */ public String generateCSR( String alias ) throws CertificateStoreConfigException { // Input validation if ( alias == null || alias.trim().isEmpty() ) { throw new IllegalArgumentException( "Argument 'alias' cannot be null or an empty String." ); } alias = alias.trim(); try { if ( !store.containsAlias( alias ) ) { throw new CertificateStoreConfigException( "Cannot generate CSR for alias '"+ alias +"': the alias does not exist in the store." ); } final Certificate certificate = store.getCertificate( alias ); if ( certificate == null || (!(certificate instanceof X509Certificate))) { throw new CertificateStoreConfigException( "Cannot generate CSR for alias '"+ alias +"': there is no corresponding certificate in the store, or it is not an X509 certificate." ); } final Key key = store.getKey( alias, configuration.getPassword() ); if ( key == null || (!(key instanceof PrivateKey) ) ) { throw new CertificateStoreConfigException( "Cannot generate CSR for alias '"+ alias +"': there is no corresponding key in the store, or it is not a private key." ); } final String pemCSR = CertificateManager.createSigningRequest( (X509Certificate) certificate, (PrivateKey) key ); return pemCSR; } catch ( IOException | NoSuchProviderException | SignatureException | InvalidKeyException | KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException e ) { throw new CertificateStoreConfigException( "Cannot generate CSR for alias '"+ alias +"'", e ); } } /** * Imports a certificate (and its chain) in this store. * * This method will fail when the provided certificate chain: * <ul> * <li>does not match the domain of this XMPP service.</li> * <li>is not a proper chain</li> * </ul> * * This method will also fail when a corresponding private key is not already in this store (it is assumed that the * CA reply follows a signing request based on a private key that was added to the store earlier). * * @param pemCertificates a PEM representation of the certificate or certificate chain (cannot be null or empty). */ public void installCSRReply( String alias, String pemCertificates ) throws CertificateStoreConfigException { // Input validation if ( alias == null || alias.trim().isEmpty() ) { throw new IllegalArgumentException( "Argument 'alias' cannot be null or an empty String." ); } if ( pemCertificates == null || pemCertificates.trim().isEmpty() ) { throw new IllegalArgumentException( "Argument 'pemCertificates' cannot be null or an empty String." ); } alias = alias.trim(); pemCertificates = pemCertificates.trim(); try { // From its PEM representation, parse the certificates. final Collection<X509Certificate> certificates = CertificateManager.parseCertificates( pemCertificates ); if ( certificates.isEmpty() ) { throw new CertificateStoreConfigException( "No certificate was found in the input." ); } // Note that PKCS#7 does not require a specific order for the certificates in the file - ordering is needed. final List<X509Certificate> ordered = CertificateUtils.order( certificates ); // Of the ordered chain, the first certificate should be for our domain. if ( !isForThisDomain( ordered.get( 0 ) ) ) { throw new CertificateStoreConfigException( "The supplied certificate chain does not cover the domain of this XMPP service." ); } // This method is used to update a pre-existing entry in the store. Find out if this entry corresponds with the provided certificate chain. if ( !corresponds( alias, ordered ) ) { throw new IllegalArgumentException( "The provided CSR reply does not match an existing certificate in the store under the provided alias '" + alias + "'." ); } // All appears to be in order. Update the existing entry in the store. store.setKeyEntry( alias, store.getKey( alias, configuration.getPassword() ), configuration.getPassword(), ordered.toArray( new X509Certificate[ ordered.size() ] ) ); } catch ( RuntimeException | IOException | CertificateException | UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException e ) { reload(); // reset state of the store. throw new CertificateStoreConfigException( "Unable to install a singing reply into an identity store.", e ); } // TODO notifiy listeners. } protected boolean corresponds( String alias, List<X509Certificate> certificates ) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException { if ( !store.containsAlias( alias ) ) { return false; } final Key key = store.getKey( alias, configuration.getPassword() ); if ( key == null ) { return false; } if ( !(key instanceof PrivateKey)) { return false; } final Certificate certificate = store.getCertificate( alias ); if ( certificate == null ) { return false; } if ( !(certificate instanceof X509Certificate) ) { return false; } final X509Certificate x509Certificate = (X509Certificate) certificate; // First certificate in the chain should correspond with the certificate in the store if ( !x509Certificate.getSerialNumber().equals( certificates.get( 0 ).getSerialNumber() ) ) { return false; } return true; } /** * Imports a certificate and the private key that was used to generate the certificate. * * This method will import the certificate and key in the store using a unique alias. This alias is returned. * * This method will fail when the provided certificate does not match the domain of this XMPP service. * * @param pemCertificates a PEM representation of the certificate or certificate chain (cannot be null or empty). * @param pemPrivateKey a PEM representation of the private key (cannot be null or empty). * @param passPhrase optional pass phrase (must be present if the private key is encrypted). * @return The alias that was used (never null). */ public String installCertificate( String pemCertificates, String pemPrivateKey, String passPhrase ) throws CertificateStoreConfigException { // Generate a unique alias. final String domain = XMPPServer.getInstance().getServerInfo().getXMPPDomain(); int index = 1; String alias = domain + "_" + index; try { while ( store.containsAlias( alias ) ) { index = index + 1; alias = domain + "_" + index; } } catch ( KeyStoreException e ) { throw new CertificateStoreConfigException( "Unable to install a certificate into an identity store.", e ); } // Perform the installation using the generated alias. installCertificate( alias, pemCertificates, pemPrivateKey, passPhrase ); return alias; } /** * Imports a certificate and the private key that was used to generate the certificate. * * This method will fail when the provided certificate does not match the domain of this XMPP service, or when the * provided alias refers to an existing entry. * * @param alias the name (key) under which the certificate is to be stored in the store (cannot be null or empty). * @param pemCertificates a PEM representation of the certificate or certificate chain (cannot be null or empty). * @param pemPrivateKey a PEM representation of the private key (cannot be null or empty). * @param passPhrase optional pass phrase (must be present if the private key is encrypted). */ public void installCertificate( String alias, String pemCertificates, String pemPrivateKey, String passPhrase ) throws CertificateStoreConfigException { // Input validation if ( alias == null || alias.trim().isEmpty() ) { throw new IllegalArgumentException( "Argument 'alias' cannot be null or an empty String." ); } if ( pemCertificates == null || pemCertificates.trim().isEmpty() ) { throw new IllegalArgumentException( "Argument 'pemCertificates' cannot be null or an empty String." ); } if ( pemPrivateKey == null || pemPrivateKey.trim().isEmpty() ) { throw new IllegalArgumentException( "Argument 'pemPrivateKey' cannot be null or an empty String." ); } alias = alias.trim(); pemCertificates = pemCertificates.trim(); // Check that there is a certificate for the specified alias try { if ( store.containsAlias( alias ) ) { throw new CertificateStoreConfigException( "Certificate already exists for alias: " + alias ); } // From its PEM representation, parse the certificates. final Collection<X509Certificate> certificates = CertificateManager.parseCertificates( pemCertificates ); if ( certificates.isEmpty() ) { throw new CertificateStoreConfigException( "No certificate was found in the input." ); } // Note that PKCS#7 does not require a specific order for the certificates in the file - ordering is needed. final List<X509Certificate> ordered = CertificateUtils.order( certificates ); // Of the ordered chain, the first certificate should be for our domain. if ( !isForThisDomain( ordered.get( 0 ) ) ) { throw new CertificateStoreConfigException( "The supplied certificate chain does not cover the domain of this XMPP service." ); } // From its PEM representation (and pass phrase), parse the private key. final PrivateKey privateKey = CertificateManager.parsePrivateKey( pemPrivateKey, passPhrase ); // All appears to be in order. Install in the store. store.setKeyEntry( alias, privateKey, configuration.getPassword(), ordered.toArray( new X509Certificate[ ordered.size() ] ) ); persist(); } catch ( CertificateException | KeyStoreException | IOException e ) { reload(); // reset state of the store. throw new CertificateStoreConfigException( "Unable to install a certificate into an identity store.", e ); } // TODO Notify listeners that a new certificate has been added. } /** * Adds a self-signed certificate for the domain of this XMPP service when no certificate for the domain (of the * provided algorithm) was found. * * This method is a thread-safe equivalent of: * <pre> * for ( String algorithm : algorithms ) { * if ( !containsDomainCertificate( algorithm ) ) { * addSelfSignedDomainCertificate( algorithm ); * } * } * </pre> * * @param algorithms The algorithms for which to verify / add a domain certificate. */ public synchronized void ensureDomainCertificates( String... algorithms ) throws CertificateStoreConfigException { for ( String algorithm : algorithms ) { Log.debug( "Verifying that a domain certificate ({} algorithm) is available in this store.", algorithm); if ( !containsDomainCertificate( algorithm ) ) { Log.debug( "Store does not contain a domain certificate ({} algorithm). A self-signed certificate will be generated.", algorithm); addSelfSignedDomainCertificate( algorithm ); } } } /** * Checks if the store contains a certificate of a particular algorithm that matches the domain of this * XMPP service. This method will not distinguish between self-signed and non-self-signed certificates. */ public synchronized boolean containsDomainCertificate( String algorithm ) throws CertificateStoreConfigException { final String domainName = XMPPServer.getInstance().getServerInfo().getXMPPDomain(); try { for ( final String alias : Collections.list( store.aliases() ) ) { final Certificate certificate = store.getCertificate( alias ); if ( !( certificate instanceof X509Certificate ) ) { continue; } if ( !certificate.getPublicKey().getAlgorithm().equalsIgnoreCase( algorithm ) ) { continue; } for ( String identity : CertificateManager.getServerIdentities( (X509Certificate) certificate ) ) { if ( DNSUtil.isNameCoveredByPattern( domainName, identity ) ) { return true; } } } return false; } catch ( KeyStoreException e ) { throw new CertificateStoreConfigException( "An exception occurred while searching for " + algorithm + " certificates that match the Openfire domain.", e ); } } /** * Populates the key store with a self-signed certificate for the domain of this XMPP service. */ public synchronized void addSelfSignedDomainCertificate( String algorithm ) throws CertificateStoreConfigException { final int keySize; final String signAlgorithm; switch ( algorithm.toUpperCase() ) { case "RSA": keySize = JiveGlobals.getIntProperty( "cert.rsa.keysize", 2048 ); signAlgorithm = "SHA1WITHRSAENCRYPTION"; break; case "DSA": keySize = JiveGlobals.getIntProperty( "cert.dsa.keysize", 1024 ); signAlgorithm = "SHA1withDSA"; break; default: throw new IllegalArgumentException( "Unsupported algorithm '" + algorithm + "'. Use 'RSA' or 'DSA'." ); } final String name = JiveGlobals.getProperty( "xmpp.domain" ).toLowerCase(); final String alias = name + "_" + algorithm.toLowerCase(); final String distinctName = "cn=" + name; final int validityInDays = 60; Log.info( "Generating a new private key and corresponding self-signed certificate for domain name '{}', using the {} algorithm (sign-algorithm: {} with a key size of {} bits). Certificate will be valid for {} days.", name, algorithm, signAlgorithm, keySize, validityInDays ); // Generate public and private keys try { final KeyPair keyPair = generateKeyPair( algorithm.toUpperCase(), keySize ); // Create X509 certificate with keys and specified domain final X509Certificate cert = CertificateManager.createX509V3Certificate( keyPair, validityInDays, distinctName, distinctName, name, signAlgorithm ); // Store new certificate and private key in the key store store.setKeyEntry( alias, keyPair.getPrivate(), configuration.getPassword(), new X509Certificate[]{cert} ); // Persist the changes in the store to disk. persist(); } catch ( CertificateStoreConfigException | IOException | GeneralSecurityException ex ) { reload(); // reset state of the store. throw new CertificateStoreConfigException( "Unable to generate new self-signed " + algorithm + " certificate.", ex ); } // TODO Notify listeners that a new certificate has been created } /** * Returns a new public & private key with the specified algorithm (e.g. DSA, RSA, etc.). * * @param algorithm DSA, RSA, etc. * @param keySize the desired key size. This is an algorithm-specific metric, such as modulus length, specified in number of bits. * @return a new public & private key with the specified algorithm (e.g. DSA, RSA, etc.). */ protected static synchronized KeyPair generateKeyPair( String algorithm, int keySize ) throws GeneralSecurityException { final KeyPairGenerator generator; if ( PROVIDER == null ) { generator = KeyPairGenerator.getInstance( algorithm ); } else { generator = KeyPairGenerator.getInstance( algorithm, PROVIDER ); } generator.initialize( keySize, new SecureRandom() ); return generator.generateKeyPair(); } /** * Verifies that the subject of the certificate matches the domain of this XMPP service. * * @param certificate The certificate to verify (cannot be null) * @return true when the certificate subject is this domain, otherwise false. */ public static boolean isForThisDomain( X509Certificate certificate ) { final String domainName = XMPPServer.getInstance().getServerInfo().getXMPPDomain(); final List<String> serverIdentities = CertificateManager.getServerIdentities( certificate ); for ( String identity : serverIdentities ) { if ( DNSUtil.isNameCoveredByPattern( domainName, identity ) ) { return true; } } Log.info( "The supplied certificate chain does not cover the domain of this XMPP service ('" + domainName + "'). Instead, it covers " + Arrays.toString( serverIdentities.toArray( new String[ serverIdentities.size() ] ) ) ); return false; } }
package org.opentdc.workrecords.file; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.UUID; import java.util.logging.Logger; import javax.servlet.ServletContext; import org.opentdc.file.AbstractFileServiceProvider; import org.opentdc.resources.ResourceModel; import org.opentdc.service.exception.DuplicateException; import org.opentdc.service.exception.InternalServerErrorException; import org.opentdc.service.exception.NotFoundException; import org.opentdc.service.exception.ValidationException; import org.opentdc.util.LanguageCode; import org.opentdc.util.PrettyPrinter; import org.opentdc.workrecords.ServiceProvider; import org.opentdc.workrecords.TagRefModel; import org.opentdc.workrecords.TaggedWorkRecord; import org.opentdc.workrecords.WorkRecordModel; import org.opentdc.workrecords.WorkRecordQueryHandler; import org.opentdc.wtt.CompanyModel; import org.opentdc.wtt.ProjectModel; public class FileServiceProvider extends AbstractFileServiceProvider<TaggedWorkRecord> implements ServiceProvider { protected static Map<String, TaggedWorkRecord> index = null; protected static Map<String, TagRefModel> tagRefIndex = null; protected static Logger logger = null; protected static boolean isResourceDerived = true; /** * Constructor. * @param context the servlet context (for config) * @param prefix the directory name where the seed and data.json reside (typically the classname of the service) * @throws IOException */ public FileServiceProvider( ServletContext context, String prefix ) throws IOException { super(context, prefix); if (index == null) { index = new HashMap<String, TaggedWorkRecord>(); List<TaggedWorkRecord> _workRecords = importJson(); for (TaggedWorkRecord _workRecord : _workRecords) { index.put(_workRecord.getModel().getId(), _workRecord); } tagRefIndex = new HashMap<String, TagRefModel>(); String _buf = context.getInitParameter("isResourceDerived"); logger = Logger.getLogger(FileServiceProvider.class.getName()); logger.info("init parameter <isResourceDerived> (_buf)=<" + _buf + ">"); isResourceDerived = Boolean.parseBoolean(context.getInitParameter("isResourceDerived")); } logger.info("isResourceDerived=<" + isResourceDerived + ">") ; } /* (non-Javadoc) * @see org.opentdc.workrecords.ServiceProvider#listWorkRecords(java.lang.String, java.lang.String, int, int) */ @Override public ArrayList<WorkRecordModel> listWorkRecords( String query, String queryType, int position, int size ) { // ArrayList<WorkRecordModel> _workRecords = new ArrayList<WorkRecordModel>(); // for (TaggedWorkRecord _taggedWR : index.values()) { // _workRecords.add(_taggedWR.getModel()); // Collections.sort(_workRecords, WorkRecordModel.WorkRecordComparator); List<TaggedWorkRecord> _list = new ArrayList<TaggedWorkRecord>(index.values()); Collections.sort(_list, TaggedWorkRecord.TaggedWorkRecordComparator); WorkRecordQueryHandler _queryHandler = new WorkRecordQueryHandler(query); ArrayList<WorkRecordModel> _selection = new ArrayList<WorkRecordModel>(); for (int i = 0; i < _list.size(); i++) { if (i >= position && i < (position + size)) { if (_queryHandler.evaluate(_list.get(i)) == true) { _selection.add(_list.get(i).getModel()); } } } logger.info("list(<" + query + ">, <" + queryType + ">, <" + position + ">, <" + size + ">) -> " + _selection.size() + " workrecords."); return _selection; } /* (non-Javadoc) * @see org.opentdc.workrecords.ServiceProvider#createWorkRecord(org.opentdc.workrecords.WorkRecordModel) */ @Override public WorkRecordModel createWorkRecord( WorkRecordModel workrecord) throws DuplicateException, ValidationException { logger.info("createWorkRecord(" + PrettyPrinter.prettyPrintAsJSON(workrecord) + ")"); String _id = workrecord.getId(); if (_id == null || _id == "") { _id = UUID.randomUUID().toString(); } else { if (index.get(_id) != null) { // object with same ID exists already throw new DuplicateException("workrecord <" + _id + "> exists already."); } else { // a new ID was set on the client; we do not allow this throw new ValidationException("workrecord <" + _id + "> contains an ID generated on the client. This is not allowed."); } } // validate mandatory attributes if (workrecord.getCompanyId() == null || workrecord.getCompanyId().isEmpty()) { throw new ValidationException("workrecord <" + _id + "> must contain a valid companyId."); } if (workrecord.getCompanyTitle() != null && !workrecord.getCompanyTitle().isEmpty()) { logger.warning("workrecord <" + _id + ">: companyTitle is a derived field and will be overwritten."); } try { CompanyModel _companyModel = org.opentdc.wtt.file.FileServiceProvider.getCompany(workrecord.getCompanyId()); workrecord.setCompanyTitle(_companyModel.getTitle()); } catch (NotFoundException _ex) { throw new ValidationException("workrecord <" + _id + "> contains an invalid companyId <" + workrecord.getCompanyId() + ">."); } if (workrecord.getProjectId() == null || workrecord.getProjectId().isEmpty()) { throw new ValidationException("workrecord <" + _id + "> must contain a valid projectId."); } if (workrecord.getProjectTitle() != null && !workrecord.getProjectTitle().isEmpty()) { logger.warning("workrecord <" + _id + ">: projectTitle is a derived field and will be overwritten."); } try { ProjectModel _projectModel = org.opentdc.wtt.file.FileServiceProvider.getProject(workrecord.getProjectId()); workrecord.setProjectTitle(_projectModel.getTitle()); } catch (NotFoundException _ex) { throw new ValidationException("workrecord <" + _id + "> contains an invalid projectId <" + workrecord.getProjectId() + ">."); } if (workrecord.getResourceId() == null || workrecord.getResourceId().isEmpty()) { throw new ValidationException("workrecord <" + _id + "> must contain a valid resourceId."); } if (isResourceDerived == true) { if (workrecord.getResourceName() != null && !workrecord.getResourceName().isEmpty()) { logger.warning("workrecord <" + _id + ">: resourceName is a derived field and will be overwritten."); } try { ResourceModel _resourceModel = org.opentdc.resources.file.FileServiceProvider.getResourceModel(workrecord.getResourceId()); workrecord.setResourceName(_resourceModel.getName()); } catch (NotFoundException _ex) { throw new ValidationException("workrecord <" + _id + "> contains an invalid resourceId <" + workrecord.getResourceId() + ">."); } } else { // TODO: this is a workaround for the Arbalo demo; resourceName is not derived, but a mandatory field if (workrecord.getResourceName() == null || workrecord.getResourceName().isEmpty()) { throw new ValidationException("workrecord <" + _id + "> must contain a valid resourceName."); } } if (workrecord.getStartAt() == null) { throw new ValidationException("workrecord <" + _id + "> must contain a valid startAt date."); } workrecord.setId(_id); Date _date = new Date(); workrecord.setCreatedAt(_date); workrecord.setCreatedBy(getPrincipal()); workrecord.setModifiedAt(_date); workrecord.setModifiedBy(getPrincipal()); TaggedWorkRecord _taggedWR = new TaggedWorkRecord(); _taggedWR.setModel(workrecord); index.put(_id, _taggedWR); // generate TagRefModel composites addTags(_id, workrecord.getTagIdList()); logger.info("createWorkRecord() -> " + PrettyPrinter.prettyPrintAsJSON(workrecord)); if (isPersistent) { exportJson(index.values()); } return workrecord; } /* (non-Javadoc) * @see org.opentdc.workrecords.ServiceProvider#readWorkRecord(java.lang.String) */ @Override public WorkRecordModel readWorkRecord( String id) throws NotFoundException { WorkRecordModel _workrecord = readTaggedWorkRecord(id).getModel(); logger.info("readWorkRecord(" + id + ") -> " + _workrecord); return _workrecord; } /** * Retrieve the TaggedWorkRecord based on the id of the WorkRecord. * @param id the unique id of the resource * @return the TaggedWorkRecord that contains the WorkRecord as its model * @throws NotFoundException if no workrecord with this id was found */ private static TaggedWorkRecord readTaggedWorkRecord( String id) throws NotFoundException { TaggedWorkRecord _taggedWR = index.get(id); if (_taggedWR == null) { throw new NotFoundException("no workrecord with id <" + id + "> was found."); } logger.info("readTaggedWorkRecord(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_taggedWR)); return _taggedWR; } /** * Retrieve a WorkRecordModel by its ID. * @param id the ID of the workrecord * @return the workrecord found * @throws NotFoundException if no workrecords with such an ID was found */ public static WorkRecordModel getWorkRecordModel( String id) throws NotFoundException { return readTaggedWorkRecord(id).getModel(); } /* (non-Javadoc) * @see org.opentdc.workrecords.ServiceProvider#updateWorkRecord(java.lang.String, org.opentdc.workrecords.WorkRecordModel) */ @Override public WorkRecordModel updateWorkRecord( String id, WorkRecordModel workrecord) throws NotFoundException, ValidationException { TaggedWorkRecord _taggedWR = readTaggedWorkRecord(id); WorkRecordModel _model = _taggedWR.getModel(); if(_model == null) { throw new NotFoundException("workrecord <" + id + "> was not found."); } if (! _model.getCreatedAt().equals(workrecord.getCreatedAt())) { logger.warning("workrecord <" + id + ">: ignoring createdAt value <" + workrecord.getCreatedAt().toString() + "> because it was set on the client."); } if (! _model.getCreatedBy().equalsIgnoreCase(workrecord.getCreatedBy())) { logger.warning("workrecord <" + id + ">: ignoring createdBy value <" + workrecord.getCreatedBy() + ">: because it was set on the client."); } // company (id and title) if (! _model.getCompanyId().equalsIgnoreCase(workrecord.getCompanyId())) { throw new ValidationException("workrecord <" + id + ">: it is not allowed to change the companyId."); } if (! _model.getCompanyTitle().equalsIgnoreCase(workrecord.getCompanyTitle())) { logger.warning("workrecord <" + id + ">: ignoring companyTitle value <" + workrecord.getCompanyTitle() + ">, because it is a derived attribute and can not be changed."); } try { CompanyModel _companyModel = org.opentdc.wtt.file.FileServiceProvider.getCompany(workrecord.getCompanyId()); _model.setCompanyTitle(_companyModel.getTitle()); } catch (NotFoundException _ex) { throw new ValidationException("workrecord <" + id + "> contains an invalid companyId <" + workrecord.getCompanyId() + ">."); } // project (id and title) if (! _model.getProjectId().equalsIgnoreCase(workrecord.getProjectId())) { throw new ValidationException("workrecord <" + id + ">: it is not allowed to change the projectId."); } if (! _model.getProjectTitle().equalsIgnoreCase(workrecord.getProjectTitle())) { logger.warning("workrecord <" + id + ">: ignoring projectTitle value <" + workrecord.getProjectTitle() + ">, because it is a derived attribute and can not be changed."); } try { ProjectModel _projectModel = org.opentdc.wtt.file.FileServiceProvider.getProject(workrecord.getProjectId()); _model.setProjectTitle(_projectModel.getTitle()); } catch (NotFoundException _ex) { throw new ValidationException("workrecord <" + id + "> contains an invalid projectId <" + workrecord.getProjectId() + ">."); } // resource (id and name) if (! _model.getResourceId().equalsIgnoreCase(workrecord.getResourceId())) { throw new ValidationException("workrecord <" + id + ">: it is not allowed to change the resourceId."); } if (isResourceDerived == true) { if (! _model.getResourceName().equalsIgnoreCase(workrecord.getResourceName())) { logger.warning("workrecord <" + id + ">: ignoring resourceName value <" + workrecord.getResourceName() + ">, because it is a derived attribute and can not be changed."); } try { ResourceModel _resourceModel = org.opentdc.resources.file.FileServiceProvider.getResourceModel(workrecord.getResourceId()); _model.setResourceName(_resourceModel.getName()); } catch (NotFoundException _ex) { throw new ValidationException("workrecord <" + id + "> contains an invalid resourceId <" + workrecord.getResourceId() + ">."); } } else { // TODO: workaround for Arbalo event: resourceName is mandatory attribute (instead of derived) if (_model.getResourceName() == null || _model.getResourceName().length() == 0) { throw new ValidationException("updating resource <" + id + ">: new data must have a valid resourceName."); } } _model.setStartAt(workrecord.getStartAt()); _model.setDurationHours(workrecord.getDurationHours()); _model.setDurationMinutes(workrecord.getDurationMinutes()); _model.setBillable(workrecord.isBillable()); _model.setRunning(workrecord.isRunning()); _model.setPaused(workrecord.isPaused()); _model.setComment(workrecord.getComment()); _model.setModifiedAt(new Date()); _model.setModifiedBy(getPrincipal()); _taggedWR.setModel(_model); index.put(id, _taggedWR); logger.info("updateWorkRecord(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_model)); if (isPersistent) { exportJson(index.values()); } return _model; } @Override public void deleteWorkRecord( String id) throws NotFoundException, InternalServerErrorException { TaggedWorkRecord _taggedWR = readTaggedWorkRecord(id); // remove all tagRefs of this TaggedWorkRecord from tagRefIndex for (TagRefModel _tagRef : _taggedWR.getTagRefs()) { if (tagRefIndex.remove(_tagRef.getId()) == null) { throw new InternalServerErrorException("tagRef <" + _tagRef.getId() + "> can not be removed, because it does not exist in the tagRefIndex"); } } if (index.remove(id) == null) { throw new InternalServerErrorException("workRecord <" + id + "> can not be removed, because it does not exist in the index."); } logger.info("deleteWorkRecord(" + id + ") -> OK"); if (isPersistent) { exportJson(index.values()); } } /* (non-Javadoc) * @see org.opentdc.workrecords.ServiceProvider#listTagRefs(java.lang.String, java.lang.String, java.lang.String, int, int) */ @Override public List<TagRefModel> listTagRefs( String id, String query, String queryType, int position, int size) { List<TagRefModel> _tags = readTaggedWorkRecord(id).getTagRefs(); Collections.sort(_tags, TagRefModel.TagRefComparator); ArrayList<TagRefModel> _selection = new ArrayList<TagRefModel>(); for (int i = 0; i < _tags.size(); i++) { if (i >= position && i < (position + size)) { _selection.add(_tags.get(i)); } } logger.info("listTagRefs(<" + id + ">, <" + queryType + ">, <" + query + ">, <" + position + ">, <" + size + ">) -> " + _selection.size() + " values"); return _selection; } /* (non-Javadoc) * @see org.opentdc.workrecords.ServiceProvider#createTagRef(java.lang.String, org.opentdc.workrecords.TagRefModel) */ @Override public TagRefModel createTagRef( String workRecordId, TagRefModel model) throws DuplicateException, ValidationException { TaggedWorkRecord _taggedWR = readTaggedWorkRecord(workRecordId); if (model.getTagId() == null || model.getTagId().isEmpty()) { throw new ValidationException("TagRef in WorkRecord <" + workRecordId + "> must contain a valid tagId."); } // a tag can be contained as a TagRef within a WorkRecord 0 or 1 times if (_taggedWR.containsTag(model.getTagId())) { throw new DuplicateException("TagRef with Tag <" + model.getTagId() + "> exists already in WorkRecord <" + workRecordId + ">."); } if (lang == null) { logger.warning("lang is null; using default"); lang = LanguageCode.getDefaultLanguageCode(); } String _id = model.getId(); if (_id == null || _id.isEmpty()) { _id = UUID.randomUUID().toString(); } else { if (tagRefIndex.get(_id) != null) { throw new DuplicateException("TagRef with id <" + _id + "> exists already in tagRefIndex."); } else { throw new ValidationException("TagRef with id <" + _id + "> contains an ID generated on the client. This is not allowed."); } } model.setId(_id); model.setCreatedAt(new Date()); model.setCreatedBy(getPrincipal()); tagRefIndex.put(_id, model); _taggedWR.addTagRef(model); logger.info("createTagRef(" + workRecordId + ") -> " + PrettyPrinter.prettyPrintAsJSON(model)); if (isPersistent) { exportJson(index.values()); } return model; } /* (non-Javadoc) * @see org.opentdc.workrecords.ServiceProvider#readTagRef(java.lang.String, java.lang.String) */ @Override public TagRefModel readTagRef( String workRecordId, String tagRefId) throws NotFoundException { readTaggedWorkRecord(workRecordId); // verify that the workrecord exists TagRefModel _tagRef = tagRefIndex.get(tagRefId); if (_tagRef == null) { throw new NotFoundException("TagRef <" + workRecordId + "/tagref/" + tagRefId + "> was not found."); } logger.info("readRateRef(" + workRecordId + ", " + tagRefId + ") -> " + PrettyPrinter.prettyPrintAsJSON(_tagRef)); return _tagRef; } /* (non-Javadoc) * @see org.opentdc.workrecords.ServiceProvider#deleteTagRef(java.lang.String, java.lang.String) */ @Override public void deleteTagRef( String workRecordId, String tagRefId) throws NotFoundException, InternalServerErrorException { TaggedWorkRecord _taggedWR = readTaggedWorkRecord(workRecordId); TagRefModel _tagRef = tagRefIndex.get(tagRefId); if (_tagRef == null) { throw new NotFoundException("TagRef <" + workRecordId + "/tagref/" + tagRefId + "> was not found."); } // 1) remove the TagRef from its Resource if (_taggedWR.removeTagRef(_tagRef) == false) { throw new InternalServerErrorException("TagRef <" + workRecordId + "/tagref/" + tagRefId + "> can not be removed, because it is an orphan."); } // 2) remove the TagRef from the tagRefIndex if (tagRefIndex.remove(_tagRef.getId()) == null) { throw new InternalServerErrorException("TagRef <" + workRecordId + "/tagref/" + tagRefId + "> can not be removed, because it does not exist in the index."); } logger.info("deleteTagRef(" + workRecordId + ", " + tagRefId + ") -> OK"); if (isPersistent) { exportJson(index.values()); } } // format of String tagIdList ::= tagId{.tagId} @Override public List<TagRefModel> addTags( String workRecordId, String tagIdList) { ArrayList<TagRefModel> _tagRefs = new ArrayList<TagRefModel>(); if (tagIdList != null && !tagIdList.isEmpty()) { StringTokenizer _st = new StringTokenizer(tagIdList, ","); while (_st.hasMoreTokens()) { _tagRefs.add(createTagRef(workRecordId, new TagRefModel(_st.nextToken()))); } } return _tagRefs; } }
package org.dspace.content; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.storage.rdbms.TableRowIterator; /** * Class representing a particular bitstream format. * <P> * Changes to the bitstream format metadata are only written to the database * when <code>update</code> is called. * * @author Robert Tansley * @version $Revision$ */ public class BitstreamFormat { /** log4j logger */ private static Logger log = Logger.getLogger(BitstreamFormat.class); /** * The "unknown" support level - for bitstream formats that are unknown to * the system */ public static final int UNKNOWN = 0; /** * The "known" support level - for bitstream formats that are known to the * system, but not fully supported */ public static final int KNOWN = 1; /** * The "supported" support level - for bitstream formats known to the system * and fully supported. */ public static final int SUPPORTED = 2; /** Our context */ private Context bfContext; /** The row in the table representing this format */ private TableRow bfRow; /** File extensions for this format */ private List extensions; /** * Class constructor for creating a BitstreamFormat object based on the * contents of a DB table row. * * @param context * the context this object exists in * @param row * the corresponding row in the table * @throws SQLException */ BitstreamFormat(Context context, TableRow row) throws SQLException { bfContext = context; bfRow = row; extensions = new ArrayList(); TableRowIterator tri = DatabaseManager.query(context, "SELECT * FROM fileextension WHERE bitstream_format_id=" + getID()); while (tri.hasNext()) { extensions.add(tri.next().getStringColumn("extension")); } // close the TableRowIterator to free up resources tri.close(); // Cache ourselves context.cache(this, row.getIntColumn("bitstream_format_id")); } /** * Get a bitstream format from the database. * * @param context * DSpace context object * @param id * ID of the bitstream format * * @return the bitstream format, or null if the ID is invalid. * @throws SQLException */ public static BitstreamFormat find(Context context, int id) throws SQLException { // First check the cache BitstreamFormat fromCache = (BitstreamFormat) context.fromCache( BitstreamFormat.class, id); if (fromCache != null) { return fromCache; } TableRow row = DatabaseManager.find(context, "bitstreamformatregistry", id); if (row == null) { if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "find_bitstream_format", "not_found,bitstream_format_id=" + id)); } return null; } // not null, return format object if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "find_bitstream", "bitstream_format_id=" + id)); } return new BitstreamFormat(context, row); } /** * Find a bitstream format by its (unique) short description * * @param context * DSpace context object * @param desc * the short description * * @return the corresponding bitstream format, or <code>null</code> if * there's no bitstream format with the given short description * @throws SQLException */ public static BitstreamFormat findByShortDescription(Context context, String desc) throws SQLException { TableRow formatRow = DatabaseManager.findByUnique(context, "bitstreamformatregistry", "short_description", desc); if (formatRow == null) { return null; } // not null if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "find_bitstream", "bitstream_format_id=" + formatRow.getIntColumn("bitstream_format_id"))); } // From cache? BitstreamFormat fromCache = (BitstreamFormat) context.fromCache( BitstreamFormat.class, formatRow .getIntColumn("bitstream_format_id")); if (fromCache != null) { return fromCache; } return new BitstreamFormat(context, formatRow); } public static BitstreamFormat findUnknown(Context context) throws SQLException { BitstreamFormat bf = findByShortDescription(context, "Unknown"); if (bf == null) { throw new IllegalStateException( "No `Unknown' bitstream format in registry"); } return bf; } /** * Retrieve all bitstream formats from the registry, ordered by ID * * @param context * DSpace context object * * @return the bitstream formats. * @throws SQLException */ public static BitstreamFormat[] findAll(Context context) throws SQLException { List formats = new ArrayList(); TableRowIterator tri = DatabaseManager .query(context, "bitstreamformatregistry", "SELECT * FROM bitstreamformatregistry ORDER BY bitstream_format_id"); while (tri.hasNext()) { TableRow row = tri.next(); // From cache? BitstreamFormat fromCache = (BitstreamFormat) context.fromCache( BitstreamFormat.class, row .getIntColumn("bitstream_format_id")); if (fromCache != null) { formats.add(fromCache); } else { formats.add(new BitstreamFormat(context, row)); } } // close the TableRowIterator to free up resources tri.close(); // Return the formats as an array BitstreamFormat[] formatArray = new BitstreamFormat[formats.size()]; formatArray = (BitstreamFormat[]) formats.toArray(formatArray); return formatArray; } /** * Retrieve all non-internal bitstream formats from the registry. The * "unknown" format is not included, and the formats are ordered by support * level (highest first) first then short description. * * @param context * DSpace context object * * @return the bitstream formats. * @throws SQLException */ public static BitstreamFormat[] findNonInternal(Context context) throws SQLException { List formats = new ArrayList(); String myQuery = null; if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { myQuery = "SELECT * FROM bitstreamformatregistry WHERE internal=0 " + "AND short_description NOT LIKE 'Unknown' " + "ORDER BY support_level DESC, short_description"; } else { // default postgres, use boolean myQuery = "SELECT * FROM bitstreamformatregistry WHERE internal=false " + "AND short_description NOT LIKE 'Unknown' " + "ORDER BY support_level DESC, short_description"; } TableRowIterator tri = DatabaseManager.query(context, "bitstreamformatregistry", myQuery); while (tri.hasNext()) { TableRow row = tri.next(); // From cache? BitstreamFormat fromCache = (BitstreamFormat) context.fromCache( BitstreamFormat.class, row .getIntColumn("bitstream_format_id")); if (fromCache != null) { formats.add(fromCache); } else { formats.add(new BitstreamFormat(context, row)); } } // close the TableRowIterator to free up resources tri.close(); // Return the formats as an array BitstreamFormat[] formatArray = new BitstreamFormat[formats.size()]; formatArray = (BitstreamFormat[]) formats.toArray(formatArray); return formatArray; } /** * Create a new bitstream format * * @param context * DSpace context object * @return the newly created BitstreamFormat * @throws SQLException * @throws AuthorizeException */ public static BitstreamFormat create(Context context) throws SQLException, AuthorizeException { // Check authorisation - only administrators can create new formats if (!AuthorizeManager.isAdmin(context)) { throw new AuthorizeException( "Only administrators can create bitstream formats"); } // Create a table row TableRow row = DatabaseManager.create(context, "bitstreamformatregistry"); log.info(LogManager.getHeader(context, "create_bitstream_format", "bitstream_format_id=" + row.getIntColumn("bitstream_format_id"))); return new BitstreamFormat(context, row); } /** * Get the internal identifier of this bitstream format * * @return the internal identifier */ public int getID() { return bfRow.getIntColumn("bitstream_format_id"); } /** * Get a short (one or two word) description of this bitstream format * * @return the short description */ public String getShortDescription() { return bfRow.getStringColumn("short_description"); } /** * Set the short description of the bitstream format * * @param s * the new short description */ public void setShortDescription(String s) throws SQLException { // You can not reset the unknown's registry's name BitstreamFormat unknown = null;; try { unknown = findUnknown(bfContext); } catch (IllegalStateException e) { // No short_description='Unknown' found in bitstreamformatregistry // table. On first load of registries this is expected because it // hasn't been inserted yet! So, catch but ignore this runtime // exception thrown by method findUnknown. } // If the exception was thrown, unknown will == null so goahead and // load s. If not, check that the unknown's registry's name is not // being reset. if (unknown == null || unknown.getID() != getID()) { bfRow.setColumn("short_description", s); } } /** * Get a description of this bitstream format, including full application or * format name * * @return the description */ public String getDescription() { return bfRow.getStringColumn("description"); } /** * Set the description of the bitstream format * * @param s * the new description */ public void setDescription(String s) { bfRow.setColumn("description", s); } /** * Get the MIME type of this bitstream format, for example * <code>text/plain</code> * * @return the MIME type */ public String getMIMEType() { return bfRow.getStringColumn("mimetype"); } /** * Set the MIME type of the bitstream format * * @param s * the new MIME type */ public void setMIMEType(String s) { bfRow.setColumn("mimetype", s); } /** * Get the support level for this bitstream format - one of * <code>UNKNOWN</code>,<code>KNOWN</code> or <code>SUPPORTED</code>. * * @return the support level */ public int getSupportLevel() { return bfRow.getIntColumn("support_level"); } /** * Set the support level for this bitstream format - one of * <code>UNKNOWN</code>,<code>KNOWN</code> or <code>SUPPORTED</code>. * * @param sl * the new support level */ public void setSupportLevel(int sl) { // Sanity check if ((sl < 0) || (sl > 2)) { throw new IllegalArgumentException("Invalid support level"); } bfRow.setColumn("support_level", sl); } /** * Find out if the bitstream format is an internal format - that is, one * that is used to store system information, rather than the content of * items in the system * * @return <code>true</code> if the bitstream format is an internal type */ public boolean isInternal() { return bfRow.getBooleanColumn("internal"); } /** * Set whether the bitstream format is an internal format * * @param b * pass in <code>true</code> if the bitstream format is an * internal type */ public void setInternal(boolean b) { bfRow.setColumn("internal", b); } /** * Update the bitstream format metadata * * @throws SQLException * @throws AuthorizeException */ public void update() throws SQLException, AuthorizeException { // Check authorisation - only administrators can change formats if (!AuthorizeManager.isAdmin(bfContext)) { throw new AuthorizeException( "Only administrators can modify bitstream formats"); } log.info(LogManager.getHeader(bfContext, "update_bitstream_format", "bitstream_format_id=" + getID())); // Delete extensions DatabaseManager.updateQuery(bfContext, "DELETE FROM fileextension WHERE bitstream_format_id=" + getID()); // Rewrite extensions for (int i = 0; i < extensions.size(); i++) { String s = (String) extensions.get(i); TableRow r = DatabaseManager.create(bfContext, "fileextension"); r.setColumn("bitstream_format_id", getID()); r.setColumn("extension", s); DatabaseManager.update(bfContext, r); } DatabaseManager.update(bfContext, bfRow); } /** * Delete this bitstream format. This converts the types of any bitstreams * that may have this type to "unknown". Use this with care! * * @throws SQLException * @throws AuthorizeException */ public void delete() throws SQLException, AuthorizeException { // Check authorisation - only administrators can delete formats if (!AuthorizeManager.isAdmin(bfContext)) { throw new AuthorizeException( "Only administrators can delete bitstream formats"); } // Find "unknown" type BitstreamFormat unknown = findUnknown(bfContext); if (unknown.getID() == getID()) throw new IllegalArgumentException("The Unknown bitstream format may not be deleted."); // Remove from cache bfContext.removeCached(this, getID()); // Set bitstreams with this format to "unknown" int numberChanged = DatabaseManager.updateQuery(bfContext, "UPDATE bitstream SET bitstream_format_id=" + unknown.getID() + " WHERE bitstream_format_id=" + getID()); // Delete extensions DatabaseManager.updateQuery(bfContext, "DELETE FROM fileextension WHERE bitstream_format_id=" + getID()); // Delete this format from database DatabaseManager.delete(bfContext, bfRow); log.info(LogManager.getHeader(bfContext, "delete_bitstream_format", "bitstream_format_id=" + getID() + ",bitstreams_changed=" + numberChanged)); } /** * Get the filename extensions associated with this format * * @return the extensions */ public String[] getExtensions() { String[] exts = new String[extensions.size()]; exts = (String[]) extensions.toArray(exts); return exts; } /** * Set the filename extensions associated with this format * * @param exts * String [] array of extensions */ public void setExtensions(String[] exts) { extensions = new ArrayList(); for (int i = 0; i < exts.length; i++) { extensions.add(exts[i]); } } }
package com.servlet; import static com.googlecode.objectify.ObjectifyService.ofy; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.blobstore.*; import com.google.appengine.api.images.*; import com.googlecode.objectify.Key; import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.Ref; import com.objects.Adherent; import com.objects.Equipe; import com.objects.Saison; public class EquipeServlet extends HttpServlet { // Enregistrement de la classe persistable auprs d'Objectify static { ObjectifyService.register(Saison.class); ObjectifyService.register(Equipe.class); ObjectifyService.register(Adherent.class); } public void doGet(HttpServletRequest req, HttpServletResponse resp) { System.out.println("GET:" + req.getRequestURL().toString()); //this.createSaison(); try { String[] path = req.getPathInfo().split("/"); System.out.print("Path split = "); for (int i = 0; i < path.length; i++) { System.out.print(path[i] + " - "); } System.out.println(""); String type = ""; List<Ref<Equipe>> rEquipes = new ArrayList<Ref<Equipe>>(); if (path.length <= 1) { resp.sendRedirect("/equipes/masculines/"); } else { String saisonIndex = "2013"; if (path.length > 2) { saisonIndex = path[2]; } else { resp.sendRedirect("/equipes/" + path[1] + "/" + saisonIndex + "/"); } int nSaisonIndex = Integer.parseInt(saisonIndex); System.out.println("saisonIndex = " + saisonIndex); req.setAttribute("saisonIndex", saisonIndex); if (path[1].contains("feminine")) { type = "fminines"; Saison saison = ofy().load().type(Saison.class).filter("year", nSaisonIndex).first().now(); rEquipes = saison.getEquipesFeminines(); req.setAttribute("equipeType", "feminines"); } else if (path[1].contains("masculine")) { type = "masculines"; Saison saison = ofy().load().type(Saison.class).filter("year", nSaisonIndex).first().now(); rEquipes = saison.getEquipesMasculines(); req.setAttribute("equipeType", "masculines"); } else { resp.sendRedirect("/equipes/masculines/"); } List<Equipe> listEquipes = new ArrayList<Equipe>(); for (Ref<Equipe> rEquipe : rEquipes) { listEquipes.add(rEquipe.get()); } req.setAttribute("equipes", listEquipes); req.setAttribute("type", type); Equipe equipe = null; if (path.length > 3) { String sEquipeId = path[3]; if (!sEquipeId.equalsIgnoreCase("nouvelle-equipe")) { long lEquipeId = Long.parseLong(sEquipeId); equipe = ofy().load().type(Equipe.class).id(lEquipeId).now(); } } else { if (listEquipes.size() > 0) { equipe = listEquipes.get(0); } } req.setAttribute("equipe", equipe); if (equipe != null) { System.out.println("Equipe id = " + equipe.getId()); } else { System.out.println("Equipe id = nul"); } // Requte Objectify List<Saison> saisons = ofy().load().type(Saison.class).order("year").list(); req.setAttribute("saisons", saisons); List<Adherent> adherents = ofy().load().type(Adherent.class).list(); req.setAttribute("adherents", adherents); String requestURL = req.getRequestURL().toString(); req.setAttribute("requestURL", requestURL); System.out.println("Dispatcher"); this.getServletContext().getRequestDispatcher("/WEB-INF/equipes.jsp").forward(req, resp); } } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { System.out.println("POST"); String formType = req.getParameter("formType"); if (formType != null && formType.equalsIgnoreCase("info")) { this.updateEquipeInfo(req, resp); } else if (formType != null && formType.equalsIgnoreCase("delete")) { } else if (formType != null && formType.equalsIgnoreCase("new")) { this.createNewEquipe(req, resp); } else { this.updateEquipePhoto(req, resp); } String requestURL = req.getRequestURL().toString(); resp.sendRedirect(requestURL); } private void createSaison() { Saison saison1 = new Saison(); saison1.setYear(2013); Equipe equipe1 = new Equipe(); equipe1.setNom("Equipe 1"); Equipe equipe2 = new Equipe(); equipe2.setNom("Equipe 2"); // Enregistrement de l'objet dans le Datastore avec Objectify ofy().save().entities(equipe1).now(); ofy().save().entities(equipe2).now(); Key<Equipe> kEquipe1 = com.googlecode.objectify.Key.create(Equipe.class, equipe1.getId()); Key<Equipe> kEquipe2 = com.googlecode.objectify.Key.create(Equipe.class, equipe2.getId()); saison1.getEquipesMasculines().add(Ref.create(kEquipe1)); saison1.getEquipesMasculines().add(Ref.create(kEquipe2)); // Enregistrement de l'objet dans le Datastore avec Objectify ofy().save().entity(saison1).now(); System.out.println(equipe1.getId()); System.out.println("saison cre"); } private void updateEquipeInfo(HttpServletRequest req, HttpServletResponse resp) { String sEquipeId = (String) req.getParameter("equipeid"); Long lEquipeId = Long.parseLong(sEquipeId); Equipe equipe = ofy().load().type(Equipe.class).id(lEquipeId).now(); // On peut rcuprer les autres champs du formulaire comme d'habitude String equipeName = req.getParameter("equipeName"); String coachName = req.getParameter("coach"); int capitaineIndex = Integer.parseInt((String) req.getParameter("capitaine")); equipe.setNom(equipeName); equipe.setCoachName(coachName); equipe.setCapitaine(capitaineIndex); ofy().save().entity(equipe).now(); } private void updateEquipePhoto(HttpServletRequest req, HttpServletResponse resp) { String sEquipeId = ""; BufferedReader reader; String line = null; try { reader = new BufferedReader(new InputStreamReader(req.getInputStream())); while ((line = reader.readLine()) != null) { if (line.contains("equipeid=")) { System.out.println(line); sEquipeId = line.substring(9); System.out.println(sEquipeId); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Long lEquipeId = Long.parseLong(sEquipeId); Equipe equipe = ofy().load().type(Equipe.class).id(lEquipeId).now(); // Rcupration du service d'images BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); ImagesService imagesService = (ImagesService) ImagesServiceFactory.getImagesService(); // Rcupre une Map de tous les champs d'upload de fichiers Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req); // Rcupre la liste des fichiers uploads dans le champ "uploadedFile" // (il peut y en avoir plusieurs si c'est un champ d'upload multiple, d'o la List) List<BlobKey> blobKeys = blobs.get("uploadedPhoto"); // Rcupre la cl identifiant du fichier upload dans le Blobstore ( sauvegarder) //String cleFichierUploade = blobKeys.get(0).getKeyString(); // Rcupration de l'URL de l'image String urlImage = imagesService.getServingUrl(ServingUrlOptions.Builder.withBlobKey(blobKeys.get(0))); equipe.setPhotoUrl(urlImage); ofy().save().entity(equipe).now(); } public void createNewEquipe(HttpServletRequest req, HttpServletResponse resp) { try { String[] path = req.getPathInfo().split("/"); System.out.print("Path split = "); for (int i = 0; i < path.length; i++) { System.out.print(path[i] + " - "); } System.out.println(""); String type = ""; List<Ref<Equipe>> rEquipes = new ArrayList<Ref<Equipe>>(); if (path.length <= 1) { resp.sendRedirect("/equipes/masculines/"); } else { String saisonIndex = "2013"; String gender = path[1]; if (path.length > 2) { saisonIndex = path[2]; } else { resp.sendRedirect("/equipes/" + gender + "/" + saisonIndex + "/"); } int nSaisonIndex = Integer.parseInt(saisonIndex); String coachName = req.getParameter("coach"); String equipeName = req.getParameter("equipeName"); Equipe equipe = new Equipe(); equipe.setNom(equipeName); equipe.setCoachName(coachName); // Enregistrement de l'objet dans le Datastore avec Objectify ofy().save().entities(equipe).now(); Key<Equipe> kEquipe1 = com.googlecode.objectify.Key.create(Equipe.class, equipe.getId()); Saison saison = null; if (path[1].contains("feminine")) { type = "fminines"; saison = ofy().load().type(Saison.class).filter("year", nSaisonIndex).first().now(); saison.getEquipesFeminines().add(Ref.create(kEquipe1)); } else if (path[1].contains("masculine")) { type = "masculines"; saison = ofy().load().type(Saison.class).filter("year", nSaisonIndex).first().now(); saison.getEquipesMasculines().add(Ref.create(kEquipe1)); } else { resp.sendRedirect("/equipes/" + gender + "/" + saisonIndex + "/"); } // Enregistrement de l'objet dans le Datastore avec Objectify ofy().save().entity(saison).now(); resp.sendRedirect("/equipes/" + gender + "/" + saisonIndex + "/" + equipe.getId() + "/"); } } catch (IOException e) { e.printStackTrace(); } } }
package org.yakindu.sct.model.sexec.transformation.test; import static org.yakindu.sct.model.sgraph.test.util.SGraphTestFactory._createEntry; import static org.yakindu.sct.model.sgraph.test.util.SGraphTestFactory._createRegion; import static org.yakindu.sct.model.sgraph.test.util.SGraphTestFactory._createState; import static org.yakindu.sct.model.sgraph.test.util.SGraphTestFactory._createStatechart; import static org.yakindu.sct.model.sgraph.test.util.SGraphTestFactory._createTransition; import static org.yakindu.sct.model.stext.test.util.StextTestFactory._createBooleanType; import static org.yakindu.sct.model.stext.test.util.StextTestFactory._createEventDefinition; import static org.yakindu.sct.model.stext.test.util.StextTestFactory._createIntegerType; import static org.yakindu.sct.model.stext.test.util.StextTestFactory._createInterfaceScope; import static org.yakindu.sct.model.stext.test.util.StextTestFactory._createReactionTrigger; import static org.yakindu.sct.model.stext.test.util.StextTestFactory._createRealType; import static org.yakindu.sct.model.stext.test.util.StextTestFactory._createRegularEventSpec; import static org.yakindu.sct.model.stext.test.util.StextTestFactory._createStringType; import static org.yakindu.sct.model.stext.test.util.StextTestFactory._createValue; import static org.yakindu.sct.model.stext.test.util.StextTestFactory._createVariableDefinition; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.EcoreUtil2; import org.yakindu.base.types.Type; import org.yakindu.sct.model.sexec.Sequence; import org.yakindu.sct.model.sexec.Step; import org.yakindu.sct.model.sgraph.Entry; import org.yakindu.sct.model.sgraph.EntryKind; import org.yakindu.sct.model.sgraph.Region; import org.yakindu.sct.model.sgraph.State; import org.yakindu.sct.model.sgraph.Statechart; import org.yakindu.sct.model.sgraph.Transition; import org.yakindu.sct.model.stext.stext.EventDefinition; import org.yakindu.sct.model.stext.stext.InterfaceScope; import org.yakindu.sct.model.stext.stext.ReactionTrigger; import org.yakindu.sct.model.stext.stext.VariableDefinition; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; public class SCTTestUtil { public static Type TYPE_INTEGER = _createIntegerType("integer"); public static List<Step> flattenSequenceStepsAsList(Step step) { return flattenSequenceStepsAsList(step, new LinkedList<Step>()); } public static List<Step> flattenSequenceStepsAsList(Step step, List<Step> result) { if (step instanceof Sequence) { Sequence sequence = (Sequence) step; for (Step s : sequence.getSteps()) { flattenSequenceStepsAsList(s, result); } } else { result.add(step); } return result; } public static State findState(Statechart sc, final String name) { Collection<EObject> states = Collections2.filter( EcoreUtil2.eAllContentsAsList(sc), new Predicate<Object>() { public boolean apply(Object obj) { // TODO Auto-generated method stub return obj != null && obj instanceof State && name.equals(((State) obj).getName()); } }); return (states.size() > 0) ? (State) states.iterator().next() : null; } public static State findStateFullyQualified(Statechart sc, final String name) { Collection<EObject> states = Collections2.filter( EcoreUtil2.eAllContentsAsList(sc), new Predicate<Object>() { public boolean apply(Object obj) { // TODO Auto-generated method stub return obj != null && obj instanceof State && name.equals(fqn((State) obj)); } }); return (states.size() > 0) ? (State) states.iterator().next() : null; } public static final String fqn(State state) { return fqn(state.getParentRegion()) + "." + state.getName(); } public static final String fqn(Region region) { if (region.getComposite() instanceof State) return fqn((State) region.getComposite()) + "." + region.getName(); return ((Statechart) region.getComposite()).getName() + "." + region.getName(); } public static class MinimalTSC { public Statechart sc = _createStatechart("test"); public InterfaceScope s_scope = _createInterfaceScope("Interface", sc); public EventDefinition e1 = _createEventDefinition("e1", s_scope); public Region r = _createRegion("main", sc); public Entry entry = _createEntry(EntryKind.INITIAL, null, r); public State s1 = _createState("S1", r); public Transition t0 = _createTransition(entry, s1); public MinimalTSC() { } } public static class InitializingTSC { public Statechart sc = _createStatechart("test"); public InterfaceScope s_scope = _createInterfaceScope("Interface", sc); public VariableDefinition e1 = _createVariableDefinition("e1", _createBooleanType("boolean"), s_scope, _createValue(true)); public InitializingTSC() { } } public static class InitializingWithoutDefaultTSC { public Statechart sc = _createStatechart("test"); public InterfaceScope s_scope = _createInterfaceScope("Interface", sc); public VariableDefinition b = _createVariableDefinition("b", _createBooleanType("boolean"), s_scope, null); public VariableDefinition i = _createVariableDefinition("i", _createIntegerType("integer"), s_scope, null); public VariableDefinition r = _createVariableDefinition("r", _createRealType("real"), s_scope, null); public VariableDefinition s = _createVariableDefinition("s", _createStringType("string"), s_scope, null); public InitializingWithoutDefaultTSC() { } } public static class SimpleFlatTSC { public Statechart sc = _createStatechart("test"); public InterfaceScope s_scope = _createInterfaceScope("Interface", sc); public EventDefinition e1 = _createEventDefinition("e1", s_scope); public Region r = _createRegion("main", sc); public Entry entry = _createEntry(EntryKind.INITIAL, null, r); public State s1 = _createState("S1", r); public State s2 = _createState("S2", r); public Transition t0 = _createTransition(entry, s1); public Transition t1 = _createTransition(s1, s2); public ReactionTrigger tr1 = _createReactionTrigger(t1); public SimpleFlatTSC() { _createRegularEventSpec(e1, tr1); } } public static class OrthogonalFlatTSC { public Statechart sc = _createStatechart("test"); public InterfaceScope s_scope = _createInterfaceScope("Interface", sc); public EventDefinition e1 = _createEventDefinition("e1", s_scope); public EventDefinition e2 = _createEventDefinition("e2", s_scope); public Region r1 = _createRegion("first", sc); public Entry entry_r1 = _createEntry(EntryKind.INITIAL, null, r1); public State s1 = _createState("S1", r1); public State s2 = _createState("S2", r1); public Transition t0 = _createTransition(entry_r1, s1); public Transition t1 = _createTransition(s1, s2); public ReactionTrigger r1_tr1 = _createReactionTrigger(t1); public Region r2 = _createRegion("second", sc); public Entry entry_r2 = _createEntry(EntryKind.INITIAL, null, r2); public State s3 = _createState("S3", r2); public State s4 = _createState("S4", r2); public Transition t0_r2 = _createTransition(entry_r2, s3); public Transition t1_r2 = _createTransition(s3, s4); public Transition t2_r2 = _createTransition(s3, s4); public ReactionTrigger r2_tr1 = _createReactionTrigger(t1_r2); public ReactionTrigger r2_tr2 = _createReactionTrigger(t2_r2); public OrthogonalFlatTSC() { _createRegularEventSpec(e1, r1_tr1); _createRegularEventSpec(e1, r2_tr1); _createRegularEventSpec(e2, r2_tr2); } } }
package com.diamondq.common.utils.context.impl.logging; import com.diamondq.common.utils.context.spi.ContextClass; import com.diamondq.common.utils.context.spi.ContextHandler; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; import javax.inject.Singleton; import org.checkerframework.checker.nullness.qual.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import org.slf4j.helpers.FormattingTuple; import org.slf4j.helpers.MessageFormatter; @Singleton public class LoggingContextHandler implements ContextHandler { private ConcurrentMap<Class<?>, Logger> mLoggerMap = new ConcurrentHashMap<>(); public static Marker sSIMPLE_ENTRY_MARKER = MarkerFactory.getMarker("ENTRY_S"); public static Marker sENTRY_MARKER = MarkerFactory.getMarker("ENTRY"); public static Marker sEXIT_MARKER = MarkerFactory.getMarker("EXIT"); private static String sEXIT_MESSAGE_0 = "EXIT {}() from {}"; private static String sEXIT_MESSAGE_1 = "EXIT {}(...) with {} from {}"; private static String sDETACH_MESSAGE_0 = "DETACH {}() from {}"; private static String sEXIT_MESSAGE_ERROR = "EXIT {}() from {} with error"; private static String[] sENTRY_MESSAGE_ARRAY = new String[] {"{}() from {}", "{}({}) from {}", "{}({}, {}) from {}", "{}({}, {}, {}) from {}", "{}({}, {}, {}, {}) from {}"}; private static int sENTRY_MESSAGE_ARRAY_LEN = sENTRY_MESSAGE_ARRAY.length; /** * @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextStart(com.diamondq.common.utils.context.spi.ContextClass) */ @Override public void executeOnContextStart(ContextClass pContext) { if (pContext.getHandlerData(ContextHandler.sSIMPLE_CONTEXT, false, Boolean.class) != null) return; Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } if (logger.isTraceEnabled(sENTRY_MARKER)) { String methodName = pContext.getLatestStackMethod(); entryWithMetaInternal(pContext, logger, sENTRY_MARKER, pContext.startThis, methodName, pContext.argsHaveMeta, true, pContext.startArguments); } } /** * @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextClose(com.diamondq.common.utils.context.spi.ContextClass, * boolean, java.lang.Object, java.util.function.Function) */ @Override public void executeOnContextClose(ContextClass pContext, boolean pWithExitValue, @Nullable Object pExitValue, @Nullable Function<@Nullable Object, @Nullable Object> pFunc) { if (pContext.getHandlerData(ContextHandler.sSIMPLE_CONTEXT, false, Boolean.class) != null) return; Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } if (logger.isTraceEnabled(sEXIT_MARKER)) { String methodName = pContext.getLatestStackMethod(); exitInternal(pContext, logger, pContext.startThis, methodName, true, null, pWithExitValue, false, pExitValue, pFunc); } } /** * @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextExplicitThrowable(com.diamondq.common.utils.context.spi.ContextClass, * java.lang.Throwable) */ @Override public void executeOnContextExplicitThrowable(ContextClass pContext, Throwable pThrowable) { Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } if (logger.isErrorEnabled()) { String methodName = pContext.getLatestStackMethod(); exitInternal(pContext, logger, pContext.startThis, methodName, false, pThrowable, false, false, null, null); } } /** * @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextReportTrace(com.diamondq.common.utils.context.spi.ContextClass, * java.lang.String, boolean, java.lang.Object[]) */ @Override public void executeOnContextReportTrace(ContextClass pContext, @Nullable String pMessage, boolean pWithMeta, @Nullable Object @Nullable... pArgs) { Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } if (pMessage == null) { if (logger.isTraceEnabled(sSIMPLE_ENTRY_MARKER)) { String methodName = pContext.getLatestStackMethod(); entryWithMetaInternal(pContext, logger, sSIMPLE_ENTRY_MARKER, pContext.startThis, methodName, pWithMeta, false, pArgs); } } else { if (logger.isTraceEnabled()) { logger.trace(pMessage, pArgs); } } } public boolean isTraceEnabled(ContextClass pContext) { Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } return logger.isTraceEnabled(); } /** * @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextReportDebug(com.diamondq.common.utils.context.spi.ContextClass, * java.lang.String, boolean, java.lang.Object[]) */ @Override public void executeOnContextReportDebug(ContextClass pContext, @Nullable String pMessage, boolean pWithMeta, @Nullable Object @Nullable... pArgs) { Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } if (logger.isDebugEnabled()) { logger.debug(pMessage, pArgs); } } public boolean isDebugEnabled(ContextClass pContext) { Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } return logger.isDebugEnabled(); } /** * @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextReportInfo(com.diamondq.common.utils.context.spi.ContextClass, * java.lang.String, java.lang.Object[]) */ @Override public void executeOnContextReportInfo(ContextClass pContext, @Nullable String pMessage, @Nullable Object @Nullable... pArgs) { Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } if (logger.isInfoEnabled()) { logger.info(pMessage, pArgs); } } public boolean isInfoEnabled(ContextClass pContext) { Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } return logger.isInfoEnabled(); } /** * @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextReportWarn(com.diamondq.common.utils.context.spi.ContextClass, * java.lang.String, java.lang.Object[]) */ @Override public void executeOnContextReportWarn(ContextClass pContext, @Nullable String pMessage, @Nullable Object @Nullable... pArgs) { Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } if (logger.isWarnEnabled()) { logger.warn(pMessage, pArgs); } } public boolean isWarnEnabled(ContextClass pContext) { Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } return logger.isWarnEnabled(); } /** * @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextReportError(com.diamondq.common.utils.context.spi.ContextClass, * java.lang.String, java.lang.Object[]) */ @Override public void executeOnContextReportError(ContextClass pContext, @Nullable String pMessage, @Nullable Object @Nullable... pArgs) { Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } if (logger.isErrorEnabled()) { logger.error(pMessage, pArgs); } } /** * @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnContextReportError(com.diamondq.common.utils.context.spi.ContextClass, * java.lang.String, java.lang.Throwable) */ @Override public void executeOnContextReportError(ContextClass pContext, @Nullable String pMessage, Throwable pThrowable) { Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } if (logger.isErrorEnabled()) { logger.error(pMessage, pThrowable); } } public boolean isErrorEnabled(ContextClass pContext) { Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } return logger.isErrorEnabled(); } /** * @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnAttachContextToThread(com.diamondq.common.utils.context.spi.ContextClass) */ @Override public void executeOnAttachContextToThread(ContextClass pContext) { } /** * @see com.diamondq.common.utils.context.spi.ContextHandler#executeOnDetachContextToThread(com.diamondq.common.utils.context.spi.ContextClass) */ @Override public void executeOnDetachContextToThread(ContextClass pContext) { Logger logger = mLoggerMap.get(pContext.startClass); if (logger == null) { Logger newLogger = LoggerFactory.getLogger(pContext.startClass); if ((logger = mLoggerMap.putIfAbsent(pContext.startClass, newLogger)) == null) logger = newLogger; } if (logger.isTraceEnabled(sEXIT_MARKER)) { String methodName = pContext.getLatestStackMethod(); exitInternal(pContext, logger, pContext.startThis, methodName, true, null, false, true, null, null); } if (pContext.getHandlerData(ContextHandler.sSIMPLE_CONTEXT, false, Boolean.class) != null) return; } /** * Common internal function to handle the entry routine * * @param pContextClass the context class * @param pLogger the logger * @param pMarker the marker * @param pThis the object representing 'this' * @param pMethodName the method name (if null, then it's calculated) * @param pWithMeta true if there is meta data in the arguments or false if there isn't. * @param pMatchEntryExit true if there must be matching exit or false if this is a standalone entry * @param pArgs any arguments to display */ private void entryWithMetaInternal(ContextClass pContextClass, Logger pLogger, Marker pMarker, @Nullable Object pThis, @Nullable String pMethodName, boolean pWithMeta, boolean pMatchEntryExit, @Nullable Object @Nullable... pArgs) { String messagePattern; if (pArgs == null) pArgs = new Object[0]; int argsLen = pArgs.length / (pWithMeta ? 2 : 1); if (argsLen < sENTRY_MESSAGE_ARRAY_LEN) messagePattern = sENTRY_MESSAGE_ARRAY[argsLen]; else messagePattern = buildMessagePattern(argsLen); int expandedLen; if (argsLen == 0) expandedLen = 2; else expandedLen = argsLen + 2; Object[] expandedArgs = new Object[expandedLen]; Object[] filteredArgs; /* See if the last entry is a Throwable */ Object lastEntry = (pArgs.length > 0 ? pArgs[pArgs.length - 1] : null); if (expandedLen > 2) { if (pWithMeta == false) { /* Copy the arguments (skipping the final throwable if it's present */ System.arraycopy(pArgs, 0, expandedArgs, 1, (lastEntry instanceof Throwable ? argsLen - 1 : argsLen)); filteredArgs = pArgs; } else { filteredArgs = new Object[argsLen]; for (int i = 0; i < argsLen; i++) { int argOffset = i * 2; @SuppressWarnings("unchecked") @Nullable Function<@Nullable Object, @Nullable Object> func = (Function<@Nullable Object, @Nullable Object>) pArgs[argOffset + 1]; if (func == null) expandedArgs[1 + i] = pArgs[argOffset]; else { expandedArgs[1 + i] = func.apply(pArgs[argOffset]); filteredArgs[i] = expandedArgs[1 + i]; } } } /* Add the throwable back in */ if (lastEntry instanceof Throwable) expandedArgs[expandedArgs.length - 1] = lastEntry; } else filteredArgs = pArgs; /* Calculate the method name */ if (pMethodName == null) { StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); String methodName = stackTraceElements[3].getMethodName(); expandedArgs[0] = methodName; pMethodName = methodName; } else expandedArgs[0] = pMethodName; /* Add the caller object */ if ("<init>".equals(pMethodName)) expandedArgs[expandedArgs.length - (lastEntry instanceof Throwable ? 2 : 1)] = pThis == null ? null : pThis.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(pThis)); else expandedArgs[expandedArgs.length - (lastEntry instanceof Throwable ? 2 : 1)] = pThis; FormattingTuple tp = MessageFormatter.arrayFormat(messagePattern, expandedArgs); pLogger.trace(pMarker, tp.getMessage(), filteredArgs); } private void exitInternal(ContextClass pContextClass, Logger pLogger, @Nullable Object pThis, @Nullable String pMethodName, boolean pMatchEntryExit, @Nullable Throwable pThrowable, boolean pWithResult, boolean pWithDetach, @Nullable Object pResult, @Nullable Function<@Nullable Object, @Nullable Object> pMeta) { String methodName; if (pMethodName == null) { /* Calculate the method name */ StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); methodName = stackTraceElements[3].getMethodName(); } else methodName = pMethodName; if (pThrowable != null) pLogger.error(sEXIT_MARKER, sEXIT_MESSAGE_ERROR, methodName, pThis, pThrowable); else if (pWithResult == true) { if (pMeta != null) { Object newResult = pMeta.apply(pResult); pLogger.trace(sEXIT_MARKER, sEXIT_MESSAGE_1, methodName, newResult, pThis); } else { pLogger.trace(sEXIT_MARKER, sEXIT_MESSAGE_1, methodName, pResult, pThis); } } else { if (pWithDetach == true) pLogger.trace(sEXIT_MARKER, sDETACH_MESSAGE_0, methodName, pThis); else pLogger.trace(sEXIT_MARKER, sEXIT_MESSAGE_0, methodName, pThis); } } private static String buildMessagePattern(int len) { StringBuilder sb = new StringBuilder(); sb.append("{}("); for (int i = 0; i < len; i++) { sb.append("{}"); if (i != (len - 1)) sb.append(", "); } sb.append(") from {}"); return sb.toString(); } }
package com.jivesoftware.os.wiki.miru.deployable.endpoints; import com.jivesoftware.os.mlogger.core.MetricLogger; import com.jivesoftware.os.mlogger.core.MetricLoggerFactory; import com.jivesoftware.os.wiki.miru.deployable.WikiMiruService; import com.jivesoftware.os.wiki.miru.deployable.region.WikiWikiPluginRegion; import com.jivesoftware.os.wiki.miru.deployable.region.WikiWikiPluginRegion.WikiWikiPluginRegionInput; import javax.inject.Singleton; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Singleton @Path("/ui/wiki") public class WikiWikiPluginEndpoints { private static final MetricLogger LOG = MetricLoggerFactory.getLogger(); private final WikiMiruService wikiMiruService; private final WikiWikiPluginRegion pluginRegion; public WikiWikiPluginEndpoints(@Context WikiMiruService wikiMiruService, @Context WikiWikiPluginRegion pluginRegion) { this.wikiMiruService = wikiMiruService; this.pluginRegion = pluginRegion; } @GET @Path("/{tenantId}/{wikiId}") @Produces(MediaType.TEXT_HTML) public Response wiki( @PathParam("tenantId") @DefaultValue("") String tenantId, @PathParam("wikiId") @DefaultValue("") String wikiId) { try { String rendered = wikiMiruService.renderPlugin(pluginRegion, new WikiWikiPluginRegionInput(tenantId, wikiId)); return Response.ok(rendered).build(); } catch (Exception x) { LOG.error("Failed to generating query ui.", x); return Response.serverError().build(); } } }
package com.xeiam.xchange.cryptofacilities.dto.marketdata; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.fasterxml.jackson.annotation.JsonProperty; import com.xeiam.xchange.cryptofacilities.dto.CryptoFacilitiesResult; /** * @author Panchen */ public class CryptoFacilitiesFill extends CryptoFacilitiesResult { private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); private final Date fillTime; private final String order_id; private final String fill_id; private final String symbol; private final String side; private final BigDecimal size; private final BigDecimal price; public CryptoFacilitiesFill(@JsonProperty("result") String result , @JsonProperty("error") String error , @JsonProperty("fillTime") String strfillTime , @JsonProperty("order_id") String order_id , @JsonProperty("fill_id") String fill_id , @JsonProperty("symbol") String symbol , @JsonProperty("side") String side , @JsonProperty("qty") BigDecimal size , @JsonProperty("price") BigDecimal price ) throws ParseException { super(result, error); this.fillTime = DATE_FORMAT.parse(strfillTime); this.order_id = order_id; this.fill_id = fill_id; this.symbol = symbol; this.side = side; this.size = size; this.price = price; } public String getSymbol() { return symbol; } public Date getFillTime() { return fillTime; } public String getOrderId() { return order_id; } public String getFillId() { return fill_id; } public String getSide() { return side; } public BigDecimal getSize() { return size; } public BigDecimal getPrice() { return price; } @Override public String toString() { return "CryptoFacilitiesFill [order_id=" + order_id + ", fill_id=" + fill_id + ", fillTime=" + DATE_FORMAT.format(fillTime) + ", symbol=" + symbol + ", side=" + side + ", size=" + size + ", price=" + price +" ]"; } }
package org.jboss.aerogear.android.unifiedpush.test.gcm; import org.jboss.aerogear.android.unifiedpush.gcm.AeroGearGCMPushConfiguration; import org.jboss.aerogear.android.unifiedpush.gcm.UnifiedPushConfig; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.List; public class UnifiedPushConfigTest { @Test public void shouldSetCategories() throws Exception { //given UnifiedPushConfig config = new UnifiedPushConfig(); List<String> categories = Arrays.asList("cat1", "cat2"); //when config.setCategories(categories); //then Assert.assertEquals(categories, config.getCategories()); } @Test public void shouldPushConfigSetCategories() throws Exception { //given AeroGearGCMPushConfiguration config = new AeroGearGCMPushConfiguration(); List<String> categories = Arrays.asList("cat1", "cat2"); //when config.setCategories(categories); config.setCategories(categories); //then Assert.assertEquals(categories, config.getCategories()); } }
package org.csstudio.channel.widgets; import static org.epics.pvmanager.ExpressionLanguage.channels; import static org.epics.pvmanager.ExpressionLanguage.latestValueOf; import static org.epics.pvmanager.data.ExpressionLanguage.column; import static org.epics.pvmanager.data.ExpressionLanguage.vStringConstants; import static org.epics.pvmanager.data.ExpressionLanguage.vTable; import static org.epics.pvmanager.util.TimeDuration.ms; import gov.bnl.channelfinder.api.Channel; import gov.bnl.channelfinder.api.ChannelUtil; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.csstudio.channel.widgets.ChannelTreeByPropertyModel.Node; import org.csstudio.utility.channelfinder.CFClientManager; import org.csstudio.utility.channelfinder.ChannelQuery; import org.csstudio.utility.channelfinder.ChannelQueryListener; import org.csstudio.utility.pvmanager.ui.SWTUtil; import org.csstudio.utility.pvmanager.widgets.ErrorBar; import org.csstudio.utility.pvmanager.widgets.VTableDisplay; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.epics.pvmanager.PVManager; import org.epics.pvmanager.PVReader; import org.epics.pvmanager.PVReaderListener; import org.epics.pvmanager.data.VTable; import org.epics.pvmanager.data.VTableColumn; public class ChannelTreeByPropertyWidget extends Composite { private String channelQuery; private Tree tree; private ErrorBar errorBar; private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); private ChannelTreeByPropertyModel model; public ChannelTreeByPropertyWidget(Composite parent, int style) { super(parent, style); GridLayout gridLayout = new GridLayout(1, false); gridLayout.verticalSpacing = 0; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; setLayout(gridLayout); tree = new Tree(this, SWT.VIRTUAL | SWT.BORDER); tree.addListener(SWT.SetData, new Listener() { public void handleEvent(Event event) { if (model != null) { TreeItem item = (TreeItem)event.item; TreeItem parentItem = item.getParentItem(); Node parentNode; Node node; int index; if (parentItem == null) { parentNode = model.getRoot(); index = tree.indexOf(item); } else { parentNode = (Node) parentItem.getData(); index = parentItem.indexOf(item); } node = parentNode.getChild(index); item.setData(node); item.setText(node.getDisplayName()); if (node.getChildrenNames() == null) { item.setItemCount(0); } else { item.setItemCount(node.getChildrenNames().size()); } } } }); tree.setItemCount(0); tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); errorBar = new ErrorBar(this, SWT.NONE); errorBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); addPropertyChangeListener(new PropertyChangeListener() { List<String> properties = Arrays.asList("channels", "rowProperty", "columnProperty"); @Override public void propertyChange(PropertyChangeEvent evt) { if (properties.contains(evt.getPropertyName())) { computeTree(); } } }); changeSupport.addPropertyChangeListener("channelQuery", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { queryChannels(); } }); } private void setLastException(Exception ex) { errorBar.setException(ex); } public void addPropertyChangeListener( PropertyChangeListener listener ) { changeSupport.addPropertyChangeListener( listener ); } public void removePropertyChangeListener( PropertyChangeListener listener ) { changeSupport.removePropertyChangeListener( listener ); } public String getChannelQuery() { return channelQuery; } public void setChannelQuery(String channelQuery) { String oldValue = this.channelQuery; this.channelQuery = channelQuery; changeSupport.firePropertyChange("channelQuery", oldValue, channelQuery); } public Collection<Channel> getChannels() { return channels; } private Collection<Channel> channels = new ArrayList<Channel>(); private List<String> properties = new ArrayList<String>(); private void setChannels(Collection<Channel> channels) { Collection<Channel> oldChannels = this.channels; this.channels = channels; changeSupport.firePropertyChange("channels", oldChannels, channels); } public List<String> getProperties() { return properties; } public void setProperties(List<String> properties) { List<String> oldProperties = this.properties; this.properties = properties; computeTree(); changeSupport.firePropertyChange("properties", oldProperties, properties); } private void queryChannels() { setChannels(new ArrayList<Channel>()); tree.setItemCount(0); tree.clearAll(true); final ChannelQuery query = ChannelQuery.Builder.query(channelQuery).create(); query.addChannelQueryListener(new ChannelQueryListener() { @Override public void getQueryResult() { SWTUtil.swtThread().execute(new Runnable() { @Override public void run() { Exception e = query.getLastException(); if (e == null) { setChannels(query.getResult()); List<String> newProperties = new ArrayList<String>(getProperties()); newProperties.retainAll(ChannelUtil.getPropertyNames(channels)); if (newProperties.size() != getProperties().size()) { setProperties(newProperties); } computeTree(); } else { errorBar.setException(e); } } }); } }); query.execute(); } private void computeTree() { tree.setItemCount(0); tree.clearAll(true); model = new ChannelTreeByPropertyModel(getChannels(), getProperties()); tree.setItemCount(model.getRoot().getChildrenNames().size()); } }
package exh3y.telebot; import static org.junit.Assert.assertTrue; import org.json.JSONObject; import org.junit.Test; import exh3y.telebot.actions.TelegramActionHandler; public class TeleBotTest implements TelegramActionHandler { @Test public void testTeleBotCreation() { TeleBot bot = new TeleBot("123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"); try { bot.registerCommandAction("/test", this); bot.unregisterCommandAction("/test"); bot.registerDefaultTextAction(this); } catch (Exception e) { assertTrue(false); } } @Override public void onCommandReceive(int chatId, JSONObject message) { return; } }
package com.valkryst.VTerminal.font; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.nio.file.AccessDeniedException; import java.nio.file.Path; import java.nio.file.Paths; @RunWith(value=BlockJUnit4ClassRunner.class) public class FontLoaderTest { private final String spriteSheetPath = System.getProperty("user.dir") + "/res/Fonts/DejaVu Sans Mono/20pt/bitmap.png"; private final String characterDataPath = System.getProperty("user.dir") + "/res/Fonts/DejaVu Sans Mono/20pt/data.fnt"; private final String spriteSheetPath_inJar = "Fonts/DejaVu Sans Mono/20pt/bitmap.png"; private final String characterDataPath_inJar = "Fonts/DejaVu Sans Mono/20pt/data.fnt"; @Test public void loadFont_withStrings() throws IOException { System.out.println(spriteSheetPath + "\n" + characterDataPath + "\n" + spriteSheetPath_inJar + "\n" + characterDataPath_inJar); FontLoader.loadFont(spriteSheetPath, characterDataPath, 1); } @Test(expected=FileNotFoundException.class) public void loadFont_withStrings_withEmptySpriteSheetPath() throws IOException { FontLoader.loadFont("", characterDataPath, 1); } @Test(expected=NullPointerException.class) public void loadFont_withStrings_withNullSpriteSheetPath() throws IOException { FontLoader.loadFont(null, characterDataPath, 1); } @Test(expected=AccessDeniedException.class) public void loadFont_withStrings_withEmptyCharacterDataPath() throws IOException { FontLoader.loadFont(spriteSheetPath, "", 1); } @Test(expected=NullPointerException.class) public void loadFont_withStrings_withNullCharacterDataPath() throws IOException { FontLoader.loadFont(spriteSheetPath, null, 1); } @Test public void loadFont_withStreamAndPath() throws IOException { final InputStream inputStream = new FileInputStream(spriteSheetPath); final Path path = Paths.get(characterDataPath); FontLoader.loadFont(inputStream, path, 1); } @Test(expected=IllegalArgumentException.class) public void loadFont_withStreamAndPath_withNullStream() throws IOException { final Path path = Paths.get(characterDataPath); FontLoader.loadFont(null, path, 1); } @Test(expected=NullPointerException.class) public void loadFont_withStreamAndPath_withNullPath() throws IOException { final InputStream inputStream = new FileInputStream(spriteSheetPath); FontLoader.loadFont(inputStream, null, 1); } @Test public void loadFontFromJar_withStrings() throws IOException, URISyntaxException { FontLoader.loadFontFromJar(spriteSheetPath_inJar, characterDataPath_inJar, 1); } @Test(expected=NullPointerException.class) public void loadFontFromJar_withStrings_withEmptySpriteSheetPath() throws IOException, URISyntaxException { FontLoader.loadFontFromJar("", characterDataPath_inJar, 1); } @Test(expected=NullPointerException.class) public void loadFontFromJar_withStrings_withNullSpriteSheetPath() throws IOException, URISyntaxException { FontLoader.loadFontFromJar(null, characterDataPath_inJar, 1); } @Test(expected=AccessDeniedException.class) public void loadFontFromJar_withStrings_withEmptyCharacterDataPath() throws IOException, URISyntaxException { FontLoader.loadFontFromJar(spriteSheetPath_inJar, "", 1); } @Test(expected=NullPointerException.class) public void loadFontFromJar_withStrings_withNullCharacterDataPath() throws IOException, URISyntaxException { FontLoader.loadFontFromJar(spriteSheetPath_inJar, null, 1); } }
package org.biojava.bio.seq.io; import java.io.*; import java.util.*; import org.biojava.utils.*; import org.biojava.bio.*; import org.biojava.bio.symbol.*; import org.biojava.bio.seq.*; /** * Format processor for handling EMBL records and similar * files. This takes a very simple approach: all * `normal' attribute lines are passed to the listener * as a tag (first two characters) and a value (the * rest of the line from the 6th character onwards). * Any data between the special `SQ' line and the * "//" entry terminator is passed as a SymbolReader. * * <p> * This low-level format processor should normally be * used in conjunction with one or more `filter' objects, * such as EmblProcessor. * </p> * * <p> * Many ideas borrowed from the old EmblFormat processor * by Thomas Down and Thad Welch. * </p> * * @author Thomas Down * @since 1.1 */ public class EmblLikeFormat implements SequenceFormat, Serializable { private boolean elideSymbols = false; /** * Should we ignore the symbols (SQ) part of the * entry? */ public void setElideSymbols(boolean b) { elideSymbols = b; } public boolean readSequence(BufferedReader reader, SymbolParser symParser, SeqIOListener listener) throws IllegalSymbolException, IOException { String line; StreamParser sparser = null; boolean hasMoreSequence = true; listener.startSequence(); while ((line = reader.readLine()) != null) { if (line.startsWith(" if (sparser != null) { // End of symbol data sparser.close(); sparser = null; } reader.mark(2); if (reader.read() == -1) hasMoreSequence = false; else reader.reset(); listener.endSequence(); return hasMoreSequence; } else if (line.startsWith("SQ")) { sparser = symParser.parseStream(listener); } else { if (sparser == null) { // Normal attribute line String tag = line.substring(0, 2); String rest = null; if (line.length() > 5) { rest = line.substring(5); } listener.addSequenceProperty(tag, rest); } else { // Sequence line if (!elideSymbols) processSequenceLine(line, sparser); } } } throw new IOException("Premature end of stream for EMBL"); } /** * Dispatch symbol data from SQ-block line of an EMBL-like file. */ protected void processSequenceLine(String line, StreamParser parser) throws IllegalSymbolException { char[] cline = line.toCharArray(); int parseStart = 0; int parseEnd = 0; while (parseStart < cline.length) { while( parseStart < cline.length && cline[parseStart] == ' ') ++parseStart; if (parseStart >= cline.length) break; if (Character.isDigit(cline[parseStart])) return; parseEnd = parseStart + 1; while (parseEnd < cline.length && cline[parseEnd] != ' ') ++parseEnd; // Got a segment of read sequence data parser.characters(cline, parseStart, parseEnd - parseStart); parseStart = parseEnd; } } /** * This is not implemented. It does not write anything to the stream. */ public void writeSequence(Sequence seq, PrintStream os) throws IOException { throw new RuntimeException("Can't write in EMBL format..."); } }
package org.broad.igv.feature; import org.apache.log4j.Logger; import org.broad.igv.ui.IGV; import org.broad.igv.util.collections.MultiMap; import htsjdk.tribble.Feature; import java.awt.*; import java.util.List; /** * @author jrobinso */ abstract public class AbstractFeature implements IGVFeature, htsjdk.tribble.Feature { private static Logger log = Logger.getLogger(AbstractFeature.class); protected Strand strand = Strand.NONE; protected String chromosome; protected int start = -1; protected int end = -1; protected String type = ""; protected Color color; protected String description; protected MultiMap<String, String> attributes; protected String name = ""; /** * The 0-based reading frame offset from start position. * Only well defined for Exon-type features */ protected int readingFrame = -1; public AbstractFeature() { } /** * @param chr * @param start * @param end * @param strand */ public AbstractFeature(String chr, int start, int end, Strand strand) { this.chromosome = chr; this.start = start; this.end = end; this.strand = strand; } public String getIdentifier() { return null; } public void setType(String type) { this.type = type; } public String getType() { return type; } public String getName() { return name; } public List<Exon> getExons() { return null; } public boolean hasExons() { return false; } public float getScore() { return Float.NaN; } public String getChr() { return chromosome; } public String getContig() { return chromosome; } /** * By default features are 1 bp wide * * @return */ public int getEnd() { return end; } public int getLength() { return end - start; } public int getStart() { return start; } /** * Return true if the feature is completely contained within the bounds of this * feature. amd is on the same strand.. * <p/> * * @param feature * @return */ public boolean contains(IGVFeature feature) { if (feature == null) { return false; } if (!this.getChr().equals(feature.getChr()) || this.getStrand() != feature.getStrand()) { return false; } if ((feature.getStart() >= this.getStart()) && (feature.getEnd() <= this.getEnd())) { return true; } else { return false; } } public void setEnd(int end) { this.end = end; } public void setStart(int start) { this.start = start; } public Strand getStrand() { return strand; } public void setStrand(Strand strand) { this.strand = strand; } public boolean hasStrand() { return ((strand != null) && (strand != Strand.NONE)); } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public void setColor(String[] rgb, int nTokens) { try { if (nTokens < 3) { if (rgb[0].equals(".")) { return; } color = new Color(Integer.parseInt(rgb[0]), Integer.parseInt(rgb[0]), Integer.parseInt(rgb[0])); } else { color = new Color(Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), Integer.parseInt(rgb[2])); } } catch (NumberFormatException numberFormatException) { } } public void setDescription(String description) { this.description = description; } public String getDescription() { return (description == null) ? getName() : description; } public MultiMap<String, String> getAttributes() { return attributes; } public void setAttributes(MultiMap<String, String> attributes) { this.attributes = attributes; } public void setAttribute(String key, String value) { if(attributes == null) { attributes = new MultiMap<String, String>(); } attributes.put(key, value); } public boolean contains(double location) { return location >= getStart() && location < getEnd(); } public boolean overlaps(Feature anotherFeature) { return end >= anotherFeature.getStart() && start <= anotherFeature.getEnd() && chromosome.equals(anotherFeature.getChr()); } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @param chromosome the chromosome to set */ public void setChr(String chromosome) { this.chromosome = chromosome; } /** * Get human readable locus string. * It is assumed that this.start and this.end are 0-based * and end-exclusive, and the returned string is 1-based * and end-inclusive. So basically we just add 1 to the start. * * @return */ public String getLocusString() { return getChr() + ":" + (getStart() + 1) + "-" + getEnd(); } protected String getAttributeString() { StringBuffer buf = new StringBuffer(); // 30 attributes is the maximum visible on a typical screen int max = IGV.getInstance().isShowDetailsOnClick() ? 10000 : 30; attributes.printHtml(buf, max); return buf.toString(); } public void setReadingFrame(int offset) { this.readingFrame = offset; } public int getReadingFrame(){ return this.readingFrame; } }
package org.clapper.util.config; import java.io.*; import java.util.*; import java.net.*; import org.clapper.util.text.*; import org.clapper.util.io.*; public class Configuration implements VariableDereferencer, VariableNameChecker { private static final String COMMENT_CHARS = "#!"; private static final char SECTION_START = '['; private static final char SECTION_END = ']'; private static final String INCLUDE = "%include"; private static final int MAX_INCLUDE_NESTING_LEVEL = 50; /** * Contains one logical input line. */ private class Line { static final int COMMENT = 0; static final int INCLUDE = 1; static final int SECTION = 2; static final int VARIABLE = 3; static final int BLANK = 4; int number = 0; int type = COMMENT; StringBuffer buffer = new StringBuffer(); Line() { } void newLine() { buffer.setLength (0); } } /** * Contents of a variable. Mostly exists to make replacing a variable * value easier while looping over a section. */ private class Variable { String name; String cookedValue; String rawValue; Variable (String name, String value) { this.name = name; setValue (value); } void setValue (String value) { this.rawValue = value; this.cookedValue = value; } } /** * Contents of a section */ private class Section { /** * Name of section */ String name; /** * Names of variables, in order encountered. Contains strings. */ List variableNames = new ArrayList(); /** * List of Variable objects, indexed by variable name */ Map valueMap = new HashMap(); Section (String name) { this.name = name; } Variable getVariable (String varName) { return (Variable) valueMap.get (varName); } Variable addVariable (String varName, String value) { Variable variable = new Variable (varName, value); valueMap.put (varName, variable); variableNames.add (varName); return variable; } } /** * Container for data used only during parsing. */ private class ParseData { /** * Current section. Only set during parsing. */ private Section currentSection = null; /** * Current variable name being processed. Used during the variable * substitution parsing phase. */ private Variable currentVariable = null; /** * Total number of variable substitutions performed on the current * variable's value during one substitution round. Used during the * variable substitution parsing phase. */ private int totalSubstitutions = 0; /** * Current include file nesting level. Used as a fail-safe during * parsing. */ private int includeFileNestingLevel = 0; /** * Table of files/URLs currently open. Used during include * processing. */ private Set openURLs = new HashSet(); ParseData() { } } /** * List of sections, in order encountered. Each element is a reference to * a Section object. */ private List sectionsInOrder = new ArrayList(); /** * Sections by name. Each index is a string. Each value is a reference to * a Section object. */ private Map sectionsByName = new HashMap(); /** * Data used during parsing. Null when parsing isn't being done. */ private ParseData parseData = null; /** * Construct an empty <tt>Configuration</tt> object. The object may * later be filled with configuration data via one of the <tt>load()</tt> * methods, or by calls to {@link #addSection addSection()} and * {@link #setVariable setVariable()}. */ public Configuration() { } /** * Construct a <tt>Configuration</tt> object that parses data from * the specified file. * * @param f The <tt>File</tt> to open and parse * * @throws IOException can't open or read file * @throws ConfigurationException error in configuration data */ public Configuration (File f) throws IOException, ConfigurationException { load (f); } /** * Construct a <tt>Configuration</tt> object that parses data from * the specified file. * * @param path the path to the file to parse * * @throws FileNotFoundException specified file doesn't exist * @throws IOException can't open or read file * @throws ConfigurationException error in configuration data */ public Configuration (String path) throws FileNotFoundException, IOException, ConfigurationException { load (path); } /** * Construct a <tt>Configuration</tt> object that parses data from * the specified URL. * * @param url the URL to open and parse * * @throws IOException can't open or read URL * @throws ConfigurationException error in configuration data */ public Configuration (URL url) throws IOException, ConfigurationException { load (url); } /** * Construct a <tt>Configuration</tt> object that parses data from * the specified <tt>InputStream</tt>. * * @param iStream the <tt>InputStream</tt> * * @throws IOException can't open or read URL * @throws ConfigurationException error in configuration data */ public Configuration (InputStream iStream) throws IOException, ConfigurationException { load (iStream); } /** * Add a new section to this configuration data. * * @param sectionName the name of the new section * * @throws SectionExistsException a section by that name already exists * * @see #containsSection * @see #getSectionNames * @see #setVariable */ public void addSection (String sectionName) throws SectionExistsException { if (sectionsByName.get (sectionName) != null) throw new SectionExistsException (sectionName); makeNewSection (sectionName); } /** * Clear this object of all configuration data. */ public void clear() { sectionsInOrder.clear(); sectionsByName.clear(); } /** * Determine whether this object contains a specified section. * * @param sectionName the section name * * @return <tt>true</tt> if the section exists in this configuration, * <tt>false</tt> if not. * * @see #getSectionNames * @see #addSection */ public boolean containsSection (String sectionName) { return (sectionsByName.get (sectionName) != null); } /** * Get the names of the sections in this object, in the order they were * parsed and/or added. * * @param collection the <tt>Collection</tt> to which to add the section * names. The names are added in the order they were * parsed and/or added to this object; of course, the * <tt>Collection</tt> may reorder them. * * @return the <tt>collection</tt> parameter, for convenience * * @see #getVariableNames */ public Collection getSectionNames (Collection collection) { for (Iterator it = sectionsInOrder.iterator(); it.hasNext(); ) collection.add (((Section) it.next()).name); return collection; } /** * Get the names of the all the variables in a section, in the order * they were parsed and/or added. * * @param sectionName the name of the section to access * @param collection the <tt>Collection</tt> to which to add the variable * names. The names are added in the order they were * parsed and/or added to this object; of course, the * <tt>Collection</tt> may reorder them. * * @return the <tt>collection</tt> parameter, for convenience * * @throws NoSuchSectionException no such section * * @see #getSectionNames * @see #containsSection * @see #getVariableValue */ public Collection getVariableNames (String sectionName, Collection collection) throws NoSuchSectionException { Section section = (Section) sectionsByName.get (sectionName); if (section == null) throw new NoSuchSectionException (sectionName); collection.addAll (section.variableNames); return collection; } /** * Get the value for a variable. * * @param sectionName the name of the section containing the variable * @param variableName the variable name * * @return the value for the variable (which may be the empty string) * * @throws NoSuchSectionException the named section does not exist * @throws NoSuchVariableException the section has no such variable */ public String getVariableValue (String sectionName, String variableName) throws NoSuchSectionException, NoSuchVariableException { Section section = (Section) sectionsByName.get (sectionName); if (section == null) throw new NoSuchSectionException (sectionName); Variable variable = (Variable) section.getVariable (variableName); if (variable == null) throw new NoSuchVariableException (sectionName, variableName); return variable.cookedValue; } /** * Convenience method to get and convert an optional integer parameter. * The default value applies if the variable is missing or is there but * has an empty value. * * @param sectionName section name * @param variableName variable name * @param defaultValue default value if not found * * @return the value, or the default value if not found * * @throws NoSuchSectionException no such section * @throws ConfigurationException bad numeric value */ public int getOptionalIntegerValue (String sectionName, String variableName, int defaultValue) throws NoSuchSectionException, ConfigurationException { try { return getRequiredIntegerValue (sectionName, variableName); } catch (NoSuchVariableException ex) { return defaultValue; } } /** * Convenience method to get and convert a required integer parameter. * The default value applies if the variable is missing or is there * but has an empty value. * * @param sectionName section name * @param variableName variable name * * @return the value * * @throws NoSuchSectionException no such section * @throws NoSuchVariableException no such variable * @throws ConfigurationException bad numeric value */ public int getRequiredIntegerValue (String sectionName, String variableName) throws NoSuchSectionException, NoSuchVariableException, ConfigurationException { String sNum = getVariableValue (sectionName, variableName); try { return Integer.parseInt (sNum); } catch (NumberFormatException ex) { throw new ConfigurationException ("Bad numeric value \"" + sNum + "\" for variable \"" + variableName + "\" in section \"" + sectionName + "\""); } } /** * Convenience method to get and convert an optional boolean parameter. * The default value applies if the variable is missing or is there * but has an empty value. * * @param sectionName section name * @param variableName variable name * @param defaultValue default value if not found * * @return the value, or the default value if not found * * @throws NoSuchSectionException no such section * @throws ConfigurationException bad numeric value */ public boolean getOptionalBooleanValue (String sectionName, String variableName, boolean defaultValue) throws NoSuchSectionException, ConfigurationException { boolean result = defaultValue; try { String s = getVariableValue (sectionName, variableName); if (s.trim().length() == 0) result = defaultValue; else result = Boolean.valueOf (s).booleanValue(); } catch (NoSuchVariableException ex) { result = defaultValue; } return result; } /** * Convenience method to get and convert a required boolean parameter. * * @param sectionName section name * @param variableName variable name * * @return the value * * @throws NoSuchSectionException no such section * @throws NoSuchVariableException no such variable * @throws ConfigurationException bad numeric value */ public boolean getRequiredBooleanValue (String sectionName, String variableName) throws NoSuchSectionException, ConfigurationException, NoSuchVariableException { return Boolean.valueOf (getVariableValue (sectionName, variableName)) .booleanValue(); } /** * Convenience method to get an optional string value. The default * value applies if the variable is missing or is there but has an * empty value. * * @param sectionName section name * @param variableName variable name * @param defaultValue default value if not found * * @return the value, or the default value if not found * * @throws NoSuchSectionException no such section * @throws ConfigurationException bad numeric value */ public String getOptionalStringValue (String sectionName, String variableName, String defaultValue) throws NoSuchSectionException, ConfigurationException { String result; try { result = getVariableValue (sectionName, variableName); if (result.trim().length() == 0) result = defaultValue; } catch (NoSuchVariableException ex) { result = defaultValue; } return result; } /** * Get the value associated with a given variable. Required by the * {@link VariableDereferencer} interface, this method is used during * parsing to handle variable substitutions (but also potentially * useful by other applications). See this class's documentation for * details on variable references. * * @param varName The name of the variable for which the value is * desired. * * @return The variable's value. If the variable has no value, this * method must return the empty string (""). It is important * <b>not</b> to return null. * * @throws VariableSubstitutionException variable references itself */ public String getValue (String varName) throws VariableSubstitutionException { if (parseData.currentVariable.name.equals (varName)) { throw new VariableSubstitutionException ("Attempt to substitute " + "value for variable \"" + varName + "\" within itself."); } int i; Section section; String value = null; i = varName.indexOf (':'); if (i == -1) { section = parseData.currentSection; } else { section = (Section) sectionsByName.get (varName.substring (0, i)); varName = varName.substring (i + 1); } if (section != null) { Variable var = (Variable) section.getVariable (varName); if (var != null) value = var.cookedValue; } parseData.totalSubstitutions++; return (value == null) ? "" : value; } public boolean legalVariableCharacter (char c) { return (Character.isLetterOrDigit (c) || (c == '_') || (c == '.') || (c == ':')); } /** * Load configuration from a <tt>File</tt>. Any existing data is * discarded. * * @param file the file * * @throws IOException read error * @throws ConfigurationException parse error */ private void load (File file) throws IOException, ConfigurationException { clear(); parse (new FileInputStream (file), file.toURL()); } /** * Load configuration from a file specified as a pathname. Any existing * data is discarded. * * @param path the path * * @throws FileNotFoundException specified file doesn't exist * @throws IOException can't open or read file * @throws ConfigurationException error in configuration data */ private void load (String path) throws FileNotFoundException, IOException, ConfigurationException { clear(); parse (new FileInputStream (path), new File (path).toURL()); } /** * Load configuration from a URL. Any existing data is discarded. * * @param url the URL * * @throws IOException read error * @throws ConfigurationException parse error */ private void load (URL url) throws IOException, ConfigurationException { clear(); parse (url.openStream(), url); } /** * Load configuration from an <tt>InputStream</tt>. Any existing data * is discarded. * * @param iStream the <tt>InputStream</tt> * * @throws IOException can't open or read URL * @throws ConfigurationException error in configuration data */ public void load (InputStream iStream) throws IOException, ConfigurationException { clear(); parse (iStream, null); } /** * Set a variable's value. If the variable does not exist, it is created. * If it does exist, its current value is overwritten with the new one. * Metacharacters and variable references are not expanded unless the * <tt>expand</tt> parameter is <tt>true</tt>. An <tt>expand</tt> value * of <tt>false</tt> is useful when creating new configuration data to * be written later. * * @param sectionName name of existing section to contain the variable * @param variableName name of variable to set * @param value variable's value * @param expand <tt>true</tt> to expand metacharacters and variable * references in the value, <tt>false</tt> to leave * the value untouched. * * @throws NoSuchSectionException section does not exist * @throws VariableSubstitutionException variable substitution error */ public void setVariable (String sectionName, String variableName, String value, boolean expand) throws NoSuchSectionException, VariableSubstitutionException { Section section = (Section) sectionsByName.get (sectionName); if (section == null) throw new NoSuchSectionException (sectionName); Variable variable = (Variable) section.getVariable (variableName); if (variable != null) variable.setValue (value); else variable = section.addVariable (variableName, value); if (expand) { try { // substituteVariables() requires that the parseData // instance variable be non-null and have valid values for // currentSection and currentVariable. parseData = new ParseData(); parseData.currentSection = section; substituteVariables (variable, new UnixShellVariableSubstituter()); } finally { parseData = null; } } } /** * Writes the configuration data to a <tt>PrintWriter</tt>. The sections * and variables within the sections are written in the order they were * originally read from the file. Non-printable characters (and a few * others) are encoded into metacharacter sequences. Comments and * variable references are not propagated, since they are not retained * when the data is parsed. * * @param out where to write the configuration data * * @see XStringBuffer#encodeMetacharacters() */ public void write (PrintWriter out) { Iterator itSect; Iterator itVar; Section section; String varName; Variable var; XStringBuffer value = new XStringBuffer(); boolean firstSection = true; out.print (COMMENT_CHARS.charAt (0)); out.print (" Written by "); out.println (this.getClass().getName()); out.print (COMMENT_CHARS.charAt (0)); out.print (" on "); out.println (new Date().toString()); out.println(); for (itSect = sectionsInOrder.iterator(); itSect.hasNext(); ) { section = (Section) itSect.next(); if (! firstSection) out.println(); out.println (SECTION_START + section.name + SECTION_END); firstSection = false; for (itVar = section.variableNames.iterator(); itVar.hasNext(); ) { varName = (String) itVar.next(); var = (Variable) section.getVariable (varName); value.setLength (0); value.append (var.cookedValue); value.encodeMetacharacters(); out.println (varName + ": " + value.toString()); } } } /** * Writes the configuration data to a <tt>PrintStream</tt>. The sections * and variables within the sections are written in the order they were * originally read from the file. Non-printable characters (and a few * others) are encoded into metacharacter sequences. Comments and * variable references are not propagated, since they are not retained * when the data is parsed. * * @param out where to write the configuration data * * @see XStringBuffer#encodeMetacharacters() */ public void write (PrintStream out) { PrintWriter w = new PrintWriter (out); write (w); w.flush(); } /** * Parse configuration data from the specified stream. * * @param in the input stream * @param url the URL associated with the stream, or null if not known * * @throws ConfigurationException parse error */ private synchronized void parse (InputStream in, URL url) throws ConfigurationException { parseData = new ParseData(); try { loadConfiguration (in, url); postProcessParsedData(); } finally { parseData = null; } } /** * Load the configuration data into memory, without processing * metacharacters or variable substitution. Includes are processed, * though. * * @param in the input stream * @param url the URL associated with the stream, or null if not known * * @throws IOException read error * @throws ConfigurationException parse error */ private void loadConfiguration (InputStream in, URL url) throws ConfigurationException { BufferedReader r = new BufferedReader (new InputStreamReader (in)); Line line = new Line(); String sURL = url.toExternalForm(); if (parseData.openURLs.contains (sURL)) { throw new ConfigurationException (getExceptionPrefix (line, url) + "Attempt to include \"" + sURL + "\" from itself, either directly or indirectly."); } parseData.openURLs.add (sURL); // Parse the entire file into memory before doing variable // substitution and metacharacter expansion. while (readLogicalLine (r, line)) { try { switch (line.type) { case Line.COMMENT: case Line.BLANK: break; case Line.INCLUDE: handleInclude (line, url); break; case Line.SECTION: parseData.currentSection = handleNewSection (line, url); break; case Line.VARIABLE: if (parseData.currentSection == null) { throw new ConfigurationException (getExceptionPrefix (line, url) + "Variable assignment before " + "first section."); } handleVariable (line, url); break; default: throw new IllegalStateException ("Bug: line.type=" + line.type); } } catch (IOException ex) { throw new ConfigurationException (getExceptionPrefix (line, url) + ex.toString()); } } parseData.openURLs.remove (sURL); } /** * Post-process the loaded configuration, doing variable substitution * and metacharacter expansion. * * @throws ConfigurationException configuration error */ private void postProcessParsedData() throws ConfigurationException { VariableSubstituter substituter; Iterator itSect; Iterator itVar; String varName; Section section; XStringBuffer buf = new XStringBuffer(); // First, expand the the metacharacter sequences. for (itSect = sectionsInOrder.iterator(); itSect.hasNext(); ) { parseData.currentSection = (Section) itSect.next(); for (itVar = parseData.currentSection.variableNames.iterator(); itVar.hasNext(); ) { varName = (String) itVar.next(); section = parseData.currentSection; parseData.currentVariable = section.getVariable (varName); buf.setLength (0); buf.append (parseData.currentVariable.cookedValue); buf.decodeMetacharacters(); parseData.currentVariable.cookedValue = buf.toString(); } } // Now, do variable substitution. parseData.currentSection = null; substituter = new UnixShellVariableSubstituter(); for (itSect = sectionsInOrder.iterator(); itSect.hasNext(); ) { parseData.currentSection = (Section) itSect.next(); for (itVar = parseData.currentSection.variableNames.iterator(); itVar.hasNext(); ) { varName = (String) itVar.next(); section = parseData.currentSection; parseData.currentVariable = section.getVariable (varName); try { substituteVariables (parseData.currentVariable, substituter); } catch (VariableSubstitutionException ex) { throw new ConfigurationException (ex); } } } } /** * Handle a new section. * * @param line line buffer * @param url URL currently being processed, or null if unknown * * @return a new Section object, which has been stored in the appropriate * places * * @throws ConfigurationException configuration error */ private Section handleNewSection (Line line, URL url) throws ConfigurationException { String s = line.buffer.toString().trim(); if (s.charAt (0) != SECTION_START) { throw new ConfigurationException (getExceptionPrefix (line, url) + "Section does not begin with '" + SECTION_START + "'"); } else if (s.charAt (s.length() - 1) != SECTION_END) { throw new ConfigurationException (getExceptionPrefix (line, url) + "Section does not end with '" + SECTION_END + "'"); } return makeNewSection (s.substring (1, s.length() - 1)); } /** * Handle a new variable. * * @param line line buffer * @param url URL currently being processed, or null if unknown * * @throws ConfigurationException configuration error */ private void handleVariable (Line line, URL url) throws ConfigurationException { String s = line.buffer.toString(); int i; if ( ((i = s.indexOf ('=')) == -1) && ((i = s.indexOf (':')) == -1) ) { throw new ConfigurationException (getExceptionPrefix (line, url) + "Missing '=' or ':' for " + "variable definition."); } if (i == 0) { throw new ConfigurationException (getExceptionPrefix (line, url) + "Missing variable name for " + "variable definition."); } String varName = s.substring (0, i); String value = s.substring (skipWhitespace (s, i + 1)); if (parseData.currentSection.getVariable (varName) != null) { throw new ConfigurationException (getExceptionPrefix (line, url) + "Section \"" + parseData.currentSection.name + "\": Duplicate definition of " + "variable \"" + varName + "\"."); } parseData.currentSection.addVariable (varName, value); } /** * Handle an include directive. * * @param line line buffer * @param url URL currently being processed, or null if unknown * * @throws IOException I/O error opening or reading include * @throws ConfigurationException configuration error */ private void handleInclude (Line line, URL url) throws IOException, ConfigurationException { if (parseData.includeFileNestingLevel >= MAX_INCLUDE_NESTING_LEVEL) { throw new ConfigurationException (getExceptionPrefix (line, url) + "Exceeded maximum nested " + "include level of " + MAX_INCLUDE_NESTING_LEVEL + "."); } parseData.includeFileNestingLevel++; String s = line.buffer.toString(); // Parse the file name. String includeTarget = s.substring (INCLUDE.length() + 1).trim(); int len = includeTarget.length(); // Make sure double quotes surround the file or URL. if ((len < 2) || (! includeTarget.startsWith ("\"")) || (! includeTarget.endsWith ("\""))) { throw new ConfigurationException (getExceptionPrefix (line, url) + "Malformed " + INCLUDE + " directive."); } // Extract the file. includeTarget = includeTarget.substring (1, len - 1); if (includeTarget.length() == 0) { throw new ConfigurationException (getExceptionPrefix (line, url) + "Missing file name or URL in " + INCLUDE + " directive."); } // Process the include try { loadInclude (new URL (includeTarget)); } catch (MalformedURLException ex) { // Not obviously a URL. First, determine whether it has // directory information or not. If not, try to use the // parent's directory information. if (FileUtils.isAbsolutePath (includeTarget)) { loadInclude (new URL (url.getProtocol(), url.getHost(), url.getPort(), includeTarget)); } else { // It's relative to the parent. If the parent URL is not // specified, then we can't do anything except try to load // the include as is. It'll probably fail... if (url == null) { loadInclude (new File (includeTarget).toURL()); } else { String parent = new File (url.getFile()).getParent(); if (parent == null) parent = ""; loadInclude (new URL (url.getProtocol(), url.getHost(), url.getPort(), parent + "/" + includeTarget)); } } } parseData.includeFileNestingLevel } /** * Actually attempts to load an include reference. This is basically just * a simplified front-end to loadConfiguration(). * * @param url the URL to be included * * @throws IOException I/O error * @throws ConfigurationException configuration error */ private void loadInclude (URL url) throws IOException, ConfigurationException { loadConfiguration (url.openStream(), url); } /** * Read the next logical line of input from a config file. * * @param r the reader * @param line where to store the line. The line number in this * object is incremented, the "buffer" field is updated, * and the "type" field is set appropriately. * * @return <tt>true</tt> if a line was read, <tt>false</tt> for EOF. * * @throws ConfigurationException read error */ private boolean readLogicalLine (BufferedReader r, Line line) throws ConfigurationException { boolean continued = false; boolean gotSomething = false; line.newLine(); for (;;) { String s; try { s = r.readLine(); } catch (IOException ex) { throw new ConfigurationException (ex); } if (s == null) break; gotSomething = true; line.number++; // Strip leading white space on all lines. int i; char[] chars = s.toCharArray(); i = skipWhitespace (chars, 0); if (i < chars.length) s = s.substring (i); else s = ""; if (! continued) { // First line. Determine what it is. char firstChar; if (s.length() == 0) line.type = Line.BLANK; else if (COMMENT_CHARS.indexOf (s.charAt (0)) != -1) line.type = Line.COMMENT; else if (s.charAt (0) == SECTION_START) line.type = Line.SECTION; else if (new StringTokenizer (s).nextToken().equals (INCLUDE)) line.type = Line.INCLUDE; else line.type = Line.VARIABLE; } if ((line.type == Line.VARIABLE) && (hasContinuationMark (s))) { continued = true; line.buffer.append (s.substring (0, s.length() - 1)); } else { line.buffer.append (s); break; } } return gotSomething; } /** * Determine whether a line has a continuation mark or not. * * @param s the line * * @return true if there's a continuation mark, false if not */ private boolean hasContinuationMark (String s) { boolean has = false; if (s.length() > 0) { char[] chars = s.toCharArray(); if (chars[chars.length-1] == '\\') { // Possibly. See if there are an odd number of them. int total = 0; for (int i = chars.length - 1; i >= 0; i { if (chars[i] != '\\') break; total++; } has = ((total % 2) == 1); } } return has; } /** * Get an appropriate exception prefix (e.g., line number, etc.) * * @param line line buffer * @param url URL currently being processed, or null if unknown * * @return a suitable string */ private String getExceptionPrefix (Line line, URL url) { StringBuffer buf = new StringBuffer(); if (url != null) { buf.append (url.toExternalForm()); buf.append (", line "); } else { buf.append ("Line "); } buf.append (line.number); buf.append (": "); return buf.toString(); } /** * Handle variable substitution for a variable value. NOTE: Requires * that the "parseData" instance be non-null, and its "currentSection" * item be appropriately set. (This method sets "currentVariable".) * * @param var The variable to expand * @param substituter VariableSubstituter to use * * @return the expanded result * * @throws VariableSubstitutionException variable substitution error */ private void substituteVariables (Variable var, VariableSubstituter substituter) throws VariableSubstitutionException { // Keep substituting the current variable's value until there no // more substitutions are performed. This handles the case where a // dereferenced variable value contains its own variable // references. parseData.currentVariable = var; do { parseData.totalSubstitutions = 0; var.cookedValue = substituter.substitute (var.cookedValue, this, this); } while (parseData.totalSubstitutions > 0); } /** * Get index of first non-whitespace character. * * @param s string to check * @param start starting point * * @return index of first non-whitespace character past "start", or -1 */ private int skipWhitespace (String s, int start) { return skipWhitespace (s.toCharArray(), start); } /** * Get index of first non-whitespace character. * * @param chars character array to check * @param start starting point * * @return index of first non-whitespace character past "start", or -1 */ private int skipWhitespace (char[] chars, int start) { while (start < chars.length) { if (! Character.isWhitespace (chars[start])) break; start++; } return start; } /** * Create and save a new Section. * * @param sectionName the name * * @return the Section object, which has been saved. */ private Section makeNewSection (String sectionName) { Section section = new Section (sectionName); sectionsInOrder.add (section); sectionsByName.put (sectionName, section); return section; } }
package org.ensembl.healthcheck; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import org.ensembl.healthcheck.testcase.EnsTestCase; import org.ensembl.healthcheck.util.DBUtils; import org.ensembl.healthcheck.util.Utils; /** * ReportManager is the main class for reporting in the Ensj Healthcheck system. It provides methods for storing reports - single * items of information - and retrieving them in various formats. */ public class ReportManager { /** * <p> * Resets attributes of the ReportManager. This way the ReportManager can be used for running more than one session. (Not at the * same time) Before starting a new session, calling ReportManager.initialise() will put the ReportManager back into a state in * which it can be used again. * </p> * */ public static void initialise() { reportsByTest = new HashMap(); reportsByDatabase = new HashMap(); outputDatabaseConnection = null; sessionID = -1; } /** A hash of lists keyed on the test name. */ protected static Map reportsByTest = new HashMap(); /** A hash of lists keyed on the database name */ protected static Map reportsByDatabase = new HashMap(); /** The logger to use for this class */ protected static Logger logger = Logger.getLogger("HealthCheckLogger"); /** * The maximum number of lines to store to prevent very verbose test cases causing memory problems */ protected static final int MAX_BUFFER_SIZE = 2000; private static boolean bufferSizeWarningPrinted = false; private static Reporter reporter; private static boolean usingDatabase = false; private static Connection outputDatabaseConnection; private static long sessionID = -1; // hide constructor to stop instantiation private ReportManager() { } /** * Set the reporter for this ReportManager. * * @param rep * The Reporter to set. */ public static void setReporter(Reporter rep) { reporter = rep; } /** * Should be called before a test case is run. * * @param testCase * The testcase to be run. * @param dbre * The database that testCase will run on. */ public static void startTestCase(EnsTestCase testCase, DatabaseRegistryEntry dbre) { if (reporter != null) { reporter.startTestCase(testCase, dbre); } } /** * Should be called immediately after a test case has run. * * @param testCase * The testcase that was run. * @param result * The result of the test case. * @param dbre * The database which the test case was run on. */ public static void finishTestCase(EnsTestCase testCase, boolean result, DatabaseRegistryEntry dbre) { if (reporter != null) { reporter.finishTestCase(testCase, result, dbre); } } /** * Add a test case report. * * @param report * The ReportLine to add. */ public static void add(ReportLine report) { if (usingDatabase) { checkAndAddToDatabase(report); return; } String testCaseName = report.getTestCaseName(); String databaseName = report.getDatabaseName(); ArrayList lines; // add to each hash if (testCaseName != null && testCaseName.length() > 0) { // create the lists if they're not there already if (reportsByTest.get(testCaseName) == null) { lines = new ArrayList(); lines.add(report); reportsByTest.put(testCaseName, lines); } else { // get the relevant list, update it, and re-add it lines = (ArrayList) reportsByTest.get(testCaseName); // prevent the buffer getting too big if (lines.size() > MAX_BUFFER_SIZE) { if (!bufferSizeWarningPrinted) { System.err.println("\n\nReportManager has reached its maximum buffer size (" + MAX_BUFFER_SIZE + " lines) - no more output will be stored\n"); bufferSizeWarningPrinted = true; } } else { // buffer small enough, add it lines.add(report); reportsByTest.put(testCaseName, lines); } } } else { logger.warning("Cannot add report with test case name not set"); } if (databaseName != null && databaseName.length() > 0) { // create the lists if they're not there already if (reportsByDatabase.get(databaseName) == null) { lines = new ArrayList(); lines.add(report); reportsByDatabase.put(databaseName, lines); } else { // get the relevant list, update it, and re-add it lines = (ArrayList) reportsByDatabase.get(databaseName); lines.add(report); reportsByDatabase.put(databaseName, lines); } } if (reporter != null) { reporter.message(report); } } // add /** * Convenience method for storing reports, intended to be easy to call from an EnsTestCase. * * @param testCase * The test case filing the report. * @param con * The database connection involved. * @param level * The level of this report. * @param message * The message to be reported. */ public static void report(EnsTestCase testCase, Connection con, int level, String message) { // this may be called when there is no DB connection String dbName = (con == null) ? "no_database" : DBUtils.getShortDatabaseName(con); add(new ReportLine(testCase, dbName, level, message, testCase.getTeamResponsible(), testCase.getSecondTeamResponsible())); } // report /** * Convenience method for storing reports, intended to be easy to call from an EnsTestCase. * * @param testCase * The test case filing the report. * @param dbName * The name of the database involved. * @param level * The level of this report. * @param message * The message to be reported. */ public static void report(EnsTestCase testCase, String dbName, int level, String message) { add(new ReportLine(testCase, dbName, level, message, testCase.getTeamResponsible(), testCase.getSecondTeamResponsible())); } // report /** * Store a ReportLine with a level of ReportLine.INFO. * * @param testCase * The test case filing the report. * @param con * The database connection involved. * @param message * The message to be reported. */ public static void problem(EnsTestCase testCase, Connection con, String message) { report(testCase, con, ReportLine.PROBLEM, message); } // problem /** * Store a ReportLine with a level of ReportLine.PROBLEM. * * @param testCase * The test case filing the report. * @param dbName * The name of the database involved. * @param message * The message to be reported. */ public static void problem(EnsTestCase testCase, String dbName, String message) { report(testCase, dbName, ReportLine.PROBLEM, message); } // problem /** * Store a ReportLine with a level of ReportLine.INFO. * * @param testCase * The test case filing the report. * @param con * The database connection involved. * @param message * The message to be reported. */ public static void info(EnsTestCase testCase, Connection con, String message) { report(testCase, con, ReportLine.INFO, message); } // info /** * Store a ReportLine with a level of ReportLine.INFO. * * @param testCase * The test case filing the report. * @param dbName * The name of the database involved. * @param message * The message to be reported. */ public static void info(EnsTestCase testCase, String dbName, String message) { report(testCase, dbName, ReportLine.INFO, message); } // info /** * Store a ReportLine with a level of ReportLine.SUMMARY. * * @param testCase * The test case filing the report. * @param con * The database connection involved. * @param message * The message to be reported. */ public static void warning(EnsTestCase testCase, Connection con, String message) { report(testCase, con, ReportLine.WARNING, message); } // summary /** * Store a ReportLine with a level of ReportLine.SUMMARY. * * @param testCase * The test case filing the report. * @param dbName * The name of the database involved. * @param message * The message to be reported. */ public static void warning(EnsTestCase testCase, String dbName, String message) { report(testCase, dbName, ReportLine.WARNING, message); } // summary /** * Store a ReportLine with a level of ReportLine.CORRECT. * * @param testCase * The test case filing the report. * @param con * The database connection involved. * @param message * The message to be reported. */ public static void correct(EnsTestCase testCase, Connection con, String message) { report(testCase, con, ReportLine.CORRECT, message); } // summary /** * Store a ReportLine with a level of ReportLine.CORRECT. * * @param testCase * The test case filing the report. * @param dbName * The name of the database involved. * @param message * The message to be reported. */ public static void correct(EnsTestCase testCase, String dbName, String message) { report(testCase, dbName, ReportLine.CORRECT, message); } // summary /** * Get a HashMap of all the reports, keyed on test case name. * * @return The HashMap of all the reports, keyed on test case name. */ public static Map getAllReportsByTestCase() { return reportsByTest; } // getAllReportsByTestCase /** * Get a HashMap of all the reports, keyed on test case name. * * @param level * The ReportLine level (e.g. PROBLEM) to filter on. * @return The HashMap of all the reports, keyed on test case name. */ public static Map getAllReportsByTestCase(int level) { return filterMap(reportsByTest, level); } // getAllReportsByTestCase /** * Get a HashMap of all the reports, keyed on database name. * * @return The HashMap of all the reports, keyed on database name. */ public static Map getAllReportsByDatabase() { return reportsByDatabase; } // getReportsByDatabase /** * Get a HashMap of all the reports, keyed on test case name. * * @param level * The ReportLine level (e.g. PROBLEM) to filter on. * @return The HashMap of all the reports, keyed on test case name. */ public static Map getAllReportsByDatabase(int level) { return filterMap(reportsByDatabase, level); } // getAllReportsByTestCase /** * Get a list of all the reports corresponding to a particular test case. * * @return A List of the results (as a list) corresponding to test. * @param testCaseName * The test case to filter by. * @param level * The minimum level of report to include, e.g. ReportLine.INFO */ public static List getReportsByTestCase(String testCaseName, int level) { List allReports = (List) reportsByTest.get(testCaseName); return filterList(allReports, level); } // getReportsByTestCase /** * Get a list of all the reports corresponding to a particular database. * * @param databaseName * The database to report on. * @param level * The minimum level of report to include, e.g. ReportLine.INFO * @return A List of the ReportLines corresponding to database. */ public static List getReportsByDatabase(String databaseName, int level) { return filterList((List) reportsByDatabase.get(databaseName), level); } // getReportsByDatabase /** * Filter a list of ReportLines so that only certain entries are returned. * * @param list * The list to filter. * @param level * All reports with a priority above this level will be returned. * @return A list of the ReportLines that have a level >= that specified. */ public static List filterList(List list, int level) { ArrayList result = new ArrayList(); if (list != null) { Iterator it = list.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); if (line.getLevel() >= level) { result.add(line); } } } return result; } // filterList /** * Filter a HashMap of lists of ReportLines so that only certain entries are returned. * * @param map * The list to filter. * @param level * All reports with a priority above this level will be returned. * @return A HashMap with the same keys as map, but with the lists filtered by level. */ public static Map filterMap(Map map, int level) { HashMap result = new HashMap(); Set keySet = map.keySet(); Iterator it = keySet.iterator(); while (it.hasNext()) { String key = (String) it.next(); List list = (List) map.get(key); result.put(key, filterList(list, level)); } return result; } // filterList /** * Count how many tests passed and failed for a particular database. A test is considered to have passed if there are no reports * of level ReportLine.PROBLEM. * * @param database * The database to check. * @return An array giving the number of passes and then fails for this database. */ public static int[] countPassesAndFailsDatabase(String database) { int[] result = new int[2]; List testsRun = new ArrayList(); // get all of them to build a list of the tests that were run List reports = getReportsByDatabase(database, ReportLine.ALL); Iterator it = reports.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); String test = line.getTestCaseName(); if (!testsRun.contains(test)) { testsRun.add(test); } } // count those that failed List testsFailed = new ArrayList(); reports = getReportsByDatabase(database, ReportLine.PROBLEM); it = reports.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); String test = line.getTestCaseName(); if (!testsFailed.contains(test)) { testsFailed.add(test); } } result[1] = testsFailed.size(); result[0] = testsRun.size() - testsFailed.size(); // if it didn't // fail, it passed return result; } /** * Count how many databases passed a particular test. A test is considered to have passed if there are no reports of level * ReportLine.PROBLEM. * * @param test * The test to check. * @return An array giving the number of databases that passed [0] and failed [1] this test. */ public static int[] countPassesAndFailsTest(String test) { int[] result = new int[2]; List allDBs = new ArrayList(); // get all of them to build a list of the tests that were run List reports = getReportsByTestCase(test, ReportLine.ALL); Iterator it = reports.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); String database = line.getDatabaseName(); if (!allDBs.contains(database)) { allDBs.add(database); } } // count those that failed List dbsFailed = new ArrayList(); reports = getReportsByTestCase(test, ReportLine.PROBLEM); it = reports.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); String database = line.getDatabaseName(); if (!dbsFailed.contains(database)) { dbsFailed.add(database); } } result[1] = dbsFailed.size(); result[0] = allDBs.size() - dbsFailed.size(); // if it didn't fail, it // passed return result; } /** * Count how many tests passed and failed. A test is considered to have passed if there are no reports of level * ReportLine.PROBLEM. * * @return An array giving the number of passes and then fails. */ public static int[] countPassesAndFailsAll() { int[] result = new int[2]; Map allByDB = getAllReportsByDatabase(); Set dbs = allByDB.keySet(); Iterator it = dbs.iterator(); while (it.hasNext()) { String database = (String) it.next(); int[] dbResult = countPassesAndFailsDatabase(database); result[0] += dbResult[0]; result[1] += dbResult[1]; } return result; } /** * Check if all the a particular database passed a particular test. * * @param test * The test to check. * @param database * The database to check. * @return true if database passed test (i.e. had no problems). */ public static boolean databasePassed(String test, String database) { List reports = getReportsByTestCase(test, ReportLine.PROBLEM); Iterator it = reports.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); if (database.equals(line.getDatabaseName())) { return false; } } return true; } /** * Check if all the databases passed a particular test. * * @param test * The test to check. * @return true if none of the databases failed this test (i.e. had no problems) */ public static boolean allDatabasesPassed(String test) { List reports = getReportsByTestCase(test, ReportLine.PROBLEM); if (reports.size() > 0) { return false; } return true; } /** * Get a list of all the reports corresponding to a particular database and test case. * * @return A List of the results (as a list) corresponding to test and database. * @param test * The test case to filter by. * @param database * The database. */ public static List getReports(String test, String database) { List result = new ArrayList(); List allReports = (List) reportsByTest.get(test); Iterator it = allReports.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); if (database.equals(line.getDatabaseName())) { result.add(line); } } return result; } // getReports /** * Check if reports for a given database have been propagated for the release * * @return boolean true if propagation has been run, false else * * @param database * The database. */ public static boolean hasPropagated(DatabaseRegistryEntry database) { boolean result = true; String sql = "SELECT count(*) FROM propagated WHERE database_name = '" + database.getName() + "'"; int rows = DBUtils.getRowCount(outputDatabaseConnection, sql); if (rows == 0) { result = false; } return result; } // getReports /** * Flag to state whether a database is being used as the output destination. */ public static boolean usingDatabase() { return usingDatabase; } /** * Set up connection to a database for output. Sets usingDatabase to true. */ public static void connectToOutputDatabase() { logger.info("Connecting to " + System.getProperty("output.databaseURL") + System.getProperty("output.database") + " as " + System.getProperty("output.user") + " password " + System.getProperty("output.password")); try { outputDatabaseConnection = DBUtils.openConnection( System.getProperty("output.driver"), System.getProperty("output.databaseURL") + System.getProperty("output.database"), System.getProperty("output.user"), System.getProperty("output.password") ); } catch(SQLException e) { throw new RuntimeException(e); } usingDatabase = true; } /** * Create a new entry in the session table. Store the ID of the created session in sessionID. */ public static void createDatabaseSession() { // build comma-separated list of hosts StringBuffer buf = new StringBuffer(); Iterator<DatabaseServer> it = DBUtils.getMainDatabaseServers().iterator(); while (it.hasNext()) { DatabaseServer server = (DatabaseServer) it.next(); buf.append(String.format("%s:%s", server.getHost(), server.getPort())); if (it.hasNext()) { buf.append(","); } } String hosts = buf.toString(); String outputDatabases = Utils.listToString(Utils.getDatabasesAndGroups(), ","); String outputRelease = System.getProperty("output.release"); String sql = String.format("INSERT INTO session (host, config, db_release, start_time) VALUES (" + "\"" + hosts.toString() + "\", " + "\"" + outputDatabases + "\", " + "\"" + outputRelease + "\", " + "NOW())"); try { Statement stmt = outputDatabaseConnection.createStatement(); stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()) { sessionID = rs.getLong(1); logger.fine("Created new session with ID " + sessionID); } stmt.close(); } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } if (sessionID == -1) { logger.severe("Could not get new session ID"); logger.severe(sql); } } /** * End a database session. Write the end time into the database. */ public static void endDatabaseSession() { String sql = "UPDATE session SET end_time=NOW() WHERE session_id=" + sessionID; try { Statement stmt = outputDatabaseConnection.createStatement(); stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); stmt.close(); } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } } /** * Delete all previous data. */ public static void deletePrevious() { String[] tables = { "session", "report", "annotation" }; for (int i = 0; i < tables.length; i++) { String sql = "DELETE FROM " + tables[i]; try { Statement stmt = outputDatabaseConnection.createStatement(); stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); stmt.close(); } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } } } /** * Update a report in the database. Two possible actions: 1. If the report already exists and hasn't changed, just update it. 2. * If the report is new, add a new record. */ public static void checkAndAddToDatabase(ReportLine report) { long reportID = reportExistsInDatabase(report); if (reportID > -1) { updateReportInDatabase(report, reportID); } else { addReportToDatabase(report); } } /** * Check if a report exists (i.e. same database, testcase, result and text). * * @return -1 if the report does not exist, report_id if it does. */ public static long reportExistsInDatabase(ReportLine report) { String sql = "SELECT report_id FROM report WHERE database_name=? AND testcase=? AND result=? AND BINARY(text)=BINARY(?)"; long reportID = -1; try { PreparedStatement stmt = outputDatabaseConnection.prepareStatement(sql); stmt.setString(1, report.getDatabaseName()); stmt.setString(2, report.getShortTestCaseName()); stmt.setString(3, report.getLevelAsString()); stmt.setString(4, report.getMessage()); ResultSet rs = stmt.executeQuery(); if (rs != null) { if (rs.first()) { reportID = rs.getLong(1); } else { reportID = -1; // probably signifies an empty ResultSet } } rs.close(); stmt.close(); } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } if (reportID > -1) { logger.finest("Report already exists (ID " + reportID + "): " + report.getDatabaseName() + " " + report.getTestCaseName() + " " + report.getLevelAsString() + " " + report.getMessage()); } else { logger.finest("Report does not already exist: " + report.getDatabaseName() + " " + report.getTestCaseName() + " " + report.getLevelAsString() + " " + report.getMessage()); } return reportID; } /** * Store a report in the database. */ public static void addReportToDatabase(ReportLine report) { if (outputDatabaseConnection == null) { logger.severe("No connection to output database!"); return; } logger.fine("Adding report for: " + report.getDatabaseName() + " " + report.getTestCaseName() + " " + report.getLevelAsString() + " " + report.getMessage()); String sql = "INSERT INTO report (first_session_id, last_session_id, database_name, species, database_type, testcase, result, text, timestamp, team_responsible, created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, NOW())"; try { PreparedStatement stmt = outputDatabaseConnection.prepareStatement(sql); stmt.setLong(1, sessionID); stmt.setLong(2, sessionID); stmt.setString(3, report.getDatabaseName()); // EG Store species name and db type from explicit report line, not from database stmt.setString(4, report.getSpeciesName()); stmt.setString(5, report.getType().toString()); stmt.setString(6, report.getShortTestCaseName()); stmt.setString(7, report.getLevelAsString()); stmt.setString(8, report.getMessage()); stmt.setString(9, report.getPrintableTeamResponsibleString()); stmt.executeUpdate(); stmt.close(); } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } } /** * Update the last_session_id of a report in the database. */ public static void updateReportInDatabase(ReportLine report, long reportID) { if (outputDatabaseConnection == null) { logger.severe("No connection to output database!"); return; } logger.fine("Updating report for: " + report.getDatabaseName() + " " + report.getTestCaseName() + " " + report.getLevelAsString() + " " + report.getMessage() + ", new last_session_id=" + sessionID); String sql = "UPDATE report SET last_session_id=?, timestamp=NOW() WHERE report_id=?"; try { PreparedStatement stmt = outputDatabaseConnection.prepareStatement(sql); stmt.setLong(1, sessionID); stmt.setLong(2, reportID); stmt.executeUpdate(); stmt.close(); } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } } public static long getSessionID() { return sessionID; } public static void setSessionID(long sessionID) { ReportManager.sessionID = sessionID; } } // ReportManager
package org.eclipse.smarthome.core.thing; public enum ThingStatusDetail { NONE, HANDLER_MISSING_ERROR, HANDLER_REGISTERING_ERROR, HANDLER_INITIALIZING_ERROR, HANDLER_CONFIGURATION_PENDING, CONFIGURATION_PENDING, COMMUNICATION_ERROR, CONFIGURATION_ERROR, BRIDGE_OFFLINE, FIRMWARE_UPDATING, DUTY_CYCLE, BRIDGE_UNINITIALIZED, /** * Device has been removed. Used for example when the device has been removed from its bridge and * the thing handler should be removed. */ GONE; public static final UninitializedStatus UNINITIALIZED = new UninitializedStatus(); public static final NoneOnlyStatus INITIALIZING = new NoneOnlyStatus(); public static final NoneOnlyStatus UNKNOWN = new NoneOnlyStatus(); public static final OnlineStatus ONLINE = new OnlineStatus(); public static final OfflineStatus OFFLINE = new OfflineStatus(); public static final NoneOnlyStatus REMOVING = new NoneOnlyStatus(); public static final NoneOnlyStatus REMOVED = new NoneOnlyStatus(); public static final class NoneOnlyStatus { private NoneOnlyStatus() { } public ThingStatusDetail NONE = ThingStatusDetail.NONE; } public static final class UninitializedStatus { private UninitializedStatus() { } public ThingStatusDetail NONE = ThingStatusDetail.NONE; public ThingStatusDetail HANDLER_MISSING_ERROR = ThingStatusDetail.HANDLER_MISSING_ERROR; public ThingStatusDetail HANDLER_REGISTERING_ERROR = ThingStatusDetail.HANDLER_REGISTERING_ERROR; public ThingStatusDetail HANDLER_CONFIGURATION_PENDING = ThingStatusDetail.HANDLER_CONFIGURATION_PENDING; public ThingStatusDetail HANDLER_INITIALIZING_ERROR = ThingStatusDetail.HANDLER_INITIALIZING_ERROR; public ThingStatusDetail BRIDGE_UNINITIALIZED = ThingStatusDetail.BRIDGE_UNINITIALIZED; }; public static final class OnlineStatus { private OnlineStatus() { } public ThingStatusDetail NONE = ThingStatusDetail.NONE; public ThingStatusDetail CONFIGURATION_PENDING = ThingStatusDetail.CONFIGURATION_PENDING; }; public static final class OfflineStatus { private OfflineStatus() { } public ThingStatusDetail NONE = ThingStatusDetail.NONE; public ThingStatusDetail COMMUNICATION_ERROR = ThingStatusDetail.COMMUNICATION_ERROR; public ThingStatusDetail CONFIGURATION_ERROR = ThingStatusDetail.CONFIGURATION_ERROR; public ThingStatusDetail BRIDGE_OFFLINE = ThingStatusDetail.BRIDGE_OFFLINE; public ThingStatusDetail FIRMWARE_UPDATING = ThingStatusDetail.FIRMWARE_UPDATING; public ThingStatusDetail DUTY_CYCLE = ThingStatusDetail.DUTY_CYCLE; public ThingStatusDetail GONE = ThingStatusDetail.GONE; }; }
/* * $Id: GoslingCrawlerImpl.java,v 1.21 2003-05-01 01:42:55 troberts Exp $ */ package org.lockss.crawler; import java.io.*; import java.util.*; import java.net.URL; import java.net.MalformedURLException; import org.lockss.daemon.*; import org.lockss.util.*; import org.lockss.plugin.*; /** * The crawler. * * @author Thomas S. Robertson * @version 0.0 */ public class GoslingCrawlerImpl implements Crawler { /** * TODO * 1) write state to harddrive using whatever system we come up for for the * rest of LOCKSS * 2) check deadline and die if we run too long */ private static final String IMGTAG = "img"; private static final String ATAG = "a"; private static final String FRAMETAG = "frame"; private static final String LINKTAG = "link"; private static final String SCRIPTTAG = "script"; private static final String SCRIPTTAGEND = "/script"; private static final String BODYTAG = "body"; private static final String TABLETAG = "table"; private static final String TDTAG = "tc"; private static final String ASRC = "href"; private static final String SRC = "src"; private static final String BACKGROUNDSRC = "background"; private static Logger logger = Logger.getLogger("GoslingCrawlerImpl"); private ArchivalUnit au; private List startUrls; private boolean followLinks; private long startTime = -1; private long endTime = -1; private int numUrlsFetched = 0; private int numUrlsParsed = 0; /** * Construct a crawl object; does NOT start the crawl * @param au {@link ArchivalUnit} that this crawl will happen on * @param urls List of Strings representing the starting urls for this crawl * @param followLinks whether or not to extract and follow links */ public GoslingCrawlerImpl(ArchivalUnit au, List startUrls, boolean followLinks) { if (au == null) { throw new IllegalArgumentException("Called with a null ArchivalUnit"); } else if (startUrls == null) { throw new IllegalArgumentException("Called with a null start url list"); } this.au = au; this.startUrls = startUrls; this.followLinks = followLinks; } public long getNumFetched() { return numUrlsFetched; } public long getNumParsed() { return numUrlsParsed; } public long getStartTime() { return startTime; } public long getEndTime() { return endTime; } public ArchivalUnit getAU() { return au; } /** * Main method of the crawler; it loops through crawling and caching * urls. * * @param deadline when to terminate by */ public boolean doCrawl(Deadline deadline) { if (deadline == null) { throw new IllegalArgumentException("Called with a null Deadline"); } boolean wasError = false; logger.info("Beginning crawl of "+au); startTime = TimeBase.nowMs(); CachedUrlSet cus = au.getAUCachedUrlSet(); Set parsedPages = new HashSet(); Set extractedUrls = new HashSet(); Iterator it = startUrls.iterator(); while (it.hasNext() && !deadline.expired()) { String url = (String)it.next(); //catch and warn if there's a url in the start urls //that we shouldn't cache if (au.shouldBeCached(url)) { if (!doCrawlLoop(url, extractedUrls, parsedPages, cus, true)) { wasError = true; } } else { logger.warning("Called with a starting url we aren't suppose to " +"cache: "+url); } } while (!extractedUrls.isEmpty() && !deadline.expired()) { String url = (String)extractedUrls.iterator().next(); extractedUrls.remove(url); if (!doCrawlLoop(url, extractedUrls, parsedPages, cus, false)) { wasError = true; } } logger.info("Finished crawl of "+au); endTime = TimeBase.nowMs(); return !wasError; } /** * This is the meat of the crawl. Fetches the specified url and adds * any urls it harvests from it to extractedUrls * @param url url to fetch * @param extractedUrls set to write harvested urls to * @param parsedPages set containing all the pages that have already * been parsed (to make sure we don't loop) * @param cus cached url set that the url belongs to * @return true if there were no errors */ protected boolean doCrawlLoop(String url, Set extractedUrls, Set parsedPages, CachedUrlSet cus, boolean overWrite) { boolean wasError = false; logger.debug("Dequeued url from list: "+url); UrlCacher uc = cus.makeUrlCacher(url); // don't cache if already cached, unless overwriting if (overWrite || !uc.getCachedUrl().hasContent()) { try { logger.debug("caching "+uc); uc.cache(); //IOException if there is a caching problem numUrlsFetched++; } catch (FileNotFoundException e) { logger.warning(uc+" not found on publisher's site"); } catch (IOException ioe) { //XXX handle this better. Requeue? logger.error("Problem caching "+uc+". Ignoring", ioe); wasError = true; } au.pause(); //XXX make sure we throw InterruptedExceptions } else { if (!parsedPages.contains(uc.getUrl())) { logger.debug2(uc+" exists, not caching"); } } try { if (followLinks && !parsedPages.contains(uc.getUrl())) { CachedUrl cu = uc.getCachedUrl(); //XXX quick fix; if statement should be removed when we rework //handling of error condition if (cu.hasContent()) { addUrlsToSet(cu, extractedUrls, parsedPages);//IOException if the CU can't be read parsedPages.add(uc.getUrl()); numUrlsParsed++; } } } catch (IOException ioe) { //XXX handle this better. Requeue? logger.error("Problem parsing "+uc+". Ignoring", ioe); wasError = true; } logger.debug("Removing from list: "+uc.getUrl()); return !wasError; } /** * Method which will parse the html file represented by cu and add all * urls in it which should be cached to set * * @param cu object representing a html file in the local file system * @param set set to which all the urs in cu should be added * @param urlsToIgnore urls which should not be added to set * @throws IOException */ protected void addUrlsToSet(CachedUrl cu, Set set, Set urlsToIgnore) throws IOException { if (shouldExtractLinksFromCachedUrl(cu)) { String cuStr = cu.getUrl(); if (cuStr == null) { logger.error("CachedUrl has null getUrl() value: "+cu); return; } InputStream is = cu.openForReading(); Reader reader = new InputStreamReader(is); //should do this elsewhere URL srcUrl = new URL(cuStr); logger.debug("Extracting urls from srcUrl"); String nextUrl = null; while ((nextUrl = extractNextLink(reader, srcUrl)) != null) { logger.debug("Extracted "+nextUrl); //should check if this is something we should cache first if (!set.contains(nextUrl) && !urlsToIgnore.contains(nextUrl) && au.shouldBeCached(nextUrl)) { set.add(nextUrl); } } } } /** * Determine if this is a CachedUrl that we can parse for new urls; currently * this is just done by verifying that the "content-type" property exists * and equals "text/html" * * @param cu CachedUrl representing the web page we may parse * @return true if cu has "content-type" set to "text/html", false otherwise */ protected static boolean shouldExtractLinksFromCachedUrl(CachedUrl cu) { boolean returnVal = false; Properties props = cu.getProperties(); if (props != null) { String contentType = props.getProperty("content-type"); if (contentType != null) { //XXX check if the string starts with this returnVal = contentType.toLowerCase().startsWith("text/html"); } } if (returnVal) { logger.debug("I should try to extract links from "+cu); } else { logger.debug("I shouldn't try to extract links from "+cu); } return returnVal; } /** * Read through the reader stream, extract and return the next url found * * @param reader Reader object to extract the link from * @param srcUrl URL object representing the page we are looking at * (for resolving relative links) * @return String representing the next url in reader * @throws IOException * @throws MalformedURLException */ protected static String extractNextLink(Reader reader, URL srcUrl) throws IOException, MalformedURLException { if (reader == null) { return null; } boolean inscript = false; //FIXME or I will break when we look at scripts String nextLink = null; int c = 0; StringBuffer lineBuf = new StringBuffer(); while(nextLink == null && c >=0) { //skip to the next tag do { c = reader.read(); } while (c >= 0 && c != '<'); if (c == '<') { int pos = 0; c = reader.read(); while (c >= 0 && c != '>') { if(pos==2 && c=='-' && lineBuf.charAt(0)=='!' && lineBuf.charAt(1)=='-') { // we're in a HTML comment pos = 0; int lc1 = 0; int lc2 = 0; while((c = reader.read()) >= 0 && (c != '>' || lc1 != '-' || lc2 != '-')) { lc1 = lc2; lc2 = c; } break; } lineBuf.append((char)c); pos++; c = reader.read(); } if (inscript) { //FIXME when you deal with the script problems // if(lookingAt(lineBuf, 0, pos, scripttagend)) { inscript = false; } else if (lineBuf.length() >= 5) { //see if the lineBuf has a link tag nextLink = parseLink(lineBuf, srcUrl); } lineBuf = new StringBuffer(); } } return nextLink; } protected static String parseLink(StringBuffer link, URL srcUrl) throws MalformedURLException { String returnStr = null; switch (link.charAt(0)) { case 'a': case 'A': if (StringUtil.getIndexIgnoringCase(link.toString(), ATAG+" ") == 0) { returnStr = getAttributeValue(ASRC, link.toString()); } break; case 'f': //<frame src=frame1.html> case 'F': if (StringUtil.getIndexIgnoringCase(link.toString(), FRAMETAG+" ") == 0) { returnStr = getAttributeValue(SRC, link.toString()); } break; case 'i': //<img src=image.gif> case 'I': if (StringUtil.getIndexIgnoringCase(link.toString(), IMGTAG+" ") == 0) { returnStr = getAttributeValue(SRC, link.toString()); } break; case 'l': //<link href=blah.css> case 'L': if (StringUtil.getIndexIgnoringCase(link.toString(), LINKTAG+" ") == 0) { returnStr = getAttributeValue(ASRC, link.toString()); } break; case 'b': //<body backgroung=background.gif> case 'B': if (StringUtil.getIndexIgnoringCase(link.toString(), BODYTAG+" ") == 0) { returnStr = getAttributeValue(BACKGROUNDSRC, link.toString()); } break; case 's': //<script src=blah.js> case 'S': if (StringUtil.getIndexIgnoringCase(link.toString(), SCRIPTTAG+" ") == 0) { returnStr = getAttributeValue(SRC, link.toString()); } break; case 't': //<tc background=back.gif> or <table background=back.gif> case 'T': if (StringUtil.getIndexIgnoringCase(link.toString(), TABLETAG+" ") == 0 || StringUtil.getIndexIgnoringCase(link.toString(), TDTAG+" ") == 0) { returnStr = getAttributeValue(BACKGROUNDSRC, link.toString()); } break; default: return null; } if (returnStr != null) { returnStr = StringUtil.trimAfterChars(returnStr, " logger.debug("Generating url from: "+srcUrl+" and "+returnStr); URL retUrl = new URL(srcUrl, returnStr); returnStr = retUrl.toString(); logger.debug("Parsed: "+returnStr); return returnStr; } return null; } private static String getAttributeValue(String attribute, String src) { logger.debug("looking for "+attribute+" in "+src); StringTokenizer st = new StringTokenizer(src, " =\"", true); String lastToken = null; while (st.hasMoreTokens()) { String token = st.nextToken(); if (!token.equals("=")) { if (!token.equals(" ") && !token.equals("\"")) { lastToken = token; } } else { if (attribute.equalsIgnoreCase(lastToken)) while (st.hasMoreTokens()) { token = st.nextToken(); if (!token.equals(" ") && !token.equals("\"")) { return token; } } } } return null; } }
package controllers; import java.util.List; import java.util.UUID; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import play.libs.Json; import play.mvc.BodyParser; import play.mvc.Controller; import play.mvc.Result; import play.mvc.Security; import play.libs.F.Function; import play.libs.F.Function0; import play.libs.F.Option; import play.libs.F.Promise; import play.libs.F.Tuple; import models.nodes.CombinationGroup; import models.nodes.Feature; import models.nodes.OutputString; import models.nodes.Part; import models.nodes.Value; import models.nodes.LHS; import models.nodes.Rule; import views.html.input; import views.html.output; import views.html.rules; import views.html.rule; public class Rules extends Controller { @Security.Authenticated(Secured.class) public static Promise<Result> rules() { Promise<List<Rule>> ruleList = Rule.all(); return ruleList.map( new Function<List<Rule>, Result>() { public Result apply(List<Rule> ruleList) { return ok(rules.render(ruleList)); } }); } @Security.Authenticated(Secured.class) public static Result rule(String name) { return ok(rule.render("Hi! You are looking at rule " + name + ".")); } @Security.Authenticated(Secured.class) public static Promise<Result> input(final String name) { Promise<List<Feature>> globalFeatureList = Feature.all(); Promise<Rule> rule = new Rule(name).get(); Promise<Tuple<List<Feature>, Rule>> results = globalFeatureList .zip(rule); return results.map( new Function<Tuple<List<Feature>, Rule>, Result>() { public Result apply(Tuple<List<Feature>, Rule> results) { return ok(input.render(results._1, results._2)); } }); } @Security.Authenticated(Secured.class) public static Promise<Result> output(final String name) { Promise<List<Part>> globalPartsList = Part.all(); Promise<Rule> rule = new Rule(name).get(); Promise<Tuple<List<Part>, Rule>> results = globalPartsList .zip(rule); return results.map( new Function<Tuple<List<Part>, Rule>, Result>() { public Result apply(Tuple<List<Part>, Rule> results) { return ok(output.render(results._1, results._2)); } }); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> create() { JsonNode json = request().body().asJson(); final String name = json.findPath("name").textValue(); final String description = json.findPath("description").textValue(); Promise<Boolean> created = new Rule(name, description).create(); return created.map( new Function<Boolean, Result>() { ObjectNode result = Json.newObject(); public Result apply(Boolean created) { if (created) { result.put("id", name); result.put("name", name); result.put("description", description); return ok(result); } return badRequest(result); } }); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> updateName(final String name) { JsonNode json = request().body().asJson(); final String newName = json.findPath("name").textValue(); Promise<Boolean> nameAlreadyTaken = new Rule(newName).exists(); return nameAlreadyTaken.flatMap( new Function<Boolean, Promise<Result>>() { ObjectNode result = Json.newObject(); public Promise<Result> apply(Boolean nameAlreadyTaken) { if (nameAlreadyTaken) { return Promise.promise( new Function0<Result>() { public Result apply() { result.put( "message", "Name already taken."); return badRequest(result); } }); } else { Promise<Boolean> nameUpdated = new Rule(name) .updateName(newName); return nameUpdated.map( new Function<Boolean, Result>() { public Result apply(Boolean updated) { if (updated) { result.put("id", newName); result.put( "message", "Name successfully updated."); return ok(result); } result.put( "message", "Name not updated."); return badRequest(result); } }); } } }); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> updateDescription(String name) { JsonNode json = request().body().asJson(); final String newDescription = json.findPath("description") .textValue(); Promise<Boolean> descriptionUpdated = new Rule(name) .updateDescription(newDescription); return descriptionUpdated.map( new Function<Boolean, Result>() { ObjectNode result = Json.newObject(); public Result apply(Boolean updated) { if (updated) { result.put("message", "Description successfully updated."); return ok(result); } result.put("message", "Description not updated."); return badRequest(result); } }); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> addFeature(String name) { JsonNode json = request().body().asJson(); Rule rule = new Rule(name); final LHS lhs = new LHS(rule); final UUID uuid = UUID.fromString(json.findPath("uuid").textValue()); final Feature feature = Feature.of( json.findPath("name").textValue(), json.findPath("type").textValue()); Promise<Boolean> added = lhs.add(feature, uuid); return added.flatMap( new Function<Boolean, Promise<Result>>() { ObjectNode result = Json.newObject(); public Promise<Result> apply(Boolean added) { if (added) { Promise<JsonNode> value = lhs .getValue(feature, uuid); return value.map( new Function<JsonNode, Result>() { public Result apply(JsonNode value) { result.put("value", value); result.put("message", "Feature successfully added."); return ok(result); } }); } result.put("message", "Feature not added."); return Promise.promise( new Function0<Result>() { public Result apply() { return badRequest(result); } }); } }); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> updateFeatureValue(String name) { JsonNode json = request().body().asJson(); Rule rule = new Rule(name); LHS lhs = new LHS(rule); final UUID uuid = UUID.fromString(json.findPath("uuid").textValue()); final Feature feature = new Feature(json.findPath("name").textValue()); Value newValue = new Value(json.findPath("newValue").textValue()); Promise<Boolean> updated = lhs.update(feature, uuid, newValue); return updated.map( new Function<Boolean, Result>() { ObjectNode result = Json.newObject(); public Result apply(Boolean updated) { if (updated) { result.put("message", "Feature successfully updated."); return ok(result); } result.put("message", "Feature not updated."); return badRequest(result); } }); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> removeFeature(String name) { JsonNode json = request().body().asJson(); Rule rule = new Rule(name); LHS lhs = new LHS(rule); final UUID uuid = UUID.fromString(json.findPath("uuid").textValue()); final Feature feature = Feature.of(json.findPath("name").textValue(), json.findPath("type").textValue()); Promise<Boolean> removed = lhs.remove(feature, uuid); return removed.map( new Function<Boolean, Result>() { ObjectNode result = Json.newObject(); public Result apply(Boolean removed) { if (removed) { result.put("message", "Feature successfully removed."); return ok(result); } result.put("message", "Feature not removed."); return badRequest(result); } }); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> addString(String name, String groupID) { final ObjectNode result = Json.newObject(); final CombinationGroup group = CombinationGroup.of(groupID); JsonNode json = request().body().asJson(); final String content = json.findPath("content").textValue(); final OutputString string = OutputString.of(content); Promise<UUID> uuid = string.getUUID(); Promise<Boolean> added = uuid.flatMap( new Function<UUID, Promise<Boolean>>() { public Promise<Boolean> apply(UUID uuid) { result.put("id", uuid.toString()); string.jsonProperties.put("uuid", uuid.toString()); return group.addString(string); } }); return added.map(new ResultFunction("String successfully added.", "String not added", result)); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> updateString( String name, String groupID, String stringID) { final ObjectNode result = Json.newObject(); OutputString oldString = OutputString.of(UUID.fromString(stringID)); final CombinationGroup group = CombinationGroup.of(groupID); Promise<Boolean> removed = group.removeString(oldString); Promise<Boolean> added = removed.flatMap( new Function<Boolean, Promise<Boolean>>() { public Promise<Boolean> apply(Boolean removed) { if (removed) { JsonNode json = request().body().asJson(); final String content = json .findPath("content").textValue(); final OutputString newString = OutputString.of(content); Promise<UUID> uuid = newString.getUUID(); Promise<Boolean> added = uuid.flatMap( new Function<UUID, Promise<Boolean>>() { public Promise<Boolean> apply(UUID uuid) { result.put("id", uuid.toString()); newString.jsonProperties .put("uuid", uuid.toString()); return group.addString(newString); } }); return added; } return Promise.pure(false); } }); return added.map(new ResultFunction("String successfully updated.", "String not updated.", result)); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> removeString( String name, String groupID, String stringID) { OutputString string = OutputString.of(UUID.fromString(stringID)); Promise<Boolean> removed = CombinationGroup.of(groupID) .removeString(string); return removed.map(new ResultFunction("String successfully removed.", "String not removed.")); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> addGroup(String name) { final ObjectNode result = Json.newObject(); JsonNode json = request().body().asJson(); final UUID uuid = UUID.randomUUID(); result.put("id", uuid.toString()); int position = json.findPath("position").intValue(); CombinationGroup group = new CombinationGroup(uuid, position); Promise<Boolean> added = new Rule(name).addGroup(group); return added.map(new ResultFunction("Group successfully added.", "Group not added.", result)); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> removeGroup(String name, String groupID) { Promise<Boolean> removed = new Rule(name).removeGroup(groupID); return removed.map(new ResultFunction("Group successfully removed.", "Group not removed.")); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> addSlot(String name, String groupID) { Promise<Boolean> added = CombinationGroup.of(groupID).addSlot(); return added.map(new ResultFunction("Slot successfully added.", "Slot not added.")); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> removeSlot( String name, String groupID, String slotID) { Promise<Boolean> removed = CombinationGroup.of(groupID) .removeSlot(slotID); return removed.map(new ResultFunction("Slot successfully removed.", "Slot not removed.")); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> addPart( String name, String groupID, String slotID) { JsonNode json = request().body().asJson(); String part = json.findPath("part").textValue(); Promise<Boolean> added = CombinationGroup.of(groupID) .addPart(slotID, part); return added.map(new ResultFunction("Part successfully added.", "Part not added.")); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> updatePart( String name, String groupID, String slotID, String partID) { JsonNode json = request().body().asJson(); String content = json.findPath("content").textValue(); Promise<Boolean> updated = CombinationGroup.of(groupID) .updatePart(slotID, partID, content); return updated.map(new ResultFunction("Part successfully updated.", "Part not updated.")); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> removePart( String name, String groupID, String slotID, String partID) { Promise<Boolean> removed = CombinationGroup.of(groupID) .removePart(slotID, partID); return removed.map(new ResultFunction("Part successfully removed.", "Part not removed.")); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> addRef( String name, String groupID, String slotID) { JsonNode json = request().body().asJson(); String ruleName = json.findPath("ruleName").textValue(); Promise<Boolean> added = CombinationGroup.of(groupID) .addRef(slotID, ruleName); return added.map(new ResultFunction( "Cross-reference successfully added.", "Cross-reference not removed.")); } @Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> delete(String name) { Promise<Boolean> deleted = new Rule(name).delete(); return deleted.map( new Function<Boolean, Result>() { ObjectNode result = Json.newObject(); public Result apply(Boolean deleted) { if (deleted) { return ok(result); } return badRequest(result); } }); } private static class ResultFunction implements Function<Boolean, Result> { private String successMsg; private String errorMsg; private ObjectNode result; public ResultFunction(String successMsg, String errorMsg) { this.successMsg = successMsg; this.errorMsg = errorMsg; } public ResultFunction(String successMsg, String errorMsg, ObjectNode result) { this(successMsg, errorMsg); this.result = result; } public Result apply(Boolean actionSuccessful) { ObjectNode result = (this.result == null) ? Json.newObject() : this.result; if (actionSuccessful) { result.put("message", successMsg); return ok(result); } result.put("message", errorMsg); return badRequest(result); } } }
package org.myrobotlab.service; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.repo.ServiceType; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.interfaces.I2CControl; import org.slf4j.Logger; import com.pi4j.io.i2c.I2CBus; public class AdafruitINA219 extends Service { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(_TemplateService.class); transient I2CControl controller; public static final byte INA219_SHUNTVOLTAGE = 0x1; public static final byte INA219_BUSVOLTAGE = 0x2; // Default i2cAddress public int busAddress = I2CBus.BUS_1; public int deviceAddress = 0x40; public String type = "INA219"; public double busVoltage; public double shuntVoltage; public double current; public double power; // TODO Add methods to calibrate // Currently only supports setting the shunt resistance to a different // value than the default, in case it has been exchanged to measure // a different range of current public double shuntResistance = 0.1; // expressed in Ohms public int scaleRange = 32; // 32V = bus full-scale range public int pga = 8; // 320 mV = shunt full-scale range public static void main(String[] args) { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.INFO); try { //AdafruitINA219 adafruitINA219 = (AdafruitINA219) Runtime.start("AdafruitINA219", "AdafruitINA219"); //Runtime.start("gui", "GUIService"); double shuntVoltage; byte[] readbuffer = {(byte)0xE0,(byte)0xC0}; // pga = 8 // shuntVoltage = (double)(((short)(readbuffer[0])<<8) + ((short)readbuffer[1] & 0xff)) * 0.00001; // pga = 4 shuntVoltage = (double)(((short)(readbuffer[0])<<8) + ((short)readbuffer[1] & 0xff)) * 0.00001; // pga = 2 shuntVoltage = (double)(((short)(readbuffer[0])<<8) + ((short)readbuffer[1] & 0xff)) * 0.00001; log.info(String.format("shuntVoltage %s", shuntVoltage)); } catch (Exception e) { Logging.logError(e); } } public AdafruitINA219(String n) { super(n); // TODO Auto-generated constructor stub } public boolean setController(I2CControl controller) { if (controller == null) { error("setting null as controller"); return false; } log.info(String.format("%s setController %s", getName(), controller.getName())); this.controller = controller; controller.createDevice(busAddress, deviceAddress, type); broadcastState(); return true; } /** * This method creates the i2c device */ boolean setDeviceAddress(int DeviceAddress){ if (controller != null) { if (deviceAddress != DeviceAddress){ controller.releaseDevice(busAddress,deviceAddress); controller.createDevice(busAddress, DeviceAddress, type); } } log.info(String.format("Setting device address to x%02X", deviceAddress)); deviceAddress = DeviceAddress; return true; } /** * This method sets the shunt resistance in ohms * Default value is .1 Ohms ( R100 ) */ void setShuntResistance(double ShuntResistance){ shuntResistance = ShuntResistance; } /** * This method reads and returns the power in Watts */ double getPower(){ power = getBusVoltage() * getCurrent(); return power; } /** * This method reads and returns the shunt current in Amperes */ double getCurrent(){ current = getShuntVoltage() / shuntResistance; return current; } /** * This method reads and returns the shunt Voltage in Volts */ double getShuntVoltage(){ byte[] writebuffer = {INA219_SHUNTVOLTAGE}; byte[] readbuffer = {0x0,0x0}; controller.i2cWrite(busAddress, deviceAddress, writebuffer, writebuffer.length); controller.i2cRead(busAddress, deviceAddress, readbuffer, readbuffer.length); log.info(String.format("getShuntVoltage x%02X x%02X", readbuffer[0], readbuffer[1])); shuntVoltage = (double)(((short)(readbuffer[0])<<8) + ((short)readbuffer[1] & 0xff)) * 0.00001; return shuntVoltage; } /** * This method reads and returns the bus Voltage in Volts */ double getBusVoltage(){ int scale = 250; byte[] writebuffer = {INA219_BUSVOLTAGE}; byte[] readbuffer = {0x0,0x0}; controller.i2cWrite(busAddress, deviceAddress, writebuffer, writebuffer.length); controller.i2cRead(busAddress, deviceAddress, readbuffer, readbuffer.length); log.info(String.format("getBusVoltage x%02X x%02X", readbuffer[0], readbuffer[1])); busVoltage = (double)(((int)(readbuffer[0])<<5 & 0x7fff) + ((int)readbuffer[1]>>3 & 0x7f)) / scale; return busVoltage; } /** * This static method returns all the details of the class without * it having to be constructed. It has description, categories, * dependencies, and peer definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData(){ ServiceType meta = new ServiceType(AdafruitINA219.class.getCanonicalName()); meta.addDescription("Adafruit INA219 Voltage and Current sensor Service"); meta.addCategory("sensor"); return meta; } }
package aeronicamc.mods.mxtune.gui; import aeronicamc.mods.mxtune.Reference; import aeronicamc.mods.mxtune.inventory.InstrumentContainer; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screen.inventory.ContainerScreen; import net.minecraft.client.util.InputMappings; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import java.util.Objects; public class InstrumentScreen extends ContainerScreen<InstrumentContainer> { private final ResourceLocation GUI = new ResourceLocation(Reference.MOD_ID, "textures/gui/instrument_inventory.png"); public InstrumentScreen(InstrumentContainer screenContainer, PlayerInventory inv, ITextComponent titleIn) { super(screenContainer, inv, titleIn); minecraft = Minecraft.getInstance(); assert minecraft.player != null; this.imageWidth = 166; this.imageWidth = 184; } @Override protected void renderBg(MatrixStack matrixStack, float partialTicks, int x, int y) { RenderSystem.clearColor(1.0F, 1.0F, 1.0F, 1.0F); Objects.requireNonNull(this.minecraft).getTextureManager().bind(GUI); int relX = (this.width - this.imageWidth) / 2; int relY = (this.height - this.imageHeight) / 2; this.blit(matrixStack, relX, relY, 0, 0, this.imageWidth, this.imageHeight); } @Override public void render(MatrixStack matrixStack , int mouseX, int mouseY, float partialTicks) { this.renderBackground(matrixStack); super.render(matrixStack, mouseX, mouseY, partialTicks); ModGuiHelper.RenderGuiItemScaled(this.itemRenderer, inventory.getSelected(), getGuiLeft() + 51, getGuiTop() + 50, 2, true); this.renderTooltip(matrixStack, mouseX, mouseY); } @Override protected void renderLabels(MatrixStack matrixStack , int mouseX, int mouseY) { this.font.draw(matrixStack, this.title, (float)(imageWidth - font.width(this.title))/2, 10, TextColorFg.DARK_GRAY); this.font.draw(matrixStack, new TranslationTextComponent("container.inventory"), 10, 72, TextColorFg.DARK_GRAY); } @Override public boolean keyPressed(int pKeyCode, int pScanCode, int pModifiers) { // Prevent the Instrument from being swapped if (Objects.requireNonNull(this.minecraft).options.keyHotbarSlots[inventory.selected].isActiveAndMatches(InputMappings.getKey(pKeyCode, pScanCode)) || (hoveredSlot != null && hoveredSlot.index == inventory.selected)) return true; return super.keyPressed(pKeyCode, pScanCode, pModifiers); } }
package org.gbif.checklistbank.service.mybatis; import org.gbif.api.model.checklistbank.Description; import org.gbif.api.model.checklistbank.Distribution; import org.gbif.api.model.checklistbank.NameUsage; import org.gbif.api.model.checklistbank.NameUsageContainer; import org.gbif.api.model.checklistbank.NameUsageMediaObject; import org.gbif.api.model.checklistbank.NameUsageMetrics; import org.gbif.api.model.checklistbank.ParsedName; import org.gbif.api.model.checklistbank.Reference; import org.gbif.api.model.checklistbank.SpeciesProfile; import org.gbif.api.model.checklistbank.TypeSpecimen; import org.gbif.api.model.checklistbank.VerbatimNameUsage; import org.gbif.api.model.checklistbank.VernacularName; import org.gbif.api.model.common.Identifier; import org.gbif.api.util.ClassificationUtils; import org.gbif.api.vocabulary.IdentifierType; import org.gbif.api.vocabulary.Rank; import org.gbif.checklistbank.model.NameUsageWritable; import org.gbif.checklistbank.model.RawUsage; import org.gbif.checklistbank.model.Usage; import org.gbif.checklistbank.service.CitationService; import org.gbif.checklistbank.service.DatasetImportService; import org.gbif.checklistbank.service.ParsedNameService; import org.gbif.checklistbank.service.mybatis.mapper.DatasetMetricsMapper; import org.gbif.checklistbank.service.mybatis.mapper.DescriptionMapper; import org.gbif.checklistbank.service.mybatis.mapper.DistributionMapper; import org.gbif.checklistbank.service.mybatis.mapper.IdentifierMapper; import org.gbif.checklistbank.service.mybatis.mapper.MultimediaMapper; import org.gbif.checklistbank.service.mybatis.mapper.NameUsageMapper; import org.gbif.checklistbank.service.mybatis.mapper.NameUsageMetricsMapper; import org.gbif.checklistbank.service.mybatis.mapper.NubRelMapper; import org.gbif.checklistbank.service.mybatis.mapper.RawUsageMapper; import org.gbif.checklistbank.service.mybatis.mapper.ReferenceMapper; import org.gbif.checklistbank.service.mybatis.mapper.SpeciesProfileMapper; import org.gbif.checklistbank.service.mybatis.mapper.TypeSpecimenMapper; import org.gbif.checklistbank.service.mybatis.mapper.UsageMapper; import org.gbif.checklistbank.service.mybatis.mapper.VernacularNameMapper; import org.gbif.checklistbank.utils.VerbatimNameUsageMapper; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Nullable; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.inject.Inject; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.TransactionIsolationLevel; import org.mybatis.guice.transactional.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implements the NameUsageService using MyBatis. * All PagingResponses will not have the count set as it can be too costly sometimes. * Write operations DO NOT update the solr index or anything else than postgres! */ public class DatasetImportServiceMyBatis implements DatasetImportService { private static final Logger LOG = LoggerFactory.getLogger(DatasetImportServiceMyBatis.class); private final UsageMapper usageMapper; private final NameUsageMapper nameUsageMapper; private final NameUsageMetricsMapper metricsMapper; private final NubRelMapper nubRelMapper; private final RawUsageMapper rawMapper; private final VerbatimNameUsageMapper vParser = new VerbatimNameUsageMapper(); private final ParsedNameService nameService; private final CitationService citationService; private final DescriptionMapper descriptionMapper; private final DistributionMapper distributionMapper; private final IdentifierMapper identifierMapper; private final MultimediaMapper multimediaMapper; private final ReferenceMapper referenceMapper; private final SpeciesProfileMapper speciesProfileMapper; private final TypeSpecimenMapper typeSpecimenMapper; private final VernacularNameMapper vernacularNameMapper; private final DatasetMetricsMapper datasetMetricsMapper; @Inject DatasetImportServiceMyBatis(UsageMapper usageMapper, NameUsageMapper nameUsageMapper, NameUsageMetricsMapper metricsMapper, NubRelMapper nubRelMapper, RawUsageMapper rawMapper, ParsedNameService nameService, CitationService citationService, DescriptionMapper descriptionMapper, DistributionMapper distributionMapper, IdentifierMapper identifierMapper, MultimediaMapper multimediaMapper, ReferenceMapper referenceMapper, SpeciesProfileMapper speciesProfileMapper, TypeSpecimenMapper typeSpecimenMapper, VernacularNameMapper vernacularNameMapper, DatasetMetricsMapper datasetMetricsMapper) { this.nameUsageMapper = nameUsageMapper; this.metricsMapper = metricsMapper; this.nameService = nameService; this.usageMapper = usageMapper; this.nubRelMapper = nubRelMapper; this.citationService = citationService; this.rawMapper = rawMapper; this.descriptionMapper = descriptionMapper; this.distributionMapper = distributionMapper; this.identifierMapper = identifierMapper; this.multimediaMapper = multimediaMapper; this.referenceMapper = referenceMapper; this.speciesProfileMapper = speciesProfileMapper; this.typeSpecimenMapper = typeSpecimenMapper; this.vernacularNameMapper = vernacularNameMapper; this.datasetMetricsMapper = datasetMetricsMapper; } @Override /** * This DOES NOT update the solr index or anything else but postgres! */ public void insertUsages(UUID datasetKey, Iterator<Usage> iter) { final int BATCH_SIZE = 1000; int batchCounter = 1; List<Usage> batch = Lists.newArrayList(); while (iter.hasNext()) { batch.add(iter.next()); if (batch.size() % BATCH_SIZE == 0) { LOG.debug("Insert nub usage batch {}", batchCounter); insertUsageBatch(datasetKey, batch); batchCounter++; batch.clear(); } } LOG.debug("Insert last nub usage batch {}", batchCounter); insertUsageBatch(datasetKey, batch); } @Override /** * This DOES NOT update the solr index or anything else but postgres! */ @Transactional( exceptionMessage = "Something went wrong syncing dataset {0}, usage {1}" ) public int syncUsage(NameUsageContainer usage, @Nullable VerbatimNameUsage verbatim, NameUsageMetrics metrics) { Preconditions.checkNotNull(usage); Preconditions.checkNotNull(usage.getDatasetKey(), "datasetKey must exist"); Preconditions.checkNotNull(metrics); Integer usageKey = nameUsageMapper.getKey(usage.getDatasetKey(), usage.getTaxonID()); int key; if (usageKey == null) { key = insertNewUsage(usage, verbatim, metrics); LOG.debug("inserted usage {} with taxonID {} from dataset {}", key, usage.getTaxonID(), usage.getDatasetKey()); } else { key = updateUsage(usageKey, usage, verbatim, metrics); LOG.debug("updated usage {} with taxonID {} from dataset {}", key, usage.getTaxonID(), usage.getDatasetKey()); } return key; } @Override public void updateForeignKeys(int usageKey, Integer parentKey, Integer proparteKey, Integer basionymKey) { nameUsageMapper.updateForeignKeys(usageKey, parentKey, proparteKey, basionymKey); } private int insertNewUsage(NameUsageContainer usage, @Nullable VerbatimNameUsage verbatim, NameUsageMetrics metrics) { final UUID datasetKey = usage.getDatasetKey(); // insert main usage, creating name and citation records before NameUsageWritable uw = toWritable(datasetKey, usage); nameUsageMapper.insert(uw); final int usageKey = uw.getKey(); usage.setKey(usageKey); // update self references indicated by -1 so that the usage does not contain any bad foreign keys anymore // this is needed for subsequent syncing of solr! updateSelfReferences(usageKey, usage); // insert extension data insertExtensions(usage); // insert usage metrics metrics.setKey(usageKey); metricsMapper.insert(datasetKey, metrics); // insert verbatim insertVerbatim(verbatim, datasetKey, usageKey); // insert nub mapping if (usage.getNubKey() != null) { nubRelMapper.insert(datasetKey, usageKey, usage.getNubKey()); } return usageKey; } private void insertVerbatim(@Nullable VerbatimNameUsage verbatim, UUID datasetKey, int usageKey) { if (verbatim != null) { RawUsage raw = new RawUsage(); raw.setUsageKey(usageKey); raw.setDatasetKey(datasetKey); raw.setData(vParser.write(verbatim)); rawMapper.insert(raw); } } private void insertExtensions(NameUsageContainer usage) { try { for (Description d : usage.getDescriptions()) { Integer sk = citationService.createOrGet(d.getSource()); descriptionMapper.insert(usage.getKey(), d, sk); } for (Distribution d : usage.getDistributions()) { distributionMapper.insert(usage.getKey(), d, citationService.createOrGet(d.getSource())); } for (Identifier i : usage.getIdentifiers()) { if (i.getType() == null) { i.setType(IdentifierType.UNKNOWN); } identifierMapper.insert(usage.getKey(), i); } for (NameUsageMediaObject m : usage.getMedia()) { multimediaMapper.insert(usage.getKey(), m, citationService.createOrGet(m.getSource())); } for (Reference r : usage.getReferenceList()) { String citation = r.getCitation(); if (Strings.isNullOrEmpty(citation)) { // try to build from pieces if full citation is not given!!! citation = buildCitation(r); } if (!Strings.isNullOrEmpty(citation)) { referenceMapper.insert(usage.getKey(), citationService.createOrGet(citation), r, citationService.createOrGet(r.getSource())); } } for (SpeciesProfile s : usage.getSpeciesProfiles()) { speciesProfileMapper.insert(usage.getKey(), s, citationService.createOrGet(s.getSource())); } for (TypeSpecimen t : usage.getTypeSpecimens()) { typeSpecimenMapper.insert(usage.getKey(), t, citationService.createOrGet(t.getSource())); } for (VernacularName v : usage.getVernacularNames()) { vernacularNameMapper.insert(usage.getKey(), v, citationService.createOrGet(v.getSource())); } } catch (Exception e) { LOG.error("Failed to sync extensions for usage {}, {}", usage.getKey(), usage.getScientificName(), e); LOG.info("failed usage {}", usage); LOG.info("failed usage descriptions {}", usage.getDescriptions()); LOG.info("failed usage distributions {}", usage.getDistributions()); LOG.info("failed usage identifiers {}", usage.getIdentifiers()); LOG.info("failed usage media {}", usage.getMedia()); LOG.info("failed usage references {}", usage.getReferenceList()); LOG.info("failed usage speciesProfiles {}", usage.getSpeciesProfiles()); LOG.info("failed usage typeSpecimens {}", usage.getTypeSpecimens()); LOG.info("failed usage vernacularNames {}", usage.getVernacularNames()); Throwables.propagate(e); } } protected static String buildCitation(Reference r) { StringBuilder sb = new StringBuilder(); if (!Strings.isNullOrEmpty(r.getAuthor())) { sb.append(r.getAuthor()); if (Strings.isNullOrEmpty(r.getDate())) { sb.append(": "); } else { sb.append(" "); } } if (!Strings.isNullOrEmpty(r.getDate())) { sb.append("("); sb.append(r.getDate()); sb.append(") "); } if (!Strings.isNullOrEmpty(r.getTitle())) { sb.append(r.getTitle()); } if (!Strings.isNullOrEmpty(r.getSource())) { if (!Strings.isNullOrEmpty(r.getTitle())) { sb.append(": "); } sb.append(r.getSource()); } return Strings.emptyToNull(sb.toString().trim()); } /** * Updates an existing usage record and all its related extensions. * Checking whether a usage has changed is a bit of work and error prone so we always update currently. * In the future we should try to update only when needed though. We would need to compare the usage itself, * the raw data, the usage metrics and all extension data in the container though. * @param usageKey existing name usage key * @param usage updated usage * @param verbatim * @param metrics * @return */ private Integer updateUsage(final int usageKey, NameUsageContainer usage, @Nullable VerbatimNameUsage verbatim, NameUsageMetrics metrics) { final UUID datasetKey = usage.getDatasetKey(); usage.setKey(usageKey); // update self references indicated by -1 updateSelfReferences(usageKey, usage); // insert main usage, creating name and citation records before NameUsageWritable uw = toWritable(datasetKey, usage); uw.setKey(usageKey); nameUsageMapper.update(uw); // remove all previous extension records descriptionMapper.deleteByUsage(usageKey); distributionMapper.deleteByUsage(usageKey); identifierMapper.deleteByUsage(usageKey); multimediaMapper.deleteByUsage(usageKey); referenceMapper.deleteByUsage(usageKey); speciesProfileMapper.deleteByUsage(usageKey); typeSpecimenMapper.deleteByUsage(usageKey); vernacularNameMapper.deleteByUsage(usageKey); // insert new extension data insertExtensions(usage); // update usage metrics metrics.setKey(usageKey); metricsMapper.update(metrics); // update verbatim // we delete and insert instead of updates to avoid updating non existing records rawMapper.delete(usageKey); insertVerbatim(verbatim, datasetKey, usageKey); // update nub mapping nubRelMapper.delete(usageKey); if (usage.getNubKey() != null) { nubRelMapper.insert(datasetKey, usageKey, usage.getNubKey()); } return usageKey; } private void updateSelfReferences(int usageKey, NameUsage u) { if (u.getBasionymKey() != null && u.getBasionymKey() == -1) { u.setBasionymKey(usageKey); } if (u.getParentKey() != null && u.getParentKey() == -1) { u.setParentKey(usageKey); } if (u.getAcceptedKey() != null && u.getAcceptedKey() == -1) { u.setAcceptedKey(usageKey); } if (u.getProParteKey() != null && u.getProParteKey() == -1) { u.setProParteKey(usageKey); } for (Rank r : Rank.LINNEAN_RANKS) { if (u.getHigherRankKey(r) != null && u.getHigherRankKey(r) == -1) { ClassificationUtils.setHigherRankKey(u, r, usageKey); } } } /** * Converts a name usage into a writable name usage by looking up or inserting name and citation records * and populating the writable instance with these keys. */ private NameUsageWritable toWritable(UUID datasetKey, NameUsageContainer u) { NameUsageWritable uw = new NameUsageWritable(); uw.setTaxonID(u.getTaxonID()); uw.setDatasetKey(datasetKey); uw.setConstituentKey(u.getConstituentKey()); uw.setBasionymKey(u.getBasionymKey()); if (u.getAcceptedKey() != null) { uw.setParentKey(u.getAcceptedKey()); } else { uw.setParentKey(u.getParentKey()); } ClassificationUtils.copyLinneanClassificationKeys(u, uw); uw.setProParteKey(u.getProParteKey()); uw.setRank(u.getRank()); uw.setOrigin(u.getOrigin()); uw.setSynonym(u.isSynonym()); uw.setNumDescendants(u.getNumDescendants()); uw.setNomenclaturalStatus(u.getNomenclaturalStatus()); uw.setTaxonomicStatus(u.getTaxonomicStatus()); uw.setReferences(u.getReferences()); uw.setRemarks(u.getRemarks()); uw.setModified(u.getModified()); uw.setIssues(u.getIssues()); // lookup or insert name record ParsedName pn = nameService.createOrGet(u.getScientificName()); uw.setNameKey(pn.getKey()); // lookup or insert citation records uw.setPublishedInKey( citationService.createOrGet(u.getPublishedIn()) ); uw.setAccordingToKey( citationService.createOrGet(u.getAccordingTo()) ); return uw; } @Transactional( executorType = ExecutorType.BATCH, isolationLevel = TransactionIsolationLevel.READ_UNCOMMITTED, exceptionMessage = "Something went wrong while inserting nub relations batch for dataset {0}" ) @Override public void insertNubRelations(UUID datasetKey, Map<Integer, Integer> relations) { nubRelMapper.deleteByDataset(datasetKey); for (Map.Entry<Integer, Integer> entry : relations.entrySet()) { nubRelMapper.insert(datasetKey, entry.getKey(), entry.getValue()); } } @Transactional( executorType = ExecutorType.BATCH, isolationLevel = TransactionIsolationLevel.READ_UNCOMMITTED, exceptionMessage = "Something went wrong while inserting usage batch for dataset {0}" ) private void insertUsageBatch(UUID datasetKey, List<Usage> usages) { for (Usage u : usages) { usageMapper.insert(datasetKey, u); } } @Override public int deleteDataset(UUID datasetKey) { LOG.info("Deleting entire dataset {}", datasetKey); int numDeleted = usageMapper.deleteByDataset(datasetKey); // we do not remove old dataset metrics, just add a new, empty one as the most recent datasetMetricsMapper.insert(datasetKey, new Date()); return numDeleted; } @Override public int deleteOldUsages(UUID datasetKey, Date before) { LOG.info("Deleting all usages in dataset {} before {}", datasetKey, before); return usageMapper.deleteByDatasetAndDate(datasetKey, before); } @Override public List<Integer> listOldUsages(UUID datasetKey, Date before) { return usageMapper.listByDatasetAndDate(datasetKey, before); } }
package org.opencms.monitor; import org.opencms.file.CmsGroup; import org.opencms.file.CmsUser; import org.opencms.main.CmsLog; import org.opencms.security.CmsRole; import org.opencms.util.CmsUUID; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.Interner; import com.google.common.collect.Interners; /** * Cache for users' groups and data derived from those groups, like role membership. * * <p>The cache can be either flushed completeley, or just for a single user id. * The data for a user must be flushed when their group membership changes. * */ public class CmsGroupListCache implements I_CmsMemoryMonitorable { /** * Internal entry which stores the cached data for a specific user id.<p> */ class Entry implements I_CmsMemoryMonitorable { /** Bare roles, with no OU information. */ private volatile List<CmsRole> m_bareRoles; /** Cache for group lists. */ private Map<String, List<CmsGroup>> m_groupCache = createLRUCacheMap(GROUP_LISTS_PER_USER); /** Cache for role memberships. */ private Map<String, Boolean> m_hasRoleCache = new ConcurrentHashMap<>(); /** * Gets the cached bare roles (with no OU information). * * @return the cached bare roles */ public List<CmsRole> getBareRoles() { return m_bareRoles; } /** * Gets the group list cache map. * * @return the group list cache */ public Map<String, List<CmsGroup>> getGroupCache() { return m_groupCache; } /** * Gets the 'hasRole' cache map. * * @return the 'hasRole' cache */ public Map<String, Boolean> getHasRoleCache() { return m_hasRoleCache; } /** * @see org.opencms.monitor.I_CmsMemoryMonitorable#getMemorySize() */ public int getMemorySize() { return (int)(CmsMemoryMonitor.getValueSize(m_groupCache) + CmsMemoryMonitor.getValueSize(m_hasRoleCache) + CmsMemoryMonitor.getValueSize(m_bareRoles)); } /** * Sets the cached bare roles (with no associated OU information). * * @param bareRoles the bare roles */ public void setBareRoles(List<CmsRole> bareRoles) { m_bareRoles = bareRoles; } } /** Max cached group lists per user. Non-final, so can be adjusted at runtime. */ public static volatile int GROUP_LISTS_PER_USER = 32; /** Log instance for this class. */ private static final Log LOG = CmsLog.getLog(CmsGroupListCache.class); /** The internal cache used. */ private LoadingCache<CmsUUID, Entry> m_internalCache; /** Interner for canonicalizing the role membership cache keys. */ private Interner<String> m_interner = Interners.newBuilder().concurrencyLevel(8).build(); /** * Creates a new cache instance. * * @param size the maximum size */ public CmsGroupListCache(int size) { m_internalCache = CacheBuilder.newBuilder().concurrencyLevel(CmsMemoryMonitor.CONCURRENCY_LEVEL).maximumSize( size).build(new CacheLoader<CmsUUID, Entry>() { @Override public Entry load(CmsUUID key) throws Exception { return new Entry(); } }); } /** * Creates a thread safe LRU cache map based on the guava cache builder.<p> * * @param capacity the cache capacity * * @return the cache map */ @SuppressWarnings("unchecked") static <T, V> Map<T, V> createLRUCacheMap(int capacity) { CacheBuilder<?, ?> builder = CacheBuilder.newBuilder().concurrencyLevel(4).maximumSize(capacity); return (Map<T, V>)(builder.build().asMap()); } /** * Removes all cache entries. */ public void clear() { if (LOG.isInfoEnabled()) { if (LOG.isDebugEnabled()) { // when DEBUG level is enabled, log a dummy exception to generate a stack trace LOG.debug("CmsGroupListCache.clear() called", new Exception("(dummy exception)")); } else { LOG.info("CmsGroupListCache.clear() called"); } } m_internalCache.invalidateAll(); } /** * Removes the cache entries for the given user id. * * @param idKey the user id */ public void clearUser(CmsUUID idKey) { if (idKey != null) { m_internalCache.invalidate(idKey); } } /** * Gets the cached bare roles for the given user id, or null if none are cached. * * <p>These are just the roles of the user, but with no OU information. * @param userId the user id * @return the bare roles for the user */ public List<CmsRole> getBareRoles(CmsUUID userId) { Entry entry = m_internalCache.getIfPresent(userId); if (entry == null) { return null; } return entry.getBareRoles(); } /** * Gets the cached user groups for the given combination of keys, or null if nothing is cached. * * @param userId the user id * @param subKey a string that consists of the parameters/flags for the group reading operation * * @return the groups for the given combination of keys */ public List<CmsGroup> getGroups(CmsUUID userId, String subKey) { Entry userEntry = m_internalCache.getIfPresent(userId); if (userEntry == null) { return null; } List<CmsGroup> result = userEntry.getGroupCache().get(subKey); if (result != null) { result = Collections.unmodifiableList(result); } return result; } /** * Gets the cached role membership for the given role key, or null if nothing is cached. * * @param userId the user id * @param roleKey the role key * * @return the cached role membership */ public Boolean getHasRole(CmsUUID userId, String roleKey) { Entry userEntry = m_internalCache.getIfPresent(userId); if (userEntry == null) { return null; } return userEntry.getHasRoleCache().get(roleKey); } /** * @see org.opencms.monitor.I_CmsMemoryMonitorable#getMemorySize() */ public int getMemorySize() { return (int)CmsMemoryMonitor.getValueSize(m_internalCache.asMap()); } /** * Sets the bare roles for a user (with no OU information). * * @param user the user * @param bareRoles the list of bare roles */ public void setBareRoles(CmsUser user, List<CmsRole> bareRoles) { if (!user.isWebuser()) { // web users take away space from normal workplace users/editors CmsUUID userId = user.getId(); m_internalCache.getUnchecked(userId).setBareRoles(bareRoles); } } /** * Caches a new value for the given combination of keys. * * @param user the user * @param subKey a string that consists of the parameters/flags for the group reading operation * @param groups the value to cache */ public void setGroups(CmsUser user, String subKey, List<CmsGroup> groups) { if (!user.isWebuser()) { // web users take away space from normal workplace users/editors CmsUUID userId = user.getId(); Map<String, List<CmsGroup>> groupCache = m_internalCache.getUnchecked(userId).getGroupCache(); groupCache.put(subKey, new ArrayList<>(groups)); } } /** * Caches the role membership for the given user id and role key. * * @param user the user * @param roleKey the role key * @param value the role membership value */ public void setHasRole(CmsUser user, String roleKey, Boolean value) { if (!user.isWebuser()) { // web users take away space from normal workplace users/editors roleKey = m_interner.intern(roleKey); CmsUUID userId = user.getId(); m_internalCache.getUnchecked(userId).getHasRoleCache().put(roleKey, value); } } /** * Returns the number of user ids for which group lists are cached. * * @return the number of user ids for which group lists are cached */ public int size() { return (int)m_internalCache.size(); } }
package net.ohloh.ohcount4j.scan; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import org.testng.annotations.Test; import static net.ohloh.ohcount4j.Entity.*; import static net.ohloh.ohcount4j.Language.*; public class CSharpScannerTest extends BaseScannerTest { @Test public void basic() { assertLine(new CSharpScanner(), new Line(LANG_CSHARP, BLANK), "\n"); assertLine(new CSharpScanner(), new Line(LANG_CSHARP, BLANK), " \n"); assertLine(new CSharpScanner(), new Line(LANG_CSHARP, BLANK), "\t\n"); assertLine(new CSharpScanner(), new Line(LANG_CSHARP, CODE), "#include <stdio.h>\n"); assertLine(new CSharpScanner(), new Line(LANG_CSHARP, COMMENT), "/* Block Comment */\n"); assertLine(new CSharpScanner(), new Line(LANG_CSHARP, COMMENT), "// Line comment\n"); assertLine(new CSharpScanner(), new Line(LANG_CSHARP, CODE), "#include <stdio.h> // with comment\n"); } @Test public void eofHandling() { // Note lack of trailing \n in all cases below assertLine(new CSharpScanner(), new Line(LANG_CSHARP, BLANK), " "); assertLine(new CSharpScanner(), new Line(LANG_CSHARP, BLANK), "\t"); assertLine(new CSharpScanner(), new Line(LANG_CSHARP, CODE), "#include <stdio.h>"); assertLine(new CSharpScanner(), new Line(LANG_CSHARP, COMMENT), "/* Block Comment */"); assertLine(new CSharpScanner(), new Line(LANG_CSHARP, COMMENT), "// Line comment"); assertLine(new CSharpScanner(), new Line(LANG_CSHARP, CODE), "#include <stdio.h> // with comment"); } @Test public void helloWorld() { String code = "/* Hello World\n" + "\t\n" + " * with multi-line comment */\n" + "\n" + "#include <stdio.h>\n" + "\n" + "main() {\n" + " printf(\"Hello world!\");\n" + "}"; Line[] expected = { new Line(LANG_CSHARP, COMMENT), new Line(LANG_CSHARP, BLANK), new Line(LANG_CSHARP, COMMENT), new Line(LANG_CSHARP, BLANK), new Line(LANG_CSHARP, CODE), new Line(LANG_CSHARP, BLANK), new Line(LANG_CSHARP, CODE), new Line(LANG_CSHARP, CODE), new Line(LANG_CSHARP, CODE) }; assertLines(new CSharpScanner(), expected, code); } @Test public void testFile() { String s = readFile("test/data/sample.cs"); Line[] expected = { new Line(LANG_CSHARP, COMMENT), new Line(LANG_CSHARP, COMMENT), new Line(LANG_CSHARP, BLANK), new Line(LANG_CSHARP, COMMENT), new Line(LANG_CSHARP, COMMENT), new Line(LANG_CSHARP, CODE), new Line(LANG_CSHARP, BLANK), new Line(LANG_CSHARP, CODE), new Line(LANG_CSHARP, COMMENT), new Line(LANG_CSHARP, CODE), new Line(LANG_CSHARP, CODE), new Line(LANG_CSHARP, CODE), new Line(LANG_CSHARP, CODE) }; assertLines(new CSharpScanner(), expected, s); } public String readFile(String loc) { try { String s = ""; BufferedReader reader = new BufferedReader(new FileReader(loc)); String line = reader.readLine(); while (line != null) { s += line + "\n"; line = reader.readLine(); } return s; } catch (IOException e) { e.printStackTrace(); } return null; } @Test public void unterminatedMultilineStringCrash() { // This minimal case caused an Arrays.copyOfRange() crash String code = "'\nA\n\n"; Line[] expected = { new Line(LANG_CSHARP, CODE), new Line(LANG_CSHARP, CODE), new Line(LANG_CSHARP, BLANK) }; assertLines(new CSharpScanner(), expected, code); } @Test public void unterminatedBlockCommentCrash() { // This minimal case caused an Arrays.copyOfRange() crash
package org.springframework.jndi; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Helper class that simplifies JNDI operations. It provides methods to lookup * and bind, and allows implementations of the ContextCallback interface to * perform any operation they like with a JNDI naming context provided. * * <p>This is the central class in this package. It is analogous to the * JdbcTemplate class. This class performs all error handling. * * @author Rod Johnson * @author Juergen Hoeller * @see ContextCallback * @see org.springframework.jdbc.core.JdbcTemplate * @version $Id: JndiTemplate.java,v 1.3 2003-11-20 18:21:27 johnsonr Exp $ */ public class JndiTemplate { protected final Log logger = LogFactory.getLog(getClass()); private Properties environment; /** * Create a new JndiTemplate instance. */ public JndiTemplate() { } /** * Create a new JndiTemplate instance, using the given environment. */ public JndiTemplate(Properties environment) { this.environment = environment; } /** * Set the environment for the InitialContext. */ public void setEnvironment(Properties environment) { this.environment = environment; } public Properties getEnvironment() { return environment; } /** * Lookup the object with the given name in the current JNDI context. * @param name JNDI name of the object * @return object found (cannot be null, if a not so well-behaved * JNDI implementations returns null, a NamingException gets thrown) * @throws NamingException if there is no object with the given * name bound to JNDI */ public Object lookup(final String name) throws NamingException { Context ctx = null; try { ctx = createInitialContext(); logger.debug("Looking up JNDI object with name '" + name + "'"); Object lookedUp = ctx.lookup(name); if (lookedUp == null) { throw new NamingException("JNDI object not found: JNDI implementation returned null"); } return lookedUp; } finally { try { if (ctx != null) ctx.close(); } catch (NamingException ex) { logger.warn("InitialContext threw exception on close", ex); } } } /** * Bind the given object to the current JNDI context, using the given name. * @param name JNDI name of the object * @param object object to bind * @throws NamingException thrown by JNDI, mostly name already bound */ public void bind(final String name, final Object object) throws NamingException { execute(new ContextCallback() { public Object doInContext(Context ctx) throws NamingException { logger.info("Binding JNDI object with name " + name); ctx.bind(name, object); return null; } }); } /** * Remove the binding for the given name from the current JNDI context. * @param name the JNDI name of the object * @throws NamingException thrown by JNDI, mostly name not found */ public void unbind(final String name) throws NamingException { execute(new ContextCallback() { public Object doInContext(Context ctx) throws NamingException { logger.info("Unbinding JNDI object with name " + name); ctx.unbind(name); return null; } }); } /** * Execute the given callback implementation. * @param contextCallback ContextCallback implementation * @return a result object returned by the callback, or null * @throws NamingException thrown by the callback implementation. */ public Object execute(ContextCallback contextCallback) throws NamingException { Context ctx = null; try { ctx = createInitialContext(); return contextCallback.doInContext(ctx); } finally { try { if (ctx != null) ctx.close(); } catch (NamingException ex) { logger.warn("InitialContext threw exception on close", ex); } } } /** * Create a new initial context. * The default implementation use this template's environment settings. * Can be subclassed for custom contexts, e.g. for testing. * @return the new InitialContext instance * @throws NamingException in case of initialization errors */ protected Context createInitialContext() throws NamingException { return new InitialContext(getEnvironment()); } }
package com.censoredsoftware.demigods.battle; import com.censoredsoftware.demigods.Demigods; import com.censoredsoftware.demigods.data.DataManager; import com.censoredsoftware.demigods.exception.SpigotNotFoundException; import com.censoredsoftware.demigods.helper.ConfigFile; import com.censoredsoftware.demigods.location.DLocation; import com.censoredsoftware.demigods.player.DCharacter; import com.censoredsoftware.demigods.player.DPlayer; import com.censoredsoftware.demigods.player.Pet; import com.censoredsoftware.demigods.structure.Structure; import com.censoredsoftware.demigods.util.*; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.*; import org.bukkit.*; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Tameable; import org.bukkit.util.Vector; import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class Battle implements ConfigurationSerializable { private UUID id; private UUID startLoc; private boolean active; private long startTime; private long deleteTime; private Set<String> involvedPlayers; private Set<String> involvedTameable; private int killCounter; private Map<String, Object> kills; private Map<String, Object> deaths; private UUID startedBy; public Battle() {} public Battle(UUID id, ConfigurationSection conf) { this.id = id; startLoc = UUID.fromString(conf.getString("startLoc")); active = conf.getBoolean("active"); startTime = conf.getLong("startTime"); deleteTime = conf.getLong("deleteTime"); involvedPlayers = Sets.newHashSet(conf.getStringList("involvedPlayers")); involvedTameable = Sets.newHashSet(conf.getStringList("involvedTameable")); killCounter = conf.getInt("killCounter"); kills = conf.getConfigurationSection("kills").getValues(false); deaths = conf.getConfigurationSection("deaths").getValues(false); startedBy = UUID.fromString(conf.getString("startedBy")); } @Override public Map<String, Object> serialize() { Map<String, Object> map = new HashMap<String, Object>(); map.put("startLoc", startLoc.toString()); map.put("active", active); map.put("startTime", startTime); map.put("deleteTime", deleteTime); map.put("involvedPlayers", Lists.newArrayList(involvedPlayers)); map.put("involvedTameable", Lists.newArrayList(involvedTameable)); map.put("killCounter", killCounter); map.put("kills", kills); map.put("deaths", deaths); map.put("startedBy", startedBy.toString()); return map; } public void generateId() { id = UUID.randomUUID(); } public void setActive() { this.active = true; Util.save(this); } public void setInactive() { this.active = false; Util.save(this); } void setStartLocation(Location location) { this.startLoc = DLocation.Util.create(location).getId(); } void setStartTime(long time) { this.startTime = time; } void setDeleteTime(long time) { this.deleteTime = time; Util.save(this); } public UUID getId() { return this.id; } public double getRange() { int base = Demigods.config.getSettingInt("battles.min_range"); int per = 5; if(getParticipants().size() > 2) return base + (per * (getParticipants().size() - 2)); return base; } public boolean isActive() { return this.active; } public long getDuration() { long base = Demigods.config.getSettingInt("battles.min_duration") * 1000; long per = Demigods.config.getSettingInt("battles.duration_multiplier") * 1000; if(getParticipants().size() > 2) return base + (per * (getParticipants().size() - 2)); return base; } public int getMinKills() { int base = Demigods.config.getSettingInt("battles.min_kills"); int per = 2; if(getParticipants().size() > 2) return base + (per * (getParticipants().size() - 2)); return base; } public int getMaxKills() { int base = Demigods.config.getSettingInt("battles.max_kills"); int per = 3; if(getParticipants().size() > 2) return base + (per * (getParticipants().size() - 2)); return base; } public Location getStartLocation() { return DLocation.Util.load(this.startLoc).toLocation(); } public long getStartTime() { return this.startTime; } public long getDeleteTime() { return this.deleteTime; } void setStarter(DCharacter character) { this.startedBy = character.getId(); addParticipant(character); } void initialize() { this.kills = Maps.newHashMap(); this.deaths = Maps.newHashMap(); this.involvedPlayers = Sets.newHashSet(); this.involvedTameable = Sets.newHashSet(); this.killCounter = 0; } public void addParticipant(Participant participant) { if(participant instanceof DCharacter) this.involvedPlayers.add((participant.getId().toString())); else this.involvedTameable.add(participant.getId().toString()); Util.save(this); } public void removeParticipant(Participant participant) { if(participant instanceof DCharacter) this.involvedPlayers.remove((participant.getId().toString())); else this.involvedTameable.remove(participant.getId().toString()); Util.save(this); } public void addKill(Participant participant) { this.killCounter += 1; DCharacter character = participant.getRelatedCharacter(); if(this.kills.containsKey(character.getId().toString())) this.kills.put(character.getId().toString(), Integer.parseInt(this.kills.get(character.getId().toString()).toString()) + 1); else this.kills.put(character.getId().toString(), 1); Util.save(this); } public void addDeath(Participant participant) { DCharacter character = participant.getRelatedCharacter(); if(this.deaths.containsKey(character)) this.deaths.put(character.getId().toString(), Integer.parseInt(this.deaths.get(character.getId().toString()).toString()) + 1); else this.deaths.put(character.getId().toString(), 1); Util.save(this); sendBattleStats(); } public DCharacter getStarter() { return DCharacter.Util.load(this.startedBy); } public Set<Participant> getParticipants() { return Sets.union(Sets.newHashSet(Collections2.transform(involvedPlayers, new Function<String, Participant>() { @Override public Participant apply(String character) { return DCharacter.Util.load(UUID.fromString(character)); } })), Sets.newHashSet(Collections2.transform(involvedTameable, new Function<String, Participant>() { @Override public Participant apply(String tamable) { return Pet.Util.load(UUID.fromString(tamable)); } }))); } public Set<String> getInvolvedAlliances() { Set<String> alliances = Sets.newHashSet(); for(String alliance : Collections2.transform(involvedPlayers, new Function<String, String>() { @Override public String apply(String stringId) { return DCharacter.Util.load(UUID.fromString(stringId)).getAlliance(); } })) alliances.add(alliance); return alliances; } public int getKills(Participant participant) { try { return Integer.parseInt(kills.get(participant.getId().toString()).toString()); } catch(Exception ignored) {} return 0; } public int getDeaths(Participant participant) { try { return Integer.parseInt(deaths.get(participant.getId().toString()).toString()); } catch(Exception ignored) {} return 0; } public Map<UUID, Integer> getScores() { Map<UUID, Integer> score = Maps.newHashMap(); for(Map.Entry<String, Object> entry : kills.entrySet()) { if(!getParticipants().contains(DCharacter.Util.load(UUID.fromString(entry.getKey())))) continue; score.put(UUID.fromString(entry.getKey()), Integer.parseInt(entry.getValue().toString())); } for(Map.Entry<String, Object> entry : deaths.entrySet()) { int base = 0; if(score.containsKey(UUID.fromString(entry.getKey()))) base = score.get(UUID.fromString(entry.getKey())); score.put(UUID.fromString(entry.getKey()), base - Integer.parseInt(entry.getValue().toString())); } return score; } public int getScore(final String alliance) { Map<UUID, Integer> score = Maps.newHashMap(); for(Map.Entry<String, Object> entry : kills.entrySet()) { if(!getParticipants().contains(DCharacter.Util.load(UUID.fromString(entry.getKey())))) continue; score.put(UUID.fromString(entry.getKey()), Integer.parseInt(entry.getValue().toString())); } for(Map.Entry<String, Object> entry : deaths.entrySet()) { int base = 0; if(score.containsKey(UUID.fromString(entry.getKey()))) base = score.get(UUID.fromString(entry.getKey())); score.put(UUID.fromString(entry.getKey()), base - Integer.parseInt(entry.getValue().toString())); } int sum = 0; for(int i : Collections2.transform(Collections2.filter(score.entrySet(), new Predicate<Map.Entry<UUID, Integer>>() { @Override public boolean apply(Map.Entry<UUID, Integer> entry) { return DCharacter.Util.load(entry.getKey()).getAlliance().equalsIgnoreCase(alliance); } }), new Function<Map.Entry<UUID, Integer>, Integer>() { @Override public Integer apply(Map.Entry<UUID, Integer> entry) { return entry.getValue(); } })) sum += i; return sum; } public Collection<DCharacter> getMVPs() { final int max = Collections.max(getScores().values()); return Collections2.transform(Collections2.filter(getScores().entrySet(), new Predicate<Map.Entry<UUID, Integer>>() { @Override public boolean apply(Map.Entry<UUID, Integer> entry) { return entry.getValue() == max; } }), new Function<Map.Entry<UUID, Integer>, DCharacter>() { @Override public DCharacter apply(Map.Entry<UUID, Integer> entry) { return DCharacter.Util.load(entry.getKey()); } }); } public int getKillCounter() { return this.killCounter; } public void end() { sendMessage(ChatColor.RED + "The battle is over!"); sendMessage(ChatColor.YELLOW + "You are safe for 60 seconds."); for(String stringId : involvedPlayers) DataManager.saveTimed(stringId, "just_finished_battle", true, 60); Map<UUID, Integer> scores = getScores(); List<UUID> participants = Lists.newArrayList(scores.keySet()); if(participants.size() == 2) { if(scores.get(participants.get(0)).equals(scores.get(participants.get(1)))) { DCharacter one = DCharacter.Util.load(participants.get(0)); DCharacter two = DCharacter.Util.load(participants.get(1)); Demigods.message.broadcast(" "); Demigods.message.broadcast(one.getDeity().getColor() + one.getName() + ChatColor.GRAY + " and " + two.getDeity().getColor() + two.getName() + ChatColor.GRAY + " just tied in a duel."); Demigods.message.broadcast(" "); } else { int winnerIndex = scores.get(participants.get(0)) > scores.get(participants.get(1)) ? 0 : 1; DCharacter winner = DCharacter.Util.load(participants.get(winnerIndex)); DCharacter loser = DCharacter.Util.load(participants.get(winnerIndex == 0 ? 1 : 0)); Demigods.message.broadcast(" "); Demigods.message.broadcast(winner.getDeity().getColor() + winner.getName() + ChatColor.GRAY + " just won in a duel against " + loser.getDeity().getColor() + loser.getName() + ChatColor.GRAY + "."); Demigods.message.broadcast(" "); } } else if(participants.size() > 2) { String winningAlliance = ""; int winningScore = 0; Collection<DCharacter> MVPs = getMVPs(); boolean oneMVP = MVPs.size() == 1; for(String alliance : getInvolvedAlliances()) { int score = getScore(alliance); if(getScore(alliance) > winningScore) { winningAlliance = alliance; winningScore = score; } } Demigods.message.broadcast(" "); Demigods.message.broadcast(ChatColor.YELLOW + "The " + winningAlliance + "s " + ChatColor.GRAY + "just won a battle involving " + getParticipants().size() + " participants."); Demigods.message.broadcast(ChatColor.GRAY + "The " + ChatColor.YELLOW + "MVP" + (oneMVP ? "" : "s") + ChatColor.GRAY + " from this battle " + (oneMVP ? "is" : "are") + ":"); for(DCharacter mvp : MVPs) Demigods.message.broadcast(" " + ChatColor.DARK_GRAY + Unicodes.rightwardArrow() + " " + mvp.getDeity().getColor() + mvp.getName() + ChatColor.GRAY + " / " + ChatColor.YELLOW + "Kills" + ChatColor.GRAY + ": " + getKills(mvp) + " / " + ChatColor.YELLOW + "Deaths" + ChatColor.GRAY + ": " + getDeaths(mvp)); Demigods.message.broadcast(" "); } // Prepare for graceful delete setDeleteTime(System.currentTimeMillis() + 3000L); setInactive(); } public void delete() { DataManager.battles.remove(getId()); } public void sendMessage(String message) { for(String stringId : involvedPlayers) { OfflinePlayer offlinePlayer = DCharacter.Util.load(UUID.fromString(stringId)).getOfflinePlayer(); if(offlinePlayer.isOnline()) offlinePlayer.getPlayer().sendMessage(message); } } public void sendRawMessage(String message) { for(String stringId : involvedPlayers) { OfflinePlayer offlinePlayer = DCharacter.Util.load(UUID.fromString(stringId)).getOfflinePlayer(); if(offlinePlayer.isOnline()) offlinePlayer.getPlayer().sendRawMessage(message); } } public void sendBattleStats() { sendMessage(ChatColor.DARK_AQUA + Titles.chatTitle("Battle Stats")); sendMessage(ChatColor.YELLOW + " " + Unicodes.rightwardArrow() + " # of Participants: " + ChatColor.WHITE + getParticipants().size()); sendMessage(ChatColor.YELLOW + " " + Unicodes.rightwardArrow() + " Duration: " + ChatColor.WHITE + (int) (System.currentTimeMillis() - getStartTime()) / 1000 + " / " + (int) getDuration() / 1000 + " seconds"); sendMessage(ChatColor.YELLOW + " " + Unicodes.rightwardArrow() + " Kill-count: " + ChatColor.WHITE + getKillCounter() + " / " + getMinKills()); } public static class File extends ConfigFile { private static String SAVE_PATH; private static final String SAVE_FILE = "battles.yml"; public File() { super(Demigods.plugin); SAVE_PATH = Demigods.plugin.getDataFolder() + "/data/"; } @Override public ConcurrentHashMap<UUID, Battle> loadFromFile() { final FileConfiguration data = getData(SAVE_PATH, SAVE_FILE); ConcurrentHashMap<UUID, Battle> map = new ConcurrentHashMap<UUID, Battle>(); for(String stringId : data.getKeys(false)) map.put(UUID.fromString(stringId), new Battle(UUID.fromString(stringId), data.getConfigurationSection(stringId))); return map; } @Override public boolean saveToFile() { FileConfiguration saveFile = getData(SAVE_PATH, SAVE_FILE); Map<UUID, Battle> currentFile = loadFromFile(); for(UUID id : DataManager.battles.keySet()) if(!currentFile.keySet().contains(id) || !currentFile.get(id).equals(DataManager.battles.get(id))) saveFile.createSection(id.toString(), Util.get(id).serialize()); for(UUID id : currentFile.keySet()) if(!DataManager.battles.keySet().contains(id)) saveFile.set(id.toString(), null); return saveFile(SAVE_PATH, SAVE_FILE, saveFile); } } public static class Util { public static void save(Battle battle) { DataManager.battles.put(battle.getId(), battle); } public static Battle create(Participant damager, Participant damaged) { Battle battle = new Battle(); battle.generateId(); battle.setStartLocation(damager.getCurrentLocation().toVector().getMidpoint(damaged.getCurrentLocation().toVector()).toLocation(damager.getCurrentLocation().getWorld())); battle.setStartTime(System.currentTimeMillis()); battle.setActive(); battle.initialize(); battle.setStarter(damager.getRelatedCharacter()); battle.addParticipant(damager); battle.addParticipant(damaged); save(battle); return battle; } public static Battle get(UUID id) { return DataManager.battles.get(id); } public static Set<Battle> getAll() { return Sets.newHashSet(DataManager.battles.values()); } public static List<Battle> getAllActive() { return Lists.newArrayList(Collections2.filter(getAll(), new Predicate<Battle>() { @Override public boolean apply(Battle battle) { return battle.isActive(); } })); } public static List<Battle> getAllInactive() { return Lists.newArrayList(Collections2.filter(getAll(), new Predicate<Battle>() { @Override public boolean apply(Battle battle) { return !battle.isActive(); } })); } public static boolean existsInRadius(Location location) { return getInRadius(location) != null; } public static Battle getInRadius(final Location location) { try { return Iterators.find(getAllActive().iterator(), new Predicate<Battle>() { @Override public boolean apply(Battle battle) { return battle.getStartLocation().distance(location) <= battle.getRange(); } }); } catch(NoSuchElementException ignored) {} return null; } public static boolean isInBattle(final Participant participant) { return Iterators.any(getAllActive().iterator(), new Predicate<Battle>() { @Override public boolean apply(Battle battle) { return battle.getParticipants().contains(participant); } }); } public static Battle getBattle(final Participant participant) { try { return Iterators.find(getAllActive().iterator(), new Predicate<Battle>() { @Override public boolean apply(Battle battle) { return battle.getParticipants().contains(participant); } }); } catch(NoSuchElementException ignored) {} return null; } public static boolean existsNear(Location location) { return getNear(location) != null; } public static Battle getNear(final Location location) { try { return Iterators.find(getAllActive().iterator(), new Predicate<Battle>() { @Override public boolean apply(Battle battle) { double distance = battle.getStartLocation().distance(location); return distance > battle.getRange() && distance <= Demigods.config.getSettingInt("battles.merge_range"); } }); } catch(NoSuchElementException ignored) {} return null; } public static Collection<Location> battleBorder(final Battle battle) { if(!Demigods.isRunningSpigot()) throw new SpigotNotFoundException(); return Collections2.transform(DLocation.Util.getCirclePoints(battle.getStartLocation(), battle.getRange(), 120), new Function<Location, Location>() { @Override public Location apply(Location point) { return new Location(point.getWorld(), point.getBlockX(), point.getWorld().getHighestBlockYAt(point), point.getBlockZ()); } }); } /* * This is completely broken. TODO */ public static Location randomRespawnPoint(Battle battle) { List<Location> respawnPoints = getSafeRespawnPoints(battle); if(respawnPoints.size() == 0) return battle.getStartLocation(); Location target = respawnPoints.get(Randoms.generateIntRange(0, respawnPoints.size() - 1)); Vector direction = target.toVector().subtract(battle.getStartLocation().toVector()).normalize(); double X = direction.getX(); double Y = direction.getY(); double Z = direction.getZ(); // Now change the angle Location changed = target.clone(); changed.setYaw(180 - DLocation.Util.toDegree(Math.atan2(Y, X))); changed.setPitch(90 - DLocation.Util.toDegree(Math.acos(Z))); return changed; } /* * This is completely broken. TODO */ public static boolean isSafeLocation(Location reference, Location checking) { if(checking.getBlock().getType().isSolid() || checking.getBlock().getType().equals(Material.LAVA)) return false; double referenceY = reference.getY(); double checkingY = checking.getY(); return Math.abs(referenceY - checkingY) <= 5; } public static List<Location> getSafeRespawnPoints(final Battle battle) { return Lists.newArrayList(Collections2.filter(Collections2.transform(DLocation.Util.getCirclePoints(battle.getStartLocation(), battle.getRange() - 1.5, 100), new Function<Location, Location>() { @Override public Location apply(Location point) { return new Location(point.getWorld(), point.getBlockX(), point.getWorld().getHighestBlockYAt(point), point.getBlockZ()); } }), new Predicate<Location>() { @Override public boolean apply(Location location) { return isSafeLocation(battle.getStartLocation(), location); } })); } public static boolean canParticipate(Entity entity) { if(!(entity instanceof Player) && !(entity instanceof Tameable)) return false; if(entity instanceof Player && DPlayer.Util.getPlayer((Player) entity).getCurrent() == null) return false; return !(entity instanceof Tameable && Pet.Util.getTameable((LivingEntity) entity) == null); } public static Participant defineParticipant(Entity entity) { if(!canParticipate(entity)) return null; if(entity instanceof Player) return DPlayer.Util.getPlayer((Player) entity).getCurrent(); return Pet.Util.getTameable((LivingEntity) entity); } public static void battleDeath(Participant damager, Participant damagee, Battle battle) { if(damager instanceof DCharacter) ((DCharacter) damager).addKill(); if(damager.getRelatedCharacter().getOfflinePlayer().isOnline()) damager.getRelatedCharacter().getOfflinePlayer().getPlayer().sendMessage(ChatColor.GREEN + "+1 Kill."); battle.addKill(damager); damagee.getEntity().setHealth(damagee.getEntity().getMaxHealth()); damagee.getEntity().teleport(randomRespawnPoint(battle)); if(damagee instanceof DCharacter) { DCharacter character = (DCharacter) damagee; character.getOfflinePlayer().getPlayer().setFoodLevel(20); character.addDeath(damager.getRelatedCharacter()); } if(damagee.getRelatedCharacter().getOfflinePlayer().isOnline()) damagee.getRelatedCharacter().getOfflinePlayer().getPlayer().sendMessage(ChatColor.RED + "+1 Death."); battle.addDeath(damagee); } public static void battleDeath(Participant damagee, Battle battle) { damagee.getEntity().setHealth(damagee.getEntity().getMaxHealth()); damagee.getEntity().teleport(randomRespawnPoint(battle)); if(damagee instanceof DCharacter) ((DCharacter) damagee).addDeath(); if(damagee.getRelatedCharacter().getOfflinePlayer().isOnline()) damagee.getRelatedCharacter().getOfflinePlayer().getPlayer().sendMessage(ChatColor.RED + "+1 Death."); battle.addDeath(damagee); } public static boolean canTarget(Entity entity) { return canParticipate(entity) && canTarget(defineParticipant(entity)); } /** * Returns true if doTargeting is allowed for <code>player</code>. * * @param participant the player to check. * @return true/false depending on if doTargeting is allowed. */ public static boolean canTarget(Participant participant) // TODO REDO THIS { return participant == null || !(participant instanceof DCharacter || participant instanceof Pet) || participant.canPvp() || participant.getCurrentLocation() != null && !Structures.isInRadiusWithFlag(participant.getCurrentLocation(), Structure.Flag.NO_PVP); } /** * Updates all battle particles. Meant for use in a Runnable. */ public static void updateBattleParticles() { for(Battle battle : Battle.Util.getAllActive()) for(Location point : Battle.Util.battleBorder(battle)) Spigots.playParticle(point, Effect.MOBSPAWNER_FLAMES, 0, 6, 0, 1F, 10, (int) (battle.getRange() * 2.5)); } /** * Updates all battles. */ public static void updateBattles() { // End all active battles that should end. for(Battle battle : Collections2.filter(Battle.Util.getAllActive(), new Predicate<Battle>() { @Override public boolean apply(Battle battle) { return battle.getKillCounter() >= battle.getMaxKills() || battle.getStartTime() + battle.getDuration() <= System.currentTimeMillis() && battle.getKillCounter() >= battle.getMinKills() || battle.getParticipants().size() < 2; } })) battle.end(); // Delete all inactive battles that should be deleted. for(Battle battle : Collections2.filter(Battle.Util.getAllInactive(), new Predicate<Battle>() { @Override public boolean apply(Battle battle) { return battle.getDeleteTime() >= System.currentTimeMillis(); } })) battle.delete(); } } }
package org.hisp.dhis.dxf2.metadata.sync; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.hisp.dhis.DhisSpringTest; import org.hisp.dhis.IntegrationTest; import org.hisp.dhis.dxf2.metadata.systemsettings.DefaultMetadataSystemSettingService; import org.hisp.dhis.render.RenderFormat; import org.hisp.dhis.render.RenderService; import org.hisp.dhis.system.SystemInfo; import org.hisp.dhis.system.SystemService; import org.hisp.dhis.system.util.HttpUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.beans.factory.annotation.Autowired; import java.io.ByteArrayInputStream; import java.io.IOException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; /** * @author aamerm */ @RunWith( PowerMockRunner.class ) @PrepareForTest( HttpUtils.class ) @Category( IntegrationTest.class ) public class MetadataSyncDelegateTest extends DhisSpringTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Autowired @InjectMocks private MetadataSyncDelegate metadataSyncDelegate; @Autowired @Mock private DefaultMetadataSystemSettingService metadataSystemSettingService; @Autowired @Mock private SystemService systemService; @Autowired @Mock private RenderService renderService; private String username = "username"; private String password = "password"; @Before public void setup() { MockitoAnnotations.initMocks( this ); PowerMockito.mockStatic( HttpUtils.class ); when( metadataSystemSettingService.getRemoteInstanceUserName() ).thenReturn( username ); when( metadataSystemSettingService.getRemoteInstancePassword() ).thenReturn( password ); } @Test public void testShouldVerifyIfStopSyncReturnFalseIfNoSystemVersionInLocal() { String versionSnapshot = "{\"system:\": {\"date\":\"2016-05-24T05:27:25.128+0000\", \"version\": \"2.26\"}, \"name\":\"testVersion\",\"created\":\"2016-05-26T11:43:59.787+0000\",\"type\":\"BEST_EFFORT\",\"id\":\"ktwh8PHNwtB\",\"hashCode\":\"12wa32d4f2et3tyt5yu6i\"}"; SystemInfo systemInfo = new SystemInfo(); when ( systemService.getSystemInfo() ).thenReturn( systemInfo ); boolean shouldStopSync = metadataSyncDelegate.shouldStopSync( versionSnapshot ); assertFalse(shouldStopSync); } @Test public void testShouldVerifyIfStopSyncReturnFalseIfNoSystemVersionInRemote() throws IOException { String versionSnapshot = "{\"system:\": {\"date\":\"2016-05-24T05:27:25.128+0000\", \"version\": \"2.26\"}, \"name\":\"testVersion\",\"created\":\"2016-05-26T11:43:59.787+0000\",\"type\":\"BEST_EFFORT\",\"id\":\"ktwh8PHNwtB\",\"hashCode\":\"12wa32d4f2et3tyt5yu6i\"}"; SystemInfo systemInfo = new SystemInfo(); systemInfo.setVersion( "2.26" ); when ( systemService.getSystemInfo() ).thenReturn( systemInfo ); when ( renderService.getSystemObject(any( ByteArrayInputStream.class), eq( RenderFormat.JSON ) ) ).thenReturn( null ); boolean shouldStopSync = metadataSyncDelegate.shouldStopSync( versionSnapshot ); assertFalse(shouldStopSync); } @Test public void testShouldVerifyIfStopSyncReturnTrueIfDHISVersionMismatch() throws IOException { String versionSnapshot = "{\"system:\": {\"date\":\"2016-06-24T05:27:25.128+0000\", \"version\": \"2.26\"}, \"name\":\"testVersion\",\"created\":\"2016-05-26T11:43:59.787+0000\",\"type\":\"BEST_EFFORT\",\"id\":\"ktwh8PHNwtB\"," + "\"hashCode\":\"12wa32d4f2et3tyt5yu6i\"}"; String systemNodeString = "{\"date\":\"2016-06-24T05:27:25.128+0000\", \"version\": \"2.26\"}"; SystemInfo systemInfo = new SystemInfo(); systemInfo.setVersion( "2.25" ); when( systemService.getSystemInfo() ).thenReturn( systemInfo ); when( metadataSystemSettingService.getStopMetadataSyncSetting() ).thenReturn( true ); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree( systemNodeString ); when( renderService.getSystemObject( any( ByteArrayInputStream.class), eq( RenderFormat.JSON ) ) ).thenReturn( jsonNode); boolean shouldStopSync = metadataSyncDelegate.shouldStopSync( versionSnapshot ); assertTrue(shouldStopSync); } @Test public void testShouldVerifyIfStopSyncReturnFalseIfDHISVersionSame() throws IOException { String versionSnapshot = "{\"system:\": {\"date\":\"2016-05-24T05:27:25.128+0000\", \"version\": \"2.26\"}, \"name\":\"testVersion\",\"created\":\"2016-05-26T11:43:59.787+0000\",\"type\":\"BEST_EFFORT\",\"id\":\"ktwh8PHNwtB\",\"hashCode\":\"12wa32d4f2et3tyt5yu6i\"}"; String systemNodeString = "{\"date\":\"2016-05-24T05:27:25.128+0000\", \"version\": \"2.26\"}"; SystemInfo systemInfo = new SystemInfo(); systemInfo.setVersion( "2.26" ); when( systemService.getSystemInfo() ).thenReturn( systemInfo ); when( metadataSystemSettingService.getStopMetadataSyncSetting() ).thenReturn( true ); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree( systemNodeString ); when( renderService.getSystemObject(any( ByteArrayInputStream.class), eq( RenderFormat.JSON ) ) ).thenReturn( jsonNode); boolean shouldStopSync = metadataSyncDelegate.shouldStopSync( versionSnapshot ); assertFalse(shouldStopSync); } @Test public void testShouldVerifyIfStopSyncReturnFalseIfStopSyncIsNotSet() throws IOException { String versionSnapshot = "{\"system:\": {\"date\":\"2016-05-24T05:27:25.128+0000\", \"version\": \"2.26\"}, \"name\":\"testVersion\",\"created\":\"2016-05-26T11:43:59.787+0000\",\"type\":\"BEST_EFFORT\",\"id\":\"ktwh8PHNwtB\",\"hashCode\":\"12wa32d4f2et3tyt5yu6i\"}"; SystemInfo systemInfo = new SystemInfo(); systemInfo.setVersion( "2.26" ); when( systemService.getSystemInfo() ).thenReturn( systemInfo ); when( metadataSystemSettingService.getStopMetadataSyncSetting() ).thenReturn( false ); boolean shouldStopSync = metadataSyncDelegate.shouldStopSync( versionSnapshot ); assertFalse(shouldStopSync); } }
package com.crawljax.browser; import com.crawljax.core.configuration.CrawljaxConfigurationReader; /** * This is the main interface for building a concrete EmbeddedBrowser implementation. By default * Crawljax uses and offers WebDriver implementation, but when other implementation is requested the * EmbeddedBrowser Interface must be implemented in a Class and a new class must be created * implementing the BrowserBuilder interface. This new class must be supplied as object to the * CrawljaxConfiguration.setBrowserBuilder(BrowserBuilder). * <p/> * This can be as simple as: * * <pre> * config.setBrowserBuilder(new BrowserBuilder() { * &#064;Override * public EmbeddedBrowser; buildEmbeddedBrowser(CrawljaxConfigurationReader configuration) { * return new WebDriverFirefox(configuration.getFilterAttributeNames(), * configuration.getCrawlSpecificationReader().getWaitAfterReloadUrl(), * configuration.getCrawlSpecificationReader().getWaitAfterEvent()); * } * }); * </pre> * * This interface offers a great flexibility and the possibility to retrieve the WebDriver core * classes to so more browser specific manipulation in plugins. * * @author Stefan Lenselink <S.R.Lenselink@student.tudelft.nl> * @version $Id$ */ public interface EmbeddedBrowserBuilder { /** * Build a new EmbeddedBrowser to be used during Crawling. This call is made everytime a new * Browser instance is requested. When running in Multi-Threaded modes with for example 4 * browsers 4 times a call will be made to this function. * * @param configuration * The configuration reader object to read the specific configuration options form. * @return the new created instance of a EmbeddedBrowser to be used. */ EmbeddedBrowser buildEmbeddedBrowser(CrawljaxConfigurationReader configuration); }
package io.realm.examples.realmintroexample; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.LinearLayout; import android.widget.TextView; import java.io.IOException; import io.realm.Realm; import io.realm.RealmResults; import io.realm.examples.realmintroexample.model.Cat; import io.realm.examples.realmintroexample.model.Dog; import io.realm.examples.realmintroexample.model.Person; public class RealmIntroExampleActivity extends Activity { public static final String TAG = RealmIntroExampleActivity.class.getName(); private LinearLayout rootLayout = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_realm_basic_example); rootLayout = ((LinearLayout) findViewById(R.id.container)); rootLayout.removeAllViews(); try { //These operations are small enough that //we can generally safely run them on the UI thread. basicReadWrite(); basicUpdate(); basicQuery(); } catch (IOException e) { e.printStackTrace(); } //More complex operations should not be //executed on the UI thread. new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { String info = null; try { info = complexReadWrite(); info += complexQuery(); } catch (IOException e) { e.printStackTrace(); } return info; } @Override protected void onPostExecute(String result) { showStatus(result); } }.execute(); } private void basicReadWrite() throws java.io.IOException { showStatus("Performing basic Read/Write operation..."); // Open a default realm Realm realm = new Realm(this); // Add a person in a write transaction realm.beginWrite(); Person person = realm.create(Person.class); person.setName("Happy Person"); person.setAge(14); realm.commit(); // Find first person person = realm.where(Person.class).findFirst(); showStatus(person.getName() + ":" + person.getAge()); } private void basicQuery() throws java.io.IOException { showStatus("\nPerforming basic Query operation..."); Realm realm = new Realm(this); showStatus("Number of persons: " + realm.allObjects(Person.class).size()); RealmResults<Person> results = realm.where(Person.class).equalTo("age", 99).findAll(); showStatus("Size of result set: " + results.size()); } private void basicUpdate() throws java.io.IOException { showStatus("\nPerforming basic Update operation..."); // Open a default realm Realm realm = new Realm(this); // Get the first object Person person = realm.where(Person.class).findFirst(); // Update person in a write transaction realm.beginWrite(); person.setName("Senior Person"); person.setAge(99); realm.commit(); showStatus(person.getName() + ":" + person.getAge()); } private void showStatus(String txt) { Log.i(TAG, txt); TextView tv = new TextView(this); tv.setText(txt); rootLayout.addView(tv); } private String complexReadWrite() throws IOException { String status = "\nPerforming complex Read/Write operation..."; // Open a default realm Realm realm = new Realm(this); // Add ten persons in one write transaction realm.beginWrite(); Dog fido = realm.create(Dog.class); fido.setName("fido"); for (int i = 0; i < 10; i++) { Person person = realm.create(Person.class); person.setName("Person no. " + i); person.setAge(i); person.setDog(fido); // The field tempReference is annotated with @Ignore. // This means setTempReference sets the Person tempReference // field directly. The tempReference is NOT saved as part of // the RealmObject: person.setTempReference(42); for (int j = 0; j < i; j++) { Cat cat = realm.create(Cat.class); cat.setName("Cat_" + j); person.getCats().add(cat); } } realm.commit(); // Implicit read transactions allow you to access your objects status += "\nNumber of persons: " + realm.allObjects(Person.class).size(); // Iterate over all objects for (Person pers : realm.allObjects(Person.class)) { String dogName; if (pers.getDog() == null) { dogName = "None"; } else { dogName = pers.getDog().getName(); } status += "\n" + pers.getName() + ":" + pers.getAge() + " : " + dogName + " : " + pers.getCats().size(); // The field tempReference is annotated with @Ignore // Though we initially set its value to 42, it has // not been saved as part of the Person RealmObject: assert(pers.getTempReference() == 0); } return status; } private String complexQuery() throws IOException { String status = "\n\nPerforming complex Query operation..."; Realm realm = new Realm(this); status += "\nNumber of persons: " + realm.allObjects(Person.class).size(); // Find all persons where age between 7 and 9 and name begins with "Person". RealmResults<Person> results = realm.where(Person.class) .between("age", 7, 9) // Notice implicit "and" operation .beginsWith("name", "Person").findAll(); status += "\nSize of result set: " + results.size(); return status; } }
package com.deathrayresearch.outlier.app.ui; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.MenuBar; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class Outlier extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Outlier!"); MenuBar menuBar = new MainMenu(primaryStage); VBox root = new VBox(); root.getChildren().add(menuBar); HBox main = new HBox(); root.getChildren().add(main); primaryStage.setScene(new Scene(root, 640, 480)); primaryStage.show(); } }
package com.devicehive.controller; import com.devicehive.auth.HiveRoles; import com.devicehive.json.strategies.JsonPolicyApply; import com.devicehive.json.strategies.JsonPolicyDef; import com.devicehive.model.Network; import com.devicehive.model.request.NetworkRequest; import com.devicehive.service.NetworkService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.security.RolesAllowed; import javax.inject.Inject; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.lang.annotation.Annotation; import java.util.List; /** * TODO JavaDoc */ @Path("/network") public class NetworkController { private static final Logger logger = LoggerFactory.getLogger(NetworkController.class); @Inject private NetworkService networkService; /** * Produces following output: * <pre> * [ * { * "description":"Network Description", * "id":1, * "key":"Network Key", * "name":"Network Name" * }, * { * "description":"Network Description", * "id":2, * "key":"Network Key", * "name":"Network Name" * } * ] * </pre> * * @param name exact network's name, ignored, when namePattern is not null * @param namePattern * @param sortField Sort Field, can be either "id", "key", "name" or "description" * @param sortOrder ASC - ascending, otherwise descending * @param take limit, default 1000 * @param skip offset, default 0 */ @GET @RolesAllowed(HiveRoles.ADMIN) @Produces(MediaType.APPLICATION_JSON) @JsonPolicyApply(JsonPolicyDef.Policy.NETWORKS_LISTED) public List<Network> getNetworkList(@QueryParam("name") String name, @QueryParam("namePattern") String namePattern, @QueryParam("sortField") String sortField, @QueryParam("sortOrder") String sortOrder, @QueryParam("take") Integer take, @QueryParam("skip") Integer skip) { return networkService.list(name, namePattern, sortField, "ASC".equals(sortOrder), take, skip); } /** * Generates JSON similar to this: * <pre> * { * "description":"Network Description", * "id":1, * "key":"Network Key", * "name":"Network Name" * } * </pre> * * @param id network id, can't be null */ @GET @Path("/{id}") @RolesAllowed(HiveRoles.ADMIN) @Produces(MediaType.APPLICATION_JSON) @JsonPolicyApply(JsonPolicyDef.Policy.NETWORK_PUBLISHED) public Network getNetworkList(@PathParam("id") long id) { return networkService.getWithDevicesAndDeviceClasses(id); } /** * Inserts new Network into database. Consumes next input: * <pre> * { * "key":"Network Key", * "name":"Network Name", * "description":"Network Description" * } * </pre> * Where * "key" is not required * "description" is not required * "name" is required * <p/> * In case of success will produce following output: * <pre> * { * "description":"Network Description", * "id":1, * "key":"Network Key", * "name":"Network Name" * } * </pre> * Where "description" and "key" will be provided, if they are specified in request. * Fields "id" and "name" will be provided anyway. * */ @POST @RolesAllowed(HiveRoles.ADMIN) @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response insert(NetworkRequest nr) { Network n = new Network(); //TODO: if request if malformed this code will fall with NullPointerException n.setKey(nr.getKey().getValue()); n.setDescription(nr.getDescription().getValue()); n.setName(nr.getName().getValue()); Network result = networkService.insert(n); Annotation[] annotations = {new JsonPolicyApply.JsonPolicyApplyLiteral(JsonPolicyDef.Policy.NETWORK_SUBMITTED)}; return Response.status(Response.Status.CREATED).entity(result,annotations).build(); } /** * This method updates network with given Id. Consumes following input: * <pre> * { * "key":"Network Key", * "name":"Network Name", * "description":"Network Description" * } * </pre> * Where * "key" is not required * "description" is not required * "name" is not required * Fields, that are not specified will stay unchanged * Method will produce following output: * <pre> * { * "description":"Network Description", * "id":1, * "key":"Network Key", * "name":"Network Name" * } * </pre> */ @PUT @Path("/{id}") @RolesAllowed(HiveRoles.ADMIN) @Produces(MediaType.APPLICATION_JSON) public Response update(NetworkRequest nr, @PathParam("id") long id) { nr.setId(id); Network n = networkService.getById(id); if (nr.getKey() != null) { n.setKey(nr.getKey().getValue()); } if (nr.getName() != null) { n.setName(nr.getName().getValue()); } if (nr.getDescription() != null) { n.setDescription(nr.getDescription().getValue()); } networkService.update(n); return Response.status(Response.Status.CREATED).build(); } /** * Deletes network by specified id. * If success, outputs empty response * * @param id network's id */ @DELETE @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed(HiveRoles.ADMIN) public Response delete(@PathParam("id") long id) { networkService.delete(id); return Response.status(Response.Status.NO_CONTENT).build(); } }
package com.ericsson.eiffel.remrem.generate.cli; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.tomcat.util.http.fileupload.FileUtils; import com.ericsson.eiffel.remrem.semantics.SemanticsService; import com.ericsson.eiffel.remrem.shared.MsgService; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * @author evasiba * */ public class CLI { private Options options=null; public CLI() { options = createCLIOptions(); } /** * Creates the options needed by command line interface * @return */ private static Options createCLIOptions() { Options options = new Options(); options.addOption("h", "help", false, "show help."); options.addOption("f", "content_file", true, "message content file"); options.addOption("t", "message_type", true, "message type, mandatory if -f is given"); options.addOption("r", "response_file", true, "file to store the response in, mandatory if -f is given"); return options; } /** * Prints the help for this application and exits. * @param options */ private static void help(Options options) { // This prints out some help HelpFormatter formater = new HelpFormatter(); formater.printHelp("java -jar", options); System.exit(0); } /** * Parse the given arguments * @param args * @return */ public boolean parse(String[] args) { CommandLineParser parser = new DefaultParser(); boolean startService = true; try { CommandLine commandLine = parser.parse(options, args); Option[] existingOptions = commandLine.getOptions(); if (existingOptions.length > 0) { startService = false; } if (commandLine.hasOption("h")) { help(options); } if (commandLine.hasOption("f") && commandLine.hasOption("t") && commandLine.hasOption("r")) { String filePath = commandLine.getOptionValue("f"); String responseFilePath = commandLine.getOptionValue("r"); String msgType = commandLine.getOptionValue("t"); handleContentFile(msgType, filePath, responseFilePath); } } catch (Exception e) { help(options); } return startService; } public void handleContentFile(String msgType, String filePath, String responseFilePath) { JsonParser parser = new JsonParser(); MsgService msgService = new SemanticsService(); try { byte[] fileBytes = Files.readAllBytes(Paths.get(filePath)); String fileContent = new String(fileBytes); JsonObject bodyJson = parser.parse(fileContent).getAsJsonObject(); JsonElement returnJson = parser.parse(msgService.generateMsg(msgType, bodyJson)); Gson gson = new Gson(); String returnJsonStr = gson.toJson(returnJson); try( PrintWriter out = new PrintWriter( responseFilePath ) ){ out.println( returnJsonStr ); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.ezardlabs.lostsector.objects.menus; import com.ezardlabs.dethsquare.GameObject; import com.ezardlabs.dethsquare.GuiRenderer; import com.ezardlabs.dethsquare.GuiText; import com.ezardlabs.dethsquare.Input; import com.ezardlabs.dethsquare.Input.KeyCode; import com.ezardlabs.dethsquare.Script; import com.ezardlabs.dethsquare.TextureAtlas; import com.ezardlabs.dethsquare.Vector2; public class Menu extends Script { private final String[] options; private final MenuAction[] actions; private final Vector2 offset; private TextureAtlas font; private GameObject background; private GameObject[] texts; private GuiText[] guiTexts; private boolean open = false; public Menu(String[] options, MenuAction[] actions) { this(options, actions, new Vector2(), false); } public Menu(String[] options, MenuAction[] actions, boolean open) { this(options, actions, new Vector2(), open); } public Menu(String[] options, MenuAction[] actions, Vector2 offset) { this(options, actions, offset, false); } public Menu(String[] options, MenuAction[] actions, Vector2 offset, boolean open) { this.options = options; this.actions = actions; this.offset = offset; this.open = open; if (options.length < 1 || options.length > 4) { throw new Error("You must supply between 1 and 4 options to the menu"); } font = new TextureAtlas("fonts/atlas.png", "fonts/atlas.txt"); } @Override public void start() { float height = (2 * options.length + 1) * 50; background = new GameObject("Menu", new GuiRenderer("images/menus/main/menu" + options.length + ".png", 400, height)); background = GameObject.instantiate(background, new Vector2(-10000, -10000)); texts = new GameObject[options.length]; guiTexts = new GuiText[options.length]; for (int i = 0; i < texts.length; i++) { guiTexts[i] = new GuiText(options[i], font, 50, 1); texts[i] = GameObject.instantiate(new GameObject("Menu Option", guiTexts[i]), new Vector2(-10000, -10000)); } if (open) { open(); } } @Override public void update() { if (open && guiTexts != null && Input.getKeyDown(KeyCode.MOUSE_LEFT)) { for (int i = 0; i < guiTexts.length; i++) { if (guiTexts[i].hitTest(Input.mousePosition)) { actions[i].onMenuItemSelected(this, i, options[i]); return; } } } } public void open() { open = true; float height = (2 * options.length + 1) * 50; background.transform.position.set(1920 / 2 - 200 + offset.x, 1080 / 2 - ((2 * options.length + 1) * 50) / 2 + offset.y); for (int i = 0; i < texts.length; i++) { texts[i].transform.position.set(1920 / 2f - guiTexts[i].getWidth() / 2f + offset.x, 1080 / 2 - height / 2 + (1 + i * 2) * 50 + offset.y); } } public void close() { open = false; // TODO implement GameObject/Component enabling/disabling in Dethsquare so this is neater background.transform.position.set(-10000, -10000); for (GameObject text : texts) { text.transform.position.set(-10000, -10000); } } public boolean isOpen() { return open; } public interface MenuAction { void onMenuItemSelected(Menu menu, int index, String text); } }
package com.faforever.client.chat; import com.faforever.client.chat.event.ChatMessageEvent; import com.faforever.client.chat.event.ChatUserCategoryChangeEvent; import com.faforever.client.chat.event.ChatUserColorChangeEvent; import com.faforever.client.config.ClientProperties; import com.faforever.client.config.ClientProperties.Irc; import com.faforever.client.domain.PlayerBean; import com.faforever.client.fx.JavaFxUtil; import com.faforever.client.net.ConnectionState; import com.faforever.client.player.PlayerOfflineEvent; import com.faforever.client.player.PlayerOnlineEvent; import com.faforever.client.player.PlayerService; import com.faforever.client.player.SocialStatus; import com.faforever.client.preferences.ChatPrefs; import com.faforever.client.preferences.PreferencesService; import com.faforever.client.remote.FafServerAccessor; import com.faforever.client.ui.tray.event.UpdateApplicationBadgeEvent; import com.faforever.client.user.UserService; import com.faforever.client.user.event.LoggedOutEvent; import com.faforever.client.user.event.LoginSuccessEvent; import com.faforever.commons.lobby.IrcPasswordInfo; import com.faforever.commons.lobby.Player.LeaderboardStats; import com.faforever.commons.lobby.SocialInfo; import com.google.common.annotations.VisibleForTesting; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.google.common.hash.Hashing; import javafx.beans.InvalidationListener; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyIntegerProperty; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.MapChangeListener; import javafx.collections.ObservableList; import javafx.collections.ObservableMap; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import net.engio.mbassy.listener.Handler; import org.jetbrains.annotations.NotNull; import org.kitteh.irc.client.library.Client; import org.kitteh.irc.client.library.Client.Builder.Server.SecurityType; import org.kitteh.irc.client.library.defaults.DefaultClient; import org.kitteh.irc.client.library.element.Channel; import org.kitteh.irc.client.library.element.User; import org.kitteh.irc.client.library.element.mode.ChannelUserMode; import org.kitteh.irc.client.library.element.mode.Mode; import org.kitteh.irc.client.library.element.mode.ModeStatus.Action; import org.kitteh.irc.client.library.event.channel.ChannelCtcpEvent; import org.kitteh.irc.client.library.event.channel.ChannelJoinEvent; import org.kitteh.irc.client.library.event.channel.ChannelMessageEvent; import org.kitteh.irc.client.library.event.channel.ChannelModeEvent; import org.kitteh.irc.client.library.event.channel.ChannelNamesUpdatedEvent; import org.kitteh.irc.client.library.event.channel.ChannelPartEvent; import org.kitteh.irc.client.library.event.channel.ChannelTopicEvent; import org.kitteh.irc.client.library.event.client.ClientNegotiationCompleteEvent; import org.kitteh.irc.client.library.event.connection.ClientConnectionEndedEvent; import org.kitteh.irc.client.library.event.user.PrivateMessageEvent; import org.kitteh.irc.client.library.event.user.PrivateNoticeEvent; import org.kitteh.irc.client.library.event.user.UserQuitEvent; import org.kitteh.irc.client.library.event.user.WhoisEvent; import org.kitteh.irc.client.library.feature.auth.NickServ; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static com.faforever.client.chat.ChatColorMode.DEFAULT; import static com.faforever.client.chat.ChatUserCategory.MODERATOR; import static java.util.Locale.US; import static javafx.collections.FXCollections.observableHashMap; import static javafx.collections.FXCollections.observableMap; @Lazy @Service @Slf4j @RequiredArgsConstructor public class KittehChatService implements ChatService, InitializingBean, DisposableBean { private static final Logger ircLog = LoggerFactory.getLogger("faf-irc"); public static final int MAX_GAMES_FOR_NEWBIE_CHANNEL = 50; private static final String NEWBIE_CHANNEL_NAME = "#newbie"; private static final Set<Character> MODERATOR_PREFIXES = Set.of('~', '&', '@', '%'); private final ChatUserService chatUserService; private final PreferencesService preferencesService; private final UserService userService; private final FafServerAccessor fafServerAccessor; private final EventBus eventBus; private final ClientProperties clientProperties; private final PlayerService playerService; /** * Maps channels by name. */ private final ObservableMap<String, ChatChannel> channels = observableHashMap(); /** Key is the result of {@link #mapKey(String, String)}. */ private final ObservableMap<String, ChatChannelUser> chatChannelUsersByChannelAndName = observableMap(new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); private final SimpleIntegerProperty unreadMessagesCount = new SimpleIntegerProperty(); @VisibleForTesting ObjectProperty<ConnectionState> connectionState = new SimpleObjectProperty<>(ConnectionState.DISCONNECTED); @VisibleForTesting String defaultChannelName; @VisibleForTesting DefaultClient client; private NickServ nickServ; private String username; private String password; /** * A list of channels the server wants us to join. */ private List<String> autoChannels; @Override public void afterPropertiesSet() { eventBus.register(this); fafServerAccessor.addEventListener(SocialInfo.class, this::onSocialMessage); connectionState.addListener((observable, oldValue, newValue) -> { switch (newValue) { case DISCONNECTED, CONNECTING -> onDisconnected(); } }); ChatPrefs chatPrefs = preferencesService.getPreferences().getChat(); JavaFxUtil.addListener(chatPrefs.userToColorProperty(), (InvalidationListener) change -> preferencesService.storeInBackground() ); JavaFxUtil.addListener(chatPrefs.groupToColorProperty(), (InvalidationListener) change -> { preferencesService.storeInBackground(); updateUserColors(chatPrefs.getChatColorMode()); } ); JavaFxUtil.addListener(chatPrefs.chatColorModeProperty(), (observable, oldValue, newValue) -> updateUserColors(newValue)); } private void updateUserColors(ChatColorMode chatColorMode) { if (chatColorMode == null) { chatColorMode = DEFAULT; } ChatPrefs chatPrefs = preferencesService.getPreferences().getChat(); synchronized (chatChannelUsersByChannelAndName) { if (chatColorMode == ChatColorMode.RANDOM) { chatChannelUsersByChannelAndName.values() .forEach(chatUser -> chatUser.setColor(ColorGeneratorUtil.generateRandomColor(chatUser.getUsername().hashCode()))); } else { chatChannelUsersByChannelAndName.values() .forEach(chatUser -> { if (chatPrefs.getUserToColor().containsKey(userToColorKey(chatUser.getUsername()))) { chatUser.setColor(chatPrefs.getUserToColor().get(userToColorKey(chatUser.getUsername()))); } else { if (chatUser.isModerator() && chatPrefs.getGroupToColor().containsKey(MODERATOR)) { chatUser.setColor(chatPrefs.getGroupToColor().get(MODERATOR)); } else { chatUser.setColor(chatUser.getSocialStatus() .map(status -> chatPrefs.getGroupToColor().getOrDefault(groupToColorKey(status), null)) .orElse(null)); } } eventBus.post(new ChatUserColorChangeEvent(chatUser)); }); } } } @NotNull private String userToColorKey(String username) { return username.toLowerCase(US); } @NotNull private ChatUserCategory groupToColorKey(SocialStatus socialStatus) { return switch (socialStatus) { case FRIEND -> ChatUserCategory.FRIEND; case FOE -> ChatUserCategory.FOE; default -> ChatUserCategory.OTHER; }; } @Override public boolean userExistsInAnyChannel(String username) { return client.getChannels().stream().anyMatch(channel -> channel.getUser(username).isPresent()); } @Override public ChatChannelUser getOrCreateChatUser(String username, String channelName) { Channel channel = client.getChannel(channelName).orElseThrow(() -> new IllegalArgumentException("Channel '" + channelName + "' is unknown")); User user = channel.getUser(username).orElseThrow(() -> new IllegalArgumentException("Chat user '" + username + "' is unknown for channel '" + channelName + "'")); return getOrCreateChatUser(user, channel); } private ChatChannelUser getOrCreateChatUser(User user, Channel channel) { String username = user.getNick(); boolean isModerator = channel.getUserModes(user).stream().flatMap(Collection::stream) .map(ChannelUserMode::getNickPrefix) .anyMatch(MODERATOR_PREFIXES::contains); return getOrCreateChatUser(username, channel.getName(), isModerator); } @Subscribe public void onIrcPassword(IrcPasswordInfo event) { username = userService.getUsername(); password = Hashing.md5().hashString(event.getPassword(), StandardCharsets.UTF_8).toString(); if (connectionState.get() == ConnectionState.DISCONNECTED) { connect(); } } @Subscribe public void onLoggedOutEvent(LoggedOutEvent event) { disconnect(); eventBus.post(UpdateApplicationBadgeEvent.ofNewValue(0)); } @Subscribe public void onLoggedInEvent(LoginSuccessEvent event) { if (userService.getOwnPlayer().getRatings().values().stream().mapToInt(LeaderboardStats::getNumberOfGames).sum() < MAX_GAMES_FOR_NEWBIE_CHANNEL) { joinChannel(NEWBIE_CHANNEL_NAME); } } @Subscribe public void onPlayerOnline(PlayerOnlineEvent event) { PlayerBean player = event.getPlayer(); synchronized (channels) { channels.values().parallelStream() .map(channel -> chatChannelUsersByChannelAndName.get(mapKey(player.getUsername(), channel.getName()))) .filter(Objects::nonNull) .forEach(chatChannelUser -> { chatUserService.associatePlayerToChatUser(chatChannelUser, player); eventBus.post(new ChatUserCategoryChangeEvent(chatChannelUser)); }); } } @Handler public void onConnect(ClientNegotiationCompleteEvent event) { connectionState.set(ConnectionState.CONNECTED); channels.keySet().forEach(this::joinChannel); joinSavedAutoChannels(); } @Handler private void onJoinEvent(ChannelJoinEvent event) { User user = event.getActor(); ircLog.debug("User joined channel: {}", user); addUserToChannel(event.getChannel().getName(), getOrCreateChatUser(user, event.getChannel())); } @Handler public void onChatUserList(ChannelNamesUpdatedEvent event) { Channel channel = event.getChannel(); List<ChatChannelUser> users = channel.getUsers().stream().map(user -> getOrCreateChatUser(user, channel)).collect(Collectors.toList()); getOrCreateChannel(channel.getName()).addUsers(users); } @Handler private void onPartEvent(ChannelPartEvent event) { User user = event.getActor(); ircLog.debug("User left channel: {}", user); onChatUserLeftChannel(event.getChannel().getName(), user.getNick()); } @Handler private void onChatUserQuit(UserQuitEvent event) { User user = event.getUser(); synchronized (channels) { channels.values().forEach(channel -> onChatUserLeftChannel(channel.getName(), user.getNick())); } } @Handler private void onTopicChange(ChannelTopicEvent event) { Channel channel = event.getChannel(); getOrCreateChannel(channel.getName()).setTopic(event.getNewTopic().getValue().orElse("")); } @Handler private void onChannelMessage(ChannelMessageEvent event) { User user = event.getActor(); String source = event.getChannel().getName(); eventBus.post(new ChatMessageEvent(new ChatMessage(source, Instant.now(), user.getNick(), event.getMessage(), false))); } @Handler private void onChannelCTCP(ChannelCtcpEvent event) { User user = event.getActor(); Channel channel = event.getChannel(); String source = channel.getName(); eventBus.post(new ChatMessageEvent(new ChatMessage(source, Instant.now(), user.getNick(), event.getMessage().replace("ACTION", user.getNick()), true))); } @Handler private void onChannelModeChanged(ChannelModeEvent event) { ChatChannel channel = getOrCreateChannel(event.getChannel().getName()); event.getStatusList().getAll().forEach(channelModeStatus -> channelModeStatus.getParameter().ifPresent(username -> { Mode changedMode = channelModeStatus.getMode(); Action modeAction = channelModeStatus.getAction(); if (changedMode instanceof ChannelUserMode) { if (MODERATOR_PREFIXES.contains(((ChannelUserMode) changedMode).getNickPrefix())) { ChatChannelUser chatChannelUser = getOrCreateChatUser(username, channel.getName(), false); if (modeAction == Action.ADD) { chatChannelUser.setModerator(true); } else if (modeAction == Action.REMOVE) { chatChannelUser.setModerator(false); } eventBus.post(new ChatUserCategoryChangeEvent(chatChannelUser)); } } })); } @Handler private void onPrivateMessage(PrivateMessageEvent event) { User user = event.getActor(); ircLog.debug("Received private message: {}", event); ChatChannelUser sender = getOrCreateChatUser(user.getNick(), user.getNick(), false); if (sender.getPlayer().map(PlayerBean::getSocialStatus).filter(status -> status == SocialStatus.FOE).isPresent() && preferencesService.getPreferences().getChat().getHideFoeMessages()) { ircLog.debug("Suppressing chat message from foe '{}'", user.getNick()); return; } eventBus.post(new ChatMessageEvent(new ChatMessage(user.getNick(), Instant.now(), user.getNick(), event.getMessage()))); } @Handler private void onWhoIs(WhoisEvent event) { if (event.getWhoisData().getRealName().map(realName -> username.equals(realName)).orElse(false)) { nickServ.startAuthentication(); } } @Handler private void onNotice(PrivateNoticeEvent event) { String message = event.getMessage(); if (message.contains("isn't registered")) { client.sendMessage("NickServ", String.format("register %s %s@users.faforever.com", password, client.getNick())); } else if (message.contains("you are now recognized")) { client.sendMessage("NickServ", String.format("recover %s", username)); } else if (message.contains("You have regained control")) { client.setNick(username); } } private void joinAutoChannels() { log.debug("Joining auto channel: {}", autoChannels); if (autoChannels == null) { return; } autoChannels.forEach(this::joinChannel); } private void joinSavedAutoChannels() { ObservableList<String> savedAutoChannels = preferencesService.getPreferences().getChat().getAutoJoinChannels(); if (savedAutoChannels == null) { return; } log.debug("Joining user's saved auto channel: {}", savedAutoChannels); savedAutoChannels.forEach(this::joinChannel); } private void onDisconnected() { synchronized (channels) { channels.values().forEach(ChatChannel::clearUsers); } synchronized (chatChannelUsersByChannelAndName) { chatChannelUsersByChannelAndName.clear(); } } private void addUserToChannel(String channelName, ChatChannelUser chatUser) { getOrCreateChannel(channelName).addUser(chatUser); if (chatUser.isModerator()) { onModeratorSet(channelName, chatUser.getUsername()); } } private void onChatUserLeftChannel(String channelName, String username) { ChatChannelUser oldChatUser = getOrCreateChannel(channelName).removeUser(username); if (oldChatUser == null) { return; } ircLog.debug("User '{}' left channel: {}", username, channelName); if (client.getNick().equalsIgnoreCase(username)) { synchronized (channels) { channels.remove(channelName); } } synchronized (chatChannelUsersByChannelAndName) { chatChannelUsersByChannelAndName.remove(mapKey(username, channelName)); } // The server doesn't yet tell us when a user goes offline, so we have to rely on the user leaving IRC. if (defaultChannelName.equals(channelName)) { oldChatUser.getPlayer().ifPresent(player -> eventBus.post(new PlayerOfflineEvent(player))); } } private void onMessage(String message) { message = message.replace(password, "*****"); ircLog.debug(message); } @Handler private void onDisconnect(ClientConnectionEndedEvent event) { connectionState.set(ConnectionState.DISCONNECTED); } private void onSocialMessage(SocialInfo socialMessage) { this.autoChannels = new ArrayList<>(socialMessage.getChannels()); autoChannels.remove(defaultChannelName); autoChannels.add(0, defaultChannelName); joinAutoChannels(); } @Override public void connect() { Irc irc = clientProperties.getIrc(); this.defaultChannelName = irc.getDefaultChannel(); client = (DefaultClient) Client.builder() .user(String.valueOf(userService.getUserId())) .realName(username) .nick(username) .server() .host(irc.getHost()) .port(irc.getPort(), SecurityType.SECURE) .secureTrustManagerFactory(new TrustEveryoneFactory()) .then() .listeners() .input(this::onMessage) .output(this::onMessage) .then() .build(); nickServ = NickServ.builder(client) .account(username) .password(password) .build(); client.getEventManager().registerEventListener(this); client.getActorTracker().setQueryChannelInformation(false); client.connect(); } @Override public void disconnect() { log.info("Disconnecting from IRC"); client.shutdown("Goodbye"); } @Override public CompletableFuture<String> sendMessageInBackground(String target, String message) { eventBus.post(new ChatMessageEvent(new ChatMessage(target, Instant.now(), client.getNick(), message))); return CompletableFuture.supplyAsync(() -> { client.sendMessage(target, message); return message; }); } @Override public ChatChannel getOrCreateChannel(String channelName) { synchronized (channels) { return channels.computeIfAbsent(channelName, ChatChannel::new); } } @Override public ChatChannelUser getOrCreateChatUser(String username, String channel, boolean isModerator) { String key = mapKey(username, channel); synchronized (chatChannelUsersByChannelAndName) { return chatChannelUsersByChannelAndName.computeIfAbsent(key, s -> { ChatChannelUser chatChannelUser = new ChatChannelUser(username, channel, isModerator); playerService.getPlayerByNameIfOnline(username) .ifPresentOrElse(player -> chatUserService.associatePlayerToChatUser(chatChannelUser, player), () -> chatUserService.populateColor(chatChannelUser)); return chatChannelUser; }); } } @Override public void addUsersListener(String channelName, MapChangeListener<String, ChatChannelUser> listener) { getOrCreateChannel(channelName).addUsersListeners(listener); } @Override public void addChatUsersByNameListener(MapChangeListener<String, ChatChannelUser> listener) { JavaFxUtil.addListener(chatChannelUsersByChannelAndName, listener); } @Override public void addChannelsListener(MapChangeListener<String, ChatChannel> listener) { JavaFxUtil.addListener(channels, listener); } @Override public void removeUsersListener(String channelName, MapChangeListener<String, ChatChannelUser> listener) { getOrCreateChannel(channelName).removeUserListener(listener); } @Override public void leaveChannel(String channelName) { client.removeChannel(channelName); } @Override public CompletableFuture<String> sendActionInBackground(String target, String action) { return CompletableFuture.supplyAsync(() -> { client.sendCtcpMessage(target, "ACTION " + action); return action; }); } @Override public void joinChannel(String channelName) { log.debug("Joining channel: {}", channelName); client.addChannel(channelName); } @Override public boolean isDefaultChannel(String channelName) { return defaultChannelName.equals(channelName); } @Override public void destroy() { close(); } public void close() { if (client != null) { client.shutdown(); } } @Override public ReadOnlyObjectProperty<ConnectionState> connectionStateProperty() { return connectionState; } @Override public void reconnect() { client.reconnect(); } @Override public void whois(String username) { client.sendRawLine("WHOIS " + username); } @Override public void incrementUnreadMessagesCount(int delta) { eventBus.post(UpdateApplicationBadgeEvent.ofDelta(delta)); } @Override public ReadOnlyIntegerProperty unreadMessagesCount() { return unreadMessagesCount; } @Override public String getDefaultChannelName() { return defaultChannelName; } private void onModeratorSet(String channelName, String username) { getOrCreateChatUser(username, channelName, true).setModerator(true); } private String mapKey(String username, String channelName) { return username + channelName; } }
package com.fasterxml.jackson.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker annotation that indicates that the logical property that * the accessor (field, getter/setter method or Creator parameter * [of {@link JsonCreator}-annotated constructor or factory method]) * is to be ignored by introspection-based * serialization and deserialization functionality. * Annotation only needs to be added to one of the accessors (often * getter method, but may be setter, field or creator parameter), * if the complete removal of the property is desired. * However: if only particular accessor is to be ignored (for example, * when ignoring one of potentially conflicting setter methods), * this can be done by annotating other not-to-be-ignored accessors * with {@link JsonProperty} (or its equivalents). This is considered * so-called "split property" case and allows definitions of * "read-only" (read from input into POJO) and "write-only" (write * in output but ignore on output) *<p> * For example, a "getter" method that would otherwise denote * a property (like, say, "getValue" to suggest property "value") * to serialize, would be ignored and no such property would * be output unless another annotation defines alternative method to use. *<p> * When ignoring the whole property, the default behavior if encountering * such property in input is to ignore it without exception; but if there * is a {@link JsonAnySetter} it will be called instead. Either way, * no exception will be thrown. *<p> * Annotation is usually used just a like a marker annotation, that * is, without explicitly defining 'value' argument (which defaults * to <code>true</code>): but argument can be explicitly defined. * This can be done to override an existing `JsonIgnore` by explicitly * defining one with 'false' argument: either in a sub-class, or by * using "mix-in annotations". */ @Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotation public @interface JsonIgnore { /** * Optional argument that defines whether this annotation is active * or not. The only use for value 'false' if for overriding purposes * (which is not needed often); most likely it is needed for use * with "mix-in annotations" (aka "annotation overrides"). * For most cases, however, default value of "true" is just fine * and should be omitted. */ boolean value() default true; }
package com.five35.minecraft.deathbox; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.Explosion; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class DeathBoxBlock extends Block implements ITileEntityProvider { DeathBoxBlock() { super(DeathBoxMaterial.getInstance()); this.disableStats(); this.setHardness(-1); // == unbreakable } @Override public boolean canEntityDestroy(final IBlockAccess world, final int x, final int y, final int z, final Entity entity) { return false; } @Override public boolean canHarvestBlock(final EntityPlayer player, final int meta) { return false; } @Override public boolean canPlaceBlockAt(final World world, final int x, final int y, final int z) { return false; } @Override public TileEntity createNewTileEntity(final World world, final int metadata) { return new DeathBoxTileEntity(); } @Override public ItemStack getPickBlock(final MovingObjectPosition target, final World world, final int x, final int y, final int z) { return null; } @Override public boolean isCollidable() { return false; } @Override public boolean isOpaqueCube() { return false; } @Override public boolean onBlockActivated(final World world, final int x, final int y, final int z, final EntityPlayer player, final int side, final float xOffset, final float yOffset, final float zOffset) { final TileEntity tileEntity = world.getTileEntity(x, y, z); if (tileEntity instanceof DeathBoxTileEntity) { final DeathBoxTileEntity deathBox = (DeathBoxTileEntity) tileEntity; if (DeathBox.INSTANCE.config.canRecover(deathBox.getOwnerName(), player)) { deathBox.recover(player); return true; } } return false; } @Override public void onBlockClicked(final World world, final int x, final int y, final int z, final EntityPlayer player) { final TileEntity tileEntity = world.getTileEntity(x, y, z); if (tileEntity instanceof DeathBoxTileEntity) { final DeathBoxTileEntity deathBox = (DeathBoxTileEntity) tileEntity; if (DeathBox.INSTANCE.config.canPop(deathBox.getOwnerName(), player)) { deathBox.pop(); } } } @Override public void onBlockExploded(final World world, final int x, final int y, final int z, final Explosion explosion) { // DeathBox is unexplodable! } @Override public void registerBlockIcons(final IIconRegister p_149651_1_) { // TODO Auto-generated method stub super.registerBlockIcons(p_149651_1_); } @Override public boolean removedByPlayer(final World world, final EntityPlayer player, final int x, final int y, final int z) { return false; } }
package com.github.cta.extractor; import opennlp.tools.tokenize.SimpleTokenizer; import opennlp.tools.tokenize.Tokenizer; import java.util.ArrayList; import java.util.List; /** * @author Krzysztof Langner on 17.05.15. */ public class EcogScoreExtractor { private static final Tokenizer TOKENIZER = SimpleTokenizer.INSTANCE; /** * Find score based on given text * If score can't be read based on given text, then by default it is 4. */ public static List<Integer> findScore(String text){ boolean inclusionCriteria = true; String[] lines = text.toLowerCase().split("\n\n"); for(String line : lines) { String[] sentences = line.split("\\."); for(String sentence : sentences) { String[] tokens = TOKENIZER.tokenize(sentence); if(isExclusionHeader(tokens)){ inclusionCriteria = false; } else if (hasToken("ecog", tokens)) { List<Integer> scores = scoreFromSentence(tokens, inclusionCriteria); if(scores.size() > 0) return scores; } } } return new ArrayList<Integer>(); } /** Exclusion header should have the following words: * "Inclusion" and "Criteria" */ public static boolean isExclusionHeader(String[] tokens){ return hasToken("exclusion", tokens) && hasToken("criteria", tokens); } /** Check if given token is on the list */ private static boolean hasToken(String pattern, String[] tokens){ for(String token : tokens){ if(token.equals(pattern)) return true; } return false; } /** Extract score from the single sentence */ private static List<Integer> scoreFromSentence(String[] tokens, boolean inclusive) { List<String> normalizedTokens = TokenTranslator.normalizeTokens(tokens); List<Integer> scores = scoreFromRange(normalizedTokens); if(scores.size() == 0) scores = scoreFromRelation(normalizedTokens, inclusive); if(scores.size() == 0) scores = scoreFromNumbers(normalizedTokens); return scores; } /** Try to extract score by finding range (0-3) in text. */ private static List<Integer> scoreFromRange(List<String> tokens) { List<Integer> scores = new ArrayList<Integer>(); for(int i = 0; i < tokens.size()-2; i++){ if(isEcogScore(tokens.get(i)) && tokens.get(i+1).equals("-") && isEcogScore(tokens.get(i+2))){ int start = Integer.parseInt(tokens.get(i)); int end = Integer.parseInt(tokens.get(i+2)); for(int j = start; j <= end; j++){ scores.add(j); } break; } } return scores; } /** Try to extract score by finding ralation (< 3) in text. */ private static List<Integer> scoreFromRelation(List<String> tokens, boolean inclusion) { boolean ecogKeyword = false; for(int i = 0; i < tokens.size()-1; i++){ if(tokens.get(i).equals("ecog")) ecogKeyword = true; String token = tokens.get(i); if(isEcogScore(tokens.get(i+1))){ int ecog = Integer.parseInt(tokens.get(i+1)); if(token.equals(">")){ return listFromScoreRange(0, ecog); } else if(token.equals("<")){ return listFromScoreRange(0, ecog-1); } else if(token.equals(">=")){ return listFromScoreRange(0, ecog-1); } else if(token.equals("<=")){ return listFromScoreRange(0, ecog); } else if(token.equals("=")){ return listFromScoreRange(ecog, ecog); } else if(ecogKeyword){ // If there was ecog keyword and there is score but no relation then // we should look father return new ArrayList<Integer>(); } } } return new ArrayList<Integer>(); } /** Try to extract score by finding all numbers in text in ECOG range (0-4) */ private static List<Integer> scoreFromNumbers(List<String> tokens) { int score = -1; for(String token : tokens){ if(isEcogScore(token)){ int v = Integer.parseInt(token); if(v < 5 && v > score){ score = v; } } } return listFromScoreRange(0, score); } /** Convert range to list elements */ private static List<Integer> listFromScoreRange(int from, int to){ List<Integer> scores = new ArrayList<Integer>(); for(int i = from; i <= to; i++){ scores.add(i); } return scores; } /** Check if given token represents ECOG score. Must be a number from 0 to 5 */ private static boolean isEcogScore(String token){ if(token.length() == 1) { char c = token.charAt(0); return (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5'); } return false; } }
package com.github.dockerjava.core; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.dockerjava.api.model.AuthConfig; import com.github.dockerjava.api.model.AuthConfigurations; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @JsonIgnoreProperties(ignoreUnknown = true) public class DockerConfigFile { private static final String DOCKER_LEGACY_CFG = ".dockercfg"; private static final String DOCKER_CFG = "config.json"; private static final ObjectMapper MAPPER = new ObjectMapper(); private static final TypeReference<Map<String, AuthConfig>> CONFIG_MAP_TYPE = new TypeReference<Map<String, AuthConfig>>() { }; @JsonProperty private final Map<String, AuthConfig> auths; public DockerConfigFile() { this(new HashMap<String, AuthConfig>()); } private DockerConfigFile(Map<String, AuthConfig> authConfigMap) { auths = authConfigMap; } @Nonnull public Map<String, AuthConfig> getAuths() { return auths; } void addAuthConfig(AuthConfig config) { auths.put(config.getRegistryAddress(), config); } @CheckForNull public AuthConfig resolveAuthConfig(@CheckForNull String hostname) { if (StringUtils.isEmpty(hostname) || AuthConfig.DEFAULT_SERVER_ADDRESS.equals(hostname)) { return auths.get(AuthConfig.DEFAULT_SERVER_ADDRESS); } AuthConfig c = auths.get(hostname); if (c != null) { return c; } // Maybe they have a legacy config file, we will iterate the keys converting // them to the new format and testing String normalizedHostname = convertToHostname(hostname); for (Map.Entry<String, AuthConfig> entry : auths.entrySet()) { String registry = entry.getKey(); AuthConfig config = entry.getValue(); if (convertToHostname(registry).equals(normalizedHostname)) { return config; } } return null; } @Nonnull public AuthConfigurations getAuthConfigurations() { final AuthConfigurations authConfigurations = new AuthConfigurations(); for (Map.Entry<String, AuthConfig> authConfigEntry : auths.entrySet()) { authConfigurations.addConfig(authConfigEntry.getValue()); } return authConfigurations; } // CHECKSTYLE:OFF @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((auths == null) ? 0 : auths.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DockerConfigFile other = (DockerConfigFile) obj; if (auths == null) { if (other.auths != null) return false; } else if (!auths.equals(other.auths)) return false; return true; } // CHECKSTYLE:ON @Override public String toString() { return "DockerConfigFile [auths=" + auths + "]"; } @Nonnull public static DockerConfigFile loadConfig(@CheckForNull String dockerConfigPath) throws IOException { // no any configs, but for empty auths return non null object if (dockerConfigPath == null) { return new DockerConfigFile(); } //parse new docker config file format DockerConfigFile dockerConfig = loadCurrentConfig(dockerConfigPath); //parse old auth config file format if (dockerConfig == null) { dockerConfig = loadLegacyConfig(dockerConfigPath); } //otherwise create default config if (dockerConfig == null) { dockerConfig = new DockerConfigFile(); } for (Map.Entry<String, AuthConfig> entry : dockerConfig.getAuths().entrySet()) { AuthConfig authConfig = entry.getValue(); decodeAuth(authConfig); authConfig.withAuth(null); authConfig.withRegistryAddress(entry.getKey()); } return dockerConfig; } @CheckForNull private static DockerConfigFile loadCurrentConfig(@CheckForNull String dockerConfigPath) throws IOException { File dockerCfgFile = new File(dockerConfigPath, DOCKER_CFG); if (!dockerCfgFile.exists() || !dockerCfgFile.isFile()) { return null; } try { return MAPPER.readValue(dockerCfgFile, DockerConfigFile.class); } catch (IOException e) { throw new IOException("Failed to parse docker " + DOCKER_CFG, e); } } @CheckForNull private static DockerConfigFile loadLegacyConfig(String dockerConfigPath) throws IOException { File dockerLegacyCfgFile = new File(dockerConfigPath, DOCKER_LEGACY_CFG); if (!dockerLegacyCfgFile.exists() || !dockerLegacyCfgFile.isFile()) { return null; } //parse legacy auth config file format try { return new DockerConfigFile(MAPPER.<Map<String, AuthConfig>>readValue(dockerLegacyCfgFile, CONFIG_MAP_TYPE)); } catch (IOException e) { // pass } List<String> authFileContent = FileUtils.readLines(dockerLegacyCfgFile, StandardCharsets.UTF_8); if (authFileContent.size() < 2) { throw new IOException("The Auth Config file is empty"); } AuthConfig config = new AuthConfig(); String[] origAuth = authFileContent.get(0).split(" = "); if (origAuth.length != 2) { throw new IOException("Invalid Auth config file"); } config.withAuth(origAuth[1]); String[] origEmail = authFileContent.get(1).split(" = "); if (origEmail.length != 2) { throw new IOException("Invalid Auth config file"); } config.withEmail(origEmail[1]); return new DockerConfigFile(new HashMap<>(Collections.singletonMap(config.getRegistryAddress(), config))); } private static void decodeAuth(AuthConfig config) throws IOException { if (config.getAuth() == null) { return; } String str = new String(Base64.decodeBase64(config.getAuth()), StandardCharsets.UTF_8); String[] parts = str.split(":", 2); if (parts.length != 2) { throw new IOException("Invalid auth configuration file"); } config.withUsername(parts[0]); config.withPassword(parts[1]); } static String convertToHostname(String server) { String stripped = server; if (server.startsWith("http: stripped = server.substring(7); } else if (server.startsWith("https: stripped = server.substring(8); } String[] numParts = stripped.split("/", 2); return numParts[0]; } }
package com.github.games647.scoreboardstats; import com.google.common.base.Objects; import com.google.common.collect.ComparisonChain; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.builder.ToStringBuilder; import org.bukkit.Bukkit; /** * Version class for comparing and detecting Minecraft and other versions */ public class Version implements Comparable<Version> { //thanks to the author of ProtocolLib aadnk private static final String VERSION_REGEX = ".*\\(.*MC.\\s*([a-zA-z0-9\\-\\.]+)\\s*\\)"; private static boolean UUID_COMPATIBLE; static { try { UUID_COMPATIBLE = compare("1.7", getMinecraftVersionString()) >= 0; } catch (Exception ex) { UUID_COMPATIBLE = false; } } /** * Gets whether server supports UUIDs * * @return whether server supports UUIDs */ public static boolean isUUIDCompatible() { return UUID_COMPATIBLE; } /** * Gets the Minecraft version * * @return the Minecraft version */ public static Version getMinecraftVersion() { return new Version(getMinecraftVersionString()); } /** * Gets the Minecraft version as string * * @return the Minecraft version as string */ public static String getMinecraftVersionString() { return getVersionStringFromServer(Bukkit.getVersion()); } /** * Compares the version with checking the first three numbers * * @param expected the object to be compared. * @param version the object to be compared. * @return 1 version is higher; 0 both are equal; -1 version is lower<br> * a negative integer, zero, or a positive integer as this object * is less than, equal to, or greater than the specified object. */ public static int compare(String expected, String version) { int[] expectedParts = parse(stripVersionDetails(version)); int[] versionParts = parse(stripVersionDetails(expected)); return ComparisonChain.start() .compare(expectedParts[0], versionParts[0]) .compare(expectedParts[1], versionParts[1]) .compare(expectedParts[2], versionParts[2]) .result(); } public static int[] parse(String version) throws IllegalArgumentException { //exludes spaces which could be added by mistake and exclude build suffixes String trimedVersion = version.trim().split("(\\-|[a-zA-Z])")[0]; if (!trimedVersion.matches("\\d+(\\.\\d+){0,5}")) { //check if it's a format like '1.5' throw new IllegalArgumentException("Invalid format: " + version); } int[] versionParts = new int[3]; //escape regEx and split by dots String[] split = trimedVersion.split("\\."); //We check if the length has min 1 entry. for (int i = 0; i < split.length && i < versionParts.length; i++) { versionParts[i] = Integer.parseInt(split[i]); } return versionParts; } private static String getVersionStringFromServer(String versionString) { Pattern versionPattern = Pattern.compile(VERSION_REGEX); Matcher versionMatcher = versionPattern.matcher(versionString); if (versionMatcher.matches() && versionMatcher.group(1) != null) { return versionMatcher.group(1); } //Couldn't extract the version throw new IllegalStateException("Cannot parse version String '" + versionString); } private static String stripVersionDetails(String version) { int end = version.indexOf('-'); if (end == -1) { end = version.length(); } return version.substring(0, end); } private final int major; private final int minor; private final int build; public Version(String version) throws IllegalArgumentException { int[] versionParts = parse(version); major = versionParts[0]; minor = versionParts[1]; build = versionParts[2]; } /** * Creates a new version based on these values. * * @param major the major version * @param minor the minor version * @param build the build version */ public Version(int major, int minor, int build) { this.major = major; this.minor = minor; this.build = build; } /** * Gets the major value * * @return the major value */ public int getMajor() { return major; } /** * Gets the minor value * * @return the minor value */ public int getMinor() { return minor; } /** * Gets the build value * * @return the build value */ public int getBuild() { return build; } @Override public int compareTo(Version other) { return ComparisonChain.start() .compare(major, other.major) .compare(minor, other.minor) .compare(build, other.build) .result(); } @Override public int hashCode() { return Objects.hashCode(major, minor, build); } @Override public boolean equals(Object obj) { //ignores also null if (obj instanceof Version) { Version other = (Version) obj; return major == other.major && minor == other.minor && build == other.build; } return false; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
package com.gmail.nossr50.listeners; import com.gmail.nossr50.Users; import com.gmail.nossr50.m; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcPermissions; import com.gmail.nossr50.config.LoadProperties; import com.gmail.nossr50.spout.SpoutStuff; import com.gmail.nossr50.datatypes.PlayerProfile; import com.gmail.nossr50.datatypes.SkillType; import org.bukkit.Material; import org.bukkit.Statistic; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.inventory.ItemStack; import org.getspout.spoutapi.SpoutManager; import org.getspout.spoutapi.player.SpoutPlayer; import org.getspout.spoutapi.sound.SoundEffect; import com.gmail.nossr50.locale.mcLocale; import com.gmail.nossr50.skills.*; import com.gmail.nossr50.datatypes.FakeBlockBreakEvent; public class mcBlockListener implements Listener { private final mcMMO plugin; public mcBlockListener(final mcMMO plugin) { this.plugin = plugin; } @EventHandler public void onBlockPlace(BlockPlaceEvent event) { //Setup some basic vars Block block; Player player = event.getPlayer(); //When blocks are placed on snow this event reports the wrong block. if (event.getBlockReplacedState() != null && event.getBlockReplacedState().getTypeId() == 78) { block = event.getBlockAgainst(); } else { block = event.getBlock(); } //Check if the blocks placed should be monitored so they do not give out XP in the future if(m.shouldBeWatched(block)) { int id = block.getTypeId(); if (id == 17 || id == 39 || id == 40 || id == 91 || id == 86 || id == 73) { plugin.misc.blockWatchList.add(block); } else { //block.setData((byte) 5); //Change the byte //The following is a method to get around a breakage in 1.1-R2 and onward //it should be removed as soon as functionality to change a block //in this event returns. plugin.changeQueue.push(block); } } if(block.getTypeId() == 42 && LoadProperties.anvilmessages) { PlayerProfile PP = Users.getProfile(player); if(LoadProperties.spoutEnabled) { SpoutPlayer sPlayer = SpoutManager.getPlayer(player); if(sPlayer.isSpoutCraftEnabled()) { if(!PP.getPlacedAnvil()) { sPlayer.sendNotification("[mcMMO] Anvil Placed", "Right click to repair!", Material.IRON_BLOCK); PP.togglePlacedAnvil(); } } else { if(!PP.getPlacedAnvil()) { event.getPlayer().sendMessage(mcLocale.getString("mcBlockListener.PlacedAnvil")); //$NON-NLS-1$ PP.togglePlacedAnvil(); } } } else { if(!PP.getPlacedAnvil()) { event.getPlayer().sendMessage(mcLocale.getString("mcBlockListener.PlacedAnvil")); //$NON-NLS-1$ PP.togglePlacedAnvil(); } } } } @EventHandler(priority = EventPriority.MONITOR) public void onBlockBreak(BlockBreakEvent event) { Player player = event.getPlayer(); PlayerProfile PP = Users.getProfile(player); Block block = event.getBlock(); ItemStack inhand = player.getItemInHand(); if(event.isCancelled()) return; if (event instanceof FakeBlockBreakEvent) return; /* * HERBALISM */ //Green Terra if(PP.getHoePreparationMode() && mcPermissions.getInstance().herbalismAbility(player) && block.getTypeId() == 59 && block.getData() == (byte) 0x07) { Herbalism.greenTerraCheck(player, block); } //Wheat && Triple drops if(PP.getGreenTerraMode() && Herbalism.canBeGreenTerra(block)) { Herbalism.herbalismProcCheck(block, player, event, plugin); Herbalism.greenTerraWheat(player, block, event, plugin); } /* * MINING */ if(mcPermissions.getInstance().mining(player)) { if(LoadProperties.miningrequirespickaxe) { if(m.isMiningPick(inhand)) { Mining.miningBlockCheck(false, player, block, plugin); } } else { Mining.miningBlockCheck(false, player, block, plugin); } } /* * WOOD CUTTING */ if(player != null && block.getTypeId() == 17 && mcPermissions.getInstance().woodcutting(player)) { if(LoadProperties.woodcuttingrequiresaxe) { if(m.isAxes(inhand)) { if(!plugin.misc.blockWatchList.contains(block)) { WoodCutting.woodCuttingProcCheck(player, block); //Default if(block.getData() == (byte)0) PP.addXP(SkillType.WOODCUTTING, LoadProperties.mpine, player); //Spruce if(block.getData() == (byte)1) PP.addXP(SkillType.WOODCUTTING, LoadProperties.mspruce, player); //Birch if(block.getData() == (byte)2) PP.addXP(SkillType.WOODCUTTING, LoadProperties.mbirch, player); } } } else { if(!plugin.misc.blockWatchList.contains(block)) { WoodCutting.woodCuttingProcCheck(player, block); //Default if(block.getData() == (byte)0) PP.addXP(SkillType.WOODCUTTING, LoadProperties.mpine, player); //Spruce if(block.getData() == (byte)1) PP.addXP(SkillType.WOODCUTTING, LoadProperties.mspruce, player); //Birch if(block.getData() == (byte)2) PP.addXP(SkillType.WOODCUTTING, LoadProperties.mbirch, player); } } Skills.XpCheckSkill(SkillType.WOODCUTTING, player); /* * IF PLAYER IS USING TREEFELLER */ if(mcPermissions.getInstance().woodCuttingAbility(player) && PP.getTreeFellerMode() && block.getTypeId() == 17 && m.blockBreakSimulate(block, player)) { if(LoadProperties.spoutEnabled) SpoutStuff.playSoundForPlayer(SoundEffect.EXPLODE, player, block.getLocation()); WoodCutting.treeFeller(block, player, plugin); for(Block blockx : plugin.misc.treeFeller) { if(blockx != null) { Material mat = Material.getMaterial(block.getTypeId()); byte type = 0; if(block.getTypeId() == 17) type = block.getData(); ItemStack item = new ItemStack(mat, 1, (byte)0, type); if(blockx.getTypeId() == 17) { m.mcDropItem(blockx.getLocation(), item); //XP WOODCUTTING if(!plugin.misc.blockWatchList.contains(block)) { WoodCutting.woodCuttingProcCheck(player, blockx); PP.addXP(SkillType.WOODCUTTING, LoadProperties.mpine, player); } } if(blockx.getTypeId() == 18) { mat = Material.SAPLING; item = new ItemStack(mat, 1, (short)0, blockx.getData()); if(Math.random() * 10 > 9) m.mcDropItem(blockx.getLocation(), item); } if(blockx.getType() != Material.AIR) player.incrementStatistic(Statistic.MINE_BLOCK, event.getBlock().getType()); blockx.setType(Material.AIR); } } if(LoadProperties.toolsLoseDurabilityFromAbilities) m.damageTool(player, (short) LoadProperties.abilityDurabilityLoss); plugin.misc.treeFeller.clear(); } } /* * EXCAVATION */ if(Excavation.canBeGigaDrillBroken(block) && mcPermissions.getInstance().excavation(player) && block.getData() != (byte) 5) Excavation.excavationProcCheck(block.getData(), block.getType(), block.getLocation(), player); /* * HERBALISM */ if(PP.getHoePreparationMode() && mcPermissions.getInstance().herbalism(player) && Herbalism.canBeGreenTerra(block)) { Herbalism.greenTerraCheck(player, block); } if(mcPermissions.getInstance().herbalism(player) && block.getData() != (byte) 5) Herbalism.herbalismProcCheck(block, player, event, plugin); //Change the byte back when broken if(block.getData() == 5 && m.shouldBeWatched(block)) { block.setData((byte) 0); if(plugin.misc.blockWatchList.contains(block)) { plugin.misc.blockWatchList.remove(block); } } } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockDamage(BlockDamageEvent event) { if(event.isCancelled()) return; Player player = event.getPlayer(); PlayerProfile PP = Users.getProfile(player); ItemStack inhand = player.getItemInHand(); Block block = event.getBlock(); Skills.monitorSkills(player, PP); /* * ABILITY PREPARATION CHECKS */ if(PP.getHoePreparationMode() && Herbalism.canBeGreenTerra(block)) Herbalism.greenTerraCheck(player, block); if(PP.getAxePreparationMode() && block.getTypeId() == 17) WoodCutting.treeFellerCheck(player, block); if(PP.getPickaxePreparationMode() && Mining.canBeSuperBroken(block)) Mining.superBreakerCheck(player, block); if(PP.getShovelPreparationMode() && Excavation.canBeGigaDrillBroken(block)) Excavation.gigaDrillBreakerActivationCheck(player, block); if(PP.getFistsPreparationMode() && (Excavation.canBeGigaDrillBroken(block) || block.getTypeId() == 78)) Unarmed.berserkActivationCheck(player); /* * TREE FELLAN STUFF */ if(LoadProperties.spoutEnabled && block.getTypeId() == 17 && Users.getProfile(player).getTreeFellerMode()) SpoutStuff.playSoundForPlayer(SoundEffect.FIZZ, player, block.getLocation()); /* * GREEN TERRA STUFF */ if(PP.getGreenTerraMode() && mcPermissions.getInstance().herbalismAbility(player) && PP.getGreenTerraMode()) { Herbalism.greenTerra(player, block); } /* * GIGA DRILL BREAKER CHECKS */ if(PP.getGigaDrillBreakerMode() && m.blockBreakSimulate(block, player) && Excavation.canBeGigaDrillBroken(block) && m.isShovel(inhand)) { int x = 0; while(x < 3) { if(block.getData() != (byte)5) Excavation.excavationProcCheck(block.getData(), block.getType(), block.getLocation(), player); x++; } Material mat = Material.getMaterial(block.getTypeId()); if(block.getType() == Material.GRASS) mat = Material.DIRT; if(block.getType() == Material.CLAY) mat = Material.CLAY_BALL; byte type = block.getData(); ItemStack item = new ItemStack(mat, 1, (byte)0, type); block.setType(Material.AIR); player.incrementStatistic(Statistic.MINE_BLOCK, event.getBlock().getType()); if(LoadProperties.toolsLoseDurabilityFromAbilities) m.damageTool(player, (short) LoadProperties.abilityDurabilityLoss); if(item.getType() == Material.CLAY_BALL) { m.mcDropItem(block.getLocation(), item); m.mcDropItem(block.getLocation(), item); m.mcDropItem(block.getLocation(), item); m.mcDropItem(block.getLocation(), item); } else { m.mcDropItem(block.getLocation(), item); } //Spout stuff if(LoadProperties.spoutEnabled) SpoutStuff.playSoundForPlayer(SoundEffect.POP, player, block.getLocation()); } /* * BERSERK MODE CHECKS */ if(PP.getBerserkMode() && m.blockBreakSimulate(block, player) && player.getItemInHand().getTypeId() == 0 && (Excavation.canBeGigaDrillBroken(block) || block.getTypeId() == 78)) { Material mat = Material.getMaterial(block.getTypeId()); if(block.getTypeId() == 2) mat = Material.DIRT; if(block.getTypeId() == 78) mat = Material.SNOW_BALL; if(block.getTypeId() == 82) mat = Material.CLAY_BALL; byte type = block.getData(); ItemStack item = new ItemStack(mat, 1, (byte)0, type); player.incrementStatistic(Statistic.MINE_BLOCK, event.getBlock().getType()); block.setType(Material.AIR); if(item.getType() == Material.CLAY_BALL) { m.mcDropItem(block.getLocation(), item); m.mcDropItem(block.getLocation(), item); m.mcDropItem(block.getLocation(), item); m.mcDropItem(block.getLocation(), item); } else { m.mcDropItem(block.getLocation(), item); } if(LoadProperties.spoutEnabled) SpoutStuff.playSoundForPlayer(SoundEffect.POP, player, block.getLocation()); } /* * SUPER BREAKER CHECKS */ if(PP.getSuperBreakerMode() && Mining.canBeSuperBroken(block) && m.blockBreakSimulate(block, player)) { if(LoadProperties.miningrequirespickaxe) { if(m.isMiningPick(inhand)) Mining.SuperBreakerBlockCheck(player, block, plugin); } else { Mining.SuperBreakerBlockCheck(player, block, plugin); } } /* * LEAF BLOWER */ if(block.getTypeId() == 18 && mcPermissions.getInstance().woodcutting(player) && PP.getSkillLevel(SkillType.WOODCUTTING) >= 100 && m.isAxes(player.getItemInHand()) && m.blockBreakSimulate(block, player)) { m.damageTool(player, (short)1); if(Math.random() * 10 > 9) { ItemStack x = new ItemStack(Material.SAPLING, 1, (short)0, block.getData()); m.mcDropItem(block.getLocation(), x); } block.setType(Material.AIR); player.incrementStatistic(Statistic.MINE_BLOCK, event.getBlock().getType()); if(LoadProperties.spoutEnabled) SpoutStuff.playSoundForPlayer(SoundEffect.POP, player, block.getLocation()); } if(block.getType() == Material.AIR && plugin.misc.blockWatchList.contains(block)) { plugin.misc.blockWatchList.remove(block); } } @EventHandler public void onBlockFromTo(BlockFromToEvent event) { Block blockFrom = event.getBlock(); Block blockTo = event.getToBlock(); if(m.shouldBeWatched(blockFrom) && blockFrom.getData() == (byte)5) { blockTo.setData((byte)5); } } }
package com.inari.firefly.physics.collision; import java.util.ArrayDeque; import com.inari.commons.GeomUtils; import com.inari.commons.geom.BitMask; import com.inari.commons.geom.Rectangle; import com.inari.commons.lang.Disposable; import com.inari.commons.lang.aspect.Aspect; public class Contact implements Disposable { private static final ArrayDeque<Contact> disposedContacts = new ArrayDeque<Contact>(); private int entityId; private final Rectangle worldBounds = new Rectangle(); private final Rectangle intersectionBounds = new Rectangle(); private final BitMask intersectionMask = new BitMask( 0, 0 ); Aspect contactType; Aspect materialType; public final int entityId() { return entityId; } public final Rectangle worldBounds() { return worldBounds; } public final Rectangle intersectionBounds() { return intersectionBounds; } public final BitMask intersectionMask() { return intersectionMask; } public final Aspect contactType() { return contactType; } public final Aspect materialType() { return materialType; } public final boolean hasContact( int x, int y ) { if ( GeomUtils.contains( intersectionBounds, x, y ) ) { if ( !intersectionMask.isEmpty() ) { return intersectionMask.getBit( x - intersectionBounds.x, y - intersectionBounds.y ); } return true; } return false; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append( "Contact [entityId=" ); builder.append( entityId ); builder.append( ", worldBounds=" ); builder.append( worldBounds ); builder.append( ", intersectionBounds=" ); builder.append( intersectionBounds ); builder.append( ", intersectionMask=" ); builder.append( intersectionMask ); builder.append( ", contactType=" ); builder.append( contactType ); builder.append( ", materialType=" ); builder.append( materialType ); builder.append( "]" ); return builder.toString(); } @Override public final void dispose() { entityId = -1; intersectionMask.clearMask(); worldBounds.clear(); contactType = null; materialType = null; intersectionBounds.clear(); disposedContacts.add( this ); } public final static Contact createContact( int entityId ) { Contact contact = disposedContacts.getFirst(); if ( contact == null ) { contact = new Contact(); } contact.entityId = entityId; return contact; } public final static Contact createContact( int entityId, Aspect materialType, Aspect contactType, int x, int y, int width, int height ) { Contact contact = ( !disposedContacts.isEmpty() )? disposedContacts.pollFirst() : new Contact(); contact.entityId = entityId; contact.contactType = contactType; contact.materialType = materialType; contact.worldBounds.x = x; contact.worldBounds.y = y; contact.worldBounds.width = width; contact.worldBounds.height = height; return contact; } }
package com.jaeksoft.searchlib.util; import java.io.Closeable; import java.util.Properties; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import com.jaeksoft.searchlib.Logging; public class ActiveDirectory implements Closeable { private DirContext dirContext = null; private String domainSearchName = null; public ActiveDirectory(String username, String password, String domain) throws NamingException { if (StringUtils.isEmpty(domain)) throw new NamingException("The domain is empty"); Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); properties.put(Context.PROVIDER_URL, StringUtils.fastConcat("LDAP://", domain)); properties.put(Context.SECURITY_PRINCIPAL, StringUtils.fastConcat(username, "@", domain)); properties.put(Context.SECURITY_CREDENTIALS, password); dirContext = new InitialDirContext(properties); domainSearchName = getDomainSearch(domain); } public final static String[] DefaultReturningAttributes = { "cn", "mail", "givenName", "objectSid", "sAMAccountName", }; public NamingEnumeration<SearchResult> findUser(String username, String... returningAttributes) throws NamingException { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (returningAttributes == null || returningAttributes.length == 0) returningAttributes = DefaultReturningAttributes; searchControls.setReturningAttributes(returningAttributes); String filterExpr = StringUtils .fastConcat( "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=", username, "))"); return dirContext.search(domainSearchName, filterExpr, searchControls); } @Override public void close() { try { if (dirContext != null) dirContext.close(); dirContext = null; } catch (NamingException e) { Logging.warn(e); } } private static String getDomainSearch(String domain) { String[] dcs = StringUtils.split(domain.toUpperCase(), '.'); StringBuilder sb = new StringBuilder(); for (String dc : dcs) { if (sb.length() > 0) sb.append(','); sb.append("DC="); sb.append(dc); } return sb.toString(); } public static String getStringAttribute(Attributes attrs, String name) { String s = attrs.get(name).toString(); if (StringUtils.isEmpty(s)) return s; int i = s.indexOf(':'); if (i == -1) throw new IllegalArgumentException(StringUtils.fastConcat( "Wrong returned value: ", s)); return s.substring(i + 1); } public static String getObjectSID(Attributes attrs) throws NamingException { byte[] sidBytes = (byte[]) attrs.get("objectsid").get(); return decodeSID(sidBytes); } public static String decodeSID(byte[] sid) { final StringBuilder strSid = new StringBuilder("S-"); // get version final int revision = sid[0]; strSid.append(Integer.toString(revision)); // next byte is the count of sub-authorities final int countSubAuths = sid[1] & 0xFF; // get the authority long authority = 0; // String rid = ""; for (int i = 2; i <= 7; i++) { authority |= ((long) sid[i]) << (8 * (5 - (i - 2))); } strSid.append("-"); strSid.append(Long.toHexString(authority)); // iterate all the sub-auths int offset = 8; int size = 4; // 4 bytes for each sub auth for (int j = 0; j < countSubAuths; j++) { long subAuthority = 0; for (int k = 0; k < size; k++) { subAuthority |= (long) (sid[offset + k] & 0xFF) << (8 * k); } strSid.append("-"); strSid.append(subAuthority); offset += size; } return strSid.toString(); } }
package com.kawansoft.aceql.gui.service; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Date; import javax.swing.JOptionPane; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.SystemUtils; /** * Helper class for windows services. * * @author Nicolas de Pomereu * */ public class ServiceUtil { public static final String ACEQL_HTTP_SERVICE = "AceQLHTTPService"; public static final int NOT_INSTALLED = -1; public static final int STOPPED = 1; public static final int STARTING = 2; public static final int STOPPING = 3; public static final int RUNNING = 4; public static final int AUTO_START = 2; public static final int DEMAND_START = 3; public static final int DISABLED = 4; /** * Protected */ protected ServiceUtil() { } /** * Says if AceQLHTTPService is installed * @return true if AceQLHTTPService is installed * @throws IOException */ public static boolean isInstalled() throws IOException { int status = ServiceUtil.getServiceStatus(ACEQL_HTTP_SERVICE); if (status == ServiceUtil.NOT_INSTALLED) { return false; } else { return true; } } /** * Says if AceQLHTTPService is running * @return true if AceQLHTTPService is running * @throws IOException */ public static boolean isRunning() throws IOException { int status = ServiceUtil.getServiceStatus(ACEQL_HTTP_SERVICE); if (status == ServiceUtil.RUNNING){ return true; } else { return false; } } /** * Says if AceQLHTTPService is stopped * @return true if AceQLHTTPService is stopped * @throws IOException */ public static boolean isStopped() throws IOException { int status = ServiceUtil.getServiceStatus(ACEQL_HTTP_SERVICE); if (status == ServiceUtil.STOPPED){ return true; } else { return false; } } /** * Says if AceQLHTTPService is running * @return true if AceQLHTTPService is running * @throws IOException */ public static boolean isStarting() throws IOException { int status = ServiceUtil.getServiceStatus(ACEQL_HTTP_SERVICE); if (status == ServiceUtil.STARTING){ return true; } else { return false; } } /** * Start the service manager AceQLHTTPServicew.exe via a bat wrapper because of Windows Authorization. * The service manager AceQLHTTPServicew.exwith same interface a Tomcat * @param directory * @parm directory the directory into which serviceProperties.bat is installed * @throws IOException */ public static void startServiceProperties(String directory) throws IOException { if ( !SystemUtils.IS_OS_WINDOWS) { return; } ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "serviceProperties.bat"); pb.directory(new File(directory)); Process p = pb.start(); try { p.waitFor(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Starts the SimplifyUploaderServic service via a bat wrapper because of Windows Authorization. * @param directory * @parm directory the directory into serviceProperties.bat ins install * @throws IOException */ public static void startService(String directory) throws IOException { if ( !SystemUtils.IS_OS_WINDOWS) { return; } //JOptionPane.showMessageDialog(null, "directory: " + directory); ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "startService.bat"); pb.directory(new File(directory)); Process p = pb.start(); try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } // long start = System.currentTimeMillis(); // while (true) { // try { // Thread.sleep(20); // } catch (InterruptedException e) { // e.printStackTrace(); // long now = System.currentTimeMillis(); // if (now - start > TWENTY_SECONDS) { // return false; // if (ServiceUtil.isRunning()) { // return true; } /** * Stops the SimplifyUploaderServic service via a bat wrapper because of Windows Authorization. * @param directory * @parm directory the directory into serviceProperties.bat ins install * @throws IOException */ public static void stopService(String directory) throws IOException { if ( !SystemUtils.IS_OS_WINDOWS) { return; } ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "stopService.bat"); pb.directory(new File(directory)); Process p = pb.start(); try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } // long start = System.currentTimeMillis(); // while (true) { // try { // Thread.sleep(20); // } catch (InterruptedException e) { // e.printStackTrace(); // long now = System.currentTimeMillis(); // if (now - start > TWENTY_SECONDS) { // return false; // if (ServiceUtil.isStopped()) { // return true; } /** * Returns the status of the passed service * @param serviceName the sercie name * @return the status of the service * @throws IOException */ public static int getServiceStatus(String serviceName) throws IOException { if ( !SystemUtils.IS_OS_WINDOWS) { return NOT_INSTALLED; } BufferedReader reader = null; try { Process p = Runtime.getRuntime().exec("sc query " + serviceName); reader = new BufferedReader(new InputStreamReader( p.getInputStream())); String line = reader.readLine(); while (line != null) { if (line.trim().startsWith("STATE")) { if (line.trim() .substring(line.trim().indexOf(":") + 1, line.trim().indexOf(":") + 4).trim() .equals("1")) //System.out.println("Stopped"); return STOPPED; else if (line .trim() .substring(line.trim().indexOf(":") + 1, line.trim().indexOf(":") + 4).trim() .equals("2")) //System.out.println("Starting...."); return STARTING; else if (line .trim() .substring(line.trim().indexOf(":") + 1, line.trim().indexOf(":") + 4).trim() .equals("3")) return STOPPING; else if (line .trim() .substring(line.trim().indexOf(":") + 1, line.trim().indexOf(":") + 4).trim() .equals("4")) //System.out.println("Running"); return RUNNING; } line = reader.readLine(); } return NOT_INSTALLED; } finally { IOUtils.closeQuietly(reader); } } /** * Returns the start mode status of the passed service * @param serviceName the sercie name * @return the start mode of the service * @throws IOException */ public static int getServiceStartMode(String serviceName) throws IOException { if ( !SystemUtils.IS_OS_WINDOWS) { return NOT_INSTALLED; } BufferedReader reader = null; try { Process p = Runtime.getRuntime().exec("sc qc " + serviceName); reader = new BufferedReader(new InputStreamReader( p.getInputStream())); String line = reader.readLine(); while (line != null) { if (line.trim().startsWith("START_TYPE")) { if (line.trim() .substring(line.trim().indexOf(":") + 1, line.trim().indexOf(":") + 4).trim() .equals("2")) //System.out.println("Stopped"); return AUTO_START; else if (line .trim() .substring(line.trim().indexOf(":") + 1, line.trim().indexOf(":") + 4).trim() .equals("3")) //System.out.println("Starting...."); return DEMAND_START; else if (line .trim() .substring(line.trim().indexOf(":") + 1, line.trim().indexOf(":") + 4).trim() .equals("4")) return DISABLED; } line = reader.readLine(); } return NOT_INSTALLED; } finally { IOUtils.closeQuietly(reader); } } /** * Returns the start mode status of the passed service * @param serviceName the service name * @return the start mode of the service * @throws IOException */ public static String getServiceStartModeLabel(String serviceName) throws IOException { int startMode = getServiceStartMode(serviceName); if (startMode == NOT_INSTALLED) return ""; else if (startMode == AUTO_START) return "Auto"; else if (startMode == DEMAND_START) return "Manual"; else if (startMode == DISABLED) return "Disabled"; else return "Unknown"; } }
package com.loginradius.sdk.raas.api; import java.util.HashMap; import java.util.Map; import com.loginradius.sdk.social.core.LoginRadiusClient; import com.loginradius.sdk.social.models.LoginRadiusPostResponse; import com.loginradius.sdk.raas.models.*; public class UserProfileAPI extends RaaSAPI{ /** * * @param userId ID generated from RaasProfile * @return RaasUserProfile with all user data */ public RaaSUserDetails getUser(String userId) { Map<String, String> params = new HashMap<String, String>(); params.put("userid", userId); String jsonResponse = executeGet("/raas/v1/user", params); return LoginRadiusClient.formatResponse(jsonResponse, RaaSUserDetails.class); } /** * * @param UserName UserName given by user * @param Password Password given by user * @return RaasUserProfile with all user data */ public RaaSUserDetails getUser(String UserName, String Password) { Map<String, String> params = new HashMap<String, String>(); params.put("username", UserName); params.put("password", Password); String jsonResponse = executeGet("/raas/v1/user", params); return LoginRadiusClient.formatResponse(jsonResponse, RaaSUserDetails.class); } /** * * @param email * @return */ public RaaSUserDetails GetUserbyEmail(String email){ Map<String, String> params = new HashMap<String, String>(); params.put("email", email); String jsonResponse = executeGet("/raas/v1/user", params); return LoginRadiusClient.formatResponse(jsonResponse, RaaSUserDetails.class); } /** * * @param userId ID generated from RaasProfile * @param userDetails Details given by user in the form * @return returns isPosted with value true */ public <T> RaaSResponse editUser(String userId, T userDetails) { Map<String, String> params = new HashMap<String, String>(); params.put("userid", userId); Map<String, String> postParams = new HashMap<String,String>(); RaaSUserDetails userData = (RaaSUserDetails) userDetails; postParams.put("firstname", userData.getFirstName()); if(userData.getLastName()!=null) postParams.put("lastname",userData.getLastName()); if(userData.getGender()!=null) postParams.put("gender",userData.getGender()); if(userData.getBirthDate()!=null) postParams.put("birthdate",userData.getBirthDate()); String jsonResponse = executePost("/raas/v1/user",params, postParams); return LoginRadiusClient.formatResponse(jsonResponse, RaaSResponse.class); } /** * * @param userId ID generated from RaasProfile * @param OldPassword oldpassword given by user * @param NewPassword newpassword given by user * @return returns isPosted with value true */ public RaaSResponse changePassword(String userId, String OldPassword, String NewPassword){ Map<String, String> params = new HashMap<String, String>(); params.put("userid", userId); Map<String, String> postParams = new HashMap<String,String>(); postParams.put("oldpassword", OldPassword); postParams.put("newpassword",NewPassword); String jsonResponse = executePost("/raas/v1/user/password",params, postParams); return LoginRadiusClient.formatResponse(jsonResponse, RaaSResponse.class); } /** * * @param userid ID generated from RaasProfile * @param password password given by the admin * @return returns isPosted with value true */ public RaaSResponse setPassword(String userid, String password) { Map<String, String> params = new HashMap<String, String>(); params.put("action", "setpassword"); params.put("userid",userid); Map<String, String> postParams = new HashMap<String,String>(); postParams.put("password", password); String jsonResponse = executePost("/raas/v1/user/password", params, postParams); return LoginRadiusClient.formatResponse(jsonResponse, RaaSResponse.class); } /** * * @param user Userdetails given by the user * return RaasUserProfile with all user data */ public RaaSUserDetails createUser(RaaSUserDetails user){ Map<String, String> params = new HashMap<String, String>(); params.put("emailid", user.getEmailId()); params.put("password",user.getPassword()); if(user.getFirstName()!=null) params.put("firstname", user.getFirstName()); if(user.getLastName()!=null) params.put("lastname",user.getLastName()); if(user.getGender()!=null) params.put("gender", user.getGender()); if(user.getBirthDate()!=null) params.put("birthdate",user.getBirthDate()); String jsonResponse = executePost("/raas/v1/user", null, params); return LoginRadiusClient.formatResponse(jsonResponse, RaaSUserDetails.class); } /** * * @param userDetails UserData given by the user * @return returns isPosted with value true */ public <T> RaaSResponse registerUser(T userDetails) { RaaSUserDetails userData = (RaaSUserDetails) userDetails; Map<String, String> postParams = new HashMap<String, String>(); postParams.clear(); postParams.put("emailid", userData.getEmailId()); postParams.put("password",userData.getPassword()); if(userData.getFirstName()!=null) postParams.put("firstname",userData.getFirstName()); if(userData.getLastName()!=null) postParams.put("lastname",userData.getLastName()); if(userData.getGender()!=null) postParams.put("gender",userData.getGender()); if(userData.getBirthDate()!=null) postParams.put("birthdate",userData.getBirthDate()); String jsonResponse = executePost("/raas/v1/user/register", null,postParams); return LoginRadiusClient.formatResponse(jsonResponse, RaaSResponse.class); } }
package com.nalin.springbootmongo.api.domain; import java.io.Serializable; import java.util.Date; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.mongodb.core.mapping.Document; /** * @author nalin * @since September 2016 * */ @Document(collection = "contactbook") public class Person implements Serializable { private static final long serialVersionUID = 1L; @Id private String id; private String firstName; private String lastName; private String address; private String phone; private String email; @CreatedDate private Date createdDate; @LastModifiedDate private Date modifiedDate; public Person() { super(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public Date getModifiedDate() { return modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } @Override public String toString() { return "Person [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", address=" + address + ", phone=" + phone + ", email=" + email + ", createdDate=" + createdDate + "]"; } }
package com.relayrides.pushy.apns.util;
package com.shc.silenceengine.graphics; import com.shc.silenceengine.core.SilenceException; import com.shc.silenceengine.graphics.opengl.Primitive; import com.shc.silenceengine.graphics.opengl.Texture; import java.awt.*; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * @author Sri Harsha Chilakapati */ public class TrueTypeFont { public static final int STYLE_NORMAL = Font.PLAIN; public static final int STYLE_BOLD = Font.BOLD; public static final int STYLE_ITALIC = Font.ITALIC; // The regular expression used for getting all trailing whitespace private static final String TRAILING_WHITESPACE = "\\s+$"; private static final int STANDARD_CHARACTERS = 256; private FontChar[] chars = new FontChar[STANDARD_CHARACTERS]; private boolean antiAlias = true; private Texture[] fontTexture; private Font awtFont; private FontMetrics fontMetrics; public TrueTypeFont(String name, int style, int size) { this(new Font(name, style, size)); } public TrueTypeFont(Font fnt) { this(fnt, true); } public TrueTypeFont(Font fnt, boolean antiAlias) { this.awtFont = fnt; this.antiAlias = antiAlias; createSet(); } public TrueTypeFont(InputStream is) { this(is, true); } public TrueTypeFont(InputStream is, boolean antiAlias) { this(is, STYLE_NORMAL, 18, antiAlias); } public TrueTypeFont(InputStream is, int style, int size, boolean antiAlias) { try { this.awtFont = Font.createFont(Font.TRUETYPE_FONT, is); this.antiAlias = antiAlias; awtFont = awtFont.deriveFont(style, (float) size); createSet(); } catch (Exception e) { throw new SilenceException(e.getMessage()); } } private void createSet() { // A temporary BufferedImage to get access to FontMetrics BufferedImage tmp = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = tmp.createGraphics(); g2d.setFont(awtFont); if (antiAlias) g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); fontMetrics = g2d.getFontMetrics(); int positionX = 0; int positionY = 0; int page = 0; final int padding = fontMetrics.getMaxAdvance(); final int maxTexWidth = 1024; final int maxTexHeight = 1024; List<Texture> pages = new ArrayList<>(); for (int i = 0; i < STANDARD_CHARACTERS; i++) { char ch = (char) i; chars[i] = new FontChar(); if (positionX + 2 * padding > maxTexWidth) { positionX = 0; positionY += fontMetrics.getHeight() + padding; } if (positionY + 2 * padding > maxTexHeight) { positionX = positionY = 0; page++; } chars[i].advance = fontMetrics.stringWidth("_" + ch) - fontMetrics.charWidth('_'); chars[i].padding = padding; chars[i].page = page; chars[i].x = positionX; chars[i].y = positionY; chars[i].w = chars[i].advance + (2 * padding); chars[i].h = fontMetrics.getHeight(); positionX += chars[i].w + 10; } g2d.dispose(); BufferedImage pageImage = new BufferedImage(maxTexWidth, maxTexHeight, BufferedImage.TYPE_INT_ARGB); g2d = pageImage.createGraphics(); g2d.setFont(awtFont); g2d.setColor(java.awt.Color.BLACK); if (antiAlias) g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); page = 0; for (int i = 0; i < STANDARD_CHARACTERS; i++) { FontChar fntChar = chars[i]; if (page != fntChar.page) { g2d.dispose(); pages.add(Texture.fromBufferedImage(pageImage)); pageImage = new BufferedImage(maxTexWidth, maxTexHeight, BufferedImage.TYPE_INT_ARGB); g2d = pageImage.createGraphics(); g2d.setFont(awtFont); g2d.setColor(java.awt.Color.BLACK); if (antiAlias) g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); page = fntChar.page; } g2d.drawString(String.valueOf((char) i), chars[i].x + padding, chars[i].y + fontMetrics.getAscent()); } g2d.dispose(); pages.add(Texture.fromBufferedImage(pageImage)); fontTexture = new Texture[pages.size()]; fontTexture = pages.toArray(fontTexture); } public void drawString(Batcher b, String text, float x, float y) { drawString(b, text, x, y, Color.WHITE); } public void drawString(Batcher b, String text, float x, float y, Color col) { // Don't draw anything if the string is null or is empty. Also removes all trailing whitespace if (text == null || (text = text.replace(TRAILING_WHITESPACE, "")).equals("")) return; Texture current = Texture.CURRENT; b.begin(Primitive.TRIANGLES); { float startX = x; Texture page = null; for (char ch : text.toCharArray()) { FontChar c = chars[(int) ch]; if (ch == '\n') { y += fontMetrics.getHeight(); x = startX; continue; } Texture charPage = fontTexture[chars[ch].page]; if (page == null || page != charPage) { b.flush(); page = charPage; page.bind(); } float minU = c.x / page.getWidth(); float maxU = (c.x + c.w) / page.getWidth(); float minV = c.y / page.getHeight(); float maxV = (c.y + c.h) / page.getHeight(); b.vertex(x - c.padding, y); b.color(col); b.texCoord(minU, minV); b.vertex(x + chars[ch].w - c.padding, y); b.color(col); b.texCoord(maxU, minV); b.vertex(x - c.padding, y + chars[ch].h); b.color(col); b.texCoord(minU, maxV); b.vertex(x + chars[ch].w - c.padding, y); b.color(col); b.texCoord(maxU, minV); b.vertex(x - c.padding, y + chars[ch].h); b.color(col); b.texCoord(minU, maxV); b.vertex(x + chars[ch].w - c.padding, y + chars[ch].h); b.color(col); b.texCoord(maxU, maxV); x += c.advance; } } b.end(); current.bind(); } public int getWidth(String str) { int width = 0; int lineWidth = 0; for (char ch : str.toCharArray()) { if (ch == '\n') { width = Math.max(width, lineWidth); lineWidth = 0; continue; } lineWidth += chars[(int) ch].advance; } width = Math.max(width, lineWidth); return width; } public TrueTypeFont derive(float size) { return new TrueTypeFont(awtFont.deriveFont(size)); } public void dispose() { for (Texture texture : fontTexture) texture.dispose(); } public int getHeight() { return fontMetrics.getHeight(); } private static class FontChar { public int x; public int y; public int w; public int h; public int advance; public int padding; public int page; } }
package com.softserveinc.tender.repo; import com.softserveinc.tender.entity.Deal; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; public interface DealRepository extends JpaRepository<Deal, Integer> { @Query("select distinct d from Deal d where d.customer.id = :customerId and (1 = :searchFlag or d.bid.proposal.tender.title like :tenderTitle)") List<Deal> findAllDealsForCustomer(@Param("customerId") Integer id, Pageable pageable,@Param("tenderTitle") String searchParam, @Param("searchFlag") Integer searchFlag); @Query("select distinct d from Deal d where d.seller.id = :sellerId and (1 = :searchFlag or d.bid.proposal.tender.title like :tenderTitle)") List<Deal> findAllDealsForSeller(@Param("sellerId") Integer id, Pageable pageable,@Param("tenderTitle") String searchParam, @Param("searchFlag") Integer searchFlag); @Query("select count(distinct d) from Deal d where d.customer.id = :customerId") Long getDealsNumberForCustomer(@Param("customerId") Integer id); @Query("select count(distinct d) from Deal d where d.seller.id = :sellerId") Long getDealsNumberForSeller(@Param("sellerId") Integer id); @Query("select count(distinct d) from Deal d, User u where d.seller.id = :sellerId and d.status.id IN (1,2) and u.profile.id = :sellerId and d.date > u.myDealsDate") Long getNewDealsNumberForSeller(@Param("sellerId") Integer id); List<Deal> findByProposalId(Integer proposalId); @Query("select d from Deal d inner join d.bid b where b.unit.id = :unitId") List<Deal> findByUnitId(@Param("unitId")Integer unitId); }
package com.strider.datadefender; import static org.apache.log4j.Logger.getLogger; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import com.strider.datadefender.database.DatabaseAnonymizerException; import com.strider.datadefender.database.IDBFactory; import com.strider.datadefender.database.metadata.MatchMetaData; import com.strider.datadefender.functions.CoreFunctions; import com.strider.datadefender.functions.Utils; import com.strider.datadefender.requirement.Column; import com.strider.datadefender.requirement.Exclude; import com.strider.datadefender.requirement.Key; import com.strider.datadefender.requirement.Parameter; import com.strider.datadefender.requirement.Requirement; import com.strider.datadefender.requirement.Table; import com.strider.datadefender.utils.CommonUtils; import com.strider.datadefender.utils.LikeMatcher; import com.strider.datadefender.utils.RequirementUtils; /** * Entry point for RDBMS data anonymizer * * @author Armenak Grigoryan */ public class DatabaseAnonymizer implements IAnonymizer { private static final Logger log = getLogger(DatabaseAnonymizer.class); /** * Adds column names from the table to the passed collection of strings. * * @param table * @param sColumns */ private void fillColumnNames(final Table table, final Collection<String> sColumns) { for (Column column : table.getColumns()) { sColumns.add(column.getName()); } } /** * Adds column names that make up the table's primary key. * * @param table * @return */ private void fillPrimaryKeyNamesList(final Table table, final Collection<String> sKeys) { final List<Key> pKeys = table.getPrimaryKeys(); if (pKeys != null && pKeys.size() != 0) { for (final Key key : pKeys) { sKeys.add(key.getName()); } } else { sKeys.add(table.getPKey()); } } /** * Creates the UPDATE query for a single row of results. * * @param table * @param columns * @param keys * @param updatableKeys * @return the SQL statement */ private String getUpdateQuery(final Table table, final Collection<String> updateColumns, final Collection<String> keys) { final StringBuilder sql = new StringBuilder(); sql.append("UPDATE "). append(table.getName()). append(" SET "). append(StringUtils.join(updateColumns, " = ?, ")). append(" = ?"). append(" WHERE " ). append(StringUtils.join(keys, " = ? AND ")). append(" = ?"); log.debug(sql.toString()); return sql.toString(); } /** * Creates the SELECT query for key and update columns. * * @param tableName * @param keys * @param columns * @return */ private PreparedStatement getSelectQueryStatement(final IDBFactory dbFactory, final Table table, final Collection<String> keys, final Collection<String> columns) throws SQLException { final List<String> params = new LinkedList<>(); final StringBuilder query = new StringBuilder("SELECT DISTINCT "); query.append(StringUtils.join(keys, ", ")). append(", "). append(StringUtils.join(columns, ", ")). append(" FROM "). append(table.getName()); final List<Exclude> exclusions = table.getExclusions(); if (exclusions != null) { String separator = " WHERE ("; for (final Exclude exc : exclusions) { final String eq = exc.getEqualsValue(); final String lk = exc.getLikeValue(); final boolean nl = exc.isExcludeNulls(); final String col = exc.getName(); if (col != null && col.length() != 0) { if (eq != null) { query.append(separator).append("(").append(col).append(" != ? OR ").append(col).append(" IS NULL)"); params.add(eq); separator = " AND "; } if (lk != null && lk.length() != 0) { query.append(separator).append("(").append(col).append(" NOT LIKE ? OR ").append(col).append(" IS NULL)"); params.add(lk); separator = " AND "; } if (nl) { query.append(separator).append(col).append(" IS NOT NULL"); separator = " AND "; } } } if (query.indexOf(" WHERE (") != -1) { separator = ") AND ("; } for (final Exclude exc : exclusions) { final String neq = exc.getNotEqualsValue(); final String nlk = exc.getNotLikeValue(); final String col = exc.getName(); if (neq != null) { query.append(separator).append(col).append(" = ?"); separator = " OR "; } if (nlk != null && nlk.length() != 0) { query.append(separator).append(col).append(" LIKE ?"); separator = " OR "; } } if (query.indexOf(" WHERE (") != -1) { query.append(")"); } } final PreparedStatement stmt = dbFactory.getConnection().prepareStatement(query.toString()); if (dbFactory.getVendorName().equalsIgnoreCase("mysql")) { stmt.setFetchSize(Integer.MIN_VALUE); } int paramIndex = 1; for (String param : params) { stmt.setString(paramIndex, param); ++paramIndex; } log.debug("Querying for: " + query.toString()); if (params.size() > 0) { log.debug("\t - with parameters: " + StringUtils.join(params, ',')); } return stmt; } private Object callAnonymizingFunctionFor(final Connection dbConn, final ResultSet row, final Column column, String vendor) throws SQLException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // Check if function has parameters final List<Parameter> parms = column.getParameters(); if (parms != null) { return callAnonymizingFunctionWithParameters(dbConn, row, column, vendor); } else { return callAnonymizingFunctionWithoutParameters(dbConn, column, vendor); } } private Object callAnonymizingFunctionWithParameters(final Connection dbConn, final ResultSet row, final Column column, String vendor) throws SQLException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { final String function = column.getFunction(); if (function == null || function.equals("")) { log.warn("Function is not defined for column [" + column + "]. Moving to the next column."); return ""; } try { final String className = Utils.getClassName(function); final String methodName = Utils.getMethodName(function); final Class<?> clazz = Class.forName(className); final CoreFunctions instance = (CoreFunctions) Class.forName(className).newInstance(); instance.setDatabaseConnection(dbConn); instance.setVendor(vendor); final List<Parameter> parms = column.getParameters(); final Map<String, Object> paramValues = new HashMap<>(parms.size()); final String columnValue = row.getString(column.getName()); for (Parameter param : parms) { if (param.getValue().equals("@@value@@")) { paramValues.put(param.getName(), columnValue); } else if (param.getValue().equals("@@row@@") && param.getType().equals("java.sql.ResultSet")) { paramValues.put(param.getName(), row); } else { paramValues.put(param.getName(), param.getTypeValue()); } } final List<Object> fnArguments = new ArrayList<>(parms.size()); final Method[] methods = clazz.getMethods(); Method selectedMethod = null; methodLoop: for (final Method m : methods) { if (m.getName().equals(methodName) && m.getReturnType() == String.class) { log.debug(" Found method: " + m.getName()); log.debug(" Match w/: " + paramValues); final java.lang.reflect.Parameter[] mParams = m.getParameters(); fnArguments.clear(); for (final java.lang.reflect.Parameter par : mParams) { //log.debug(" Name present? " + par.isNamePresent()); // Note: requires -parameter compiler flag log.debug(" Real param: " + par.getName()); if (!paramValues.containsKey(par.getName())) { continue methodLoop; } final Object value = paramValues.get(par.getName()); Class<?> fnParamType = par.getType(); final Class<?> confParamType = (value == null) ? fnParamType : value.getClass(); if (fnParamType.isPrimitive() && value == null) { continue methodLoop; } if (ClassUtils.isPrimitiveWrapper(confParamType)) { if (!ClassUtils.isPrimitiveOrWrapper(fnParamType)) { continue methodLoop; } fnParamType = ClassUtils.primitiveToWrapper(fnParamType); } if (!fnParamType.equals(confParamType)) { continue methodLoop; } fnArguments.add(value); } // actual parameters check less than xml defined parameters size, because values could be auto-assigned (like 'values' and 'row' params) if (fnArguments.size() != mParams.length || fnArguments.size() < paramValues.size()) { continue; } selectedMethod = m; break; } } if (selectedMethod == null) { final StringBuilder s = new StringBuilder("Anonymization method: "); s.append(methodName).append(" with parameters matching ("); String comma = ""; for (final Parameter p : parms) { s.append(comma).append(p.getType()).append(' ').append(p.getName()); comma = ", "; } s.append(") was not found in class ").append(className); throw new NoSuchMethodException(s.toString()); } log.debug("Anonymizing function: " + methodName + " with parameters: " + Arrays.toString(fnArguments.toArray())); final Object anonymizedValue = selectedMethod.invoke(instance, fnArguments.toArray()); if (anonymizedValue == null) { return null; } return anonymizedValue.toString(); } catch (AnonymizerException | InstantiationException | ClassNotFoundException ex) { log.error(ex.toString()); } return ""; } private Object callAnonymizingFunctionWithoutParameters(final Connection dbConn, final Column column, String vendor) throws SQLException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { final String function = column.getFunction(); if (function == null || function.equals("")) { log.warn("Function is not defined for column [" + column + "]. Moving to the next column."); return ""; } try { final String className = Utils.getClassName(function); final String methodName = Utils.getMethodName(function); final Class<?> clazz = Class.forName(className); final CoreFunctions instance = (CoreFunctions) Class.forName(className).newInstance(); instance.setDatabaseConnection(dbConn); final Method[] methods = clazz.getMethods(); Method selectedMethod = null; Object returnType = null; methodLoop: for (final Method m : methods) { //if (m.getName().equals(methodName) && m.getReturnType() == String.class) { if (m.getName().equals(methodName)) { log.debug(" Found method: " + m.getName()); selectedMethod = m; returnType = m.getReturnType(); break; } } if (selectedMethod == null) { final StringBuilder s = new StringBuilder("Anonymization method: "); s.append(methodName).append(") was not found in class ").append(className); throw new NoSuchMethodException(s.toString()); } log.debug("Anonymizing function name: " + methodName); final Object anonymizedValue = selectedMethod.invoke(instance); log.debug("anonymizedValue " + anonymizedValue); if (anonymizedValue == null) { return null; } log.debug(returnType.toString()); if (returnType == String.class) { return anonymizedValue.toString(); } else if (returnType == java.sql.Date.class) { return anonymizedValue; } else if (returnType.toString().equals("int")) { return anonymizedValue; } } catch (AnonymizerException | InstantiationException | ClassNotFoundException ex) { log.error(ex.toString()); } return ""; } /** * Returns true if the current column's value is excluded by the rulesets * defined by the Requirements. * * @param db * @param row * @param column * @return the columns value * @throws SQLException */ private boolean isExcludedColumn(final ResultSet row, final Column column) throws SQLException { final String columnName = column.getName(); final List<Exclude> exclusions = column.getExclusions(); boolean hasInclusions = false; boolean passedInclusion = false; if (exclusions != null) { for (final Exclude exc : exclusions) { String name = exc.getName(); final String eq = exc.getEqualsValue(); final String lk = exc.getLikeValue(); final String neq = exc.getNotEqualsValue(); final String nlk = exc.getNotLikeValue(); final boolean nl = exc.isExcludeNulls(); if (name == null || name.length() == 0) { name = columnName; } final String testValue = row.getString(name); if (nl && testValue == null) { return true; } else if (eq != null && eq.equals(testValue)) { return true; } else if (lk != null && lk.length() != 0) { final LikeMatcher matcher = new LikeMatcher(lk); if (matcher.matches(testValue)) { return true; } } if (neq != null) { hasInclusions = true; if (neq.equals(testValue)) { passedInclusion = true; } } if (nlk != null && nlk.length() != 0) { hasInclusions = true; final LikeMatcher matcher = new LikeMatcher(nlk); if (matcher.matches(testValue)) { passedInclusion = true; } } } } return (hasInclusions && !passedInclusion); } /** * Returns the passed colValue truncated to the column's size in the table. * * @param colValue * @param index * @param columnMetaData * @return * @throws SQLException */ private String getTruncatedColumnValue(final String colValue, final int index, final List<MatchMetaData> columnMetaData) throws SQLException { final MatchMetaData md = columnMetaData.get(index); final int colSize = md.getColumnSize(); final String type = md.getColumnType(); if ("String".equals(type) && colValue.length() > colSize) { return colValue.substring(0, colSize); } return colValue; } private void anonymizeRow( final PreparedStatement updateStmt, final Collection<Column> tableColumns, final Collection<String> keyNames, final Connection db, final ResultSet row, final List<MatchMetaData> columnMetaData, final String vendor ) throws SQLException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, AnonymizerException { int fieldIndex = 0; final Map<String, Integer> columnIndexes = new HashMap<>(tableColumns.size()); final Set<String> anonymized = new HashSet<>(tableColumns.size()); for (final Column column : tableColumns) { final String columnName = column.getName(); if (anonymized.contains(columnName)) { continue; } if (!columnIndexes.containsKey(columnName)) { final int columnIndex = ++fieldIndex; columnIndexes.put(columnName, columnIndex); } if (isExcludedColumn(row, column)) { final String columnValue = row.getString(columnName); updateStmt.setString(columnIndexes.get(columnName), columnValue); log.debug("Excluding column: " + columnName + " with value: " + columnValue); continue; } anonymized.add(columnName); final Object colValue = callAnonymizingFunctionFor(db, row, column, vendor); log.debug("colValue = " + colValue); //log.debug("type= " + colValue.getClass()); if (colValue == null) { updateStmt.setNull(columnIndexes.get(columnName), Types.NULL); } else if (colValue.getClass() == java.sql.Date.class) { updateStmt.setDate(columnIndexes.get(columnName), CommonUtils.stringToDate(colValue.toString(), "dd-MM-yyyy") ); } else if (colValue.getClass() == java.lang.Integer.class) { updateStmt.setInt(columnIndexes.get(columnName), (int) colValue); } else { updateStmt.setString( columnIndexes.get(columnName), getTruncatedColumnValue( (String) colValue, columnIndexes.get(columnName), columnMetaData ) ); } } int whereIndex = fieldIndex; for (final String key : keyNames) { updateStmt.setString(++whereIndex, row.getString(key)); } updateStmt.addBatch(); } /** * Anonymization function for a single table. * * Sets up queries, loops over columns and anonymizes columns for the passed * Table. * * @param table */ private void anonymizeTable(final int batchSize, final IDBFactory dbFactory, final Table table) throws AnonymizerException { log.info("Table [" + table.getName() + "]. Start ..."); final List<Column> tableColumns = table.getColumns(); // colNames is looked up with contains, and iterated over. Using LinkedHashSet means // duplicate column names won't be added to the query, so a check in the column loop // below was created to ensure a reasonable warning message is logged if that happens. final Set<String> colNames = new LinkedHashSet<>(tableColumns.size()); // keyNames is only iterated over, so no need for a hash set final List<String> keyNames = new LinkedList<>(); fillColumnNames(table, colNames); fillPrimaryKeyNamesList(table, keyNames); // required in this scope for 'catch' block PreparedStatement selectStmt = null; PreparedStatement updateStmt = null; ResultSet rs = null; final Connection updateCon = dbFactory.getUpdateConnection(); try { selectStmt = getSelectQueryStatement(dbFactory, table, keyNames, colNames); rs = selectStmt.executeQuery(); final List<MatchMetaData> columnMetaData = dbFactory.fetchMetaData().getMetaDataForRs(rs); final String updateString = getUpdateQuery(table, colNames, keyNames); updateStmt = updateCon.prepareStatement(updateString); int batchCounter = 0; int rowCount = 0; while (rs.next()) { anonymizeRow(updateStmt, tableColumns, keyNames, updateCon, rs, columnMetaData, dbFactory.getVendorName()); batchCounter++; if (batchCounter == batchSize) { updateStmt.executeBatch(); updateCon.commit(); batchCounter = 0; } rowCount++; } log.debug("Rows processed: " + rowCount); updateStmt.executeBatch(); log.debug("Batch executed"); updateCon.commit(); log.debug("Commit"); selectStmt.close(); updateStmt.close(); rs.close(); log.debug("Closing open resources"); } catch (SQLException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { log.error(ex.toString()); if (ex.getCause() != null) { log.error(ex.getCause().toString()); } try { if (selectStmt != null) { selectStmt.close(); } if (updateStmt != null) { updateStmt.close(); } if (rs != null) { rs.close(); } } catch (SQLException sqlex) { log.error(sqlex.toString()); } } log.info("Table " + table.getName() + ". End ..."); log.info(""); } @Override public void anonymize(final IDBFactory dbFactory, final Properties anonymizerProperties, final Set<String> tables) throws DatabaseAnonymizerException, AnonymizerException{ final int batchSize = Integer.parseInt(anonymizerProperties.getProperty("batch_size")); final Requirement requirement = RequirementUtils.load(anonymizerProperties.getProperty("requirement")); // Iterate over the requirement log.info("Anonymizing data for client " + requirement.getClient() + " Version " + requirement.getVersion()); for(final Table reqTable : requirement.getTables()) { if (tables.isEmpty() || tables.contains(reqTable.getName())) { anonymizeTable(batchSize, dbFactory, reqTable); } } } }
package com.suse.salt.netapi.calls.modules; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import com.google.gson.JsonElement; import com.google.gson.annotations.SerializedName; import com.suse.salt.netapi.calls.LocalCall; import com.google.gson.reflect.TypeToken; import com.suse.salt.netapi.parser.JsonParser; /** * salt.modules.saltutil */ public class SaltUtil { public static LocalCall<List<String>> syncGrains( Optional<Boolean> refresh, Optional<String> saltenv) { LinkedHashMap<String, Object> args = syncArgs(refresh, saltenv); return new LocalCall<>("saltutil.sync_grains", Optional.empty(), Optional.of(args), new TypeToken<List<String>>() { }); } public static LocalCall<List<String>> syncModules( Optional<Boolean> refresh, Optional<String> saltenv) { LinkedHashMap<String, Object> args = syncArgs(refresh, saltenv); return new LocalCall<>("saltutil.sync_modules", Optional.empty(), Optional.of(args), new TypeToken<List<String>>() { }); } public static LocalCall<Map<String, Object>> syncAll( Optional<Boolean> refresh, Optional<String> saltenv) { LinkedHashMap<String, Object> args = syncArgs(refresh, saltenv); return new LocalCall<>("saltutil.sync_all", Optional.empty(), Optional.of(args), new TypeToken<Map<String, Object>>() { }); } public static LocalCall<Boolean> refreshPillar( Optional<Boolean> refresh, Optional<String> saltenv) { LinkedHashMap<String, Object> args = syncArgs(refresh, saltenv); return new LocalCall<>("saltutil.refresh_pillar", Optional.empty(), Optional.of(args), new TypeToken<Boolean>() { }); } private static LinkedHashMap<String, Object> syncArgs( Optional<Boolean> refresh, Optional<String> saltenv) { LinkedHashMap<String, Object> args = new LinkedHashMap<>(); refresh.ifPresent(value -> args.put("refresh", value)); saltenv.ifPresent(value -> args.put("saltenv", value)); return args; } /** * Info about a running job on a minion */ public static class RunningInfo { private String jid; private String fun; private int pid; private String target; @SerializedName("tgt_type") private String targetType; private String user; private Optional<JsonElement> metadata = Optional.empty(); public <R> Optional<R> getMetadata(Class<R> type) { return metadata.map(json -> JsonParser.GSON.fromJson(json, type)); } public <R> Optional<R> getMetadata(TypeToken<R> type) { return metadata.map(json -> JsonParser.GSON.fromJson(json, type.getType())); } public String getJid() { return jid; } public String getFun() { return fun; } public int getPid() { return pid; } public String getTarget() { return target; } public String getTargetType() { return targetType; } public String getUser() { return user; } } public static LocalCall<List<RunningInfo>> running() { return new LocalCall<>("saltutil.running", Optional.empty(), Optional.empty(), new TypeToken<List<RunningInfo>>() {}); } }
package com.thedeanda.util.properties; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PropertyUtils { private static final Logger log = LoggerFactory.getLogger(PropertyUtils.class); /** * reads properties from local resource but overrides when others existing * such that: * <ul> * <li>/etc/${name}.properties</li> * <li>/etc/${name}/${name}.properties</li> * <li>${user.home}/${name}.properties * </ul> * * @param name * name of properties file without path or extension: "example" * @return */ public static Properties readProperties(String name) { Properties properties = new Properties(); boolean loaded = false; String filename = name + ".properties"; loaded = loadAndMerge(properties, PropertyUtils.class.getResourceAsStream("/" + filename)); if (loaded) { log.debug("Properties file loaded: classpath:/" + filename); } else { log.warn("Properties file not loaded: classpath:/" + filename); } String[] paths = { "/etc/" + filename, "/etc/" + name + File.separator + filename, System.getProperty("user.home") + File.separator + filename, filename }; for (String path : paths) { File overrides = new File(path); loadAndMerge(properties, overrides); } log.info("Loaded properties: {}", properties); return properties; } private static void loadAndMerge(Properties properties, File file) { if (file.exists()) { log.debug("Loading overrides file: {}", file); FileInputStream fis = null; try { fis = new FileInputStream(file); loadAndMerge(properties, fis); } catch (IOException e) { log.warn(e.getMessage(), e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { log.warn(e.getMessage(), e); } } } } else { log.debug("File not found: {}, skipping", file); } } private static boolean loadAndMerge(Properties props, InputStream is) { boolean loaded = false; Properties newProps = new Properties(); if (is != null) { try { newProps.load(is); loaded = true; } catch (IOException e) { log.warn(e.getMessage(), e); } } if (loaded) { // merge Set<Object> keys = newProps.keySet(); for (Object k : keys) { String key = (String) k; String value = newProps.getProperty(key); props.put(key, value); } } return loaded; } }
package com.zanclus.scanalyzer.services; import java.net.InetAddress; import java.net.UnknownHostException; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.jersey.core.spi.factory.ResponseBuilderImpl; import com.zanclus.scanalyzer.domain.access.HostDAO; import com.zanclus.scanalyzer.domain.access.PortsDAO; import com.zanclus.scanalyzer.domain.access.ScanDAO; import com.zanclus.scanalyzer.domain.entities.Host; import com.zanclus.scanalyzer.domain.entities.PortsCollectionWrapper; import com.zanclus.scanalyzer.domain.entities.ScanCollectionWrapper; @Path("/host") public class HostService { @Context private Request request; @Context UriInfo url; private Logger log = null; public HostService() { super(); log = LoggerFactory.getLogger(this.getClass()); } @GET @Path("/id/{id : ([0-9]*)}") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Host getHostById(@PathParam("id") Long hostId) { log.info("Processing GET request for host ID '" + hostId + "'"); HostDAO dao = new HostDAO(); return dao.findById(hostId); } @GET @Path("/id/{id : ([0-9]*)}/scans") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public ScanCollectionWrapper getHostScans(@PathParam("id") Long id, @QueryParam("limit") @DefaultValue("20") int limit, @QueryParam("offset") @DefaultValue("0") int offset) { ScanDAO dao = new ScanDAO() ; return new ScanCollectionWrapper(dao.getPagedScansByHostId(id, limit, offset)) ; } @GET @Path("/id/{id : ([0-9]*)}/portHistory") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public PortsCollectionWrapper getHostPortHistory(@PathParam("id") Long id, @QueryParam("limit") @DefaultValue("20") int limit, @QueryParam("offset") @DefaultValue("0") int offset) { PortsDAO dao = new PortsDAO() ; return new PortsCollectionWrapper(dao.getPagedPortsHistoryByHostId(id, limit, offset)) ; } @GET @Path("/address/{address : (.*)$}") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Host getHostByAddress(@PathParam("address") String address) { log.info("Processing GET request for address '" + address + "'"); byte[] inetAddress = null; try { inetAddress = InetAddress.getByName(address).getAddress(); } catch (UnknownHostException e) { throw new WebApplicationException(e, Status.BAD_REQUEST); } HostDAO dao = new HostDAO(); return dao.getHostByAddress(inetAddress); } @POST @Path("/address/{address : (.*)$}") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Host addHostByAddress(@PathParam("address") String address) { log.info("Request URL: "+url.getPath()); log.info("Processing POST request for address '" + address + "'"); if (address == null) { log.error("Address is NULL"); } byte[] inetAddress = null; try { inetAddress = InetAddress.getByName(address).getAddress(); } catch (UnknownHostException e) { throw new WebApplicationException(e, Status.BAD_REQUEST); } HostDAO dao = new HostDAO(); Host retVal = null; try { retVal = dao.addHost(inetAddress); } catch (Exception e) { throw new WebApplicationException(e, Status.CONFLICT); } return retVal; } @DELETE @Path("/id/{id : ([0-9]*)$}") public Response deleteHost(@PathParam("id") Long id) throws WebApplicationException { try { HostDAO dao = new HostDAO() ; dao.delete(id) ; } catch (Throwable t) { throw new WebApplicationException(t, Status.NOT_FOUND) ; } Response retVal = new ResponseBuilderImpl().status(202).build() ; return retVal ; } @PUT @Path("/id/{id : ([0-9]*)$}") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response updateHost(Host updates) { log.info("Request URL: "+url.getPath()); log.info("Processing PUT request for host ID '" + updates.getId() + "'"); HostDAO dao = new HostDAO() ; Host updatedHost = dao.update(updates) ; Response retVal = new ResponseBuilderImpl().entity(updatedHost).status(204).build() ; return retVal ; } }
package de.prob2.ui.visualisation; import java.io.FileNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob2.ui.internal.StageManager; import de.prob2.ui.prob2fx.CurrentTrace; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ScrollPane; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; @Singleton public class VisualisationView extends AnchorPane { private static final Logger LOGGER = LoggerFactory.getLogger(VisualisationView.class); @FXML private StackPane probLogoStackPane; @FXML private ScrollPane visualisationScrollPane; @FXML private StateVisualisationView currentStateVisualisation; @FXML private StateVisualisationView previousStateVisualisation; @FXML private VBox previousStateVBox; private final CurrentTrace currentTrace; private final StageManager stageManager; @Inject public VisualisationView(final CurrentTrace currentTrace, final StageManager stageManager) { this.currentTrace = currentTrace; this.stageManager = stageManager; stageManager.loadFXML(this, "visualisation_view.fxml"); } @FXML public void initialize() { visualisationScrollPane.visibleProperty().bind(probLogoStackPane.visibleProperty().not()); probLogoStackPane.visibleProperty().bind(currentStateVisualisation.visualisationPossibleProperty().not()); previousStateVBox.managedProperty().bind(previousStateVisualisation.visualisationPossibleProperty()); previousStateVBox.visibleProperty().bind(previousStateVBox.managedProperty()); currentTrace.currentStateProperty().addListener((observable, from, to) -> { try { currentStateVisualisation.visualiseState(to); if (to != null && currentTrace.canGoBack()) { previousStateVisualisation.visualiseState(currentTrace.get().getPreviousState()); } } catch (FileNotFoundException e) { LOGGER.warn("Failed to open images for visualisation", e); Alert alert = stageManager.makeAlert(Alert.AlertType.WARNING, e.getMessage()); alert.setHeaderText("Visualisation not possible"); alert.showAndWait(); } }); } }
package org.ovirt.engine.ui.uicommonweb.models.vms; import java.util.ArrayList; import org.ovirt.engine.core.common.action.AddDiskParameters; import org.ovirt.engine.core.common.action.AttachDettachVmDiskParameters; import org.ovirt.engine.core.common.action.HotPlugDiskToVmParameters; import org.ovirt.engine.core.common.action.RemoveDiskParameters; import org.ovirt.engine.core.common.action.UpdateVmDiskParameters; import org.ovirt.engine.core.common.action.VdcActionParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.action.VmDiskOperatinParameterBase; import org.ovirt.engine.core.common.businessentities.ActionGroup; import org.ovirt.engine.core.common.businessentities.Disk; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.DiskImageBase; import org.ovirt.engine.core.common.businessentities.DiskInterface; import org.ovirt.engine.core.common.businessentities.ImageStatus; import org.ovirt.engine.core.common.businessentities.PropagateErrors; import org.ovirt.engine.core.common.businessentities.Quota; import org.ovirt.engine.core.common.businessentities.QuotaEnforcementTypeEnum; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.StorageType; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VolumeType; import org.ovirt.engine.core.common.businessentities.storage_domains; import org.ovirt.engine.core.common.businessentities.storage_pool; import org.ovirt.engine.core.common.queries.GetAllDisksByVmIdParameters; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.compat.PropertyChangedEventArgs; import org.ovirt.engine.core.compat.StringHelper; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.ui.frontend.AsyncQuery; import org.ovirt.engine.ui.frontend.Frontend; import org.ovirt.engine.ui.frontend.INewAsyncCallback; import org.ovirt.engine.ui.uicommonweb.DataProvider; import org.ovirt.engine.ui.uicommonweb.Linq; import org.ovirt.engine.ui.uicommonweb.Linq.DiskByAliasComparer; import org.ovirt.engine.ui.uicommonweb.UICommand; import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider; import org.ovirt.engine.ui.uicommonweb.models.EntityModel; import org.ovirt.engine.ui.uicommonweb.models.SearchableListModel; import org.ovirt.engine.ui.uicompat.ConstantsManager; import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult; import org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult; import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback; import org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback; @SuppressWarnings("unused") public class VmDiskListModel extends SearchableListModel { private UICommand privateNewCommand; public UICommand getNewCommand() { return privateNewCommand; } private void setNewCommand(UICommand value) { privateNewCommand = value; } private UICommand privateEditCommand; public UICommand getEditCommand() { return privateEditCommand; } private void setEditCommand(UICommand value) { privateEditCommand = value; } private UICommand privateRemoveCommand; public UICommand getRemoveCommand() { return privateRemoveCommand; } private void setRemoveCommand(UICommand value) { privateRemoveCommand = value; } private UICommand privatePlugCommand; public UICommand getPlugCommand() { return privatePlugCommand; } private void setPlugCommand(UICommand value) { privatePlugCommand = value; } private UICommand privateUnPlugCommand; public UICommand getUnPlugCommand() { return privateUnPlugCommand; } private void setUnPlugCommand(UICommand value) { privateUnPlugCommand = value; } private boolean privateIsDiskHotPlugSupported; public boolean getIsDiskHotPlugSupported() { VM vm = (VM) getEntity(); boolean isVmStatusApplicableForHotPlug = vm != null && (vm.getstatus() == VMStatus.Up || vm.getstatus() == VMStatus.Down | vm.getstatus() == VMStatus.Paused || vm.getstatus() == VMStatus.Suspended); return privateIsDiskHotPlugSupported && isVmStatusApplicableForHotPlug; } private void setIsDiskHotPlugSupported(boolean value) { if (privateIsDiskHotPlugSupported != value) { privateIsDiskHotPlugSupported = value; OnPropertyChanged(new PropertyChangedEventArgs("IsDiskHotPlugSupported")); //$NON-NLS-1$ } } private UICommand privateMoveCommand; public UICommand getMoveCommand() { return privateMoveCommand; } private void setMoveCommand(UICommand value) { privateMoveCommand = value; } private ArrayList<DiskImageBase> presets; private String nextAlias; private storage_pool datacenter; public VmDiskListModel() { setTitle(ConstantsManager.getInstance().getConstants().virtualDisksTitle()); setHashName("virtual_disks"); //$NON-NLS-1$ setNewCommand(new UICommand("New", this)); //$NON-NLS-1$ setEditCommand(new UICommand("Edit", this)); //$NON-NLS-1$ setRemoveCommand(new UICommand("Remove", this)); //$NON-NLS-1$ setPlugCommand(new UICommand("Plug", this)); //$NON-NLS-1$ setUnPlugCommand(new UICommand("Unplug", this)); //$NON-NLS-1$ setMoveCommand(new UICommand("Move", this)); //$NON-NLS-1$ UpdateActionAvailability(); } @Override public VM getEntity() { return (VM) super.getEntity(); } public void setEntity(VM value) { super.setEntity(value); UpdateIsDiskHotPlugAvailable(); } @Override protected void OnEntityChanged() { super.OnEntityChanged(); if (getEntity() != null) { getSearchCommand().Execute(); } UpdateActionAvailability(); } @Override protected void SyncSearch() { if (getEntity() == null) { return; } VM vm = (VM) getEntity(); super.SyncSearch(VdcQueryType.GetAllDisksByVmId, new GetAllDisksByVmIdParameters(vm.getId())); } @Override protected void AsyncSearch() { super.AsyncSearch(); VM vm = (VM) getEntity(); setAsyncResult(Frontend.RegisterQuery(VdcQueryType.GetAllDisksByVmId, new GetAllDisksByVmIdParameters(vm.getId()))); setItems(getAsyncResult().getData()); } @Override public void setItems(Iterable value) { ArrayList<DiskImage> disks = value != null ? Linq.<DiskImage> Cast(value) : new ArrayList<DiskImage>(); Linq.Sort(disks, new DiskByAliasComparer()); super.setItems(disks); UpdateActionAvailability(); } private void New() { final VM vm = (VM) getEntity(); if (getWindow() != null) { return; } DiskModel model = new DiskModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().addVirtualDiskTitle()); model.setHashName("new_virtual_disk"); //$NON-NLS-1$ model.setIsNew(true); model.setDatacenterId(vm.getstorage_pool_id()); model.StartProgress(null); AddDiskUpdateData(); } private void AddDiskUpdateData() { AsyncDataProvider.GetPermittedStorageDomainsByStoragePoolId(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { VmDiskListModel vmDiskListModel = (VmDiskListModel) target; ArrayList<storage_domains> storageDomains = (ArrayList<storage_domains>) returnValue; DiskModel diskModel = (DiskModel) vmDiskListModel.getWindow(); ArrayList<DiskImage> disks = getItems() != null ? Linq.<DiskImage> Cast(getItems()) : new ArrayList<DiskImage>(); ArrayList<storage_domains> filteredStorageDomains = new ArrayList<storage_domains>(); for (storage_domains a : (ArrayList<storage_domains>) storageDomains) { if (a.getstorage_domain_type() != StorageDomainType.ISO && a.getstorage_domain_type() != StorageDomainType.ImportExport && a.getstatus() == StorageDomainStatus.Active) { filteredStorageDomains.add(a); } } Linq.Sort(filteredStorageDomains, new Linq.StorageDomainByNameComparer()); storage_domains selectedStorage = Linq.FirstOrDefault(filteredStorageDomains); StorageType storageType = selectedStorage == null ? StorageType.UNKNOWN : selectedStorage.getstorage_type(); diskModel.getStorageDomain().setItems(filteredStorageDomains); diskModel.getStorageDomain().setSelectedItem(selectedStorage); AsyncDataProvider.GetDiskPresetList(new AsyncQuery(vmDiskListModel, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { VmDiskListModel vmDiskListModel = (VmDiskListModel) target; DiskModel diskModel1 = (DiskModel) vmDiskListModel.getWindow(); ArrayList<DiskImageBase> presets = (ArrayList<DiskImageBase>) returnValue; diskModel1.getPreset().setItems(presets); vmDiskListModel.presets = presets; vmDiskListModel.AddDiskPostData(); } }), getEntity().getvm_type(), storageType); } }), getEntity().getstorage_pool_id(), ActionGroup.CREATE_VM); AsyncDataProvider.GetNextAvailableDiskAliasNameByVMId(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object returnValue) { String suggestedDiskName = (String) returnValue; VmDiskListModel vmDiskListModel = (VmDiskListModel) model; DiskModel diskModel = (DiskModel) vmDiskListModel.getWindow(); diskModel.getAlias().setEntity(suggestedDiskName); vmDiskListModel.nextAlias = suggestedDiskName; vmDiskListModel.AddDiskPostData(); } }), getEntity().getId()); AsyncDataProvider.GetDataCenterById(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object returnValue) { storage_pool datacenter = (storage_pool) returnValue; VmDiskListModel vmDiskListModel = (VmDiskListModel) model; DiskModel dModel = (DiskModel) vmDiskListModel.getWindow(); if (datacenter.getQuotaEnforcementType().equals(QuotaEnforcementTypeEnum.DISABLED)) { dModel.getQuota().setIsAvailable(false); } else { dModel.getQuota().setIsAvailable(true); dModel.quota_storageSelectedItemChanged(getEntity().getQuotaId()); } vmDiskListModel.datacenter = datacenter; vmDiskListModel.AddDiskPostData(); } }), getEntity().getstorage_pool_id()); } private void AddDiskPostData() { if (presets == null || nextAlias == null || datacenter == null) { return; } DiskModel diskModel = (DiskModel) getWindow(); storage_domains storage = (storage_domains) diskModel.getStorageDomain().getSelectedItem(); ArrayList<DiskImage> disks = getItems() != null ? Linq.<DiskImage> Cast(getItems()) : new ArrayList<DiskImage>(); boolean hasDisks = disks.size() > 0; diskModel.getInterface().setItems(DataProvider.GetDiskInterfaceList( getEntity().getvm_os(), getEntity().getvds_group_compatibility_version())); diskModel.getInterface().setSelectedItem(DataProvider.GetDefaultDiskInterface( getEntity().getvm_os(), disks)); if (storage != null) { UpdateWipeAfterDelete(storage.getstorage_type(), diskModel.getWipeAfterDelete(), true); } else { String cantCreateMessage = hasDisks ? ConstantsManager.getInstance().getMessages().errorRetrievingStorageDomains() : ConstantsManager.getInstance().getMessages().noActiveStorageDomains(); diskModel.setMessage(cantCreateMessage); } diskModel.getPreset().setItems(presets); for (DiskImageBase a : presets) { if ((hasDisks && !a.isBoot()) || (!hasDisks && a.isBoot())) { diskModel.getPreset().setSelectedItem(a); break; } } boolean hasBootableDisk = false; for (DiskImage a : disks) { if (a.isBoot()) { hasBootableDisk = true; break; } } diskModel.getIsBootable().setEntity(!hasBootableDisk); if (hasBootableDisk) { diskModel.getIsBootable().setIsChangable(false); diskModel.getIsBootable() .getChangeProhibitionReasons() .add("There can be only one bootable disk defined."); //$NON-NLS-1$ } ArrayList<UICommand> commands = new ArrayList<UICommand>(); UICommand tempVar2 = new UICommand("OnSave", this); //$NON-NLS-1$ tempVar2.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar2.setIsDefault(true); diskModel.getCommands().add(tempVar2); UICommand tempVar3 = new UICommand("Cancel", this); //$NON-NLS-1$ tempVar3.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar3.setIsCancel(true); diskModel.getCommands().add(tempVar3); diskModel.StopProgress(); } private void Edit() { final DiskImage disk = (DiskImage) getSelectedItem(); if (getWindow() != null) { return; } DiskModel model = new DiskModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().editVirtualDiskTitle()); model.setHashName("edit_virtual_disk"); //$NON-NLS-1$ model.getStorageDomain().setIsChangable(false); model.getSize().setEntity(disk.getSizeInGigabytes()); model.getSize().setIsChangable(false); model.getAttachDisk().setIsChangable(false); AsyncQuery _asyncQuery1 = new AsyncQuery(); _asyncQuery1.setModel(this); _asyncQuery1.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object result) { VmDiskListModel vmDiskListModel = (VmDiskListModel) model; DiskModel diskModel = (DiskModel) vmDiskListModel.getWindow(); VM vm = (VM) vmDiskListModel.getEntity(); storage_domains storageDomain = (storage_domains) result; DiskImage disk = (DiskImage) vmDiskListModel.getSelectedItem(); diskModel.getStorageDomain().setSelectedItem(storageDomain); DiskImageBase preset = new DiskImage(); diskModel.getPreset().setSelectedItem(preset); diskModel.getPreset().setIsChangable(false); diskModel.getVolumeType().setSelectedItem(disk.getvolume_type()); diskModel.getVolumeType().setIsChangable(false); diskModel.setVolumeFormat(disk.getvolume_format()); ArrayList<DiskInterface> interfaces = DataProvider.GetDiskInterfaceList(vm.getvm_os(), vm.getvds_group_compatibility_version()); if (!interfaces.contains(disk.getDiskInterface())) { interfaces.add(disk.getDiskInterface()); } diskModel.getInterface().setItems(interfaces); diskModel.getInterface().setSelectedItem(disk.getDiskInterface()); // Allow interface type to be edited only if the disk is not sharable diskModel.getInterface().setIsChangable(!disk.isShareable()); storage_domains storage = (storage_domains) diskModel.getStorageDomain().getSelectedItem(); diskModel.getWipeAfterDelete().setEntity(disk.isWipeAfterDelete()); if (diskModel.getStorageDomain() != null && diskModel.getStorageDomain().getSelectedItem() != null) { vmDiskListModel.UpdateWipeAfterDelete(storage.getstorage_type(), diskModel.getWipeAfterDelete(), false); } ArrayList<DiskImage> disks = vmDiskListModel.getItems() != null ? Linq.<DiskImage> Cast(vmDiskListModel.getItems()) : new ArrayList<DiskImage>(); DiskImage bootableDisk = null; for (DiskImage a : disks) { if (a.isBoot()) { bootableDisk = a; break; } } if (bootableDisk != null && !bootableDisk.getImageId().equals(disk.getImageId())) { diskModel.getIsBootable().setIsChangable(false); diskModel.getIsBootable() .getChangeProhibitionReasons() .add("There can be only one bootable disk defined."); //$NON-NLS-1$ } diskModel.getIsBootable().setEntity(disk.isBoot()); diskModel.getAlias().setEntity(disk.getDiskAlias()); diskModel.getDescription().setEntity(disk.getDiskDescription()); UICommand tempVar = new UICommand("OnSave", vmDiskListModel); //$NON-NLS-1$ tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); diskModel.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", vmDiskListModel); //$NON-NLS-1$ tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); diskModel.getCommands().add(tempVar2); } }; AsyncDataProvider.GetStorageDomainById(_asyncQuery1, disk.getstorage_ids().get(0)); AsyncDataProvider.GetDataCenterById(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object returnValue) { storage_pool dataCenter = (storage_pool) returnValue; VmDiskListModel vmDiskListModel1 = (VmDiskListModel) model; DiskModel dModel = (DiskModel) vmDiskListModel1.getWindow(); if (dataCenter.getQuotaEnforcementType().equals(QuotaEnforcementTypeEnum.DISABLED)) { dModel.getQuota().setIsAvailable(false); } else { dModel.getQuota().setIsAvailable(true); dModel.quota_storageSelectedItemChanged(disk.getQuotaId()); } } }), ((VM) getEntity()).getstorage_pool_id()); } private void remove() { if (getWindow() != null) { return; } boolean hasSystemDiskWarning = false; RemoveDiskModel model = new RemoveDiskModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().removeDisksTitle()); model.setHashName("remove_disk"); //$NON-NLS-1$ model.setMessage(ConstantsManager.getInstance().getConstants().disksMsg()); model.getLatch().setEntity(true); ArrayList<String> items = new ArrayList<String>(); for (Object item : getSelectedItems()) { DiskImage a = (DiskImage) item; items.add(a.getDiskAlias()); } model.setItems(items); UICommand tempVar = new UICommand("OnRemove", this); //$NON-NLS-1$ tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$ tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); } private void OnRemove() { VM vm = (VM) getEntity(); RemoveDiskModel model = (RemoveDiskModel) getWindow(); boolean removeDisk = (Boolean) model.getLatch().getEntity(); VdcActionType actionType = removeDisk ? VdcActionType.RemoveDisk : VdcActionType.DetachDiskFromVm; ArrayList<VdcActionParametersBase> paramerterList = new ArrayList<VdcActionParametersBase>(); for (Object item : getSelectedItems()) { Disk disk = (Disk) item; VdcActionParametersBase parameters = removeDisk ? new RemoveDiskParameters(disk.getId()) : new AttachDettachVmDiskParameters(vm.getId(), disk.getId(), true); paramerterList.add(parameters); } model.StartProgress(null); Frontend.RunMultipleAction(actionType, paramerterList, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { VmDiskListModel localModel = (VmDiskListModel) result.getState(); localModel.StopProgress(); Cancel(); } }, this); } private void OnSave() { VM vm = (VM) getEntity(); DiskModel model = (DiskModel) getWindow(); if (model.getProgress() != null || !model.Validate()) { return; } if ((Boolean) model.getAttachDisk().getEntity()) { OnAttachDisks(); return; } // Save changes. storage_domains storageDomain = (storage_domains) model.getStorageDomain().getSelectedItem(); DiskImage disk = model.getIsNew() ? new DiskImage() : (DiskImage) getSelectedItem(); disk.setSizeInGigabytes(Integer.parseInt(model.getSize().getEntity().toString())); disk.setDiskAlias((String) model.getAlias().getEntity()); disk.setDiskDescription((String) model.getDescription().getEntity()); disk.setDiskInterface((DiskInterface) model.getInterface().getSelectedItem()); disk.setvolume_type((VolumeType) model.getVolumeType().getSelectedItem()); disk.setvolume_format(model.getVolumeFormat()); disk.setWipeAfterDelete((Boolean) model.getWipeAfterDelete().getEntity()); disk.setBoot((Boolean) model.getIsBootable().getEntity()); disk.setPlugged((Boolean) model.getIsPlugged().getEntity()); if (model.getQuota().getIsAvailable()) { disk.setQuotaId(((Quota) model.getQuota().getSelectedItem()).getId()); } // NOTE: Since we doesn't support partial snapshots in GUI, propagate errors flag always must be set false. // disk.propagate_errors = model.PropagateErrors.ValueAsBoolean() ? PropagateErrors.On : PropagateErrors.Off; disk.setPropagateErrors(PropagateErrors.Off); model.StartProgress(null); VdcActionType actionType; VmDiskOperatinParameterBase parameters; if (model.getIsNew()) { parameters = new AddDiskParameters(vm.getId(), disk); ((AddDiskParameters) parameters).setStorageDomainId(storageDomain.getId()); actionType = VdcActionType.AddDisk; } else { parameters = new UpdateVmDiskParameters(vm.getId(), disk.getId(), disk); actionType = VdcActionType.UpdateVmDisk; } Frontend.RunAction(actionType, parameters, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmDiskListModel localModel = (VmDiskListModel) result.getState(); localModel.PostOnSaveInternal(result.getReturnValue()); } }, this); } private void OnAttachDisks() { VM vm = (VM) getEntity(); DiskModel model = (DiskModel) getWindow(); ArrayList<VdcActionParametersBase> paramerterList = new ArrayList<VdcActionParametersBase>(); for (EntityModel item : (ArrayList<EntityModel>) model.getAttachableDisks().getSelectedItems()) { DiskModel disk = (DiskModel) item.getEntity(); disk.getDiskImage().setPlugged((Boolean) model.getIsPlugged().getEntity()); UpdateVmDiskParameters parameters = new UpdateVmDiskParameters(vm.getId(), disk.getDiskImage().getId(), disk.getDiskImage()); paramerterList.add(parameters); } model.StartProgress(null); Frontend.RunMultipleAction(VdcActionType.AttachDiskToVm, paramerterList, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { VmDiskListModel localModel = (VmDiskListModel) result.getState(); localModel.getWindow().StopProgress(); Cancel(); } }, this); } public void PostOnSaveInternal(VdcReturnValueBase returnValue) { DiskModel model = (DiskModel) getWindow(); model.StopProgress(); if (returnValue != null && returnValue.getSucceeded()) { Cancel(); } } private void Plug(boolean plug) { VM vm = (VM) getEntity(); ArrayList<VdcActionParametersBase> paramerterList = new ArrayList<VdcActionParametersBase>(); for (Object item : getSelectedItems()) { DiskImage disk = (DiskImage) item; disk.setPlugged(plug); paramerterList.add(new HotPlugDiskToVmParameters(vm.getId(), disk.getId())); } VdcActionType plugAction = VdcActionType.HotPlugDiskToVm; if (!plug) { plugAction = VdcActionType.HotUnPlugDiskFromVm; } Frontend.RunMultipleAction(plugAction, paramerterList, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { } }, this); } private void Move() { ArrayList<DiskImage> disks = (ArrayList<DiskImage>) getSelectedItems(); if (disks == null) { return; } if (getWindow() != null) { return; } VM vm = (VM) getEntity(); MoveDiskModel model = new MoveDiskModel(); model.setIsSingleDiskMove(disks.size() == 1); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().moveDisksTitle()); model.setHashName("move_disk"); //$NON-NLS-1$ model.setIsSourceStorageDomainNameAvailable(true); model.setEntity(this); model.init(disks); model.StartProgress(null); } private void ResetData() { presets = null; nextAlias = null; datacenter = null; } private void Cancel() { setWindow(null); ResetData(); } @Override protected void OnSelectedItemChanged() { super.OnSelectedItemChanged(); UpdateActionAvailability(); } @Override protected void SelectedItemsChanged() { super.SelectedItemsChanged(); UpdateActionAvailability(); } @Override protected void EntityPropertyChanged(Object sender, PropertyChangedEventArgs e) { super.EntityPropertyChanged(sender, e); if (e.PropertyName.equals("status")) //$NON-NLS-1$ { UpdateActionAvailability(); } } private void UpdateActionAvailability() { VM vm = (VM) getEntity(); DiskImage disk = (DiskImage) getSelectedItem(); boolean isDiskLocked = disk != null && disk.getimageStatus() == ImageStatus.LOCKED; getNewCommand().setIsExecutionAllowed(isVmDown()); getEditCommand().setIsExecutionAllowed(getSelectedItem() != null && getSelectedItems() != null && getSelectedItems().size() == 1 && isVmDown() && !isDiskLocked); getRemoveCommand().setIsExecutionAllowed(getSelectedItems() != null && getSelectedItems().size() > 0 && isRemoveCommandAvailable()); getMoveCommand().setIsExecutionAllowed(getSelectedItems() != null && getSelectedItems().size() > 0 && isMoveCommandAvailable()); getPlugCommand().setIsExecutionAllowed(isPlugCommandAvailable(true)); getUnPlugCommand().setIsExecutionAllowed(isPlugCommandAvailable(false)); } public boolean isVmDown() { VM vm = (VM) getEntity(); return vm != null && vm.getstatus() == VMStatus.Down; } public boolean isHotPlugAvailable() { VM vm = (VM) getEntity(); return vm != null && (vm.getstatus() == VMStatus.Up || vm.getstatus() == VMStatus.Paused || vm.getstatus() == VMStatus.Suspended); } private boolean isPlugCommandAvailable(boolean plug) { return getSelectedItems() != null && getSelectedItems().size() > 0 && isPlugAvailableByDisks(plug) && (isVmDown() || (isHotPlugAvailable() && getIsDiskHotPlugSupported())); } private boolean isPlugAvailableByDisks(boolean plug) { ArrayList<DiskImage> disks = getSelectedItems() != null ? Linq.<DiskImage> Cast(getSelectedItems()) : new ArrayList<DiskImage>(); for (DiskImage disk : disks) { if (disk.getPlugged() == plug || disk.getDiskInterface() == DiskInterface.IDE || disk.getimageStatus() == ImageStatus.LOCKED) { return false; } } return true; } private boolean isMoveCommandAvailable() { ArrayList<DiskImage> disks = getSelectedItems() != null ? Linq.<DiskImage> Cast(getSelectedItems()) : new ArrayList<DiskImage>(); for (DiskImage disk : disks) { if (disk.getimageStatus() != ImageStatus.OK || (!isVmDown() && disk.getPlugged())) { return false; } } return true; } private boolean isRemoveCommandAvailable() { ArrayList<DiskImage> disks = getSelectedItems() != null ? Linq.<DiskImage> Cast(getSelectedItems()) : new ArrayList<DiskImage>(); for (DiskImage disk : disks) { if (disk.getimageStatus() == ImageStatus.LOCKED || (!isVmDown() && disk.getPlugged())) { return false; } } return true; } @Override public void ExecuteCommand(UICommand command) { super.ExecuteCommand(command); if (command == getNewCommand()) { New(); } else if (command == getEditCommand()) { Edit(); } else if (command == getRemoveCommand()) { remove(); } else if (command == getMoveCommand()) { Move(); } else if (StringHelper.stringsEqual(command.getName(), "OnSave")) //$NON-NLS-1$ { OnSave(); } else if (StringHelper.stringsEqual(command.getName(), "Cancel")) //$NON-NLS-1$ { Cancel(); } else if (StringHelper.stringsEqual(command.getName(), "OnRemove")) //$NON-NLS-1$ { OnRemove(); } else if (command == getPlugCommand()) { Plug(true); } else if (command == getUnPlugCommand()) { Plug(false); } } private void UpdateWipeAfterDelete(StorageType storageType, EntityModel wipeAfterDeleteModel, boolean isNew) { if (storageType == StorageType.NFS || storageType == StorageType.LOCALFS) { wipeAfterDeleteModel.setIsChangable(false); } else { wipeAfterDeleteModel.setIsChangable(true); if (isNew) { AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(getWindow()); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object result) { DiskModel diskModel = (DiskModel) model; diskModel.getWipeAfterDelete().setEntity(result); } }; AsyncDataProvider.GetSANWipeAfterDelete(_asyncQuery); } } } protected void UpdateIsDiskHotPlugAvailable() { if (getEntity() == null) { return; } VM vm = (VM) getEntity(); Version clusterCompatibilityVersion = vm.getvds_group_compatibility_version() != null ? vm.getvds_group_compatibility_version() : new Version(); AsyncDataProvider.IsDiskHotPlugAvailable(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { VmDiskListModel model = (VmDiskListModel) target; model.setIsDiskHotPlugSupported((Boolean) returnValue); } }), clusterCompatibilityVersion.toString()); } @Override protected String getListName() { return "VmDiskListModel"; //$NON-NLS-1$ } }
package de.retest.recheck.auth; import static org.keycloak.adapters.rotation.AdapterTokenVerifier.verifyToken; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.keycloak.OAuth2Constants; import org.keycloak.OAuthErrorException; import org.keycloak.adapters.KeycloakDeployment; import org.keycloak.adapters.KeycloakDeploymentBuilder; import org.keycloak.adapters.ServerRequest; import org.keycloak.adapters.ServerRequest.HttpFailure; import org.keycloak.common.VerificationException; import org.keycloak.common.util.KeycloakUriBuilder; import org.keycloak.representations.AccessTokenResponse; import org.keycloak.representations.adapters.config.AdapterConfig; import lombok.Cleanup; import lombok.extern.slf4j.Slf4j; @Slf4j public class RetestAuthentication { public static final String AUTH_SERVER_PROPERTY = "de.retest.auth.server"; private static final String AUTH_SERVER_PROPERTY_DEFAULT = "https://sso.prod.cloud.retest.org/auth"; public static final String RESOURCE_PROPERTY = "de.retest.auth.resource"; private static final String RESOURCE_PROPERTY_DEFAULT = "review"; private final KeycloakDeployment deployment; private String offlineToken; private String accessToken; private static RetestAuthentication instance; private RetestAuthentication() { final AdapterConfig config = new AdapterConfig(); config.setRealm( "customer" ); config.setAuthServerUrl( System.getProperty( AUTH_SERVER_PROPERTY, AUTH_SERVER_PROPERTY_DEFAULT ) ); config.setSslRequired( "external" ); config.setResource( System.getProperty( RESOURCE_PROPERTY, RESOURCE_PROPERTY_DEFAULT ) ); config.setPublicClient( true ); deployment = KeycloakDeploymentBuilder.build( config ); } public static RetestAuthentication getInstance() { if ( instance == null ) { instance = new RetestAuthentication(); } return instance; } public URI getAccountUrl() { return URI.create( deployment.getAccountUrl() ); } public boolean isAuthenticated( final String offlineToken ) { if ( offlineToken != null ) { this.offlineToken = offlineToken; try { final AccessTokenResponse response = ServerRequest.invokeRefresh( deployment, offlineToken ); accessToken = response.getToken(); return true; } catch ( IOException | HttpFailure e ) { log.info( "Token not recognized, initiating authentication" ); } } return false; } public void login( final AuthenticationHandler handler ) throws IOException, HttpFailure { try { final CallbackListener callback = new CallbackListener(); callback.start(); final String redirectUri = "http://localhost:" + callback.server.getLocalPort(); final String state = UUID.randomUUID().toString(); final KeycloakUriBuilder builder = deployment.getAuthUrl().clone() .queryParam( OAuth2Constants.RESPONSE_TYPE, OAuth2Constants.CODE ) .queryParam( OAuth2Constants.CLIENT_ID, deployment.getResourceName() ) .queryParam( OAuth2Constants.REDIRECT_URI, redirectUri ) .queryParam( OAuth2Constants.STATE, state ) .queryParam( OAuth2Constants.SCOPE, OAuth2Constants.OFFLINE_ACCESS ); final URI loginUri = URI.create( builder.build().toString() ); handler.showWebLoginUri( loginUri ); callback.join(); if ( !state.equals( callback.result.getState() ) ) { final VerificationException reason = new VerificationException( "Invalid state" ); handler.authenticationFailed( reason ); } if ( callback.result.getError() != null ) { final OAuthErrorException reason = new OAuthErrorException( callback.result.getError(), callback.result.getErrorDescription() ); handler.authenticationFailed( reason ); } if ( callback.result.getErrorException() != null ) { handler.authenticationFailed( callback.result.getErrorException() ); } final AccessTokenResponse tokenResponse = ServerRequest.invokeAccessCodeToToken( deployment, callback.result.getCode(), redirectUri, null ); accessToken = tokenResponse.getToken(); offlineToken = tokenResponse.getRefreshToken(); handler.authenticated(); } catch ( final InterruptedException e ) { log.error( "Error during authentication, thread interrupted", e ); Thread.currentThread().interrupt(); } } public String getAccessToken() { refreshTokens(); return accessToken; } public String getOfflineToken() { return offlineToken; } private void refreshTokens() { if ( !isTokenValid() ) { try { ServerRequest.invokeRefresh( deployment, offlineToken ); } catch ( final IOException | HttpFailure e ) { log.error( "Error refreshing token(s)", e ); } } } private boolean isTokenValid() { try { return accessToken != null && verifyToken( accessToken, deployment ).isActive(); } catch ( final VerificationException e ) { log.info( "Current token is invalid, requesting new one" ); } return false; } static KeycloakResult getRequestParameters( final String request ) { final String url = "http://localhost/" + request.split( " " )[1]; final Map<String, String> parameters = URLEncodedUtils.parse( URI.create( url ), StandardCharsets.UTF_8 ) .stream() .collect( Collectors.toMap( NameValuePair::getName, NameValuePair::getValue ) ); return KeycloakResult.builder() .code( parameters.get( OAuth2Constants.CODE ) ) .error( parameters.get( OAuth2Constants.ERROR ) ) .errorDescription( parameters.get( "error-description" ) ) .state( parameters.get( OAuth2Constants.STATE ) ) .build(); } private class CallbackListener extends Thread { private final ServerSocket server; private KeycloakResult result; public CallbackListener() throws IOException { server = new ServerSocket( 0 ); } @Override public void run() { try ( Socket socket = server.accept() ) { @Cleanup final BufferedReader br = new BufferedReader( new InputStreamReader( socket.getInputStream() ) ); final String request = br.readLine(); result = getRequestParameters( request ); @Cleanup final OutputStreamWriter out = new OutputStreamWriter( socket.getOutputStream() ); @Cleanup final PrintWriter writer = new PrintWriter( out ); if ( result.getError() == null ) { writer.println( "HTTP/1.1 302 Found" ); writer.println( "Location: " + deployment.getTokenUrl().replace( "/token", "/delegated" ) ); } else { writer.println( "HTTP/1.1 302 Found" ); writer.println( "Location: " + deployment.getTokenUrl().replace( "/token", "/delegated?error=true" ) ); } } catch ( final IOException e ) { log.error( "Error during communication with sso.cloud.retest.org", e ); } } } }
package jolie.net; import com.ibm.wsdl.extensions.schema.SchemaImpl; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.URI; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.soap.Detail; import javax.xml.soap.DetailEntry; import javax.xml.soap.MessageFactory; import javax.xml.soap.Name; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPBodyElement; import javax.xml.soap.SOAPConstants; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPFault; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPHeaderElement; import javax.xml.soap.SOAPMessage; import jolie.lang.Constants; import jolie.Interpreter; import jolie.runtime.FaultException; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.VariablePath; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.sun.xml.xsom.XSAttributeDecl; import com.sun.xml.xsom.XSAttributeUse; import com.sun.xml.xsom.XSComplexType; import com.sun.xml.xsom.XSContentType; import com.sun.xml.xsom.XSElementDecl; import com.sun.xml.xsom.XSModelGroup; import com.sun.xml.xsom.XSModelGroupDecl; import com.sun.xml.xsom.XSParticle; import com.sun.xml.xsom.XSSchema; import com.sun.xml.xsom.XSSchemaSet; import com.sun.xml.xsom.XSTerm; import com.sun.xml.xsom.XSType; import com.sun.xml.xsom.parser.XSOMParser; import java.io.ByteArrayInputStream; import java.io.StringReader; import java.io.StringWriter; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.wsdl.BindingOperation; import javax.wsdl.BindingOutput; import javax.wsdl.Definition; import javax.wsdl.Operation; import javax.wsdl.Part; import javax.wsdl.Port; import javax.wsdl.Service; import javax.wsdl.Types; import javax.wsdl.WSDLException; import javax.wsdl.extensions.ExtensibilityElement; import javax.wsdl.extensions.soap.SOAPOperation; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import jolie.net.http.HttpMessage; import jolie.net.http.HttpParser; import jolie.net.http.HttpUtils; import jolie.net.ports.Interface; import jolie.net.protocols.SequentialCommProtocol; import jolie.net.soap.WSDLCache; import jolie.runtime.typing.OneWayTypeDescription; import jolie.runtime.typing.RequestResponseTypeDescription; import jolie.runtime.typing.Type; import jolie.runtime.typing.TypeCastingException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; /** * Implements the SOAP over HTTP protocol. * * @author Fabrizio Montesi * * 2006 - Fabrizio Montesi, Mauro Silvagni: first write. 2007 - Fabrizio * Montesi: rewritten from scratch, exploiting new JOLIE capabilities. 2008 - * Fabrizio Montesi: initial support for schemas. 2008 - Claudio Guidi: initial * support for WS-Addressing. 2010 - Fabrizio Montesi: initial support for WSDL * documents. * */ public class SoapProtocol extends SequentialCommProtocol { private String inputId = null; private final Interpreter interpreter; private final MessageFactory messageFactory; private XSSchemaSet schemaSet = null; private URI uri = null; private Definition wsdlDefinition = null; private Port wsdlPort = null; private final TransformerFactory transformerFactory; private final Map<String, String> namespacePrefixMap = new HashMap<String, String>(); private boolean received = false; private final static String CRLF = new String( new char[]{13, 10} ); /* * it forced the insertion of namespaces within the soap message * * * type Attribute: void { * .name: string * .value: string * } * * parameter add_attribute: void { * .envelope: void { attribute*: Attribute * } * .operation*: void { * .operation_name: string * .attribute: Attribute * } * } */ private final static String SOAP_PARAMETER_ABSTRACT_TYPE = "abstract_type"; private final static String SOAP_PARAMETER_ADD_ATTRIBUTE = "add_attribute"; private final static String SOAP_PARAMETER_ENVELOPE = "envelope"; private final static String SOAP_PARAMETER_OPERATION = "operation"; public String name() { return "soap"; } public SoapProtocol( VariablePath configurationPath, URI uri, Interpreter interpreter ) throws SOAPException { super( configurationPath ); this.uri = uri; this.transformerFactory = TransformerFactory.newInstance(); this.interpreter = interpreter; this.messageFactory = MessageFactory.newInstance( SOAPConstants.SOAP_1_1_PROTOCOL ); } private void parseSchemaElement( Definition definition, Element element, XSOMParser schemaParser ) throws IOException { try { Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty( "indent", "yes" ); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult( sw ); DOMSource source = new DOMSource( element ); transformer.transform( source, result ); InputSource schemaSource = new InputSource( new StringReader( sw.toString() ) ); schemaSource.setSystemId( definition.getDocumentBaseURI() ); schemaParser.parse( schemaSource ); } catch( TransformerConfigurationException e ) { throw new IOException( e ); } catch( TransformerException e ) { throw new IOException( e ); } catch( SAXException e ) { throw new IOException( e ); } } private void parseWSDLTypes( XSOMParser schemaParser ) throws IOException { Definition definition = getWSDLDefinition(); if ( definition != null ) { Types types = definition.getTypes(); if ( types != null ) { List<ExtensibilityElement> list = types.getExtensibilityElements(); for( ExtensibilityElement element : list ) { if ( element instanceof SchemaImpl ) { Element schemaElement = ((SchemaImpl) element).getElement(); Map<String, String> namespaces = definition.getNamespaces(); for( Entry<String, String> entry : namespaces.entrySet() ) { if ( entry.getKey().equals( "xmlns" ) || entry.getKey().trim().isEmpty() ) { continue; } if ( schemaElement.getAttribute( "xmlns:" + entry.getKey() ).isEmpty() ) { schemaElement.setAttribute( "xmlns:" + entry.getKey(), entry.getValue() ); } } parseSchemaElement( definition, schemaElement, schemaParser ); } } } } } private XSSchemaSet getSchemaSet() throws IOException, SAXException { if ( schemaSet == null ) { XSOMParser schemaParser = new XSOMParser(); ValueVector vec = getParameterVector( "schema" ); if ( vec.size() > 0 ) { for( Value v : vec ) { schemaParser.parse( new File( v.strValue() ) ); } } parseWSDLTypes( schemaParser ); schemaSet = schemaParser.getResult(); String nsPrefix = "jolie"; int i = 1; for( XSSchema schema : schemaSet.getSchemas() ) { if ( !schema.getTargetNamespace().equals( XMLConstants.W3C_XML_SCHEMA_NS_URI ) ) { namespacePrefixMap.put( schema.getTargetNamespace(), nsPrefix + i++ ); } } } return schemaSet; } private boolean convertAttributes() { boolean ret = false; if ( hasParameter( "convertAttributes" ) ) { ret = checkBooleanParameter( "convertAttributes" ); } return ret; } private void initNamespacePrefixes( SOAPElement element ) throws SOAPException { for( Entry<String, String> entry : namespacePrefixMap.entrySet() ) { element.addNamespaceDeclaration( entry.getValue(), entry.getKey() ); } } private void valueToSOAPElement( Value value, SOAPElement element, SOAPEnvelope soapEnvelope ) throws SOAPException { String type = "any"; if ( value.isDefined() ) { if ( value.isInt() ) { type = "int"; } else if ( value.isString() ) { type = "string"; } else if ( value.isDouble() ) { type = "double"; } element.addAttribute( soapEnvelope.createName( "type", "xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI ), "xsd:" + type ); element.addTextNode( value.strValue() ); } if ( convertAttributes() ) { Map<String, ValueVector> attrs = getAttributesOrNull( value ); if ( attrs != null ) { for( Entry<String, ValueVector> attrEntry : attrs.entrySet() ) { element.addAttribute( soapEnvelope.createName( attrEntry.getKey() ), attrEntry.getValue().first().strValue() ); } } } for( Entry<String, ValueVector> entry : value.children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { for( Value val : entry.getValue() ) { valueToSOAPElement( val, element.addChildElement( entry.getKey() ), soapEnvelope ); } } } } private static Map<String, ValueVector> getAttributesOrNull( Value value ) { Map<String, ValueVector> ret = null; ValueVector vec = value.children().get( Constants.Predefined.ATTRIBUTES.token().content() ); if ( vec != null && vec.size() > 0 ) { ret = vec.first().children(); } if ( ret == null ) { ret = new HashMap<String, ValueVector>(); } return ret; } private static Value getAttributeOrNull( Value value, String attrName ) { Value ret = null; Map<String, ValueVector> attrs = getAttributesOrNull( value ); if ( attrs != null ) { ValueVector vec = attrs.get( attrName ); if ( vec != null && vec.size() > 0 ) { ret = vec.first(); } } return ret; } private static Value getAttribute( Value value, String attrName ) { return value.getChildren( Constants.Predefined.ATTRIBUTES.token().content() ).first().getChildren( attrName ).first(); } private String getPrefixOrNull( XSAttributeDecl decl ) { if ( decl.getOwnerSchema().attributeFormDefault() ) { return namespacePrefixMap.get( decl.getOwnerSchema().getTargetNamespace() ); } return null; } private String getPrefixOrNull( XSElementDecl decl ) { if ( decl.getOwnerSchema().elementFormDefault() ) { return namespacePrefixMap.get( decl.getOwnerSchema().getTargetNamespace() ); } return null; } private String getPrefix( XSElementDecl decl ) { return namespacePrefixMap.get( decl.getOwnerSchema().getTargetNamespace() ); } private void termProcessing( Value value, SOAPElement element, SOAPEnvelope envelope, boolean first, XSTerm currTerm, int getMaxOccur, ValueVector abstractTypeExtender ) throws SOAPException { if ( currTerm.isElementDecl() ) { ValueVector vec; XSElementDecl currElementDecl = currTerm.asElementDecl(); String name = currElementDecl.getName(); String prefix = (first) ? getPrefix( currElementDecl ) : getPrefixOrNull( currElementDecl ); SOAPElement childElement = null; if ( (vec = value.children().get( name )) != null ) { int k = 0; while( vec.size() > 0 && (getMaxOccur > k || getMaxOccur == XSParticle.UNBOUNDED) ) { if ( prefix == null ) { childElement = element.addChildElement( name ); } else { childElement = element.addChildElement( name, prefix ); } Value v = vec.remove( 0 ); valueToTypedSOAP( v, currElementDecl, childElement, envelope, false, abstractTypeExtender, name ); k++; } } } } private void groupProcessing( Value value, XSElementDecl xsDecl, SOAPElement element, SOAPEnvelope envelope, boolean first, XSModelGroup modelGroup, ValueVector abstractTypeExtender ) throws SOAPException { XSParticle[] children = modelGroup.getChildren(); XSTerm currTerm; for( int i = 0; i < children.length; i++ ) { currTerm = children[i].getTerm(); if ( currTerm.isModelGroup() ) { groupProcessing( value, xsDecl, element, envelope, first, currTerm.asModelGroup(), abstractTypeExtender ); } else { termProcessing( value, element, envelope, first, currTerm, children[i].getMaxOccurs(), abstractTypeExtender ); } } } private void addForcedAttribute( ValueVector abstractTypeExtender, String valueNodeName, SOAPElement element, SOAPEnvelope envelope ) throws SOAPException { if ( abstractTypeExtender != null ) { boolean extenderFound = false; int extenderIndex = 0; while( !extenderFound && extenderIndex < abstractTypeExtender.size() ) { Value extender = abstractTypeExtender.get( extenderIndex ); if ( extender.getFirstChild( "node" ).strValue().equals( valueNodeName ) ) { Value attribute = extender.getFirstChild( "attribute" ); String nameType = attribute.getFirstChild( "name" ).strValue(); String prefixType = attribute.getFirstChild( "prefix" ).strValue(); QName attrName = envelope.createQName( nameType, prefixType ); element.addAttribute( attrName, attribute.getFirstChild( "value" ).strValue() ); extenderFound = true; } extenderIndex++; } } } private void valueToTypedSOAP( Value value, XSElementDecl xsDecl, SOAPElement element, SOAPEnvelope envelope, boolean first, ValueVector abstractTypeExtender, String valueNodeName// Ugly fix! This should be removed as soon as another option arises. ) throws SOAPException { XSType type = xsDecl.getType(); if ( type.isSimpleType() ) { element.addTextNode( value.strValue() ); // check if there are forced attributes addForcedAttribute( abstractTypeExtender, valueNodeName, element, envelope ); } else if ( type.isComplexType() ) { String name; Value currValue; XSComplexType complexT = type.asComplexType(); XSParticle particle; XSContentType contentT; //end new stuff // Iterate over attributes Collection<? extends XSAttributeUse> attributeUses = complexT.getAttributeUses(); for( XSAttributeUse attrUse : attributeUses ) { name = attrUse.getDecl().getName(); if ( (currValue = getAttributeOrNull( value, name )) != null ) { QName attrName = envelope.createQName( name, getPrefixOrNull( attrUse.getDecl() ) ); element.addAttribute( attrName, currValue.strValue() ); } } // check if there are forced attributes addForcedAttribute( abstractTypeExtender, valueNodeName, element, envelope ); // processing content (no base type parent ) contentT = complexT.getContentType(); if ( contentT.asSimpleType() != null ) { element.addTextNode( value.strValue() ); } else if ( (particle = contentT.asParticle()) != null ) { XSTerm term = particle.getTerm(); XSModelGroupDecl modelGroupDecl; XSModelGroup modelGroup = null; if ( (modelGroupDecl = term.asModelGroupDecl()) != null ) { modelGroup = modelGroupDecl.getModelGroup(); } else if ( term.isModelGroup() ) { modelGroup = term.asModelGroup(); } if ( modelGroup != null ) { XSModelGroup.Compositor compositor = modelGroup.getCompositor(); if ( compositor.equals( XSModelGroup.SEQUENCE ) ) { groupProcessing( value, xsDecl, element, envelope, first, modelGroup, abstractTypeExtender ); } } } } } private Definition getWSDLDefinition() throws IOException { if ( wsdlDefinition == null && hasParameter( "wsdl" ) ) { String wsdlUrl = getStringParameter( "wsdl" ); try { wsdlDefinition = WSDLCache.getInstance().get( wsdlUrl ); } catch( WSDLException e ) { throw new IOException( e ); } } return wsdlDefinition; } private String getSoapActionForOperation( String operationName ) throws IOException { String soapAction = null; Port port = getWSDLPort(); if ( port != null ) { BindingOperation bindingOperation = port.getBinding().getBindingOperation( operationName, null, null ); for( ExtensibilityElement element : (List<ExtensibilityElement>) bindingOperation.getExtensibilityElements() ) { if ( element instanceof SOAPOperation ) { soapAction = ((SOAPOperation) element).getSoapActionURI(); } } } if ( soapAction == null ) { soapAction = getStringParameter( "namespace" ) + "/" + operationName; } return soapAction; } private Port getWSDLPort() throws IOException { Port port = wsdlPort; if ( port == null && hasParameter( "wsdl" ) && getParameterFirstValue( "wsdl" ).hasChildren( "port" ) ) { String portName = getParameterFirstValue( "wsdl" ).getFirstChild( "port" ).strValue(); Definition definition = getWSDLDefinition(); if ( definition != null ) { Map<QName, Service> services = definition.getServices(); Iterator<Entry<QName, Service>> it = services.entrySet().iterator(); while( port == null && it.hasNext() ) { port = it.next().getValue().getPort( portName ); } } if ( port != null ) { wsdlPort = port; } } return port; } private String getOutputMessageRootElementName( String operationName ) throws IOException { String elementName = operationName + ((received) ? "Response" : ""); Port port = getWSDLPort(); if ( port != null ) { try { Operation operation = port.getBinding().getPortType().getOperation( operationName, null, null ); Part part = null; if ( received ) { // We are sending a response part = ((Entry<String, Part>) operation.getOutput().getMessage().getParts().entrySet().iterator().next()).getValue(); } else { // We are sending a request part = ((Entry<String, Part>) operation.getInput().getMessage().getParts().entrySet().iterator().next()).getValue(); } elementName = part.getElementName().getLocalPart(); } catch( Exception e ) { } } return elementName; } private String getOutputMessageNamespace( String operationName ) throws IOException { String messageNamespace = ""; Port port = getWSDLPort(); if ( port == null ) { if ( hasParameter( "namespace" ) ) { messageNamespace = getStringParameter( "namespace" ); } } else { Operation operation = port.getBinding().getPortType().getOperation( operationName, null, null ); if ( operation != null ) { Map<String, Part> parts = operation.getOutput().getMessage().getParts(); if ( parts.size() > 0 ) { Part part = parts.entrySet().iterator().next().getValue(); if ( part.getElementName() == null ) { messageNamespace = operation.getOutput().getMessage().getQName().getNamespaceURI(); } else { messageNamespace = part.getElementName().getNamespaceURI(); } } } } return messageNamespace; } private String[] getParameterOrder( String operationName ) throws IOException { List<String> parameters = null; Port port = getWSDLPort(); if ( port != null ) { Operation operation = port.getBinding().getPortType().getOperation( operationName, null, null ); if ( operation != null ) { parameters = operation.getParameterOrdering(); } } return (parameters == null) ? null : parameters.toArray( new String[0] ); } private void setOutputEncodingStyle( SOAPEnvelope soapEnvelope, String operationName ) throws IOException, SOAPException { Port port = getWSDLPort(); if ( port != null ) { BindingOperation bindingOperation = port.getBinding().getBindingOperation( operationName, null, null ); if ( bindingOperation == null ) { return; } BindingOutput output = bindingOperation.getBindingOutput(); if ( output == null ) { return; } for( ExtensibilityElement element : (List<ExtensibilityElement>) output.getExtensibilityElements() ) { if ( element instanceof javax.wsdl.extensions.soap.SOAPBody ) { List<String> list = ((javax.wsdl.extensions.soap.SOAPBody) element).getEncodingStyles(); if ( list != null && list.isEmpty() == false ) { soapEnvelope.setEncodingStyle( list.get( 0 ) ); soapEnvelope.addNamespaceDeclaration( "enc", list.get( 0 ) ); } } } } } public void send( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException { try { inputId = message.operationName(); String messageNamespace = getOutputMessageNamespace( message.operationName() ); if ( received ) { // We're responding to a request inputId += "Response"; } SOAPMessage soapMessage = messageFactory.createMessage(); SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope(); setOutputEncodingStyle( soapEnvelope, message.operationName() ); SOAPBody soapBody = soapEnvelope.getBody(); if ( checkBooleanParameter( "wsAddressing" ) ) { SOAPHeader soapHeader = soapEnvelope.getHeader(); // WS-Addressing namespace soapHeader.addNamespaceDeclaration( "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing" ); // Message ID Name messageIdName = soapEnvelope.createName( "MessageID", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing" ); SOAPHeaderElement messageIdElement = soapHeader.addHeaderElement( messageIdName ); if ( received ) { // TODO: remove this after we implement a mechanism for being sure message.id() is the one received before. messageIdElement.setValue( "uuid:1" ); } else { messageIdElement.setValue( "uuid:" + message.id() ); } // Action element Name actionName = soapEnvelope.createName( "Action", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing" ); SOAPHeaderElement actionElement = soapHeader.addHeaderElement( actionName ); /* * TODO: the action element could be specified within the * parameter. Perhaps wsAddressing.action ? We could also allow * for giving a prefix or a suffix to the operation name, like * wsAddressing.action.prefix, wsAddressing.action.suffix */ actionElement.setValue( message.operationName() ); // From element Name fromName = soapEnvelope.createName( "From", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing" ); SOAPHeaderElement fromElement = soapHeader.addHeaderElement( fromName ); Name addressName = soapEnvelope.createName( "Address", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing" ); SOAPElement addressElement = fromElement.addChildElement( addressName ); addressElement.setValue( "http://schemas.xmlsoap.org/ws/2004/03/addressing/role/anonymous" ); // To element } if ( message.isFault() ) { FaultException f = message.fault(); SOAPFault soapFault = soapBody.addFault(); soapFault.setFaultCode( soapEnvelope.createQName( "Server", soapEnvelope.getPrefix() ) ); soapFault.setFaultString( f.getMessage() ); Detail detail = soapFault.addDetail(); DetailEntry de = detail.addDetailEntry( soapEnvelope.createName( f.faultName(), null, messageNamespace ) ); valueToSOAPElement( f.value(), de, soapEnvelope ); } else { XSSchemaSet sSet = getSchemaSet(); XSElementDecl elementDecl; String messageRootElementName = getOutputMessageRootElementName( message.operationName() ); if ( sSet == null || (elementDecl = sSet.getElementDecl( messageNamespace, messageRootElementName )) == null ) { Name operationName = null; soapEnvelope.addNamespaceDeclaration( "xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI ); soapEnvelope.addNamespaceDeclaration( "xsd", XMLConstants.W3C_XML_SCHEMA_NS_URI ); if ( messageNamespace.isEmpty() ) { operationName = soapEnvelope.createName( messageRootElementName ); } else { soapEnvelope.addNamespaceDeclaration( "jolieMessage", messageNamespace ); operationName = soapEnvelope.createName( messageRootElementName, "jolieMessage", messageNamespace ); } SOAPBodyElement opBody = soapBody.addBodyElement( operationName ); String[] parameters = getParameterOrder( message.operationName() ); if ( parameters == null ) { valueToSOAPElement( message.value(), opBody, soapEnvelope ); } else { for( String parameterName : parameters ) { valueToSOAPElement( message.value().getFirstChild( parameterName ), opBody.addChildElement( parameterName ), soapEnvelope ); } } } else { initNamespacePrefixes( soapEnvelope ); if ( hasParameter( SOAP_PARAMETER_ADD_ATTRIBUTE ) ) { Value add_parameter = getParameterFirstValue( SOAP_PARAMETER_ADD_ATTRIBUTE ); if ( add_parameter.hasChildren( SOAP_PARAMETER_ENVELOPE ) ) { // attributes must be added to the envelope ValueVector attributes = add_parameter.getFirstChild( SOAP_PARAMETER_ENVELOPE ).getChildren( "attribute" ); for( Value att : attributes ) { soapEnvelope.addNamespaceDeclaration( att.getFirstChild( "name" ).strValue(), att.getFirstChild( "value" ).strValue() ); } } } boolean wrapped = true; Value vStyle = getParameterVector( "style" ).first(); if ( "document".equals( vStyle.strValue() ) ) { wrapped = (vStyle.getChildren( "wrapped" ).first().intValue() > 0); } SOAPElement opBody = soapBody; ValueVector abstractTypeExtender = null; if ( wrapped ) { opBody = soapBody.addBodyElement( soapEnvelope.createName( messageRootElementName, namespacePrefixMap.get( elementDecl.getOwnerSchema().getTargetNamespace() ), null ) ); // adding forced attributes to operation if ( hasParameter( SOAP_PARAMETER_ADD_ATTRIBUTE ) ) { Value add_parameter = getParameterFirstValue( SOAP_PARAMETER_ADD_ATTRIBUTE ); if ( add_parameter.hasChildren( SOAP_PARAMETER_OPERATION ) ) { ValueVector operations = add_parameter.getChildren( SOAP_PARAMETER_OPERATION ); for( Value op : operations ) { if ( op.getFirstChild( "operation_name" ).strValue().equals( message.operationName() ) ) { // attributes must be added to the envelope Value attribute = op.getFirstChild( "attribute" ); QName attrName; if ( attribute.hasChildren( "prefix" ) ) { attrName = opBody.createQName( attribute.getFirstChild( "name" ).strValue(), attribute.getFirstChild( "prefix" ).strValue() ); } else { attrName = opBody.createQName( attribute.getFirstChild( "name" ).strValue(), null ); } opBody.addAttribute( attrName, attribute.getFirstChild( "value" ).strValue() ); } } } } /* * check if there are abstract type extensions to be added to some nodes * type AbstractType: void { * .operation*: void { * .operation_name: string * .extension*: void { * .attribute: string attribute to add * .node: string node to be extended * } * } * * soap parameter = abstract_type: AbstractType * } */ if ( hasParameter( SOAP_PARAMETER_ABSTRACT_TYPE ) ) { ValueVector operation_vec = getParameterFirstValue( SOAP_PARAMETER_ABSTRACT_TYPE ).getChildren( "operation" ); for( Value op : operation_vec ) { if ( op.getFirstChild( "operation_name" ).strValue().equals( message.operationName() ) ) { abstractTypeExtender = op.getChildren( "extension" ); } } } } valueToTypedSOAP( message.value(), elementDecl, opBody, soapEnvelope, !wrapped, abstractTypeExtender, "" ); } } if ( soapEnvelope.getHeader().hasChildNodes() == false ) { // Some service implementations do not like empty headers soapEnvelope.getHeader().detachNode(); } ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(); soapMessage.writeTo( tmpStream ); String soapString = CRLF + "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + new String( tmpStream.toByteArray() ); String messageString = ""; String soapAction = null; if ( received ) { // We're responding to a request messageString += "HTTP/1.1 200 OK" + CRLF; received = false; } else { // We're sending a notification or a solicit String path = uri.getPath(); // TODO: fix this to consider resourcePaths if ( path == null || path.length() == 0 ) { path = "*"; } messageString += "POST " + path + " HTTP/1.1" + CRLF; messageString += "Host: " + uri.getHost() + CRLF; /* * soapAction = "SOAPAction: \"" + messageNamespace + "/" + * message.operationName() + '\"' + CRLF; */ soapAction = "SOAPAction: \"" + getSoapActionForOperation( message.operationName() ) + '\"' + CRLF; } if ( getParameterVector( "keepAlive" ).first().intValue() != 1 ) { channel().setToBeClosed( true ); messageString += "Connection: close" + CRLF; } //messageString += "Content-Type: application/soap+xml; charset=\"utf-8\"\n"; messageString += "Content-Type: text/xml; charset=\"utf-8\"" + CRLF; messageString += "Content-Length: " + soapString.length() + CRLF; if ( soapAction != null ) { messageString += soapAction; } messageString += soapString + CRLF; if ( getParameterVector( "debug" ).first().intValue() > 0 ) { interpreter.logInfo( "[SOAP debug] Sending:\n" + tmpStream.toString() ); } inputId = message.operationName(); Writer writer = new OutputStreamWriter( ostream ); writer.write( messageString ); writer.flush(); } catch( SOAPException se ) { throw new IOException( se ); } catch( SAXException saxe ) { throw new IOException( saxe ); } } private void xmlNodeToValue( Value value, Node node ) { String type = "xsd:string"; Node currNode; // Set attributes NamedNodeMap attributes = node.getAttributes(); if ( attributes != null ) { for( int i = 0; i < attributes.getLength(); i++ ) { currNode = attributes.item( i ); if ( "type".equals( currNode.getNodeName() ) == false && convertAttributes() ) { getAttribute( value, currNode.getNodeName() ).setValue( currNode.getNodeValue() ); } else { type = currNode.getNodeValue(); } } } // Set children NodeList list = node.getChildNodes(); Value childValue; for( int i = 0; i < list.getLength(); i++ ) { currNode = list.item( i ); switch( currNode.getNodeType() ) { case Node.ELEMENT_NODE: childValue = value.getNewChild( currNode.getLocalName() ); xmlNodeToValue( childValue, currNode ); break; case Node.TEXT_NODE: value.setValue( currNode.getNodeValue() ); break; } } if ( "xsd:int".equals( type ) ) { value.setValue( value.intValue() ); } else if ( "xsd:double".equals( type ) ) { value.setValue( value.doubleValue() ); } else if ( "xsd:boolean".equals( type ) ) { value.setValue( value.boolValue() ); } } private static Element getFirstElement( Node node ) { NodeList nodes = node.getChildNodes(); for( int i = 0; i < nodes.getLength(); i++ ) { if ( nodes.item( i ).getNodeType() == Node.ELEMENT_NODE ) { return (Element) nodes.item( i ); } } return null; } /* * private Schema getRecvMessageValidationSchema() throws IOException { * List< Source > sources = new ArrayList< Source >(); Definition definition * = getWSDLDefinition(); if ( definition != null ) { Types types = * definition.getTypes(); if ( types != null ) { List< ExtensibilityElement * > list = types.getExtensibilityElements(); for( ExtensibilityElement * element : list ) { if ( element instanceof SchemaImpl ) { sources.add( * new DOMSource( ((SchemaImpl)element).getElement() ) ); } } } } * SchemaFactory schemaFactory = SchemaFactory.newInstance( * XMLConstants.W3C_XML_SCHEMA_NS_URI ); try { return * schemaFactory.newSchema( sources.toArray( new Source[sources.size()] ) ); * } catch( SAXException e ) { throw new IOException( e ); } } */ public CommMessage recv( InputStream istream, OutputStream ostream ) throws IOException { HttpParser parser = new HttpParser( istream ); HttpMessage message = parser.parse(); HttpUtils.recv_checkForChannelClosing( message, channel() ); CommMessage retVal = null; String messageId = message.getPropertyOrEmptyString( "soapaction" ); FaultException fault = null; Value value = Value.create(); try { if ( message.content() != null && message.content().length > 0 ) { if ( checkBooleanParameter( "debug" ) ) { interpreter.logInfo( "[SOAP debug] Receiving:\n" + new String( message.content(), "UTF8" ) ); } SOAPMessage soapMessage = messageFactory.createMessage(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); /* * Schema messageSchema = getRecvMessageValidationSchema(); if ( * messageSchema != null ) { * factory.setIgnoringElementContentWhitespace( true ); * factory.setSchema( messageSchema ); } */ factory.setNamespaceAware( true ); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) ); Document doc = builder.parse( src ); DOMSource dom = new DOMSource( doc ); soapMessage.getSOAPPart().setContent( dom ); /* * if ( checkBooleanParameter( "debugAfter" ) ) { * ByteArrayOutputStream tmpStream = new * ByteArrayOutputStream(); soapMessage.writeTo( tmpStream ); * interpreter.logInfo( "[SOAP debug] Receiving:\n" + * tmpStream.toString() ); } */ SOAPFault soapFault = soapMessage.getSOAPBody().getFault(); if ( soapFault == null ) { Element soapValueElement = getFirstElement( soapMessage.getSOAPBody() ); messageId = soapValueElement.getLocalName(); xmlNodeToValue( value, soapValueElement ); ValueVector schemaPaths = getParameterVector( "schema" ); if ( schemaPaths.size() > 0 ) { List<Source> sources = new LinkedList<Source>(); Value schemaPath; for( int i = 0; i < schemaPaths.size(); i++ ) { schemaPath = schemaPaths.get( i ); if ( schemaPath.getChildren( "validate" ).first().intValue() > 0 ) { sources.add( new StreamSource( new File( schemaPaths.get( i ).strValue() ) ) ); } } if ( !sources.isEmpty() ) { Schema schema = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI ).newSchema( sources.toArray( new Source[0] ) ); schema.newValidator().validate( new DOMSource( soapMessage.getSOAPBody().getFirstChild() ) ); } } } else { String faultName = "UnknownFault"; Value faultValue = Value.create(); Detail d = soapFault.getDetail(); if ( d != null ) { Node n = d.getFirstChild(); if ( n != null ) { faultName = n.getLocalName(); xmlNodeToValue( faultValue, n ); } else { faultValue.setValue( soapFault.getFaultString() ); } } fault = new FaultException( faultName, faultValue ); } } String resourcePath = recv_getResourcePath( message ); if ( message.isResponse() ) { if ( fault != null && message.httpCode() == 500 ) { fault = new FaultException( "InternalServerError", "" ); } retVal = new CommMessage( CommMessage.GENERIC_ID, inputId, resourcePath, value, fault ); } else if ( !message.isError() ) { if ( messageId.isEmpty() ) { throw new IOException( "Received SOAP Message without a specified operation" ); } retVal = new CommMessage( CommMessage.GENERIC_ID, messageId, resourcePath, value, fault ); } } catch( SOAPException e ) { throw new IOException( e ); } catch( ParserConfigurationException e ) { throw new IOException( e ); } catch( SAXException e ) { //TODO support resourcePath retVal = new CommMessage( CommMessage.GENERIC_ID, messageId, "/", value, new FaultException( "TypeMismatch", e ) ); } received = true; if ( "/".equals( retVal.resourcePath() ) && channel().parentPort() != null && channel().parentPort().getInterface().containsOperation( retVal.operationName() ) ) { try { // The message is for this service Interface iface = channel().parentPort().getInterface(); OneWayTypeDescription oneWayTypeDescription = iface.oneWayOperations().get( retVal.operationName() ); if ( oneWayTypeDescription != null && message.isResponse() == false ) { // We are receiving a One-Way message oneWayTypeDescription.requestType().cast( retVal.value() ); } else { RequestResponseTypeDescription rrTypeDescription = iface.requestResponseOperations().get( retVal.operationName() ); if ( retVal.isFault() ) { Type faultType = rrTypeDescription.faults().get( retVal.fault().faultName() ); if ( faultType != null ) { faultType.cast( retVal.value() ); } } else { if ( message.isResponse() ) { rrTypeDescription.responseType().cast( retVal.value() ); } else { rrTypeDescription.requestType().cast( retVal.value() ); } } } } catch( TypeCastingException e ) { // TODO: do something here? } } return retVal; } private String recv_getResourcePath( HttpMessage message ) { String ret = "/"; if ( checkBooleanParameter( "interpretResource" ) ) { ret = message.requestPath(); } return ret; } }
package de.retest.recheck.ui.diff; import static de.retest.recheck.ui.image.ImageUtils.image2Screenshot; import static de.retest.recheck.ui.image.ImageUtils.screenshot2Image; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import javax.xml.bind.Marshaller; import de.retest.recheck.ignore.ShouldIgnore; import de.retest.recheck.persistence.xml.XmlTransformer; import de.retest.recheck.ui.descriptors.AttributeUtil; import de.retest.recheck.ui.descriptors.Element; import de.retest.recheck.ui.descriptors.IdentifyingAttributes; import de.retest.recheck.ui.image.ImageUtils; import de.retest.recheck.ui.image.Screenshot; import de.retest.recheck.util.ChecksumCalculator; public class ElementDifference implements Difference, Comparable<ElementDifference> { protected static final long serialVersionUID = 2L; protected final AttributesDifference attributesDifference; protected final LeafDifference identifyingAttributesDifference; protected Collection<ElementDifference> childDifferences = new ArrayList<>(); protected final Screenshot expectedScreenshot; protected final Screenshot actualScreenshot; private Element element; public ElementDifference( final Element element, final AttributesDifference attributesDifference, final LeafDifference identifyingAttributesDifference, final Screenshot expectedScreenshot, final Screenshot actualScreenshot, final Collection<ElementDifference> childDifferences ) { this.element = element; this.attributesDifference = attributesDifference; this.identifyingAttributesDifference = identifyingAttributesDifference; this.expectedScreenshot = expectedScreenshot; this.actualScreenshot = actualScreenshot; this.childDifferences.addAll( childDifferences ); } public Screenshot mark( final Screenshot screenshot, final ShouldIgnore ignore ) { if ( screenshot == null ) { return null; } final List<Rectangle> marks = new ArrayList<>(); if ( childDifferences != null ) { for ( final Difference childDifference : childDifferences ) { for ( final ElementDifference compDiff : childDifference.getNonEmptyDifferences() ) { if ( !ignore.shouldIgnoreElement( element ) && !compDiff.getAttributeDifferences( ignore ).isEmpty() ) { marks.add( AttributeUtil.getAbsoluteOutline( compDiff.getIdentifyingAttributes() ) ); } } } } return image2Screenshot( screenshot.getPersistenceIdPrefix(), ImageUtils.mark( screenshot2Image( screenshot ), marks ) ); } public static ElementDifference getCopyWithFlattenedChildDifferenceHierarchy( final ElementDifference elementDifference ) { ElementDifference result = elementDifference; while ( result.childDifferences.size() == 1 && result.identifyingAttributesDifference == null && result.attributesDifference == null ) { result = result.childDifferences.iterator().next(); } return result; } public List<Difference> getImmediateDifferences() { final List<Difference> differences = new ArrayList<>(); if ( identifyingAttributesDifference != null ) { differences.add( identifyingAttributesDifference ); } if ( attributesDifference != null ) { differences.add( attributesDifference ); } return differences; } public List<AttributeDifference> getAttributeDifferences( final ShouldIgnore ignore ) { final List<AttributeDifference> differences = new ArrayList<>(); if ( identifyingAttributesDifference instanceof IdentifyingAttributesDifference ) { final List<AttributeDifference> attributeDifferences = ((IdentifyingAttributesDifference) identifyingAttributesDifference).getAttributeDifferences(); differences.addAll( attributeDifferences ); } if ( attributesDifference != null ) { differences.addAll( attributesDifference.getDifferences() ); } if ( ignore == null ) { return differences; } return differences.stream() .filter( d -> !ignore.shouldIgnoreAttributeDifference( element, d ) ) .collect( Collectors.toList() ); } public String getIdentifier() { String result = getIdentifyingAttributes().identifier(); if ( identifyingAttributesDifference != null ) { result += getSumIdentifier( identifyingAttributesDifference.getNonEmptyDifferences() ); } if ( attributesDifference != null ) { result += attributesDifference.getIdentifier(); } return ChecksumCalculator.getInstance().sha256( result ); } public static String getSumIdentifier( final Collection<ElementDifference> differences ) { String result = ""; for ( final ElementDifference difference : differences ) { result += " # " + difference.getIdentifier(); } return ChecksumCalculator.getInstance().sha256( result ); } public boolean hasAttributesDifferences() { return attributesDifference != null; } public boolean hasIdentAttributesDifferences() { return identifyingAttributesDifference instanceof IdentifyingAttributesDifference; } public boolean isInsertionOrDeletion() { return identifyingAttributesDifference instanceof InsertedDeletedElementDifference; } public boolean isInsertion() { return isInsertionOrDeletion() && ((InsertedDeletedElementDifference) identifyingAttributesDifference).isInserted(); } public boolean isDeletion() { return isInsertionOrDeletion() && !((InsertedDeletedElementDifference) identifyingAttributesDifference).isInserted(); } // For Difference @Override public int size() { if ( identifyingAttributesDifference != null || attributesDifference != null ) { return 1; } if ( !childDifferences.isEmpty() ) { int size = 0; for ( final Difference difference : childDifferences ) { size += difference.size(); } return size; } return 0; } @Override public List<ElementDifference> getNonEmptyDifferences() { final List<ElementDifference> result = new ArrayList<>(); if ( identifyingAttributesDifference != null || attributesDifference != null ) { result.add( this ); } for ( final Difference childDifference : childDifferences ) { result.addAll( childDifference.getNonEmptyDifferences() ); } return result; } @Override public List<ElementDifference> getElementDifferences() { final List<ElementDifference> differences = new ArrayList<>(); differences.add( this ); for ( final ElementDifference childDifference : childDifferences ) { differences.addAll( childDifference.getElementDifferences() ); } return differences; } @Override public String toString() { if ( identifyingAttributesDifference != null ) { return getIdentifyingAttributes().toString() + ":\n at: " + getIdentifyingAttributes().getPath() + ":\n\t" + identifyingAttributesDifference; } if ( attributesDifference != null ) { final String differences = attributesDifference.getDifferences().stream() .map( Object::toString ) .collect( Collectors.joining( "\n\t" ) ); return getIdentifyingAttributes().toString() + ":\n at: " + getIdentifyingAttributes().getPath() + ":\n\t" + differences; } if ( !childDifferences.isEmpty() ) { if ( size() > 50 ) { String result = ""; int diffCnt = 0; final Iterator<ElementDifference> diffIter = childDifferences.iterator(); while ( diffCnt < 50 && diffIter.hasNext() ) { final Difference difference = diffIter.next(); diffCnt += difference.size(); result += difference.toString() + ", "; } return result.substring( 0, result.length() - 2 ); } return childDifferences.toString(); } return "noDifferences: " + getIdentifyingAttributes().toString(); } // For Comparable @Override public int compareTo( final ElementDifference other ) { if ( getIdentifyingAttributes() == null || other.getIdentifyingAttributes() == null ) { throw new IllegalStateException( "Identifying attributes may not be null. Loaded leighweight XML?" ); } return getIdentifyingAttributes().compareTo( other.getIdentifyingAttributes() ); } // For JAXB protected ElementDifference() { attributesDifference = null; identifyingAttributesDifference = null; expectedScreenshot = null; actualScreenshot = null; } void beforeMarshal( final Marshaller m ) { if ( XmlTransformer.isLightweightMarshaller( m ) && identifyingAttributesDifference == null && attributesDifference == null ) { final List<ElementDifference> childDifferences = getClippedNonEmptyChildren(); childDifferences.remove( this ); this.childDifferences = childDifferences; } } private List<ElementDifference> getClippedNonEmptyChildren() { final List<ElementDifference> result = new ArrayList<>(); if ( identifyingAttributesDifference != null || attributesDifference != null ) { result.add( this ); } else { for ( final ElementDifference childDifference : childDifferences ) { result.addAll( childDifference.getClippedNonEmptyChildren() ); } } return result; } // Getters public IdentifyingAttributes getIdentifyingAttributes() { return element.getIdentifyingAttributes(); } public String getRetestId() { return element.getRetestId(); } public AttributesDifference getAttributesDifference() { return attributesDifference; } public LeafDifference getIdentifyingAttributesDifference() { return identifyingAttributesDifference; } public Screenshot getExpectedScreenshot() { return expectedScreenshot; } public Screenshot getActualScreenshot() { return actualScreenshot; } public Element getElement() { return element; } }
package de.synaxon.graphitereceiver; import com.vmware.ee.statsfeeder.ExecutionContext; import com.vmware.ee.statsfeeder.PerfMetricSet; import com.vmware.ee.statsfeeder.PerfMetricSet.PerfMetric; import com.vmware.ee.statsfeeder.StatsExecutionContextAware; import com.vmware.ee.statsfeeder.StatsFeederListener; import com.vmware.ee.statsfeeder.StatsListReceiver; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.net.Socket; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Iterator; import java.util.Properties; import java.util.TimeZone; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @author karl spies */ public class MetricsReceiver implements StatsListReceiver, StatsFeederListener, StatsExecutionContextAware { Log logger = LogFactory.getLog(MetricsReceiver.class); private String name = "SampleStatsReceiver"; private ExecutionContext context; private PrintStream writer; private Socket client; PrintWriter out; private Properties props; /** * This constructor will be called by StatsFeeder to load this receiver. The props object passed is built * from the content in the XML configuration for the receiver. * <pre> * {@code * <receiver> * <name>sample</name> * <class>com.vmware.ee.statsfeeder.SampleStatsReceiver</class> * <!-- If you need some properties specify them like this * <properties> * <property> * <name>some_property</name> * <value>some_value</value> * </property> * </properties> * --> * </receiver> * } * </pre> * * @param name * @param props */ public MetricsReceiver(String name, Properties props) { this.name = name; this.props = props; } /** * * @param name */ public void setName(String name) { this.name = name; } /** * * @return */ public String getName() { return name; } /** * This method is called when the receiver is initialized and passes the StatsFeeder execution context * which can be used to look up properties or other configuration data. * * It can also be used to retrieve the vCenter connection information * * @param context - The current execution context */ @Override public void setExecutionContext(ExecutionContext context) { this.context = context; } /** * Main receiver entry point. This will be called for each entity and each metric which were retrieved by * StatsFeeder. * * @param entityName - The name of the statsfeeder entity being retrieved * @param metricSet - The set of metrics retrieved for the entity */ @Override public void receiveStats(String entityName, PerfMetricSet metricSet) { if (metricSet != null) { //-- Samples come with the following date format final DateFormat SDF = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); SDF.setTimeZone(TimeZone.getTimeZone("UTC")); String node; node = String.format( "monitoring.nagios.%s.%s_%s", metricSet.getEntityName().replace("[vCenter]", "").replace("[VirtualMachine]", "").replace("[HostSystem]", "").replace('.', '_').replace('-', '_'), metricSet.getCounterName(), metricSet.getStatType() ); try { Iterator<PerfMetric> metrics = metricSet.getMetrics(); while (metrics.hasNext()) { PerfMetric sample = metrics.next(); out.printf("%s %s %s%n", node, sample.getValue(), SDF.parse(sample.getTimestamp()).getTime() / 1000); } } catch (Throwable t) { logger.error("Error processing entity stats ", t); } } } /** * This method is guaranteed to be called at the start of each retrieval in single or feeder mode. * Receivers can place initialization code here that should be executed before retrieval is started. */ @Override public void onStartRetrieval() { try { this.client = new Socket( this.props.getProperty("host"), Integer.parseInt(this.props.getProperty("port", "2003")) ); OutputStream s = this.client.getOutputStream(); this.out = new PrintWriter(s, true); } catch (IOException ex) { logger.error("Can't connect to graphite.", ex); } } /** * This method is guaranteed to be called, just once, at the end of each retrieval in single or feeder * mode. Receivers can place termination code here that should be executed after the retrieval is * completed. */ @Override public void onEndRetrieval() { try { this.out.close(); this.client.close(); } catch (IOException ex) { logger.error("Can't close resources.", ex); } } }
package de.synaxon.graphitereceiver; import com.vmware.ee.statsfeeder.ExecutionContext; import com.vmware.ee.statsfeeder.PerfMetricSet; import com.vmware.ee.statsfeeder.PerfMetricSet.PerfMetric; import com.vmware.ee.statsfeeder.StatsExecutionContextAware; import com.vmware.ee.statsfeeder.StatsFeederListener; import com.vmware.ee.statsfeeder.StatsListReceiver; import com.vmware.ee.statsfeeder.MOREFRetriever; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.net.Socket; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Iterator; import java.util.Properties; import java.util.TimeZone; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @author karl spies */ public class MetricsReceiver implements StatsListReceiver, StatsFeederListener, StatsExecutionContextAware { Log logger = LogFactory.getLog(MetricsReceiver.class); private String name = "SampleStatsReceiver"; private String graphite_prefix = "vmware"; //set to true for backwards compatibility private Boolean use_fqdn = true; //set to true for backwards compatibility private Boolean use_entity_type_prefix = false; private Boolean only_one_sample_x_period=true; private ExecutionContext context; private PrintStream writer; private Socket client; PrintWriter out; private Properties props; private int freq; private MOREFRetriever mor; /** * This constructor will be called by StatsFeeder to load this receiver. The props object passed is built * from the content in the XML configuration for the receiver. * <pre> * {@code * <receiver> * <name>sample</name> * <class>com.vmware.ee.statsfeeder.SampleStatsReceiver</class> * <!-- If you need some properties specify them like this * <properties> * <property> * <name>some_property</name> * <value>some_value</value> * </property> * </properties> * --> * </receiver> * } * </pre> * * @param name * @param props */ public MetricsReceiver(String name, Properties props) { this.name = name; this.props = props; } /** * * @param name */ public void setName(String name) { this.name = name; } /** * * @return */ public String getName() { return name; } /** * This method is called when the receiver is initialized and passes the StatsFeeder execution context * which can be used to look up properties or other configuration data. * * It can also be used to retrieve the vCenter connection information * * @param context - The current execution context */ @Override public void setExecutionContext(ExecutionContext context) { this.context = context; this.mor=context.getMorefRetriever(); this.freq=context.getConfiguration().getFrequencyInSeconds(); String prefix=this.props.getProperty("prefix"); String use_fqdn=this.props.getProperty("use_fqdn"); String use_entity_type_prefix=this.props.getProperty("use_entity_type_prefix"); String only_one_sample_x_period=this.props.getProperty("only_one_sample_x_period"); if(prefix != null && !prefix.isEmpty()) this.graphite_prefix=prefix; if(use_fqdn != null && !use_fqdn.isEmpty()) this.use_fqdn=Boolean.valueOf(use_fqdn); if(use_entity_type_prefix != null && !use_entity_type_prefix.isEmpty()) this.use_entity_type_prefix=Boolean.valueOf(use_entity_type_prefix); if(only_one_sample_x_period!= null && !only_one_sample_x_period.isEmpty()) this.only_one_sample_x_period=Boolean.valueOf(only_one_sample_x_period); } private void sendAllMetrics(String node,PerfMetricSet metricSet){ final DateFormat SDF = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); SDF.setTimeZone(TimeZone.getTimeZone("UTC")); try { Iterator<PerfMetric> metrics = metricSet.getMetrics(); while (metrics.hasNext()) { PerfMetric sample = metrics.next(); out.printf("%s %s %s%n", node, sample.getValue(), SDF.parse(sample.getTimestamp()).getTime() / 1000); } } catch (Throwable t) { logger.error("Error processing entity stats on metric: "+node, t); } } private void sendMetricsAverage(String node,PerfMetricSet metricSet,int n){ //averaging all values with last timestamp final DateFormat SDF = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); SDF.setTimeZone(TimeZone.getTimeZone("UTC")); try { double value; Iterator<PerfMetric> metrics = metricSet.getMetrics(); //sample initialization PerfMetric sample=metrics.next(); value=Double.valueOf(sample.getValue()); while (metrics.hasNext()) { sample = metrics.next(); value+=Double.valueOf(sample.getValue()); } out.printf("%s %f %s%n", node, value/n, SDF.parse(sample.getTimestamp()).getTime() / 1000); } catch (NumberFormatException t) { logger.error("Error on number format on metric: "+node, t); } catch (ParseException t) { logger.error("Error processing entity stats on metric: "+node, t); } } private void sendMetricsLatest(String node,PerfMetricSet metricSet) { final DateFormat SDF = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); SDF.setTimeZone(TimeZone.getTimeZone("UTC")); try{ //get last Iterator<PerfMetric> metrics = metricSet.getMetrics(); PerfMetric sample=metrics.next(); while (metrics.hasNext()) { sample = metrics.next(); } out.printf("%s %s %s%n", node,sample.getValue() , SDF.parse(sample.getTimestamp()).getTime() / 1000); } catch (ParseException t) { logger.error("Error processing entity stats on metric: "+node, t); } } private void sendMetricsMaximum(String node,PerfMetricSet metricSet) { final DateFormat SDF = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); SDF.setTimeZone(TimeZone.getTimeZone("UTC")); try { double value; Iterator<PerfMetric> metrics = metricSet.getMetrics(); //first value to compare PerfMetric sample=metrics.next(); value=Double.valueOf(sample.getValue()); //begin comparison iteration while (metrics.hasNext()) { sample = metrics.next(); double last=Double.valueOf(sample.getValue()); if(last > value) value=last; } out.printf("%s %f %s%n", node, value, SDF.parse(sample.getTimestamp()).getTime() / 1000); } catch (ParseException t) { logger.error("Error processing entity stats on metric: "+node, t); } } private void sendMetricsMinimim(String node,PerfMetricSet metricSet) { final DateFormat SDF = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); SDF.setTimeZone(TimeZone.getTimeZone("UTC")); try { //get minimum values with last timestamp double value; Iterator<PerfMetric> metrics = metricSet.getMetrics(); //first value to compare PerfMetric sample=metrics.next(); value=Double.valueOf(sample.getValue()); //begin comparison iteration while (metrics.hasNext()) { sample = metrics.next(); double last=Double.valueOf(sample.getValue()); if(last < value) value=last; } out.printf("%s %f %s%n", node, value, SDF.parse(sample.getTimestamp()).getTime() / 1000); } catch (ParseException t) { logger.error("Error processing entity stats on metric: "+node, t); } } private void sendMetricsSummation(String node,PerfMetricSet metricSet){ final DateFormat SDF = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); SDF.setTimeZone(TimeZone.getTimeZone("UTC")); try { //get minimum values with last timestamp double value; Iterator<PerfMetric> metrics = metricSet.getMetrics(); //first value to compare PerfMetric sample=metrics.next(); value=Double.valueOf(sample.getValue()); //begin comparison iteration while (metrics.hasNext()) { sample = metrics.next(); value+=Double.valueOf(sample.getValue()); } out.printf("%s %f %s%n", node, value, SDF.parse(sample.getTimestamp()).getTime() / 1000); } catch (ParseException t) { logger.error("Error processing entity stats on metric: "+node, t); } } private String[] splitCounterName(String counterName) { //should split string in a 3 componet array // [0] = groupName // [1] = metricName // [2] = rollup String[] result=new String[3]; String[] tmp=counterName.split("[.]"); //group Name result[0]=tmp[0]; //rollup result[2]=tmp[tmp.length-1]; result[1]=tmp[1]; if ( tmp.length > 3){ for(int i=2;i<tmp.length-1;++i) { result[1]=result[1]+"."+tmp[i]; } } return result; } /** * Main receiver entry point. This will be called for each entity and each metric which were retrieved by * StatsFeeder. * * @param entityName - The name of the statsfeeder entity being retrieved * @param metricSet - The set of metrics retrieved for the entity */ @Override public void receiveStats(String entityName, PerfMetricSet metricSet) { if (metricSet != null) { //-- Samples come with the following date format String node; String eName=null; String counterName=metricSet.getCounterName(); //Get Instance Name String instanceName=metricSet.getInstanceId() .replace('.','_') .replace('-','_') .replace('/','.') .replace(' ','_'); String statType=metricSet.getStatType(); String container=null; int interval=metricSet.getInterval(); String rollup=null; if(use_entity_type_prefix) { if(entityName.contains("[VirtualMachine]")) { eName="vm." +entityName.replace("[vCenter]", "").replace("[VirtualMachine]", "").replace('.', '_'); }else if (entityName.contains("[HostSystem]")) { //for ESX only hostname if(!use_fqdn) { eName="esx." +entityName.replace("[vCenter]", "").replace("[HostSystem]", "").split("[.]",2)[0]; }else { eName="esx." +entityName.replace("[vCenter]", "").replace("[HostSystem]", "").replace('.', '_'); } }else if (entityName.contains("[Datastore]")) { eName="dts." +entityName.replace("[vCenter]", "").replace("[Datastore]", "").replace('.', '_'); }else if (entityName.contains("[ResourcePool]")) { eName="rp." +entityName.replace("[vCenter]", "").replace("[ResourcePool]", "").replace('.', '_'); } } else { eName=entityName.replace("[vCenter]", "") .replace("[VirtualMachine]", "") .replace("[HostSystem]", "") .replace("[Datastore]", "") .replace("[ResourcePool]", ""); if(!use_fqdn && entityName.contains("[HostSystem]")){ eName=eName.split("[.]",2)[0]; } eName=eName.replace('.', '_'); } eName=eName.replace(' ','_').replace('-','_'); container=mor.getContainerName(eName); logger.debug("Container Name :" +container + " Interval: "+Integer.toString(interval)+ " Frequency :"+Integer.toString(freq)); if (instanceName.equals("")) { String[] counterInfo=splitCounterName(counterName); String groupName =counterInfo[0]; String metricName =counterInfo[1]; rollup =counterInfo[2]; node = String.format("%s.%s.%s.%s_%s_%s",graphite_prefix,eName,groupName,metricName,rollup,statType); logger.debug("GP :" +graphite_prefix+ " EN: "+eName+" CN :"+ counterName +" ST :"+statType); } else { //Get group name (xxxx) metric name (yyyy) and rollup (zzzz) // from "xxxx.yyyyyy.xxxxx" on the metricName String[] counterInfo=splitCounterName(counterName); String groupName =counterInfo[0]; String metricName =counterInfo[1]; rollup =counterInfo[2]; node = String.format("%s.%s.%s.%s.%s_%s_%s",graphite_prefix,eName,groupName,instanceName,metricName,rollup,statType); logger.debug("GP :" +graphite_prefix+ " EN: "+eName+" GN :"+ groupName +" IN :"+instanceName+" MN :"+metricName+" RU"+rollup +"ST :"+statType); } if(only_one_sample_x_period) { logger.debug("one sample x period"); //check if metricSet has the expected number of metrics int itv=metricSet.getInterval(); if(freq % itv != 0) { logger.warn("frequency "+freq+ " is not multiple of interval: "+itv+ " at metric : "+node); return; } int n=freq/itv; if(n != metricSet.getValues().size()){ logger.error("ERROR: "+n+" expected samples but got "+metricSet.getValues().size()+ "at metric :"+node); return; } if(rollup.equals("average")) { sendMetricsAverage(node,metricSet,n); } else if(rollup.equals("latest")) { sendMetricsLatest(node,metricSet); } else if(rollup.equals("maximum")) { sendMetricsMaximum(node,metricSet); } else if(rollup.equals("minimum")) { sendMetricsMinimim(node,metricSet); } else if(rollup.equals("summation")) { sendMetricsSummation(node,metricSet); } else { logger.info("Not supported Rollup agration:"+rollup); } } else { logger.debug("all samples"); sendAllMetrics(node,metricSet); } } } /** * This method is guaranteed to be called at the start of each retrieval in single or feeder mode. * Receivers can place initialization code here that should be executed before retrieval is started. */ @Override public void onStartRetrieval() { try { this.client = new Socket( this.props.getProperty("host"), Integer.parseInt(this.props.getProperty("port", "2003")) ); OutputStream s = this.client.getOutputStream(); this.out = new PrintWriter(s, true); } catch (IOException ex) { logger.error("Can't connect to graphite.", ex); } } /** * This method is guaranteed to be called, just once, at the end of each retrieval in single or feeder * mode. Receivers can place termination code here that should be executed after the retrieval is * completed. */ @Override public void onEndRetrieval() { try { this.out.close(); this.client.close(); } catch (IOException ex) { logger.error("Can't close resources.", ex); } } }
package org.eigenbase.jmi; import java.util.*; import java.util.logging.*; import javax.jmi.model.*; import javax.jmi.reflect.*; import org.eigenbase.trace.*; import org.eigenbase.util.*; import org.netbeans.api.mdr.*; import org.netbeans.api.mdr.events.*; /** * JmiChangeSet manages the process of applying changes to a JMI repository * (currently relying on MDR specifics). * * <p>TODO jvs 16-Nov-2005: I factored a lot of this out of DdlValidator, but I * didn't update DdlValidator because Jason is working on CREATE OR REPLACE in * there. Once things settle down, make DdlValidator rely on JmiChangeSet * instead of duplicating it. * * @author John V. Sichi * @version $Id$ */ public class JmiChangeSet implements MDRPreChangeListener { private static final Logger tracer = EigenbaseTrace.getJmiChangeSetTracer(); /** * Queue of excns detected during plannedChange. */ private DeferredException enqueuedValidationExcn; /** * Map (from RefAssociation.Class to JmiDeletionRule) of associations for * which special handling is required during deletion. */ private MultiMap<Class<? extends Object>, JmiDeletionRule> deletionRules; /** * Map containing scheduled validation actions. The key is the MofId of the * object scheduled for validation; the value is the action type. */ private Map<String, JmiValidationAction> schedulingMap; /** * Map of objects in transition between schedulingMap and validatedMap. * Content format is same as for schedulingMap. */ private Map<String, JmiValidationAction> transitMap; /** * Map of object validations which have already taken place. The key is the * RefObject itself; the value is the action type. */ private Map<RefObject, JmiValidationAction> validatedMap; /** * Set of objects which a recursive deletion has encountered but not yet * processed. */ private final Set<RefObject> deleteQueue; /** * Thread binding to prevent cross-talk. */ private Thread activeThread; private final JmiChangeDispatcher dispatcher; private boolean singleLevelCascade; /** * Creates a new JmiChangeSet which will listen for repository change events * and schedule appropriate validation actions on the affected objects. * Validation is deferred until validate() is called. * * @param dispatcher implementation of {@link JmiChangeDispatcher} to use */ public JmiChangeSet(JmiChangeDispatcher dispatcher) { this.dispatcher = dispatcher; // NOTE jvs 25-Jan-2004: Use LinkedHashXXX, since order // matters for these. schedulingMap = new LinkedHashMap<String, JmiValidationAction>(); validatedMap = new LinkedHashMap<RefObject, JmiValidationAction>(); deleteQueue = new LinkedHashSet<RefObject>(); // NOTE: deletionRules are populated implicitly as action handlers // are set up below. deletionRules = new MultiMap<Class<? extends Object>, JmiDeletionRule>(); // MDR pre-change instance creation events are useless, since they don't // refer to the new instance. Instead, we rely on the fact that it's // pretty much guaranteed that the new object will have attributes or // associations set (though someone will probably come up with a // pathological case eventually). activeThread = Thread.currentThread(); getMdrRepos().addListener(this, InstanceEvent.EVENT_INSTANCE_DELETE | AttributeEvent.EVENTMASK_ATTRIBUTE | AssociationEvent.EVENTMASK_ASSOCIATION); } /** * Releases any resources associated with this change. * * <p>TODO jvs 16-Nov-2005: move FarragoAllocation framework up to * org.eigenbase level. */ public void closeAllocation() { stopListening(); } /** * Controls cascaded delete behavior. By default, cascades recursively. * * @param singleLevelCascade if true, only cascade to one level; if * false, cascade recursively. */ public void setSingleLevelCascade(boolean singleLevelCascade) { this.singleLevelCascade = singleLevelCascade; } /** * Determines whether an object is being deleted by this change. * * @param refObject object in question * * @return true if refObject is being deleted */ public boolean isDeletedObject(RefObject refObject) { return testObjectStatus(refObject, JmiValidationAction.DELETION); } public boolean isCreatedObject(RefObject refObject) { return testObjectStatus(refObject, JmiValidationAction.CREATION); } private boolean testObjectStatus( RefObject refObject, JmiValidationAction status) { return (schedulingMap.get(refObject.refMofId()) == status) || (validatedMap.get(refObject) == status) || ( (transitMap != null) && (transitMap.get(refObject.refMofId()) == status) ); } private void stopListening() { if (activeThread != null) { getMdrRepos().removeListener(this); activeThread = null; } } public MDRepository getMdrRepos() { return dispatcher.getMdrRepos(); } public void execute() { // catalog updates which occur during execution should not result in // further validation stopListening(); // build deletion list List<RefObject> deletionList = new ArrayList<RefObject>(); for (Map.Entry<RefObject, JmiValidationAction> mapEntry : validatedMap.entrySet()) { RefObject obj = (RefObject) mapEntry.getKey(); Object action = mapEntry.getValue(); if (action != JmiValidationAction.DELETION) { continue; } dispatcher.clearDependencySuppliers(obj); RefFeatured container = obj.refImmediateComposite(); if (container != null) { JmiValidationAction containerAction = validatedMap.get(container); if (containerAction == JmiValidationAction.DELETION) { // container is also being deleted; don't try // deleting this contained object--depending on order, // the attempt could cause an excn } else { // container is not being deleted deletionList.add(obj); } } else { // top-level object deletionList.add(obj); } } // now we can finally consummate any requested deletions, since we're // all done referencing the objects Collections.reverse(deletionList); for (RefObject refObj : deletionList) { if (tracer.isLoggable(Level.FINE)) { tracer.fine("really deleting " + refObj); } refObj.refDelete(); } // verify repository integrity post-delete for (Map.Entry<RefObject, JmiValidationAction> mapEntry : validatedMap.entrySet()) { RefObject obj = (RefObject) mapEntry.getKey(); Object action = mapEntry.getValue(); if (action != JmiValidationAction.DELETION) { checkJmiConstraints(obj); } } } // TODO jvs 4-Sept-2006: Move this interface to JmiChangeDispatcher protected void checkJmiConstraints(RefObject obj) { // e.g. subclass can call FarragoRepos.verifyIntegrity } // implement MDRPreChangeListener public void plannedChange(MDRChangeEvent event) { if (tracer.isLoggable(Level.FINE)) { tracer.fine(event.toString()); } // ignore events from other threads if (activeThread != Thread.currentThread()) { // REVIEW: This isn't going to be good enough if we have // reentrant change set activity. return; } // NOTE: do not throw exceptions from this method, because MDR will // swallow them! Instead, use enqueueValidationExcn(), and the // exception will be thrown when validate() is called. if (event.getType() == InstanceEvent.EVENT_INSTANCE_DELETE) { RefObject obj = (RefObject) (event.getSource()); dispatcher.clearDependencySuppliers(obj); scheduleDeletion(obj); } else if (event instanceof AttributeEvent) { RefObject obj = (RefObject) (event.getSource()); scheduleModification(obj); } else if (event instanceof AssociationEvent) { AssociationEvent associationEvent = (AssociationEvent) event; if (tracer.isLoggable(Level.FINE)) { tracer.fine("end name = " + associationEvent.getEndName()); } scheduleModification(associationEvent.getFixedElement()); if (associationEvent.getOldElement() != null) { scheduleModification(associationEvent.getOldElement()); } if (associationEvent.getNewElement() != null) { scheduleModification(associationEvent.getNewElement()); } if (event.getType() == AssociationEvent.EVENT_ASSOCIATION_REMOVE) { RefAssociation refAssoc = (RefAssociation) associationEvent.getSource(); List<JmiDeletionRule> rules = deletionRules.getMulti(refAssoc.getClass()); for (JmiDeletionRule rule : rules) { if ((rule != null) && rule.getEndName().equals( associationEvent.getEndName())) { fireDeletionRule( refAssoc, rule, associationEvent.getFixedElement(), associationEvent.getOldElement()); } } } } else { // REVIEW jvs 19-Nov-2005: Somehow these slip through even // though we mask them out. Probably an MDR bug. assert (event.getType() == InstanceEvent.EVENT_INSTANCE_CREATE); } } // implement MDRPreChangeListener public void changeCancelled(MDRChangeEvent event) { // don't care } // implement MDRChangeListener public void change(MDRChangeEvent event) { // don't care } public void validate() { checkValidationExcnQueue(); boolean deleting = !deleteQueue.isEmpty(); // Process deletions until a fixpoint is reached, using MDR events // to implement RESTRICT/CASCADE. while (!deleteQueue.isEmpty()) { RefObject refObj = deleteQueue.iterator().next(); deleteQueue.remove(refObj); JmiValidationAction action = schedulingMap.get(refObj.refMofId()); if (action != JmiValidationAction.DELETION) { if (tracer.isLoggable(Level.FINE)) { tracer.fine("probe deleting " + refObj); } refObj.refDelete(); } } // In order to validate deletion, we need the objects to exist, but // they've already been deleted. So rollback the deletion now, but // we still remember the objects encountered above. if (deleting) { rollbackDeletions(); } // REVIEW: This may need to get more complicated in the future. // Like, if deletions triggered modifications to some referencing // object which needs to have its update validation run AFTER the // deletion takes place, not before. while (!schedulingMap.isEmpty()) { checkValidationExcnQueue(); // Swap in a new map so new scheduling calls aren't handled until // the next round. transitMap = schedulingMap; schedulingMap = new LinkedHashMap<String, JmiValidationAction>(); sortOrderedAssocsInTransitMap(); boolean progress = false; boolean unvalidatedDependency = false; for (Map.Entry<String, JmiValidationAction> mapEntry : transitMap.entrySet()) { RefObject obj = (RefObject) getMdrRepos().getByMofId(mapEntry.getKey()); if (obj == null) { continue; } JmiValidationAction action = mapEntry.getValue(); // TODO jvs 12-Sept-2006: enable this assertion once // all dependencies fixed if (false) { JmiValidationAction prevAction = validatedMap.get(obj); if (prevAction != null) { if (action != JmiValidationAction.DELETION) { assert(action == prevAction) : "Illegal conflict from prevAction = " + prevAction + " to action = " + action; } } } // mark this object as already validated so it doesn't slip // back in by updating itself validatedMap.put(obj, action); try { if (tracer.isLoggable(Level.FINE)) { tracer.fine( "validating " + obj + " on " + action); } dispatcher.validateAction(obj, action); progress = true; } catch (JmiUnvalidatedDependencyException ex) { // Something hit an unvalidated dependency; we'll have // to retry this object later. unvalidatedDependency = true; validatedMap.remove(obj); schedulingMap.put( obj.refMofId(), action); } } transitMap = null; if (unvalidatedDependency && !progress) { // Every single object hit a // JmiUnvalidatedDependencyException. This implies a // cycle. TODO: identify the cycle in the exception. throw new JmiUnvalidatedDependencyException(); } } // one last time checkValidationExcnQueue(); } public void defineDeletionRule( RefAssociation refAssoc, JmiDeletionRule dropRule) { // NOTE: use class object because in some circumstances MDR makes up // multiple instances of the same association, but doesn't implement // equals/hashCode correctly. deletionRules.putMulti( refAssoc.getClass(), dropRule); } public void validateUniqueNames( RefObject container, Collection<RefObject> collection, boolean includeType) { Map<String, RefObject> nameMap = new LinkedHashMap<String, RefObject>(); for (RefObject element : collection) { String nameKey = dispatcher.getNameKey(element, includeType); if (nameKey == null) { continue; } RefObject other = nameMap.get(nameKey); if (other != null) { if (dispatcher.isNewObject(other) && dispatcher.isNewObject(element)) { // clash between two new objects being defined // simultaneously dispatcher.notifyNameCollision( container, element, other, true); continue; } else { RefObject newElement; RefObject oldElement; if (dispatcher.isNewObject(other)) { newElement = other; oldElement = element; } else { newElement = element; oldElement = other; } // new object clashes with existing object dispatcher.notifyNameCollision( container, newElement, oldElement, false); continue; } } nameMap.put(nameKey, element); } } private void enqueueValidationExcn(DeferredException excn) { if (enqueuedValidationExcn != null) { // for now, only deal with one at a time return; } enqueuedValidationExcn = excn; } private void checkValidationExcnQueue() { if (enqueuedValidationExcn != null) { // rollback any deletions so that exception construction can // rely on pre-deletion state (e.g. for object identification) rollbackDeletions(); throw enqueuedValidationExcn.getException(); } } private void fireDeletionRule( RefAssociation refAssoc, JmiDeletionRule rule, RefObject droppedEnd, RefObject otherEnd) { if (rule.isReversed()) { if (singleLevelCascade) { // REVIEW jvs 12-Sept-2006: This is a kludge to suppress // the rule from firing in the case where we're // actually editing a table to delete a column. return; } // Swap ends RefObject tmp = droppedEnd; droppedEnd = otherEnd; otherEnd = tmp; } JmiValidationAction scheduledAction = schedulingMap.get(droppedEnd.refMofId()); if (scheduledAction != JmiValidationAction.DELETION) { // Spurious notification from opposite end return; } if ((rule.getSuperInterface() != null) && !(rule.getSuperInterface().isInstance(droppedEnd))) { return; } JmiDeletionAction action = rule.getAction(); if ((action == JmiDeletionAction.CASCADE) || (dispatcher.getDeletionAction() == JmiDeletionAction.CASCADE)) { if (singleLevelCascade) { scheduleDeletion(otherEnd); } else { deleteQueue.add(otherEnd); } dispatcher.notifyDeleteEffect( otherEnd, JmiDeletionAction.CASCADE); return; } if (dispatcher.getDeletionAction() == JmiDeletionAction.INVALIDATE) { // Don't actually delete anything; instead just // break the link and leave a dangling reference. // NOTE jvs 29-Dec-2005: This won't work if we ever need to // INVALIDATE a composite association; in that case // we would need to explicitly queue an action to // break the link. dispatcher.notifyDeleteEffect( otherEnd, JmiDeletionAction.INVALIDATE); return; } // NOTE: We can't construct the exception now since the object is // deleted. Instead, defer until after rollback. final String mofId = droppedEnd.refMofId(); enqueueValidationExcn(new DeferredException() { RuntimeException getException() { RefObject droppedElement = (RefObject) getMdrRepos().getByMofId(mofId); return new JmiRestrictException(droppedElement); } }); } private void rollbackDeletions() { // A savepoint or chained transaction would be smoother, but MDR doesn't // support those. Instead, have to restart the txn altogether. Take // advantage of the fact that MDR allows us to retain references across // txns. getMdrRepos().endTrans(true); // TODO: really need a lock to protect us against someone else's // change here, which could invalidate our schedulingMap. getMdrRepos().beginTrans(true); } /** * Explicitly schedules an object for deletion. Objects may also be * scheduled for deletion implicitly via cascades, or by listening for * refDelete events. * * @param obj object whose deletion is to be scheduled as part of this * change */ public void scheduleDeletion(RefObject obj) { assert (!validatedMap.containsKey(obj)); // delete overrides anything else schedulingMap.put( obj.refMofId(), JmiValidationAction.DELETION); } /** * Decides whether an object requires validation processing on creation or * modification. (Deletion validation processing is carried out * regardless of this decision.) * * @param obj object being touched * * @return true to carry out validation processing; false to * suppress */ protected boolean shouldValidateModification(RefObject obj) { return true; } private void scheduleModification(RefObject obj) { if (obj == null) { return; } if (!shouldValidateModification(obj)) { return; } if (validatedMap.containsKey(obj)) { return; } if (schedulingMap.containsKey(obj.refMofId())) { return; } JmiValidationAction action = JmiValidationAction.MODIFICATION; if (dispatcher.isNewObject(obj)) { action = JmiValidationAction.CREATION; } schedulingMap.put( obj.refMofId(), action); } /** * Explicitly schedules an object for creation or modification (which one * depends on the result of JmiChangeDispatcher.isNewObject). This can be * used to include objects for which events were not heard by the listener * mechanism. * * @param obj object whose creation or modification is to be scheduled as * part of this change */ public void scheduleObject(RefObject obj) { scheduleModification(obj); } /** * Requests that events on an object be ignored. * * @param obj object to be ignored */ public void scheduleIgnore(RefObject obj) { schedulingMap.remove(obj.refMofId()); validatedMap.put(obj, JmiValidationAction.MODIFICATION); } /** * Calls sortOrderedAssocs for each object being created or modified in * transitMap. */ private void sortOrderedAssocsInTransitMap() { for (Map.Entry<String, JmiValidationAction> mapEntry : transitMap.entrySet()) { JmiValidationAction action = mapEntry.getValue(); if (action == JmiValidationAction.DELETION) { continue; } RefObject refObj = (RefObject) getMdrRepos().getByMofId(mapEntry.getKey()); // Check for null because object might have been deleted // by a trigger. if (refObj != null) { sortOrderedAssocs(refObj); } } } /** * Synchronizes the "ordinal" attribute of targets in ordered composite * associations of which the given object is a source. * *<p> * * If none of the targets has a null ordinal value, it is assumed that the * existing ordinals should be used to reorder the association. Otherwise, * it is assumed that the ordinals should be reassigned based on existing * association order (ignoring existing ordinal values). * *<p> * * Either way, the result is always a contiguous sequence of * ordinals from 0 to n-1 for n targets. * * @param refObj source of associations to maintain */ private void sortOrderedAssocs(RefObject refObj) { JmiModelView modelView = dispatcher.getModelView(); JmiClassVertex classVertex = modelView.getModelGraph().getVertexForRefClass( refObj.refClass()); assert (classVertex != null); Set edges = modelView.getAllOutgoingAssocEdges(classVertex); for (Object edgeObj : edges) { JmiAssocEdge edge = (JmiAssocEdge) edgeObj; if (edge.getSourceEnd().getAggregation() != AggregationKindEnum.COMPOSITE) { continue; } if (!edge.getTargetEnd().getMultiplicity().isOrdered()) { continue; } Collection targets = edge.getRefAssoc().refQuery( edge.getSourceEnd(), refObj); // It's an ordered end, so it should be a List. assert (targets instanceof List); if (shouldSortByOrdinal()) { sortByOrdinal((List<RefObject>) targets); } // Now reassign ordinals to match List order int nextOrdinal = 0; for (Object targetObj : targets) { RefObject target = (RefObject) targetObj; Integer newOrdinal = nextOrdinal; ++nextOrdinal; Integer oldOrdinal; try { oldOrdinal = (Integer) target.refGetValue("ordinal"); } catch (InvalidNameException ex) { // No ordinal attribute to be maintained. continue; } // Avoid unnecessary updates in the case where ordinals // are already correct. if (oldOrdinal.intValue() != newOrdinal.intValue()) { target.refSetValue("ordinal", newOrdinal); } } } } private void sortByOrdinal(List<RefObject> targets) { boolean sort = true; boolean strictlyIncreasing = true; int lastOrdinal = -1; boolean zeroSeen = false; for (RefObject target : targets) { Integer ordinal; try { ordinal = (Integer) target.refGetValue("ordinal"); } catch (InvalidNameException ex) { // No ordinal attribute to be maintained. return; } if (ordinal == null) { sort = false; } else { if (ordinal <= lastOrdinal) { strictlyIncreasing = false; } if (ordinal == 0) { if (zeroSeen) { // Oops, we've seen more than one ordinal with value 0. // This means we really shouldn't be sorting by // ordinal, since someone probably left the default // ordinal value set on a new object. sort = false; } else { zeroSeen = true; } } lastOrdinal = ordinal; } } if (strictlyIncreasing || !sort) { // Avoid unnecessary updates by skipping sort if it would have // no effect. return; } ArrayList<RefObject> copy = new ArrayList<RefObject>( (List<RefObject>) targets); Collections.sort( copy, new JmiOrdinalComparator()); targets.clear(); targets.addAll(copy); } protected boolean shouldSortByOrdinal() { // subclasses have to explicitly override this to return true // if they want sort-by-ordinal behavior return false; } /** * DeferredException allows an exception's creation to be deferred. This is * needed since it is not possible to correctly construct an exception in * certain validation contexts. */ private static abstract class DeferredException { abstract RuntimeException getException(); } private static class JmiOrdinalComparator implements Comparator<RefObject> { // implement Comparator public int compare(RefObject o1, RefObject o2) { Integer ord1 = (Integer) o1.refGetValue("ordinal"); Integer ord2 = (Integer) o2.refGetValue("ordinal"); return ord1 - ord2; } // implement Comparator public boolean equals(JmiOrdinalComparator obj) { return obj instanceof JmiOrdinalComparator; } } } // End JmiChangeSet.java
package org.innovateuk.ifs.application; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.LongNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.innovateuk.ifs.application.finance.service.FinanceService; import org.innovateuk.ifs.application.finance.view.FinanceHandler; import org.innovateuk.ifs.application.finance.view.jes.JESFinanceFormHandler; import org.innovateuk.ifs.application.finance.viewmodel.AcademicFinanceViewModel; import org.innovateuk.ifs.application.form.ApplicationForm; import org.innovateuk.ifs.application.populator.*; import org.innovateuk.ifs.application.resource.*; import org.innovateuk.ifs.application.service.*; import org.innovateuk.ifs.application.viewmodel.OpenFinanceSectionViewModel; import org.innovateuk.ifs.application.viewmodel.OpenSectionViewModel; import org.innovateuk.ifs.application.viewmodel.QuestionOrganisationDetailsViewModel; import org.innovateuk.ifs.application.viewmodel.QuestionViewModel; import org.innovateuk.ifs.commons.error.Error; import org.innovateuk.ifs.commons.rest.RestResult; import org.innovateuk.ifs.commons.rest.ValidationMessages; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.controller.ValidationHandler; import org.innovateuk.ifs.exception.AutosaveElementException; import org.innovateuk.ifs.exception.BigDecimalNumberFormatException; import org.innovateuk.ifs.exception.IntegerNumberFormatException; import org.innovateuk.ifs.exception.UnableToReadUploadedFile; import org.innovateuk.ifs.file.resource.FileEntryResource; import org.innovateuk.ifs.filter.CookieFlashMessageFilter; import org.innovateuk.ifs.finance.resource.ApplicationFinanceResource; import org.innovateuk.ifs.finance.resource.cost.FinanceRowItem; import org.innovateuk.ifs.finance.resource.cost.FinanceRowType; import org.innovateuk.ifs.finance.service.FinanceRowRestService; import org.innovateuk.ifs.form.resource.FormInputResource; import org.innovateuk.ifs.form.resource.FormInputType; import org.innovateuk.ifs.form.service.FormInputResponseRestService; import org.innovateuk.ifs.form.service.FormInputRestService; import org.innovateuk.ifs.profiling.ProfileExecution; import org.innovateuk.ifs.user.resource.OrganisationTypeEnum; import org.innovateuk.ifs.user.resource.ProcessRoleResource; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.service.ProcessRoleService; import org.innovateuk.ifs.user.service.UserService; import org.innovateuk.ifs.util.AjaxResult; import org.innovateuk.ifs.util.TimeZoneUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.core.io.ByteArrayResource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.request.WebRequest; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.support.StringMultipartFileEditor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.io.IOException; import java.time.LocalDate; import java.util.*; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static org.innovateuk.ifs.commons.error.Error.fieldError; import static org.innovateuk.ifs.commons.error.ErrorConverterFactory.toField; import static org.innovateuk.ifs.commons.rest.ValidationMessages.collectValidationMessages; import static org.innovateuk.ifs.commons.rest.ValidationMessages.noErrors; import static org.innovateuk.ifs.controller.ErrorLookupHelper.lookupErrorMessageResourceBundleEntries; import static org.innovateuk.ifs.controller.ErrorLookupHelper.lookupErrorMessageResourceBundleEntry; import static org.innovateuk.ifs.file.controller.FileDownloadControllerUtils.getFileResponseEntity; import static org.innovateuk.ifs.form.resource.FormInputScope.APPLICATION; import static org.innovateuk.ifs.form.resource.FormInputType.FILEUPLOAD; import static org.innovateuk.ifs.util.CollectionFunctions.simpleFilter; import static org.innovateuk.ifs.util.CollectionFunctions.simpleMap; import static org.innovateuk.ifs.util.HttpUtils.requestParameterPresent; import static org.springframework.util.StringUtils.hasText; /** * This controller will handle all requests that are related to the application form. */ @Controller @RequestMapping(ApplicationFormController.APPLICATION_BASE_URL + "{applicationId}/form") @PreAuthorize("hasAuthority('applicant')") public class ApplicationFormController { private static final Log LOG = LogFactory.getLog(ApplicationFormController.class); public static final String QUESTION_URL = "/question/"; public static final String QUESTION_ID = "questionId"; public static final String MODEL_ATTRIBUTE_MODEL = "model"; public static final String MODEL_ATTRIBUTE_FORM = "form"; public static final String APPLICATION_ID = "applicationId"; public static final String APPLICATION_FORM = "application-form"; public static final String SECTION_URL = "/section/"; public static final String EDIT_QUESTION = "edit_question"; public static final String ASSIGN_QUESTION_PARAM = "assign_question"; public static final String MARK_AS_COMPLETE = "mark_as_complete"; public static final String MARK_SECTION_AS_COMPLETE = "mark_section_as_complete"; public static final String ADD_COST = "add_cost"; public static final String REMOVE_COST = "remove_cost"; public static final String MARK_SECTION_AS_INCOMPLETE = "mark_section_as_incomplete"; public static final String MARK_AS_INCOMPLETE = "mark_as_incomplete"; public static final String NOT_REQUESTING_FUNDING = "not_requesting_funding"; public static final String ACADEMIC_FINANCE_REMOVE = "remove_finance_document"; public static final String REQUESTING_FUNDING = "requesting_funding"; public static final String UPLOAD_FILE = "upload_file"; public static final String REMOVE_UPLOADED_FILE = "remove_uploaded_file"; public static final String TERMS_AGREED_KEY = "termsAgreed"; public static final String STATE_AID_AGREED_KEY = "stateAidAgreed"; public static final String ORGANISATION_SIZE_KEY = "organisationSize"; public static final String APPLICATION_BASE_URL = "/application/"; public static final String APPLICATION_START_DATE = "application.startDate"; @Autowired private FinanceRowRestService financeRowRestService; @Autowired private FinanceService financeService; @Autowired private MessageSource messageSource; @Autowired private QuestionModelPopulator questionModelPopulator; @Autowired private OpenSectionModelPopulator openSectionModel; @Autowired private OrganisationDetailsViewModelPopulator organisationDetailsViewModelPopulator; @Autowired private OpenApplicationFinanceSectionModelPopulator openFinanceSectionModel; @Autowired private ApplicationNavigationPopulator applicationNavigationPopulator; @Autowired private OrganisationService organisationService; @Autowired private FinanceHandler financeHandler; @Autowired private ProcessRoleService processRoleService; @Autowired private FormInputResponseRestService formInputResponseRestService; @Autowired private SectionService sectionService; @Autowired private ApplicationService applicationService; @Autowired private ApplicationModelPopulator applicationModelPopulator; @Autowired private QuestionService questionService; @Autowired private CompetitionService competitionService; @Autowired private FormInputRestService formInputRestService; @Autowired private CookieFlashMessageFilter cookieFlashMessageFilter; @Autowired private UserService userService; @Autowired private OverheadFileSaver overheadFileSaver; @InitBinder protected void initBinder(WebDataBinder dataBinder, WebRequest webRequest) { dataBinder.registerCustomEditor(String.class, new StringMultipartFileEditor()); } @ProfileExecution @GetMapping(value = {QUESTION_URL + "{" + QUESTION_ID + "}", QUESTION_URL + "edit/{" + QUESTION_ID + "}"}) public String showQuestion(@ModelAttribute(name = MODEL_ATTRIBUTE_FORM, binding = false) ApplicationForm form, @SuppressWarnings("unused") BindingResult bindingResult, @SuppressWarnings("unused") ValidationHandler validationHandler, Model model, @PathVariable(APPLICATION_ID) final Long applicationId, @PathVariable(QUESTION_ID) final Long questionId, UserResource user) { QuestionOrganisationDetailsViewModel organisationDetailsViewModel = organisationDetailsViewModelPopulator.populateModel(applicationId); QuestionViewModel questionViewModel = questionModelPopulator.populateModel(questionId, applicationId, user, model, form, organisationDetailsViewModel); model.addAttribute(MODEL_ATTRIBUTE_MODEL, questionViewModel); applicationNavigationPopulator.addAppropriateBackURLToModel(applicationId, model, null); return APPLICATION_FORM; } @ProfileExecution @GetMapping(QUESTION_URL + "{" + QUESTION_ID + "}/forminput/{formInputId}/download") public @ResponseBody ResponseEntity<ByteArrayResource> downloadApplicationFinanceFile( @PathVariable(APPLICATION_ID) final Long applicationId, @PathVariable("formInputId") final Long formInputId, UserResource user) { ProcessRoleResource processRole = processRoleService.findProcessRole(user.getId(), applicationId); final ByteArrayResource resource = formInputResponseRestService.getFile(formInputId, applicationId, processRole.getId()).getSuccessObjectOrThrowException(); final FormInputResponseFileEntryResource fileDetails = formInputResponseRestService.getFileDetails(formInputId, applicationId, processRole.getId()).getSuccessObjectOrThrowException(); return getFileResponseEntity(resource, fileDetails.getFileEntryResource()); } @GetMapping("/{applicationFinanceId}/finance-download") public @ResponseBody ResponseEntity<ByteArrayResource> downloadApplicationFinanceFile( @PathVariable("applicationFinanceId") final Long applicationFinanceId) { final ByteArrayResource resource = financeService.getFinanceDocumentByApplicationFinance(applicationFinanceId).getSuccessObjectOrThrowException(); final FileEntryResource fileDetails = financeService.getFinanceEntryByApplicationFinanceId(applicationFinanceId).getSuccessObjectOrThrowException(); return getFileResponseEntity(resource, fileDetails); } @ProfileExecution @GetMapping(SECTION_URL + "{sectionId}") public String applicationFormWithOpenSection(@Valid @ModelAttribute(name = MODEL_ATTRIBUTE_FORM, binding = false) ApplicationForm form, BindingResult bindingResult, Model model, @PathVariable(APPLICATION_ID) final Long applicationId, @PathVariable("sectionId") final Long sectionId, UserResource user) { ApplicationResource application = applicationService.getById(applicationId); List<SectionResource> allSections = sectionService.getAllByCompetitionId(application.getCompetition()); SectionResource section = simpleFilter(allSections, s -> sectionId.equals(s.getId())).get(0); Long organisationId = userService.getUserOrganisationId(user.getId(), applicationId); populateSection(model, form, bindingResult, application, user, organisationId, section, allSections); return APPLICATION_FORM; } private void populateSection(Model model, ApplicationForm form, BindingResult bindingResult, ApplicationResource application, UserResource user, Long organisationId, SectionResource section, List<SectionResource> allSections) { if (SectionType.GENERAL.equals(section.getType()) || SectionType.OVERVIEW_FINANCES.equals(section.getType())) { OpenSectionViewModel viewModel = (OpenSectionViewModel) openSectionModel.populateModel( form, model, application, section, user, bindingResult, allSections, organisationId); model.addAttribute(MODEL_ATTRIBUTE_MODEL, viewModel); } else { OpenFinanceSectionViewModel viewModel = (OpenFinanceSectionViewModel) openFinanceSectionModel.populateModel( form, model, application, section, user, bindingResult, allSections, organisationId); if (viewModel.getFinanceViewModel() instanceof AcademicFinanceViewModel) { viewModel.setNavigationViewModel(applicationNavigationPopulator.addNavigation(section, application.getId(), asList(SectionType.ORGANISATION_FINANCES, SectionType.FUNDING_FINANCES))); } model.addAttribute(MODEL_ATTRIBUTE_MODEL, viewModel); } applicationNavigationPopulator.addAppropriateBackURLToModel(application.getId(), model, section); } @ProfileExecution @PostMapping(value = {QUESTION_URL + "{" + QUESTION_ID + "}", QUESTION_URL + "edit/{" + QUESTION_ID + "}"}) public String questionFormSubmit(@Valid @ModelAttribute(MODEL_ATTRIBUTE_FORM) ApplicationForm form, BindingResult bindingResult, ValidationHandler validationHandler, Model model, @PathVariable(APPLICATION_ID) final Long applicationId, @PathVariable(QUESTION_ID) final Long questionId, UserResource user, HttpServletRequest request, HttpServletResponse response) { Map<String, String[]> params = request.getParameterMap(); // Check if the request is to just open edit view or to save if (params.containsKey(EDIT_QUESTION)) { ProcessRoleResource processRole = processRoleService.findProcessRole(user.getId(), applicationId); if (processRole != null) { questionService.markAsInComplete(questionId, applicationId, processRole.getId()); } else { LOG.error("Not able to find process role for user " + user.getName() + " for application id " + applicationId); } return showQuestion(form, bindingResult, validationHandler, model, applicationId, questionId, user); } else { QuestionResource question = questionService.getById(questionId); ApplicationResource application = applicationService.getById(applicationId); CompetitionResource competition = competitionService.getById(application.getCompetition()); if (params.containsKey(ASSIGN_QUESTION_PARAM)) { assignQuestion(applicationId, user, request); cookieFlashMessageFilter.setFlashMessage(response, "assignedQuestion"); } ValidationMessages errors = new ValidationMessages(); // First check if any errors already exist in bindingResult if (isAllowedToUpdateQuestion(questionId, applicationId, user.getId()) || isMarkQuestionRequest(params)) { /* Start save action */ errors.addAll(saveApplicationForm(application, competition, form, null, question, user, request, response, bindingResult, true)); } model.addAttribute("form", form); /* End save action */ if (isUploadWithValidationErrors(request, errors) || isMarkAsCompleteRequestWithValidationErrors(params, errors, bindingResult)) { validationHandler.addAnyErrors(errors); // Add any validated fields back in invalid entries are displayed on re-render QuestionOrganisationDetailsViewModel organisationDetailsViewModel = organisationDetailsViewModelPopulator.populateModel(applicationId); QuestionViewModel questionViewModel = questionModelPopulator.populateModel(questionId, applicationId, user, model, form, organisationDetailsViewModel); model.addAttribute(MODEL_ATTRIBUTE_MODEL, questionViewModel); applicationNavigationPopulator.addAppropriateBackURLToModel(applicationId, model, null); return APPLICATION_FORM; } else { return getRedirectUrl(request, applicationId, Optional.empty()); } } } private Boolean isMarkAsCompleteRequestWithValidationErrors(Map<String, String[]> params, ValidationMessages errors, BindingResult bindingResult) { return ((errors.hasErrors() || bindingResult.hasErrors()) && isMarkQuestionRequest(params)); } private Boolean isUploadWithValidationErrors(HttpServletRequest request, ValidationMessages errors) { return (request.getParameter(UPLOAD_FILE) != null && errors.hasErrors()); } private Boolean isAllowedToUpdateQuestion(Long questionId, Long applicationId, Long userId) { List<QuestionStatusResource> questionStatuses = questionService.findQuestionStatusesByQuestionAndApplicationId(questionId, applicationId); return questionStatuses.isEmpty() || questionStatuses.stream() .anyMatch(questionStatusResource -> ( questionStatusResource.getAssignee() == null || questionStatusResource.getAssigneeUserId().equals(userId)) && (questionStatusResource.getMarkedAsComplete() == null || !questionStatusResource.getMarkedAsComplete())); } private String getRedirectUrl(HttpServletRequest request, Long applicationId, Optional<SectionType> sectionType) { if (request.getParameter("submit-section") == null && (request.getParameter(ASSIGN_QUESTION_PARAM) != null || request.getParameter(MARK_AS_INCOMPLETE) != null || request.getParameter(MARK_SECTION_AS_INCOMPLETE) != null || request.getParameter(ADD_COST) != null || request.getParameter(REMOVE_COST) != null || request.getParameter(MARK_AS_COMPLETE) != null || request.getParameter(REMOVE_UPLOADED_FILE) != null || request.getParameter(UPLOAD_FILE) != null || request.getParameter(JESFinanceFormHandler.REMOVE_FINANCE_DOCUMENT) != null || request.getParameter(JESFinanceFormHandler.UPLOAD_FINANCE_DOCUMENT) != null || request.getParameter(EDIT_QUESTION) != null || request.getParameter(REQUESTING_FUNDING) != null || request.getParameter(NOT_REQUESTING_FUNDING) != null || request.getParameter(ACADEMIC_FINANCE_REMOVE) != null)) { // user did a action, just display the same page. LOG.debug("redirect: " + request.getRequestURI()); return "redirect:" + request.getRequestURI(); } else if (request.getParameter("submit-section-redirect") != null) { return "redirect:" + APPLICATION_BASE_URL + applicationId + request.getParameter("submit-section-redirect"); } else { if (sectionType.isPresent() && sectionType.get().getParent().isPresent()) { return redirectToSection(sectionType.get().getParent().get(), applicationId); } // add redirect, to make sure the user cannot resubmit the form by refreshing the page. LOG.debug("default redirect: "); return "redirect:" + APPLICATION_BASE_URL + applicationId; } } @GetMapping(value = "/add_cost/{" + QUESTION_ID + "}") public String addCostRow(@ModelAttribute(name = MODEL_ATTRIBUTE_FORM, binding = false) ApplicationForm form, BindingResult bindingResult, Model model, @PathVariable(APPLICATION_ID) final Long applicationId, @PathVariable(QUESTION_ID) final Long questionId, UserResource user) { FinanceRowItem costItem = addCost(applicationId, questionId, user); FinanceRowType costType = costItem.getCostType(); Long organisationId = userService.getUserOrganisationId(user.getId(), applicationId); Set<Long> markedAsComplete = new TreeSet<>(); model.addAttribute("markedAsComplete", markedAsComplete); Long organisationType = organisationService.getOrganisationType(user.getId(), applicationId); financeHandler.getFinanceModelManager(organisationType).addCost(model, costItem, applicationId, organisationId, user.getId(), questionId, costType); form.setBindingResult(bindingResult); return String.format("finance/finance :: %s_row(viewmode='edit')", costType.getType()); } @GetMapping("/remove_cost/{costId}") public @ResponseBody String removeCostRow(@PathVariable("costId") final Long costId) throws JsonProcessingException { financeRowRestService.delete(costId).getSuccessObjectOrThrowException(); AjaxResult ajaxResult = new AjaxResult(HttpStatus.OK, "true"); ObjectMapper mapper = new ObjectMapper(); return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(ajaxResult); } private FinanceRowItem addCost(Long applicationId, Long questionId, UserResource user) { Long organisationType = organisationService.getOrganisationType(user.getId(), applicationId); return financeHandler.getFinanceFormHandler(organisationType).addCostWithoutPersisting(applicationId, user.getId(), questionId); } private ValidationMessages saveApplicationForm(ApplicationResource application, CompetitionResource competition, ApplicationForm form, Long sectionId, QuestionResource question, UserResource user, HttpServletRequest request, HttpServletResponse response, BindingResult bindingResult, Boolean validFinanceTerms) { ProcessRoleResource processRole = processRoleService.findProcessRole(user.getId(), application.getId()); SectionResource selectedSection = null; if (sectionId != null) { selectedSection = sectionService.getById(sectionId); } // Check if action is mark as complete. Check empty values if so, ignore otherwise. (INFUND-1222) Map<String, String[]> params = request.getParameterMap(); logSaveApplicationDetails(params); boolean ignoreEmpty = (!params.containsKey(MARK_AS_COMPLETE)) && (!params.containsKey(MARK_SECTION_AS_COMPLETE)); ValidationMessages errors = new ValidationMessages(); if (null != selectedSection) { if (isMarkSectionAsCompleteRequest(params)) { application.setStateAidAgreed(form.isStateAidAgreed()); } else if (isMarkSectionAsIncompleteRequest(params) && selectedSection.getType() == SectionType.FINANCE) { application.setStateAidAgreed(Boolean.FALSE); } } // Prevent saving question when it's a unmark question request (INFUND-2936) if (!isMarkQuestionAsInCompleteRequest(params)) { if (question != null) { errors.addAll(saveQuestionResponses(request, singletonList(question), user.getId(), processRole.getId(), application.getId(), ignoreEmpty)); } else { List<QuestionResource> questions = simpleMap(selectedSection.getQuestions(), questionService::getById); errors.addAll(saveQuestionResponses(request, questions, user.getId(), processRole.getId(), application.getId(), ignoreEmpty)); } } if (isNotRequestingFundingRequest(params)) { setRequestingFunding(NOT_REQUESTING_FUNDING, user.getId(), application.getId(), competition.getId(), processRole.getId(), errors); } if (isRequestingFundingRequest(params)) { setRequestingFunding(REQUESTING_FUNDING, user.getId(), application.getId(), competition.getId(), processRole.getId(), errors); } setApplicationDetails(application, form.getApplication()); if (applicationModelPopulator.userIsLeadApplicant(application, user.getId())) { applicationService.save(application); } errors.addAll(overheadFileSaver.handleOverheadFileRequest(request)); if (!isMarkSectionAsIncompleteRequest(params)) { Long organisationType = organisationService.getOrganisationType(user.getId(), application.getId()); ValidationMessages saveErrors = financeHandler.getFinanceFormHandler(organisationType).update(request, user.getId(), application.getId(), competition.getId()); if (!overheadFileSaver.isOverheadFileRequest(request)) { errors.addAll(saveErrors); } markAcademicFinancesAsNotRequired(organisationType, selectedSection, application.getId(), competition.getId(), processRole.getId()); } if (isMarkQuestionRequest(params)) { errors.addAll(handleApplicationDetailsMarkCompletedRequest(application, request, response, processRole, errors, bindingResult)); } else if (isMarkSectionRequest(params)) { errors.addAll(handleMarkSectionRequest(application, sectionId, request, processRole, errors, validFinanceTerms)); } if (errors.hasErrors()) { errors.setErrors(sortValidationMessages(errors)); } cookieFlashMessageFilter.setFlashMessage(response, "applicationSaved"); return errors; } private void setRequestingFunding(String requestingFunding, Long userId, Long applicationId, Long competitionId, Long processRoleId, ValidationMessages errors) { ApplicationFinanceResource finance = financeService.getApplicationFinanceDetails(userId, applicationId); QuestionResource financeQuestion = questionService.getQuestionByCompetitionIdAndFormInputType(competitionId, FormInputType.FINANCE).getSuccessObjectOrThrowException(); if (finance.getGrantClaim() != null) { finance.getGrantClaim().setGrantClaimPercentage(0); } errors.addAll(financeRowRestService.add(finance.getId(), financeQuestion.getId(), finance.getGrantClaim())); if (!errors.hasErrors()) { SectionResource organisationSection = sectionService.getSectionsForCompetitionByType(competitionId, SectionType.ORGANISATION_FINANCES).get(0); SectionResource fundingSection = sectionService.getSectionsForCompetitionByType(competitionId, SectionType.FUNDING_FINANCES).get(0); if (REQUESTING_FUNDING.equals(requestingFunding)) { sectionService.markAsInComplete(organisationSection.getId(), applicationId, processRoleId); sectionService.markAsInComplete(fundingSection.getId(), applicationId, processRoleId); } else if (NOT_REQUESTING_FUNDING.equals(requestingFunding)) { sectionService.markAsNotRequired(organisationSection.getId(), applicationId, processRoleId); sectionService.markAsNotRequired(fundingSection.getId(), applicationId, processRoleId); } } } private void markAcademicFinancesAsNotRequired(long organisationType, SectionResource selectedSection, long applicationId, long competitionId, long processRoleId) { if (selectedSection != null && SectionType.PROJECT_COST_FINANCES.equals(selectedSection.getType()) && OrganisationTypeEnum.RESEARCH.getId().equals(organisationType)) { SectionResource organisationSection = sectionService.getSectionsForCompetitionByType(competitionId, SectionType.ORGANISATION_FINANCES).get(0); SectionResource fundingSection = sectionService.getSectionsForCompetitionByType(competitionId, SectionType.FUNDING_FINANCES).get(0); sectionService.markAsNotRequired(organisationSection.getId(), applicationId, processRoleId); sectionService.markAsNotRequired(fundingSection.getId(), applicationId, processRoleId); } } private List<Error> sortValidationMessages(ValidationMessages errors) { List<Error> sortedErrors = errors.getErrors().stream().filter(error -> error.getErrorKey().equals("application.validation.MarkAsCompleteFailed")).collect(toList()); sortedErrors.addAll(errors.getErrors()); return sortedErrors.parallelStream().distinct().collect(toList()); } private void logSaveApplicationDetails(Map<String, String[]> params) { params.forEach((key, value) -> LOG.debug(String.format("saveApplicationForm key %s => value %s", key, value[0]))); } private ValidationMessages handleApplicationDetailsMarkCompletedRequest(ApplicationResource application, HttpServletRequest request, HttpServletResponse response, ProcessRoleResource processRole, ValidationMessages errorsSoFar, BindingResult bindingResult) { ValidationMessages messages = new ValidationMessages(); if (!errorsSoFar.hasErrors() && !bindingResult.hasErrors()) { List<ValidationMessages> applicationMessages = markApplicationQuestions(application, processRole.getId(), request, response, errorsSoFar); if (collectValidationMessages(applicationMessages).hasErrors()) { messages.addAll(handleApplicationDetailsValidationMessages(applicationMessages, application)); } } return messages; } private ValidationMessages handleApplicationDetailsValidationMessages(List<ValidationMessages> applicationMessages, ApplicationResource application) { ValidationMessages toFieldErrors = new ValidationMessages(); applicationMessages.forEach(validationMessage -> validationMessage.getErrors().stream() .filter(Objects::nonNull) .filter(e -> hasText(e.getErrorKey())) .forEach(e -> { if (validationMessage.getObjectName().equals("target")) { if (hasText(e.getErrorKey())) { toFieldErrors.addError(fieldError("application." + e.getFieldName(), e.getFieldRejectedValue(), e.getErrorKey())); } } })); return toFieldErrors; } private ValidationMessages handleMarkSectionRequest(ApplicationResource application, Long sectionId, HttpServletRequest request, ProcessRoleResource processRole, ValidationMessages errorsSoFar, Boolean validFinanceTerms) { ValidationMessages messages = new ValidationMessages(); if (errorsSoFar.hasErrors()) { messages.addError(fieldError("formInput[cost]", "", "application.validation.MarkAsCompleteFailed")); } else if (isMarkSectionAsIncompleteRequest(request.getParameterMap()) || (isMarkSectionAsCompleteRequest(request.getParameterMap()) && validFinanceTerms)) { SectionResource selectedSection = sectionService.getById(sectionId); List<ValidationMessages> financeErrorsMark = markAllQuestionsInSection(application, selectedSection, processRole.getId(), request); if (collectValidationMessages(financeErrorsMark).hasErrors()) { messages.addError(fieldError("formInput[cost]", "", "application.validation.MarkAsCompleteFailed")); messages.addAll(handleMarkSectionValidationMessages(financeErrorsMark)); } } else { } return messages; } private ValidationMessages handleMarkSectionValidationMessages(List<ValidationMessages> financeErrorsMark) { ValidationMessages toFieldErrors = new ValidationMessages(); financeErrorsMark.forEach(validationMessage -> validationMessage.getErrors().stream() .filter(Objects::nonNull) .filter(e -> hasText(e.getErrorKey())) .forEach(e -> { if (validationMessage.getObjectName().equals("costItem")) { if (hasText(e.getErrorKey())) { toFieldErrors.addError(fieldError("formInput[cost-" + validationMessage.getObjectId() + "-" + e.getFieldName() + "]", e)); } else { toFieldErrors.addError(fieldError("formInput[cost-" + validationMessage.getObjectId() + "]", e)); } } else { toFieldErrors.addError(fieldError("formInput[" + validationMessage.getObjectId() + "]", e)); } }) ); return toFieldErrors; } private List<ValidationMessages> markAllQuestionsInSection(ApplicationResource application, SectionResource selectedSection, Long processRoleId, HttpServletRequest request) { Map<String, String[]> params = request.getParameterMap(); String action = params.containsKey(MARK_SECTION_AS_COMPLETE) ? MARK_AS_COMPLETE : MARK_AS_INCOMPLETE; if (action.equals(MARK_AS_COMPLETE)) { return sectionService.markAsComplete(selectedSection.getId(), application.getId(), processRoleId); } else { sectionService.markAsInComplete(selectedSection.getId(), application.getId(), processRoleId); } return emptyList(); } private boolean isMarkQuestionRequest(@NotNull Map<String, String[]> params) { return params.containsKey(MARK_AS_COMPLETE) || params.containsKey(MARK_AS_INCOMPLETE); } private boolean isMarkQuestionAsInCompleteRequest(@NotNull Map<String, String[]> params) { return params.containsKey(MARK_AS_INCOMPLETE); } private boolean isNotRequestingFundingRequest(@NotNull Map<String, String[]> params) { return params.containsKey(NOT_REQUESTING_FUNDING); } private boolean isRequestingFundingRequest(@NotNull Map<String, String[]> params) { return params.containsKey(REQUESTING_FUNDING); } private boolean isMarkSectionRequest(@NotNull Map<String, String[]> params) { return params.containsKey(MARK_SECTION_AS_COMPLETE) || params.containsKey(MARK_SECTION_AS_INCOMPLETE); } private boolean isMarkSectionAsIncompleteRequest(@NotNull Map<String, String[]> params) { return params.containsKey(MARK_SECTION_AS_INCOMPLETE); } private boolean isMarkSectionAsCompleteRequest(@NotNull Map<String, String[]> params) { return params.containsKey(MARK_SECTION_AS_COMPLETE); } private List<ValidationMessages> markApplicationQuestions(ApplicationResource application, Long processRoleId, HttpServletRequest request, HttpServletResponse response, ValidationMessages errorsSoFar) { if (processRoleId == null) { return emptyList(); } Map<String, String[]> params = request.getParameterMap(); if (params.containsKey(MARK_AS_COMPLETE)) { Long questionId = Long.valueOf(request.getParameter(MARK_AS_COMPLETE)); List<ValidationMessages> markAsCompleteErrors = questionService.markAsComplete(questionId, application.getId(), processRoleId); if (collectValidationMessages(markAsCompleteErrors).hasErrors()) { questionService.markAsInComplete(questionId, application.getId(), processRoleId); } else { cookieFlashMessageFilter.setFlashMessage(response, "applicationSaved"); } if (errorsSoFar.hasFieldErrors(questionId + "")) { markAsCompleteErrors.add(new ValidationMessages(fieldError(questionId + "", "", "mark.as.complete.invalid.data.exists"))); } return markAsCompleteErrors; } else if (params.containsKey(MARK_AS_INCOMPLETE)) { Long questionId = Long.valueOf(request.getParameter(MARK_AS_INCOMPLETE)); questionService.markAsInComplete(questionId, application.getId(), processRoleId); } return emptyList(); } @ProfileExecution @PostMapping(SECTION_URL + "{sectionId}") public String applicationFormSubmit(@Valid @ModelAttribute(MODEL_ATTRIBUTE_FORM) ApplicationForm form, BindingResult bindingResult, ValidationHandler validationHandler, Model model, @PathVariable(APPLICATION_ID) final Long applicationId, @PathVariable("sectionId") final Long sectionId, UserResource user, HttpServletRequest request, HttpServletResponse response) { logSaveApplicationBindingErrors(validationHandler); ApplicationResource application = applicationService.getById(applicationId); CompetitionResource competition = competitionService.getById(application.getCompetition()); List<SectionResource> allSections = sectionService.getAllByCompetitionId(application.getCompetition()); SectionResource section = sectionService.getById(sectionId); Long organisationId = userService.getUserOrganisationId(user.getId(), applicationId); model.addAttribute("form", form); Map<String, String[]> params = request.getParameterMap(); Boolean validFinanceTerms = validFinanceTermsForMarkAsComplete(form, bindingResult, section, params, user.getId(), applicationId); ValidationMessages saveApplicationErrors = saveApplicationForm(application, competition, form, sectionId, null, user, request, response, bindingResult, validFinanceTerms); logSaveApplicationErrors(bindingResult); if (params.containsKey(ASSIGN_QUESTION_PARAM)) { assignQuestion(applicationId, user, request); cookieFlashMessageFilter.setFlashMessage(response, "assignedQuestion"); } if (saveApplicationErrors.hasErrors() || !validFinanceTerms || overheadFileSaver.isOverheadFileRequest(request)) { validationHandler.addAnyErrors(saveApplicationErrors); populateSection(model, form, bindingResult, application, user, organisationId, section, allSections); return APPLICATION_FORM; } else { return getRedirectUrl(request, applicationId, Optional.of(section.getType())); } } private Boolean validFinanceTermsForMarkAsComplete(ApplicationForm form, BindingResult bindingResult, SectionResource section, Map<String, String[]> params, Long userId, Long applicationId) { Boolean valid = Boolean.TRUE; if (!isMarkSectionAsCompleteRequest(params)) { return valid; } if (SectionType.FUNDING_FINANCES.equals(section.getType())) { if (!form.isTermsAgreed()) { bindingResult.rejectValue(TERMS_AGREED_KEY, "APPLICATION_AGREE_TERMS_AND_CONDITIONS"); valid = Boolean.FALSE; } } if (SectionType.PROJECT_COST_FINANCES.equals(section.getType()) && !userIsResearch(userId)) { if (!form.isStateAidAgreed()) { bindingResult.rejectValue(STATE_AID_AGREED_KEY, "APPLICATION_AGREE_STATE_AID_CONDITIONS"); valid = Boolean.FALSE; } } if (SectionType.ORGANISATION_FINANCES.equals(section.getType())) { List<String> financePositionKeys = params.keySet().stream().filter(k -> k.contains("financePosition-")).collect(Collectors.toList()); Long organisationType = organisationService.getOrganisationType(userId, applicationId); if (financePositionKeys.isEmpty() && !OrganisationTypeEnum.RESEARCH.getId().equals(organisationType)) { bindingResult.rejectValue(ORGANISATION_SIZE_KEY, "APPLICATION_ORGANISATION_SIZE_REQUIRED"); valid = Boolean.FALSE; } } return valid; } private boolean userIsResearch(Long userId) { return organisationService.getOrganisationForUser(userId).getOrganisationType().equals(OrganisationTypeEnum.RESEARCH.getId()); } private void logSaveApplicationBindingErrors(ValidationHandler validationHandler) { if (LOG.isDebugEnabled()) validationHandler.getAllErrors().forEach(e -> LOG.debug("Validations on application : " + e.getObjectName() + " v: " + e.getDefaultMessage())); } private void logSaveApplicationErrors(BindingResult bindingResult) { if (LOG.isDebugEnabled()) { bindingResult.getFieldErrors().forEach(e -> LOG.debug("Remote validation field: " + e.getObjectName() + " v: " + e.getField() + " v: " + e.getDefaultMessage())); bindingResult.getGlobalErrors().forEach(e -> LOG.debug("Remote validation global: " + e.getObjectName() + " v: " + e.getCode() + " v: " + e.getDefaultMessage())); } } private ValidationMessages saveQuestionResponses(HttpServletRequest request, List<QuestionResource> questions, Long userId, Long processRoleId, Long applicationId, boolean ignoreEmpty) { final Map<String, String[]> params = request.getParameterMap(); ValidationMessages errors = new ValidationMessages(); errors.addAll(saveNonFileUploadQuestions(questions, params, request, userId, applicationId, ignoreEmpty)); errors.addAll(saveFileUploadQuestionsIfAny(questions, params, request, applicationId, processRoleId)); return errors; } private ValidationMessages saveNonFileUploadQuestions(List<QuestionResource> questions, Map<String, String[]> params, HttpServletRequest request, Long userId, Long applicationId, boolean ignoreEmpty) { ValidationMessages allErrors = new ValidationMessages(); questions.forEach(question -> { List<FormInputResource> formInputs = formInputRestService.getByQuestionIdAndScope(question.getId(), APPLICATION).getSuccessObjectOrThrowException(); formInputs .stream() .filter(formInput1 -> FILEUPLOAD != formInput1.getType()) .forEach(formInput -> { String formInputKey = "formInput[" + formInput.getId() + "]"; requestParameterPresent(formInputKey, request).ifPresent(value -> { ValidationMessages errors = formInputResponseRestService.saveQuestionResponse( userId, applicationId, formInput.getId(), value, ignoreEmpty).getSuccessObjectOrThrowException(); allErrors.addAll(errors, toField(formInputKey)); }); }); } ); return allErrors; } private ValidationMessages saveFileUploadQuestionsIfAny(List<QuestionResource> questions, final Map<String, String[]> params, HttpServletRequest request, Long applicationId, Long processRoleId) { ValidationMessages allErrors = new ValidationMessages(); questions.forEach(question -> { List<FormInputResource> formInputs = formInputRestService.getByQuestionIdAndScope(question.getId(), APPLICATION).getSuccessObjectOrThrowException(); formInputs .stream() .filter(formInput1 -> FILEUPLOAD == formInput1.getType() && request instanceof MultipartHttpServletRequest) .forEach(formInput -> allErrors.addAll(processFormInput(formInput.getId(), params, applicationId, processRoleId, request)) ); }); return allErrors; } private ValidationMessages processFormInput(Long formInputId, Map<String, String[]> params, Long applicationId, Long processRoleId, HttpServletRequest request) { if (params.containsKey(REMOVE_UPLOADED_FILE)) { formInputResponseRestService.removeFileEntry(formInputId, applicationId, processRoleId).getSuccessObjectOrThrowException(); return noErrors(); } else { final Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) request).getFileMap(); final MultipartFile file = fileMap.get("formInput[" + formInputId + "]"); if (file != null && !file.isEmpty()) { try { RestResult<FileEntryResource> result = formInputResponseRestService.createFileEntry(formInputId, applicationId, processRoleId, file.getContentType(), file.getSize(), file.getOriginalFilename(), file.getBytes()); if (result.isFailure()) { ValidationMessages errors = new ValidationMessages(); result.getFailure().getErrors().forEach(e -> { errors.addError(fieldError("formInput[" + formInputId + "]", e.getFieldRejectedValue(), e.getErrorKey())); }); return errors; } } catch (IOException e) { LOG.error(e); throw new UnableToReadUploadedFile(); } } } return noErrors(); } /** * Set the submitted values, if not null. If they are null, then probably the form field was not in the current html form. * * @param application * @param updatedApplication */ private void setApplicationDetails(ApplicationResource application, ApplicationResource updatedApplication) { if (updatedApplication == null) { return; } if (updatedApplication.getName() != null) { LOG.debug("setApplicationDetails: " + updatedApplication.getName()); application.setName(updatedApplication.getName()); } setResubmissionDetails(application, updatedApplication); if (updatedApplication.getStartDate() != null) { LOG.debug("setApplicationDetails date 123: " + updatedApplication.getStartDate().toString()); if (updatedApplication.getStartDate().isEqual(LocalDate.MIN) || updatedApplication.getStartDate().isBefore(LocalDate.now(TimeZoneUtil.UK_TIME_ZONE))) { // user submitted a empty date field or date before today application.setStartDate(null); } else { application.setStartDate(updatedApplication.getStartDate()); } } else { application.setStartDate(null); } if (updatedApplication.getDurationInMonths() != null) { LOG.debug("setApplicationDetails: " + updatedApplication.getDurationInMonths()); application.setDurationInMonths(updatedApplication.getDurationInMonths()); } else { application.setDurationInMonths(null); } } /** * Set the submitted details relating to resubmission of applications. * * @param application * @param updatedApplication */ private void setResubmissionDetails(ApplicationResource application, ApplicationResource updatedApplication) { if (updatedApplication.getResubmission() != null) { LOG.debug("setApplicationDetails: resubmission " + updatedApplication.getResubmission()); application.setResubmission(updatedApplication.getResubmission()); if (updatedApplication.getResubmission()) { application.setPreviousApplicationNumber(updatedApplication.getPreviousApplicationNumber()); application.setPreviousApplicationTitle(updatedApplication.getPreviousApplicationTitle()); } else { application.setPreviousApplicationNumber(null); application.setPreviousApplicationTitle(null); } } } /** * This method is for supporting ajax saving from the application form. */ @ProfileExecution @PostMapping("/{competitionId}/saveFormElement") @ResponseBody public JsonNode saveFormElement(@RequestParam("formInputId") String inputIdentifier, @RequestParam("value") String value, @PathVariable(APPLICATION_ID) Long applicationId, @PathVariable("competitionId") Long competitionId, UserResource user, HttpServletRequest request) { List<String> errors = new ArrayList<>(); Long fieldId = null; try { String fieldName = request.getParameter("fieldName"); LOG.info(String.format("saveFormElement: %s / %s", fieldName, value)); StoreFieldResult storeFieldResult = storeField(applicationId, user.getId(), competitionId, fieldName, inputIdentifier, value); fieldId = storeFieldResult.getFieldId(); return this.createJsonObjectNode(true, fieldId); } catch (Exception e) { AutosaveElementException ex = new AutosaveElementException(inputIdentifier, value, applicationId, e); handleAutosaveException(errors, e, ex); return this.createJsonObjectNode(false, fieldId); } } private void handleAutosaveException(List<String> errors, Exception e, AutosaveElementException ex) { List<Object> args = new ArrayList<>(); args.add(ex.getErrorMessage()); if (e.getClass().equals(IntegerNumberFormatException.class) || e.getClass().equals(BigDecimalNumberFormatException.class)) { errors.add(lookupErrorMessageResourceBundleEntry(messageSource, e.getMessage(), args)); } else { LOG.error("Got an exception on autosave : " + e.getMessage()); LOG.debug("Autosave exception: ", e); errors.add(ex.getErrorMessage()); } } private StoreFieldResult storeField(Long applicationId, Long userId, Long competitionId, String fieldName, String inputIdentifier, String value) { Long organisationType = organisationService.getOrganisationType(userId, applicationId); if (fieldName.startsWith("application.")) { // this does not need id List<String> errors = this.saveApplicationDetails(applicationId, fieldName, value); return new StoreFieldResult(errors); } else if (inputIdentifier.startsWith("financePosition-") || fieldName.startsWith("financePosition-")) { financeHandler.getFinanceFormHandler(organisationType).updateFinancePosition(userId, applicationId, fieldName, value, competitionId); return new StoreFieldResult(); } else if (inputIdentifier.startsWith("cost-") || fieldName.startsWith("cost-")) { ValidationMessages validationMessages = financeHandler.getFinanceFormHandler(organisationType).storeCost(userId, applicationId, fieldName, value, competitionId); if (validationMessages == null || validationMessages.getErrors() == null || validationMessages.getErrors().isEmpty()) { LOG.debug("no errors"); if (validationMessages == null) { return new StoreFieldResult(); } else { return new StoreFieldResult(validationMessages.getObjectId()); } } else { String[] fieldNameParts = fieldName.split("-"); // fieldname = other_costs-description-34-219 List<String> errors = validationMessages.getErrors() .stream() .peek(e -> LOG.debug(String.format("Compare: %s => %s ", fieldName.toLowerCase(), e.getFieldName().toLowerCase()))) .filter(e -> fieldNameParts[1].toLowerCase().contains(e.getFieldName().toLowerCase())) // filter out the messages that are related to other fields. .map(this::lookupErrorMessage) .collect(toList()); return new StoreFieldResult(validationMessages.getObjectId(), errors); } } else { Long formInputId = Long.valueOf(inputIdentifier); ValidationMessages saveErrors = formInputResponseRestService.saveQuestionResponse(userId, applicationId, formInputId, value, false).getSuccessObjectOrThrowException(); List<String> lookedUpErrorMessages = lookupErrorMessageResourceBundleEntries(messageSource, saveErrors); return new StoreFieldResult(lookedUpErrorMessages); } } private String lookupErrorMessage(Error e) { return lookupErrorMessageResourceBundleEntry(messageSource, e); } private ObjectNode createJsonObjectNode(boolean success, Long fieldId) { ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("success", success ? "true" : "false"); if (fieldId != null) { node.set("fieldId", new LongNode(fieldId)); } return node; } private List<String> saveApplicationDetails(Long applicationId, String fieldName, String value) { List<String> errors = new ArrayList<>(); ApplicationResource application = applicationService.getById(applicationId); if ("application.name".equals(fieldName)) { String trimmedValue = value.trim(); if (StringUtils.isEmpty(trimmedValue)) { errors.add("Please enter the full title of the project"); } else { application.setName(trimmedValue); applicationService.save(application); } } else if (fieldName.startsWith("application.durationInMonths")) { Long durationInMonth = Long.valueOf(value); if (durationInMonth < 1L || durationInMonth > 36L) { errors.add("Your project should last between 1 and 36 months"); application.setDurationInMonths(durationInMonth); } else { application.setDurationInMonths(durationInMonth); applicationService.save(application); } } else if (fieldName.startsWith(APPLICATION_START_DATE)) { errors = this.saveApplicationStartDate(application, fieldName, value); } else if (fieldName.equals("application.resubmission")) { application.setResubmission(Boolean.valueOf(value)); applicationService.save(application); } else if (fieldName.equals("application.previousApplicationNumber")) { application.setPreviousApplicationNumber(value); applicationService.save(application); } else if (fieldName.equals("application.previousApplicationTitle")) { application.setPreviousApplicationTitle(value); applicationService.save(application); } return errors; } private List<String> saveApplicationStartDate(ApplicationResource application, String fieldName, String value) { List<String> errors = new ArrayList<>(); LocalDate startDate = application.getStartDate(); if (fieldName.endsWith(".dayOfMonth")) { startDate = LocalDate.of(startDate.getYear(), startDate.getMonth(), Integer.parseInt(value)); } else if (fieldName.endsWith(".monthValue")) { startDate = LocalDate.of(startDate.getYear(), Integer.parseInt(value), startDate.getDayOfMonth()); } else if (fieldName.endsWith(".year")) { startDate = LocalDate.of(Integer.parseInt(value), startDate.getMonth(), startDate.getDayOfMonth()); } else if ("application.startDate".equals(fieldName)) { String[] parts = value.split("-"); startDate = LocalDate.of(Integer.parseInt(parts[2]), Integer.parseInt(parts[1]), Integer.parseInt(parts[0])); } if (startDate.isBefore(LocalDate.now())) { errors.add("Please enter a future date"); startDate = null; } else { LOG.debug("Save startdate: " + startDate.toString()); } application.setStartDate(startDate); applicationService.save(application); return errors; } private void assignQuestion(@PathVariable(APPLICATION_ID) final Long applicationId, UserResource user, HttpServletRequest request) { ProcessRoleResource assignedBy = processRoleService.findProcessRole(user.getId(), applicationId); questionService.assignQuestion(applicationId, request, assignedBy); } private static class StoreFieldResult { private Long fieldId; private List<String> errors = new ArrayList<>(); public StoreFieldResult() { } public StoreFieldResult(Long fieldId) { this.fieldId = fieldId; } public StoreFieldResult(List<String> errors) { this.errors = errors; } public StoreFieldResult(Long fieldId, List<String> errors) { this.fieldId = fieldId; this.errors = errors; } public List<String> getErrors() { return errors; } public Long getFieldId() { return fieldId; } } @ProfileExecution @GetMapping("/{sectionType}") public String redirectToSection(@PathVariable("sectionType") SectionType type, @PathVariable(APPLICATION_ID) Long applicationId) { ApplicationResource application = applicationService.getById(applicationId); List<SectionResource> sections = sectionService.getSectionsForCompetitionByType(application.getCompetition(), type); if (sections.size() == 1) { return "redirect:/application/" + applicationId + "/form/section/" + sections.get(0).getId(); } return "redirect:/application/" + applicationId; } }
package edu.kit.ipd.crowdcontrol.objectservice; import edu.kit.ipd.crowdcontrol.objectservice.crowdworking.PlatformManager; import edu.kit.ipd.crowdcontrol.objectservice.database.DatabaseManager; import edu.kit.ipd.crowdcontrol.objectservice.database.operations.*; import edu.kit.ipd.crowdcontrol.objectservice.rest.Router; import edu.kit.ipd.crowdcontrol.objectservice.rest.resources.*; import org.jooq.SQLDialect; import javax.naming.NamingException; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.Properties; import java.util.function.Function; /** * @author Niklas Keller */ public class Main { public static void main(String[] args) throws IOException { Properties properties = new Properties(); try (InputStream in = Main.class.getResourceAsStream("/config.properties")) { properties.load(in); } catch (IOException e) { e.printStackTrace(); System.exit(1); } Function<String, String> trimIfNotNull = s -> { if (s != null) { return s.trim(); } else { return null; } }; String url = trimIfNotNull.apply(properties.getProperty("database.url")); String username = trimIfNotNull.apply(properties.getProperty("database.username")); String password = trimIfNotNull.apply(properties.getProperty("database.password")); String databasePool = trimIfNotNull.apply(properties.getProperty("database.poolName")); String readOnlyUsername = trimIfNotNull.apply(properties.getProperty("database.readonly.username")); String readOnlyPassword = trimIfNotNull.apply(properties.getProperty("database.readonly.password")); SQLDialect dialect = SQLDialect.valueOf(properties.getProperty("database.dialect").trim()); DatabaseManager databaseManager = null; try { databaseManager = new DatabaseManager(username, password, url, databasePool, dialect); databaseManager.initDatabase(); boot(databaseManager, readOnlyUsername, readOnlyPassword); } catch (NamingException | SQLException e) { System.err.println("Unable to establish database connection."); e.printStackTrace(); System.exit(-1); } } private static void boot(DatabaseManager databaseManager, String readOnlyDBUser, String readOnlyDBPassword) throws SQLException { PlatformManager platformManager = null; // TODO TemplateOperations templateOperations = new TemplateOperations(databaseManager.getContext()); NotificationOperations notificationRestOperations = new NotificationOperations(databaseManager, readOnlyDBUser, readOnlyDBPassword); PlatformOperations platformOperations = new PlatformOperations(databaseManager.getContext()); WorkerOperations workerOperations = new WorkerOperations(databaseManager.getContext()); CalibrationOperations calibrationOperations = new CalibrationOperations(databaseManager.getContext()); ExperimentOperations experimentOperations = new ExperimentOperations(databaseManager.getContext()); AnswerRatingOperations answerRatingOperations = new AnswerRatingOperations(databaseManager.getContext()); TagConstraintsOperations tagConstraintsOperations = new TagConstraintsOperations(databaseManager.getContext()); AlgorithmOperations algorithmsOperations = new AlgorithmOperations(databaseManager.getContext()); new Router( new TemplateResource(templateOperations), new NotificationResource(notificationRestOperations), new PlatformResource(platformOperations), new WorkerResource(workerOperations, platformManager), new CalibrationResource(calibrationOperations), new ExperimentResource(experimentOperations, calibrationOperations, tagConstraintsOperations, algorithmsOperations), new AlgorithmResources(algorithmsOperations), new AnswerRatingResource(experimentOperations, answerRatingOperations, workerOperations) ) .init(); } }
package edu.neu.cloudaddy.service; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.util.ArrayList; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import edu.neu.cloudaddy.dao.ReportDao; import edu.neu.cloudaddy.model.Report; @Service("reportService") public class ReportServiceImpl implements ReportService { @Autowired DataSource dataSource; @Autowired ReportDao reportDao; @Override public ArrayList<Report> getReportService(int userID) { return reportDao.getReports(dataSource, userID); } @Override public Report getFileContentService(String repoName) { Report report = reportDao.getFileContent(dataSource, repoName); writefile(report.getReportName(), report.getAttached()); return report; } public String writefile(String reportName, String fileContent) { try { Writer output = null; File index = new File("tmp"); if(!index.exists()){ index.mkdir(); }else{ index = new File("tmp String[] entries = index.list(); for (String s : entries) { File currentFile = new File(index.getPath(), s); currentFile.delete(); } File file = new File("tmp//" + reportName); output = new BufferedWriter(new FileWriter(file)); if(fileContent!=null){ for(String content: fileContent.split("\n")){ output.write(content + "\n"); } } output.close(); System.out.println("File has been written"); } } catch (Exception e) { System.out.println("Could not create file"); } return reportName; } @Override public void deleteFileService(String repoId) { reportDao.deleteFile(dataSource, repoId); } }
package eu.bitwalker.useragentutils; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; /** * Enum constants for most common operating systems. * @author harald */ public enum OperatingSystem { // the order is important since the agent string is being compared with the aliases /** * Windows Mobile / Windows CE. Exact version unknown. */ WINDOWS( Manufacturer.MICROSOFT,null,1, "Windows", new String[] { "Windows" }, new String[] { "Palm", "ggpht.com" }, DeviceType.COMPUTER, null ), // catch the rest of older Windows systems (95, NT,...) WINDOWS_10( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,24, "Windows 10", new String[] { "Windows NT 6.4" }, null, DeviceType.COMPUTER, null ), // before Win, yes, Windows 10 is called 6.4 LOL WINDOWS_81( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,23, "Windows 8.1", new String[] { "Windows NT 6.3" }, null, DeviceType.COMPUTER, null ), // before Win, yes, Windows 8.1 is called 6.3 LOL WINDOWS_8( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,22, "Windows 8", new String[] { "Windows NT 6.2" }, null, DeviceType.COMPUTER, null ), // before Win, yes, Windows 8 is called 6.2 LOL WINDOWS_7( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,21, "Windows 7", new String[] { "Windows NT 6.1" }, null, DeviceType.COMPUTER, null ), // before Win, yes, Windows 7 is called 6.1 LOL WINDOWS_VISTA( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,20, "Windows Vista", new String[] { "Windows NT 6" }, null, DeviceType.COMPUTER, null ), // before Win WINDOWS_2000( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,15, "Windows 2000", new String[] { "Windows NT 5.0" }, null, DeviceType.COMPUTER, null ), // before Win WINDOWS_XP( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,10, "Windows XP", new String[] { "Windows NT 5"}, new String[] { "ggpht.com" }, DeviceType.COMPUTER, null ), // before Win, 5.1 and 5.2 are basically XP systems WINDOWS_PHONE8_1(Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 53, "Windows Phone 8.1", new String[] { "Windows Phone 8.1" }, null, DeviceType.MOBILE, null ), // before Win WINDOWS_PHONE8(Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 52, "Windows Phone 8", new String[] { "Windows Phone 8" }, null, DeviceType.MOBILE, null ), // before Win WINDOWS_MOBILE7(Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 51, "Windows Phone 7", new String[] { "Windows Phone OS 7" }, null, DeviceType.MOBILE, null ), // should be Windows Phone 7 but to keep it compatible we'll leave the name as is. WINDOWS_MOBILE( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 50, "Windows Mobile", new String[] { "Windows CE" }, null, DeviceType.MOBILE, null ), // before Win WINDOWS_98( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,5, "Windows 98", new String[] { "Windows 98","Win98" }, new String[] { "Palm" }, DeviceType.COMPUTER, null ), // before Win ANDROID( Manufacturer.GOOGLE,null, 0, "Android", new String[] { "Android" }, null, DeviceType.MOBILE, null ), ANDROID5( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 5, "Android 5.x", new String[] { "Android 5", "Android-5" }, new String[] { "glass" }, DeviceType.MOBILE, null ), ANDROID5_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID5, 50, "Android 5.x Tablet", new String[] { "Android 5", "Android-5"}, new String[] { "mobile", "glass" }, DeviceType.TABLET, null ), ANDROID4( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 4, "Android 4.x", new String[] { "Android 4", "Android-4" }, new String[] { "glass" }, DeviceType.MOBILE, null ), ANDROID4_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID4, 40, "Android 4.x Tablet", new String[] { "Android 4", "Android-4"}, new String[] { "mobile", "glass" }, DeviceType.TABLET, null ), ANDROID4_WEARABLE(Manufacturer.GOOGLE,OperatingSystem.ANDROID, 400, "Android 4.x", new String[] { "Android 4" }, null, DeviceType.WEARABLE, null ), ANDROID3_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID, 30, "Android 3.x Tablet", new String[] { "Android 3" }, null, DeviceType.TABLET, null ), // as long as there are not Android 3.x phones this should be enough ANDROID2( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 2, "Android 2.x", new String[] { "Android 2" }, null, DeviceType.MOBILE, null ), ANDROID2_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID2, 20, "Android 2.x Tablet", new String[] { "Kindle Fire", "GT-P1000","SCH-I800" }, null, DeviceType.TABLET, null ), ANDROID1( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 1, "Android 1.x", new String[] { "Android 1" }, null, DeviceType.MOBILE, null ), /** * Generic Android mobile device without OS version number information */ ANDROID_MOBILE( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 11, "Android Mobile", new String[] { "Mobile" }, null, DeviceType.MOBILE, null ), /** * Generic Android tablet device without OS version number information */ ANDROID_TABLET( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 12, "Android Tablet", new String[] { "Tablet" }, null, DeviceType.TABLET, null ), /** * Chrome OS by Google, mostly used on Chromebooks and Chromeboxes */ CHROME_OS( Manufacturer.GOOGLE,null, 1000, "Chrome OS", new String[] { "CrOS" }, null, DeviceType.COMPUTER, null ), /** * PalmOS, exact version unkown */ WEBOS( Manufacturer.HP,null,11, "WebOS", new String[] { "webOS" }, null, DeviceType.MOBILE, null ), PALM( Manufacturer.HP,null,10, "PalmOS", new String[] { "Palm" }, null, DeviceType.MOBILE, null ), MEEGO( Manufacturer.NOKIA,null,3, "MeeGo", new String[] { "MeeGo" }, null, DeviceType.MOBILE, null ), /** * iOS4, with the release of the iPhone 4, Apple renamed the OS to iOS. */ IOS( Manufacturer.APPLE,null, 2, "iOS", new String[] { "iPhone OS", "like Mac OS X" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions iOS8_1_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 46, "iOS 8.1 (iPhone)", new String[] { "iPhone OS 8_1" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions iOS8_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 45, "iOS 8 (iPhone)", new String[] { "iPhone OS 8_0" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions iOS7_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 44, "iOS 7 (iPhone)", new String[] { "iPhone OS 7" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions iOS6_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 43, "iOS 6 (iPhone)", new String[] { "iPhone OS 6" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions iOS5_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 42, "iOS 5 (iPhone)", new String[] { "iPhone OS 5" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions iOS4_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 41, "iOS 4 (iPhone)", new String[] { "iPhone OS 4" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions MAC_OS_X_IPAD( Manufacturer.APPLE, OperatingSystem.IOS, 50, "Mac OS X (iPad)", new String[] { "iPad" }, null, DeviceType.TABLET, null ), // before Mac OS X iOS8_1_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 54, "iOS 8.1 (iPad)", new String[] { "OS 8_1" }, null, DeviceType.TABLET, null ), // before Mac OS X iOS8_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 53, "iOS 8 (iPad)", new String[] { "OS 8_0" }, null, DeviceType.TABLET, null ), // before Mac OS X iOS7_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 52, "iOS 7 (iPad)", new String[] { "OS 7" }, null, DeviceType.TABLET, null ), // before Mac OS X iOS6_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 51, "iOS 6 (iPad)", new String[] { "OS 6" }, null, DeviceType.TABLET, null ), // before Mac OS X MAC_OS_X_IPHONE(Manufacturer.APPLE, OperatingSystem.IOS, 40, "Mac OS X (iPhone)", new String[] { "iPhone" }, null, DeviceType.MOBILE, null ), // before Mac OS X MAC_OS_X_IPOD( Manufacturer.APPLE, OperatingSystem.IOS, 30, "Mac OS X (iPod)", new String[] { "iPod" }, null, DeviceType.MOBILE, null ), // before Mac OS X MAC_OS_X( Manufacturer.APPLE,null, 10, "Mac OS X", new String[] { "Mac OS X" , "CFNetwork"}, null, DeviceType.COMPUTER, null ), // before Mac /** * Older Mac OS systems before Mac OS X */ MAC_OS( Manufacturer.APPLE,null, 1, "Mac OS", new String[] { "Mac" }, null, DeviceType.COMPUTER, null ), // older Mac OS systems MAEMO( Manufacturer.NOKIA,null, 2, "Maemo", new String[] { "Maemo" }, null, DeviceType.MOBILE, null ), /** * Bada is a mobile operating system being developed by Samsung Electronics. */ BADA( Manufacturer.SAMSUNG,null, 2, "Bada", new String[] { "Bada" }, null, DeviceType.MOBILE, null ), /** * Google TV uses Android 2.x or 3.x but doesn't identify itself as Android. */ GOOGLE_TV( Manufacturer.GOOGLE,null, 100, "Android (Google TV)", new String[] { "GoogleTV" }, null, DeviceType.DMR, null ), /** * Various Linux based operating systems. */ KINDLE( Manufacturer.AMAZON,null, 1, "Linux (Kindle)", new String[] { "Kindle" }, null, DeviceType.TABLET, null ), KINDLE3( Manufacturer.AMAZON,OperatingSystem.KINDLE, 30, "Linux (Kindle 3)", new String[] { "Kindle/3" }, null, DeviceType.TABLET, null ), KINDLE2( Manufacturer.AMAZON,OperatingSystem.KINDLE, 20, "Linux (Kindle 2)", new String[] { "Kindle/2" }, null, DeviceType.TABLET, null ), LINUX( Manufacturer.OTHER,null, 2, "Linux", new String[] { "Linux" , "CamelHttpStream" }, null, DeviceType.COMPUTER, null ), // CamelHttpStream is being used by Evolution, an email client for Linux /** * Other Symbian OS versions */ SYMBIAN( Manufacturer.SYMBIAN,null, 1, "Symbian OS", new String[] { "Symbian", "Series60"}, null, DeviceType.MOBILE, null ), /** * Symbian OS 9.x versions. Being used by Nokia (N71, N73, N81, N82, N91, N92, N95, ...) */ SYMBIAN9( Manufacturer.SYMBIAN,OperatingSystem.SYMBIAN, 20, "Symbian OS 9.x", new String[] {"SymbianOS/9", "Series60/3"}, null, DeviceType.MOBILE, null ), /** * Symbian OS 8.x versions. Being used by Nokia (6630, 6680, 6681, 6682, N70, N72, N90). */ SYMBIAN8( Manufacturer.SYMBIAN,OperatingSystem.SYMBIAN, 15, "Symbian OS 8.x", new String[] { "SymbianOS/8", "Series60/2.6", "Series60/2.8"}, null, DeviceType.MOBILE, null ), /** * Symbian OS 7.x versions. Being used by Nokia (3230, 6260, 6600, 6620, 6670, 7610), * Panasonic (X700, X800), Samsung (SGH-D720, SGH-D730) and Lenovo (P930). */ SYMBIAN7( Manufacturer.SYMBIAN,OperatingSystem.SYMBIAN, 10, "Symbian OS 7.x", new String[] { "SymbianOS/7"}, null, DeviceType.MOBILE, null ), /** * Symbian OS 6.x versions. */ SYMBIAN6( Manufacturer.SYMBIAN,OperatingSystem.SYMBIAN, 5, "Symbian OS 6.x", new String[] { "SymbianOS/6"}, null, DeviceType.MOBILE, null ), /** * Nokia's Series 40 operating system. Series 60 (S60) uses the Symbian OS. */ SERIES40 ( Manufacturer.NOKIA,null, 1, "Series 40", new String[] { "Nokia6300"}, null, DeviceType.MOBILE, null ), SONY_ERICSSON ( Manufacturer.SONY_ERICSSON, null, 1, "Sony Ericsson", new String[] { "SonyEricsson"}, null, DeviceType.MOBILE, null ), // after symbian, some SE phones use symbian SUN_OS( Manufacturer.SUN, null, 1, "SunOS", new String[] { "SunOS" } , null, DeviceType.COMPUTER, null ), PSP( Manufacturer.SONY, null, 1, "Sony Playstation", new String[] { "Playstation" }, null, DeviceType.GAME_CONSOLE, null ), /** * Nintendo Wii game console. */ WII( Manufacturer.NINTENDO,null, 1, "Nintendo Wii", new String[] { "Wii" }, null, DeviceType.GAME_CONSOLE, null ), /** * BlackBerryOS. The BlackBerryOS exists in different version. How relevant those versions are, is not clear. */ BLACKBERRY( Manufacturer.BLACKBERRY,null, 1, "BlackBerryOS", new String[] { "BlackBerry" }, null, DeviceType.MOBILE, null ), BLACKBERRY7( Manufacturer.BLACKBERRY,OperatingSystem.BLACKBERRY, 7, "BlackBerry 7", new String[] { "Version/7" }, null, DeviceType.MOBILE, null ), BLACKBERRY6( Manufacturer.BLACKBERRY,OperatingSystem.BLACKBERRY, 6, "BlackBerry 6", new String[] { "Version/6" }, null, DeviceType.MOBILE, null ), BLACKBERRY_TABLET(Manufacturer.BLACKBERRY,null, 100, "BlackBerry Tablet OS", new String[] { "RIM Tablet OS" }, null, DeviceType.TABLET, null ), ROKU( Manufacturer.ROKU,null, 1, "Roku OS", new String[] { "Roku" }, null, DeviceType.DMR, null ), /** * Proxy server that hides the original user-agent. * ggpht.com = Gmail proxy server */ PROXY( Manufacturer.OTHER,null, 10, "Proxy", new String[] { "ggpht.com" }, null, DeviceType.UNKNOWN, null ), UNKNOWN_MOBILE( Manufacturer.OTHER,null, 3, "Unknown mobile", new String[] {"Mobile"}, null, DeviceType.MOBILE, null ), UNKNOWN_TABLET( Manufacturer.OTHER,null, 4, "Unknown tablet", new String[] {"Tablet"}, null, DeviceType.TABLET, null ), UNKNOWN( Manufacturer.OTHER,null, 1, "Unknown", new String[0], null, DeviceType.UNKNOWN, null ); private final short id; private final String name; private final String[] aliases; private final String[] excludeList; // don't match when these values are in the agent-string private final Manufacturer manufacturer; private final DeviceType deviceType; private final OperatingSystem parent; private List<OperatingSystem> children; private Pattern versionRegEx; private static List<OperatingSystem> topLevelOperatingSystems; private OperatingSystem(Manufacturer manufacturer, OperatingSystem parent, int versionId, String name, String[] aliases, String[] exclude, DeviceType deviceType, String versionRegexString) { this.manufacturer = manufacturer; this.parent = parent; this.children = new ArrayList<OperatingSystem>(); // combine manufacturer and version id to one unique id. this.id = (short) ((manufacturer.getId() << 8) + (byte) versionId); this.name = name; if (aliases == null) { this.aliases = aliases; } else { this.aliases = new String[aliases.length]; for (int i = 0; i < aliases.length; i++) { this.aliases[i] = aliases[i].toLowerCase(); } } if (exclude == null) { this.excludeList = exclude; } else { this.excludeList = new String[exclude.length]; for (int i = 0; i < exclude.length; i++) { this.excludeList[i] = exclude[i].toLowerCase(); } } this.deviceType = deviceType; if (versionRegexString != null) { // not implemented yet this.versionRegEx = Pattern.compile(versionRegexString); } if (this.parent == null) addTopLevelOperatingSystem(this); else this.parent.children.add(this); } // create collection of top level operating systems during initialization private static void addTopLevelOperatingSystem(OperatingSystem os) { if(topLevelOperatingSystems == null) topLevelOperatingSystems = new ArrayList<OperatingSystem>(); topLevelOperatingSystems.add(os); } public short getId() { return id; } public String getName() { return name; } /* * Shortcut to check of an operating system is a mobile device. * Left in here for backwards compatibility. Use .getDeciceType() instead. */ @Deprecated public boolean isMobileDevice() { return deviceType.equals(DeviceType.MOBILE); } public DeviceType getDeviceType() { return deviceType; } /* * Gets the top level grouping operating system */ public OperatingSystem getGroup() { if (this.parent != null) { return parent.getGroup(); } return this; } /** * Returns the manufacturer of the operating system * @return the manufacturer */ public Manufacturer getManufacturer() { return manufacturer; } /** * Checks if the given user-agent string matches to the operating system. * Only checks for one specific operating system. * @param agentString * @return boolean */ public boolean isInUserAgentString(String agentString) { for (String alias : aliases) { if (agentString != null && agentString.toLowerCase().indexOf(alias) != -1) return true; } return false; } /** * Checks if the given user-agent does not contain one of the tokens which should not match. * In most cases there are no excluding tokens, so the impact should be small. * @param agentString * @return */ private boolean containsExcludeToken(String agentString) { if (excludeList != null) { for (String exclude : excludeList) { if (agentString != null && agentString.toLowerCase().indexOf(exclude) != -1) return true; } } return false; } private OperatingSystem checkUserAgent(String agentString) { if (this.isInUserAgentString(agentString)) { if (this.children.size() > 0) { for (OperatingSystem childOperatingSystem : this.children) { OperatingSystem match = childOperatingSystem.checkUserAgent(agentString); if (match != null) { return match; } } } // if children didn't match we continue checking the current to prevent false positives if (!this.containsExcludeToken(agentString)) { return this; } } return null; } /** * Parses user agent string and returns the best match. * Returns OperatingSystem.UNKNOWN if there is no match. * @param agentString * @return OperatingSystem */ public static OperatingSystem parseUserAgentString(String agentString) { return parseUserAgentString(agentString, topLevelOperatingSystems); } /** * Parses the user agent string and returns the best match for the given operating systems. * Returns OperatingSystem.UNKNOWN if there is no match. * Be aware that if the order of the provided operating systems is incorrect or the set is too limited it can lead to false matches! * @param agentString * @return OperatingSystem */ public static OperatingSystem parseUserAgentString(String agentString, List<OperatingSystem> operatingSystems) { for (OperatingSystem operatingSystem : operatingSystems) { OperatingSystem match = operatingSystem.checkUserAgent(agentString); if (match != null) { return match; // either current operatingSystem or a child object } } return OperatingSystem.UNKNOWN; } public static OperatingSystem valueOf(short id) { for (OperatingSystem operatingSystem : OperatingSystem.values()) { if (operatingSystem.getId() == id) return operatingSystem; } // same behavior as standard valueOf(string) method throw new IllegalArgumentException( "No enum const for id " + id); } }
package eu.proteus.producer.model; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public abstract class SensorMeasurement extends Measurement{ protected int coilId; protected int varName; protected double value; protected byte type; protected double x; public SensorMeasurement() { if( this.getClass() == SensorMeasurement2D.class) this.type = 0x1; else this.type = 0x0; } public String toJson() { ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(this); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } public int getCoilId() { return coilId; } public void setCoilId(int coilId) { this.coilId = coilId; } public int getVarName() { return varName; } public void setVarName(int varName) { this.varName = varName; } public double getValue() { return value; } public double getX() { return x; } public void setX(double x) { this.x = x; } public void setValue(double value) { this.value = value; } public byte getType() { return type; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + coilId; result = prime * result + type; long temp; temp = Double.doubleToLongBits(value); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + varName; temp = Double.doubleToLongBits(x); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SensorMeasurement other = (SensorMeasurement) obj; if (coilId != other.coilId) return false; if (type != other.type) return false; if (Double.doubleToLongBits(value) != Double.doubleToLongBits(other.value)) return false; if (varName != other.varName) return false; if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x)) return false; return true; } @Override public String toString() { return "Row [coilId=" + coilId + ", varName=" + varName + ", value=" + value + ", type=" + type + ", x=" + x + "]"; } }
package com.jivesoftware.os.miru.stream.plugins.filter; import com.google.common.base.Optional; import com.google.common.collect.Maps; import com.jivesoftware.os.filer.io.api.StackBuffer; import com.jivesoftware.os.miru.api.MiruHost; import com.jivesoftware.os.miru.api.MiruQueryServiceException; import com.jivesoftware.os.miru.api.activity.MiruPartitionId; import com.jivesoftware.os.miru.api.base.MiruStreamId; import com.jivesoftware.os.miru.api.query.filter.MiruAuthzExpression; import com.jivesoftware.os.miru.plugin.backfill.MiruJustInTimeBackfillerizer; import com.jivesoftware.os.miru.plugin.bitmap.MiruBitmaps; import com.jivesoftware.os.miru.plugin.bitmap.MiruBitmapsDebug; import com.jivesoftware.os.miru.plugin.context.MiruRequestContext; import com.jivesoftware.os.miru.plugin.index.BitmapAndLastId; import com.jivesoftware.os.miru.plugin.solution.MiruAggregateUtil; import com.jivesoftware.os.miru.plugin.solution.MiruPartitionResponse; import com.jivesoftware.os.miru.plugin.solution.MiruRemotePartition; import com.jivesoftware.os.miru.plugin.solution.MiruRequest; import com.jivesoftware.os.miru.plugin.solution.MiruRequestHandle; import com.jivesoftware.os.miru.plugin.solution.MiruSolutionLog; import com.jivesoftware.os.miru.plugin.solution.MiruSolutionLogLevel; import com.jivesoftware.os.miru.plugin.solution.MiruTimeRange; import com.jivesoftware.os.miru.plugin.solution.Question; import com.jivesoftware.os.mlogger.core.MetricLogger; import com.jivesoftware.os.mlogger.core.MetricLoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; /** * @author jonathan */ public class AggregateCountsCustomQuestion implements Question<AggregateCountsQuery, AggregateCountsAnswer, AggregateCountsReport> { private static final MetricLogger LOG = MetricLoggerFactory.getLogger(); private final AggregateCounts aggregateCounts; private final MiruJustInTimeBackfillerizer backfillerizer; private final MiruRequest<AggregateCountsQuery> request; private final MiruRemotePartition<AggregateCountsQuery, AggregateCountsAnswer, AggregateCountsReport> remotePartition; private final Set<MiruStreamId> verboseStreamIds; private final boolean verboseAllStreamIds; private final MiruBitmapsDebug bitmapsDebug = new MiruBitmapsDebug(); private final MiruAggregateUtil aggregateUtil = new MiruAggregateUtil(); public AggregateCountsCustomQuestion(AggregateCounts aggregateCounts, MiruJustInTimeBackfillerizer backfillerizer, MiruRequest<AggregateCountsQuery> request, MiruRemotePartition<AggregateCountsQuery, AggregateCountsAnswer, AggregateCountsReport> remotePartition, Set<MiruStreamId> verboseStreamIds, boolean verboseAllStreamIds) { this.aggregateCounts = aggregateCounts; this.backfillerizer = backfillerizer; this.request = request; this.remotePartition = remotePartition; this.verboseStreamIds = verboseStreamIds; this.verboseAllStreamIds = verboseAllStreamIds; } @Override public <BM extends IBM, IBM> MiruPartitionResponse<AggregateCountsAnswer> askLocal(MiruRequestHandle<BM, IBM, ?> handle, Optional<AggregateCountsReport> report) throws Exception { StackBuffer stackBuffer = new StackBuffer(); MiruSolutionLog solutionLog = new MiruSolutionLog(request.logLevel); MiruRequestContext<BM, IBM, ?> context = handle.getRequestContext(); MiruBitmaps<BM, IBM> bitmaps = handle.getBitmaps(); MiruStreamId streamId = request.query.streamId; boolean verbose = verboseAllStreamIds || verboseStreamIds != null && streamId != null && !MiruStreamId.NULL.equals(streamId) && verboseStreamIds.contains(streamId); MiruTimeRange answerTimeRange = request.query.answerTimeRange; if (!context.getTimeIndex().intersects(answerTimeRange)) { solutionLog.log(MiruSolutionLogLevel.WARN, "No time index intersection. Partition {}: {} doesn't intersect with {}", handle.getCoord().partitionId, context.getTimeIndex(), answerTimeRange); return new MiruPartitionResponse<>(aggregateCounts.getAggregateCounts("aggregateCountsCustom", solutionLog, bitmaps, context, request, handle.getCoord(), report, bitmaps.create(), Optional.absent(), verbose), solutionLog.asList()); } List<IBM> ands = new ArrayList<>(); int lastId = context.getActivityIndex().lastId(stackBuffer); BM filtered = aggregateUtil.filter("aggregateCountsCustom", bitmaps, context, request.query.streamFilter, solutionLog, null, lastId, -1, -1, stackBuffer); ands.add(filtered); ands.add(bitmaps.buildIndexMask(lastId, context.getRemovalIndex(), null, stackBuffer)); if (streamId != null && !MiruStreamId.NULL.equals(streamId) && (request.query.includeUnreadState || request.query.unreadOnly)) { if (request.query.suppressUnreadFilter != null && handle.canBackfill()) { backfillerizer.backfillUnread(request.name, bitmaps, context, solutionLog, request.tenantId, handle.getCoord().partitionId, streamId, request.query.suppressUnreadFilter); } if (request.query.unreadOnly) { BitmapAndLastId<BM> container = new BitmapAndLastId<>(); context.getUnreadTrackingIndex().getUnread(streamId).getIndex(container, stackBuffer); if (container.isSet()) { ands.add(container.getBitmap()); } else { // Short-circuit if the user doesn't have any unread LOG.debug("No user unread"); return new MiruPartitionResponse<>( aggregateCounts.getAggregateCounts("aggregateCountsCustom", solutionLog, bitmaps, context, request, handle.getCoord(), report, bitmaps.create(), Optional.of(bitmaps.create()), verbose), solutionLog.asList()); } } } if (!MiruAuthzExpression.NOT_PROVIDED.equals(request.authzExpression)) { ands.add(context.getAuthzIndex().getCompositeAuthz(request.authzExpression, stackBuffer)); } if (!MiruTimeRange.ALL_TIME.equals(request.query.answerTimeRange)) { ands.add(bitmaps.buildTimeRangeMask(context.getTimeIndex(), answerTimeRange.smallestTimestamp, answerTimeRange.largestTimestamp, stackBuffer)); } bitmapsDebug.debug(solutionLog, bitmaps, "ands", ands); BM answer = bitmaps.and(ands); LOG.debug("Aggregate Counts answer: {}", answer); BM counter = null; if (!MiruTimeRange.ALL_TIME.equals(request.query.countTimeRange)) { counter = bitmaps.and(Arrays.asList(answer, bitmaps.buildTimeRangeMask( context.getTimeIndex(), request.query.countTimeRange.smallestTimestamp, request.query.countTimeRange.largestTimestamp, stackBuffer))); } return new MiruPartitionResponse<>( aggregateCounts.getAggregateCounts("aggregateCountsCustom", solutionLog, bitmaps, context, request, handle.getCoord(), report, answer, Optional.fromNullable(counter), verbose), solutionLog.asList()); } @Override public MiruPartitionResponse<AggregateCountsAnswer> askRemote(MiruHost host, MiruPartitionId partitionId, Optional<AggregateCountsReport> report) throws MiruQueryServiceException { return remotePartition.askRemote(host, partitionId, request, report); } @Override public Optional<AggregateCountsReport> createReport(Optional<AggregateCountsAnswer> answer) { Optional<AggregateCountsReport> report = Optional.absent(); if (answer.isPresent()) { AggregateCountsAnswer currentAnswer = answer.get(); Map<String, AggregateCountsReportConstraint> constraintReport = Maps.newHashMapWithExpectedSize(currentAnswer.constraints.size()); for (Map.Entry<String, AggregateCountsAnswerConstraint> entry : currentAnswer.constraints.entrySet()) { AggregateCountsAnswerConstraint value = entry.getValue(); constraintReport.put(entry.getKey(), new AggregateCountsReportConstraint(value.aggregateTerms, value.uncollectedTerms, value.skippedDistincts, value.collectedDistincts)); } report = Optional.of(new AggregateCountsReport(constraintReport)); } return report; } }
package fr.onagui.alignment.container; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; import org.eclipse.rdf4j.common.iteration.Iterations; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.model.vocabulary.SKOS; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.repository.RepositoryException; import org.eclipse.rdf4j.repository.RepositoryResult; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.RDFHandlerException; import org.eclipse.rdf4j.rio.RDFParseException; import org.eclipse.rdf4j.rio.helpers.AbstractRDFHandler; import org.eclipse.rdf4j.sail.memory.MemoryStore; import fr.onagui.alignment.OntoContainer; import fr.onagui.alignment.OntoVisitor; /** * @author Laurent Mazuel */ public class SKOSContainer implements OntoContainer<Resource> { private Repository triplestore = null; private ValueFactory factory = null; private URI onto_uri = null; private static Map<IRI, boolean[]> propertyForConcepts = null; static { /* First value is "subject is concept", second "object is concept" */ propertyForConcepts = new HashMap<IRI, boolean[]>(); propertyForConcepts.put(SKOS.TOP_CONCEPT_OF, new boolean[] {true, false}); propertyForConcepts.put(SKOS.HAS_TOP_CONCEPT, new boolean[] {false, true}); propertyForConcepts.put(SKOS.BROADER, new boolean[] {true, true}); propertyForConcepts.put(SKOS.BROADER_TRANSITIVE, new boolean[] {true, true}); propertyForConcepts.put(SKOS.NARROWER, new boolean[] {true, true}); propertyForConcepts.put(SKOS.NARROWER_TRANSITIVE, new boolean[] {true, true}); } private SortedSet<String> languages = null; // Lazy initialization private Set<Resource> conceptSchemes = null; // Lazy initialization private Map<Resource, Resource> topConceptOfCache = null; // Cache public SKOSContainer(File physicalPath) throws RepositoryException, RDFParseException, IOException { triplestore = new SailRepository(new MemoryStore()); triplestore.initialize(); factory = triplestore.getValueFactory(); RepositoryConnection connect = triplestore.getConnection(); // Try RDF/XML, fallback to N3 and fail if it's not enough try { connect.add(physicalPath, null, RDFFormat.RDFXML); } catch (RDFParseException e) { connect.add(physicalPath, null, RDFFormat.N3); } connect.close(); onto_uri = physicalPath.toURI(); // Preload getAllLanguageInLabels(); topConceptOfCache = new HashMap<Resource, Resource>(); for(Resource scheme: getConceptSchemes()) { for(Resource topConcept: getTopConcepts(scheme)) { topConceptOfCache.put(topConcept, scheme); } } } private class SkosConceptHandler extends AbstractRDFHandler { private OntoVisitor<Resource> myvisitor; public SkosConceptHandler(OntoVisitor<Resource> visitor) { myvisitor = visitor; } @Override public void handleStatement(Statement stmt) throws RDFHandlerException { IRI predicate = stmt.getPredicate(); if(predicate.equals(RDF.TYPE) || propertyForConcepts.get(predicate)[0]) { // Subject is concept myvisitor.visit(stmt.getSubject()); } else if (propertyForConcepts.get(predicate)[1]) { // Object is concept myvisitor.visit((Resource) stmt.getObject()); } } } @Override public void accept(OntoVisitor<Resource> visitor) { SkosConceptHandler myhandler = new SkosConceptHandler(visitor); RepositoryConnection connect = null; try { connect = triplestore.getConnection(); connect.exportStatements(null, RDF.TYPE, SKOS.CONCEPT, true, myhandler); for(IRI property: propertyForConcepts.keySet()) { connect.exportStatements(null, property, null, true, myhandler); } } catch (RepositoryException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (RDFHandlerException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { if(connect != null) { try { connect.close(); } catch (RepositoryException e) {} } } } @Override public String getFormalism() { return "skos"; } private Set<Resource> getAllFromType(IRI type) { Set<Resource> result = new HashSet<Resource>(); try { RepositoryConnection connect = triplestore.getConnection(); RepositoryResult<Statement> stmts = connect.getStatements(null, RDF.TYPE, type, true); List<Statement> stmts_list = Iterations.asList(stmts); for (Statement s : stmts_list) { result.add(s.getSubject()); } connect.close(); } catch (RepositoryException e) { e.printStackTrace(); } return result; } private class SkosConceptCollector implements OntoVisitor<Resource>{ private Set<Resource> result = new HashSet<Resource>(); public Set<Resource> getResult() { return result; } @Override public void visit(Resource concept) { result.add(concept); } } @Override public Set<Resource> getAllConcepts() { SkosConceptCollector collector = new SkosConceptCollector(); accept(collector); return collector.getResult(); } @Override public boolean isIndividual(Resource cpt) { return false; } @Override public Set<Resource> getChildren(Resource cpt) { if(cpt.equals(getRoot())) { return getConceptSchemes(); } if(conceptSchemes.contains(cpt)) { return getTopConcepts(cpt); } /* "usual" concept */ Set<Resource> result = new HashSet<Resource>(); try { RepositoryConnection connect = triplestore.getConnection(); for(Statement res : getStatementWhereSubject(connect, cpt)) { if(res.getPredicate().equals(SKOS.NARROWER) || res.getPredicate().equals(SKOS.NARROWER_TRANSITIVE)) { result.add((Resource) res.getObject()); } } for(Statement res : getStatementWhereObject(connect, cpt)) { if(res.getPredicate().equals(SKOS.BROADER) || res.getPredicate().equals(SKOS.BROADER_TRANSITIVE)) { result.add(res.getSubject()); } } connect.close(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } @Override public Set<Resource> getParents(Resource cpt) { if(cpt.equals(getRoot())) { return new HashSet<Resource>(); } if(conceptSchemes.contains(cpt)) { return Collections.singleton(getRoot()); } if(topConceptOfCache.containsKey(cpt)) { return Collections.singleton(topConceptOfCache.get(cpt)); } /* "usual" concept */ Set<Resource> result = new HashSet<Resource>(); try { RepositoryConnection connect = triplestore.getConnection(); for(Statement res : getStatementWhereSubject(connect, cpt)) { if(res.getPredicate().equals(SKOS.BROADER) || res.getPredicate().equals(SKOS.BROADER_TRANSITIVE)) { result.add((Resource) res.getObject()); } } for(Statement res : getStatementWhereObject(connect, cpt)) { if(res.getPredicate().equals(SKOS.NARROWER) || res.getPredicate().equals(SKOS.NARROWER_TRANSITIVE)) { result.add(res.getSubject()); } } connect.close(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } public Set<Resource> getTopConcepts(Resource scheme) { Set<Resource> result = new HashSet<Resource>(); RepositoryResult<Statement> stmts = null; RepositoryConnection connect = null; try { connect = triplestore.getConnection(); // Has top concept stmts = connect.getStatements(scheme, SKOS.HAS_TOP_CONCEPT, null, true); for (Statement s : Iterations.asList(stmts)) { result.add((Resource) s.getObject()); } // top concept of stmts = connect.getStatements(null, SKOS.TOP_CONCEPT_OF, scheme, true); for (Statement s : Iterations.asList(stmts)) { result.add(s.getSubject()); } connect.close(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } private List<Statement> getStatementWhereSubject(RepositoryConnection connect, Resource res) { try { RepositoryResult<Statement> stmts = connect.getStatements(res, null, null, true); return Iterations.asList(stmts); } catch (RepositoryException e) { e.printStackTrace(); } return new Vector<Statement>(); } private List<Statement> getStatementWhereObject(RepositoryConnection connect, Resource res) { try { RepositoryResult<Statement> stmts = connect.getStatements(null, null, res, true); return Iterations.asList(stmts); } catch (RepositoryException e) { e.printStackTrace(); } return new Vector<Statement>(); } private Set<Resource> getSubjectsWhereProp(RepositoryConnection connect, IRI prop) { Set<Resource> result = new HashSet<Resource>(); // Has top concept try { RepositoryResult<Statement> stmts = connect.getStatements(null, prop, null, true); List<Statement> stmts_list = Iterations.asList(stmts); for (Statement s : stmts_list) { result.add(s.getSubject()); } return result; } catch (RepositoryException e) { e.printStackTrace(); } return result; } private Set<Resource> getResourceObjectWhereProp(RepositoryConnection connect, IRI prop) { Set<Resource> result = new HashSet<Resource>(); // Has top concept try { RepositoryResult<Statement> stmts = connect.getStatements(null, prop, null, true); List<Statement> stmts_list = Iterations.asList(stmts); for (Statement s : stmts_list) { try { result.add((Resource) s.getObject()); } catch (ClassCastException e) { // Nothing, is a literal } } return result; } catch (RepositoryException e) { e.printStackTrace(); } return result; } @Override public Set<Resource> getAllProperties() { return Collections.emptySet(); } @Override public URI getURI(Resource cpt) { try { return new URI(((IRI) cpt).toString()); } catch (URISyntaxException e) { e.printStackTrace(); throw new IllegalArgumentException("Strange resource..."); } } public Set<String> getLabels(Resource cpt, String prop) { return getLabels(cpt, factory.createIRI(prop)); } private Set<String> getLabels(Resource cpt, IRI prop) { if (cpt == null) throw new IllegalArgumentException("cpt cannot be null"); Set<String> result = new HashSet<String>(); // "prefLabel" try { RepositoryConnection connect = triplestore.getConnection(); String queryString = "PREFIX skos:<http://www.w3.org/2004/02/skos/core +"PREFIX skosxl:<http://www.w3.org/2008/05/skos-xl + "INSERT { ?x skos:prefLabel ?y} " + "WHERE {?x skosxl:prefLabel/skosxl:literalForm ?y}"; //TupleQuery tupleQuery = connect.prepareTupleQuery(QueryLanguage.SPARQL,queryString); connect.prepareUpdate(QueryLanguage.SPARQL, queryString); RepositoryResult<Statement> stmts = connect.getStatements(cpt, prop, null, true); List<Statement> stmts_list = Iterations.asList(stmts); for (Statement s : stmts_list) { Literal literal = (Literal) s.getObject(); result.add(literal.getLabel()); } connect.close(); } catch (RepositoryException e) { e.printStackTrace(); } return result; } private Set<String> getLabels(Resource cpt, String lang, IRI prop) { if (cpt == null || lang == null) throw new IllegalArgumentException( "cpt or lang cannot be null: cpt=" + cpt + " lang=" + lang); Set<String> result = new HashSet<String>(); // "prefLabel" try { RepositoryConnection connect = triplestore.getConnection(); String queryString = "PREFIX skos:<http://www.w3.org/2004/02/skos/core +"PREFIX skosxl:<http://www.w3.org/2008/05/skos-xl + "INSERT { ?x skos:prefLabel ?y} " + "WHERE {?x skosxl:prefLabel/skosxl:literalForm ?y}"; //TupleQuery tupleQuery = connect.prepareTupleQuery(QueryLanguage.SPARQL,queryString); connect.prepareUpdate(QueryLanguage.SPARQL, queryString); RepositoryResult<Statement> stmts = connect.getStatements(cpt, prop, null, true); List<Statement> stmts_list = Iterations.asList(stmts); for (Statement s : stmts_list) { Literal literal = (Literal) s.getObject(); Optional<String> language = literal.getLanguage(); if (lang.equals(language.orElse(""))) result.add(literal.getLabel()); } connect.close(); } catch (RepositoryException e) { e.printStackTrace(); } return result; } public Set<String> getAnnotations(Resource cpt) { if (cpt == null) throw new IllegalArgumentException("cpt cannot be null"); Set<String> result = new HashSet<String>(); try { RepositoryConnection connect = triplestore.getConnection(); RepositoryResult<Statement> stmts = connect.getStatements(cpt, null, null, true); List<Statement> stmts_list = Iterations.asList(stmts); for (Statement s : stmts_list) { IRI predicate = s.getPredicate(); Value object = s.getObject(); if(object instanceof Literal) { result.add(predicate.toString()); } } connect.close(); } catch (RepositoryException e) { e.printStackTrace(); } return result; } @Override public Set<String> getPrefLabels(Resource cpt) { return getLabels(cpt, SKOS.PREF_LABEL); } @Override public Set<String> getPrefLabels(Resource cpt, String lang) { return getLabels(cpt, lang, SKOS.PREF_LABEL); } @Override public Set<String> getAltLabels(Resource cpt) { return getLabels(cpt, SKOS.ALT_LABEL); } @Override public Set<String> getAltLabels(Resource cpt, String lang) { return getLabels(cpt, lang, SKOS.ALT_LABEL); } @Override public SortedSet<String> getAllLanguageInLabels() { if (this.languages == null) { this.languages = new TreeSet<String>(); Collection<IRI> props = Arrays.asList( SKOS.PREF_LABEL, SKOS.ALT_LABEL); for (IRI prop : props) { try { RepositoryConnection connect = triplestore.getConnection(); RepositoryResult<Statement> stmts = connect.getStatements(null, prop, null, true); List<Statement> stmts_list = Iterations.asList(stmts); for (Statement s : stmts_list) { Literal literal = (Literal) s.getObject(); if (literal.getLanguage().isPresent()) languages.add(literal.getLanguage().get()); } connect.close(); } catch (RepositoryException e) { e.printStackTrace(); } } } return languages; } @Override public Resource getConceptFromURI(URI uri) { return factory.createIRI(uri.toString()); } @Override public URI getURI() { return onto_uri; } @Override public Resource getRoot() { // Create a fake root with OWL Thing uri. Better than nothing... (joke). return factory.createIRI("http://www.w3.org/2002/07/owl#Thing"); } public Set<Resource> getConceptSchemes() { if(this.conceptSchemes == null) { try { RepositoryConnection connect = triplestore.getConnection(); this.conceptSchemes = getAllFromType(SKOS.CONCEPT_SCHEME); this.conceptSchemes.addAll(getSubjectsWhereProp(connect, SKOS.HAS_TOP_CONCEPT)); this.conceptSchemes.addAll(getResourceObjectWhereProp(connect, SKOS.TOP_CONCEPT_OF)); connect.close(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return this.conceptSchemes; } }
package gov.nasa.jpl.mbee.ems.sync; import gov.nasa.jpl.mbee.ems.ExportUtility; import gov.nasa.jpl.mbee.ems.ImportException; import gov.nasa.jpl.mbee.ems.ImportUtility; import gov.nasa.jpl.mbee.ems.ServerException; import gov.nasa.jpl.mbee.ems.validation.ModelValidator; import gov.nasa.jpl.mbee.ems.validation.ViewValidator; import gov.nasa.jpl.mbee.ems.validation.actions.DetailDiff; import gov.nasa.jpl.mbee.ems.validation.actions.ImportHierarchy; import gov.nasa.jpl.mbee.generator.DocumentGenerator; import gov.nasa.jpl.mbee.lib.Utils; import gov.nasa.jpl.mbee.model.Document; import gov.nasa.jpl.mbee.viewedit.ViewHierarchyVisitor; import gov.nasa.jpl.mgss.mbee.docgen.validation.ValidationRule; import gov.nasa.jpl.mgss.mbee.docgen.validation.ValidationRuleViolation; import gov.nasa.jpl.mgss.mbee.docgen.validation.ValidationSuite; import gov.nasa.jpl.mgss.mbee.docgen.validation.ViolationSeverity; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import com.nomagic.magicdraw.core.Application; import com.nomagic.magicdraw.core.GUILog; import com.nomagic.magicdraw.core.Project; import com.nomagic.magicdraw.core.ProjectUtilities; import com.nomagic.magicdraw.openapi.uml.ModelElementsManager; import com.nomagic.magicdraw.openapi.uml.SessionManager; import com.nomagic.magicdraw.teamwork.application.TeamworkUtils; import com.nomagic.task.ProgressStatus; import com.nomagic.task.RunnableWithProgress; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Constraint; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Property; public class ManualSyncRunner implements RunnableWithProgress { private boolean commit; private GUILog gl = Application.getInstance().getGUILog(); private Logger log = Logger.getLogger(ManualSyncRunner.class); private boolean isFromTeamwork = false; private boolean loggedIn = true; private boolean failure = false; private boolean skipUpdate = false; private ValidationSuite suite = new ValidationSuite("Updated Elements/Failed Updates"); private ValidationRule updated = new ValidationRule("updated", "updated", ViolationSeverity.INFO); private ValidationRule cannotUpdate = new ValidationRule("cannotUpdate", "cannotUpdate", ViolationSeverity.ERROR); private ValidationRule cannotRemove = new ValidationRule("cannotDelete", "cannotDelete", ViolationSeverity.WARNING); private ValidationRule cannotCreate = new ValidationRule("cannotCreate", "cannotCreate", ViolationSeverity.ERROR); public ManualSyncRunner(boolean commit, boolean skipUpdate) { this.commit = commit; this.skipUpdate = skipUpdate; } public ManualSyncRunner(boolean commit) { this.commit = commit; } private void tryToLock(Project project) { if (!ProjectUtilities.isFromTeamworkServer(project.getPrimaryProject())) return; for (Element e: project.getModel().getOwnedElement()) { if (ProjectUtilities.isElementInAttachedProject(e)) continue; TeamworkUtils.lockElement(project, e, true); } } private boolean tryToLock(Project project, Element e) { return Utils.tryToLock(project, e, isFromTeamwork); } @SuppressWarnings("unchecked") @Override public void run(ProgressStatus ps) { if (!skipUpdate) Utils.guilog("[INFO] Getting changes from MMS..."); suite.addValidationRule(updated); suite.addValidationRule(cannotUpdate); suite.addValidationRule(cannotRemove); suite.addValidationRule(cannotCreate); Project project = Application.getInstance().getProject(); if (ProjectUtilities.isFromTeamworkServer(project.getPrimaryProject())) { isFromTeamwork = true; if (TeamworkUtils.getLoggedUserName() == null) { loggedIn = false; failure = true; Utils.guilog("[ERROR] You need to be logged in to teamwork first."); return; } } AutoSyncCommitListener listener = AutoSyncProjectListener.getCommitListener(Application.getInstance().getProject()); if (listener == null) { Utils.guilog("[ERROR] Unexpected error happened, cannot get commit listener."); failure = true; return; //some error here } listener.disable(); Map<String, Set<String>> jms = AutoSyncProjectListener.getJMSChanges(Application.getInstance().getProject()); listener.enable(); if (jms == null) { failure = true; return; } Map<String, Element> localAdded = listener.getAddedElements(); Map<String, Element> localDeleted = listener.getDeletedElements(); Map<String, Element> localChanged = listener.getChangedElements(); //account for possible teamwork updates JSONObject previousUpdates = AutoSyncProjectListener.getUpdatesOrFailed(Application.getInstance().getProject(), "update"); if (previousUpdates != null) { for (String added: (List<String>)previousUpdates.get("added")) { if (localAdded.containsKey(added) || localChanged.containsKey(added)) continue; Element e = ExportUtility.getElementFromID(added); if (e != null) localAdded.put(added, e); } for (String updated: (List<String>)previousUpdates.get("changed")) { if (!localChanged.containsKey(updated)) { Element e = ExportUtility.getElementFromID(updated); if (e != null) localChanged.put(updated, e); } localAdded.remove(updated); } for (String deleted: (List<String>)previousUpdates.get("deleted")) { if (ExportUtility.getElementFromID(deleted) != null) { if (localDeleted.containsKey(deleted)) localDeleted.remove(deleted); continue; //not deleted? } if (!localDeleted.containsKey(deleted)) { localDeleted.put(deleted, null); } localAdded.remove(deleted); localChanged.remove(deleted); } } Set<String> webChanged = jms.get("changed"); Set<String> webAdded = jms.get("added"); Set<String> webDeleted = jms.get("deleted"); Set<String> toGet = new HashSet<String>(webChanged); toGet.addAll(webAdded); Set<String> cannotAdd = new HashSet<String>(); Set<String> cannotChange = new HashSet<String>(); Set<String> cannotDelete = new HashSet<String>(); if (!toGet.isEmpty()) { //TeamworkUtils.lockElement(project, project.getModel(), true); //tryToLock(project); JSONObject getJson = new JSONObject(); JSONArray getElements = new JSONArray(); getJson.put("elements", getElements); for (String e: toGet) { JSONObject el = new JSONObject(); el.put("sysmlid", e); getElements.add(el); } String url = ExportUtility.getUrlWithWorkspace(); url += "/elements"; Utils.guilog("[INFO] Getting " + getElements.size() + " elements from MMS."); String response = null; try { response = ExportUtility.getWithBody(url, getJson.toJSONString()); } catch (ServerException ex) { Utils.guilog("[ERROR] Get elements failed."); } if (response == null) return; //should repopulate error block? Map<String, JSONObject> webElements = new HashMap<String, JSONObject>(); JSONObject webObject = (JSONObject)JSONValue.parse(response); JSONArray webArray = (JSONArray)webObject.get("elements"); for (Object o: webArray) { String webId = (String)((JSONObject)o).get("sysmlid"); webElements.put(webId, (JSONObject)o); } //if (webElements.size() != toGet.size()) // return; //?? //calculate order to create web added elements List<JSONObject> webAddedObjects = new ArrayList<JSONObject>(); for (String webAdd: webAdded) { if (webElements.containsKey(webAdd)) webAddedObjects.add(webElements.get(webAdd)); } //calculate potential conflicted set and clean web updated set Set<String> localChangedIds = new HashSet<String>(localChanged.keySet()); localChangedIds.retainAll(webChanged); JSONArray webConflictedObjects = new JSONArray(); Set<Element> localConflictedElements = new HashSet<Element>(); if (!localChangedIds.isEmpty()) { for (String conflictId: localChangedIds) { if (webElements.containsKey(conflictId)) { webConflictedObjects.add(webElements.get(conflictId)); localConflictedElements.add(localChanged.get(conflictId)); } } } //find web changed that are not conflicted List<JSONObject> webChangedObjects = new ArrayList<JSONObject>(); for (String webUpdate: webChanged) { if (localChangedIds.contains(webUpdate)) continue; if (webElements.containsKey(webUpdate)) webChangedObjects.add(webElements.get(webUpdate)); } Utils.guilog("[INFO] Applying changes..."); SessionManager sm = SessionManager.getInstance(); sm.createSession("mms delayed sync change"); try { Map<String, List<JSONObject>> toCreate = ImportUtility.getCreationOrder(webAddedObjects); List<JSONObject> webAddedSorted = toCreate.get("create"); List<JSONObject> fails = toCreate.get("fail"); List<Map<String, Object>> toChange = new ArrayList<Map<String, Object>>(); //take care of web added if (webAddedSorted != null) { ImportUtility.outputError = false; for (Object element : webAddedSorted) { try { ImportUtility.createElement((JSONObject) element, false); } catch (ImportException ex) { } } ImportUtility.outputError = true; for (Object element : webAddedSorted) { try { Element newe = ImportUtility.createElement((JSONObject) element, true); //Utils.guilog("[SYNC ADD] " + newe.getHumanName() + " created."); updated.addViolation(new ValidationRuleViolation(newe, "[CREATED]")); } catch (Exception ex) { log.error("", ex); cannotAdd.add((String)((JSONObject)element).get("sysmlid")); ValidationRuleViolation vrv = new ValidationRuleViolation(null, "[CREATE FAILED] " + ex.getMessage()); vrv.addAction(new DetailDiff(new JSONObject(), (JSONObject)element)); cannotCreate.addViolation(vrv); } } } for (JSONObject element: fails) { cannotAdd.add((String)element.get("sysmlid")); ValidationRuleViolation vrv = new ValidationRuleViolation(null, "[CREATE FAILED] Owner or chain of owners not found"); vrv.addAction(new DetailDiff(new JSONObject(), element)); cannotCreate.addViolation(vrv); } //take care of updated for (JSONObject webUpdated: webChangedObjects) { Element e = ExportUtility.getElementFromID((String)webUpdated.get("sysmlid")); if (e == null) { //TODO bad? maybe it was supposed to have been added? continue; } JSONObject spec = (JSONObject)webUpdated.get("specialization"); if (spec != null && spec.get("contents") != null) { Constraint c = Utils.getViewConstraint(e); if (c != null) { if (!tryToLock(project, c)) { cannotChange.add(ExportUtility.getElementID(e)); //this is right since contents is embedded in view //Utils.guilog("[ERROR - SYNC UPDATE] " + e.getHumanName() + " not editable."); cannotUpdate.addViolation(new ValidationRuleViolation(c, "[UPDATE FAILED] - not editable")); continue; } } } if (!tryToLock(project, e)) { cannotChange.add(ExportUtility.getElementID(e)); //Utils.guilog("[ERROR - SYNC UPDATE] " + e.getHumanName() + " not editable."); cannotUpdate.addViolation(new ValidationRuleViolation(e, "[UPDATE FAILED] - not editable")); continue; } try { ImportUtility.updateElement(e, webUpdated); ImportUtility.setOwner(e, webUpdated); updated.addViolation(new ValidationRuleViolation(e, "[UPDATED]")); //Utils.guilog("[SYNC UPDATE] " + e.getHumanName() + " updated."); /*if (webUpdated.containsKey("specialization")) { //do auto doc hierarchy? very risky JSONArray view2view = (JSONArray)((JSONObject)webUpdated.get("specialization")).get("view2view"); if (view2view != null) { JSONObject web = ExportUtility.keyView2View(view2view); DocumentGenerator dg = new DocumentGenerator(e, null, null); Document dge = dg.parseDocument(true, true, true); ViewHierarchyVisitor vhv = new ViewHierarchyVisitor(); dge.accept(vhv); JSONObject model = vhv.getView2View(); if (!ViewValidator.viewHierarchyMatch(e, dge, vhv, (JSONObject)webUpdated.get("specialization"))) { Map<String, Object> result = ImportHierarchy.importHierarchy(e, model, web); if (result != null && (Boolean)result.get("success")) { Utils.guilog("[SYNC] Document hierarchy updated for " + e.getHumanName()); toChange.add(result); } else cannotChange.add(ExportUtility.getElementID(e)); } } }*/ } catch (Exception ex) { //Utils.guilog("[ERROR - SYNC UPDATE] " + e.getHumanName() + " failed to update from MMS: " + ex.getMessage()); ValidationRuleViolation vrv = new ValidationRuleViolation(e, "[UPDATE FAILED] " + ex.getMessage()); cannotUpdate.addViolation(vrv); log.error("", ex); cannotChange.add(ExportUtility.getElementID(e)); } } //take care of deleted for (String e: webDeleted) { Element toBeDeleted = ExportUtility.getElementFromID(e); if (toBeDeleted == null) continue; if (!tryToLock(project, toBeDeleted)) { cannotDelete.add(e); cannotRemove.addViolation(new ValidationRuleViolation(toBeDeleted, "[DELETE FAILED] - not editable")); //Utils.guilog("[ERROR - SYNC DELETE] " + toBeDeleted.getHumanName() + " not editable."); continue; } try { ModelElementsManager.getInstance().removeElement(toBeDeleted); Utils.guilog("[SYNC DELETE] " + toBeDeleted.getHumanName() + " deleted."); } catch (Exception ex) { log.error("", ex); cannotDelete.add(e); } } listener.disable(); sm.closeSession(); listener.enable(); if (!skipUpdate) Utils.guilog("[INFO] Finished applying changes."); for (Map<String, Object> r: toChange) { ImportHierarchy.sendChanges(r); //what about if doc is involved in conflict? } } catch (Exception ex) { //something really bad happened, save all changes for next time; log.error("", ex); sm.cancelSession(); Utils.printException(ex); cannotAdd.clear(); cannotChange.clear(); cannotDelete.clear(); updated.getViolations().clear(); cannotUpdate.getViolations().clear(); cannotRemove.getViolations().clear(); cannotCreate.getViolations().clear(); for (String e: webDeleted) { cannotDelete.add(e); } for (JSONObject element: webAddedObjects) { cannotAdd.add((String)((JSONObject)element).get("sysmlid")); } for (JSONObject element: webChangedObjects) { cannotChange.add((String)element.get("sysmlid")); } Utils.guilog("[ERROR] Unexpected exception happened, all changes will be reattempted at next update."); } if (!cannotAdd.isEmpty() || !cannotChange.isEmpty() || !cannotDelete.isEmpty()) { JSONObject failed = new JSONObject(); JSONArray failedAdd = new JSONArray(); failedAdd.addAll(cannotAdd); JSONArray failedChange = new JSONArray(); failedChange.addAll(cannotChange); JSONArray failedDelete = new JSONArray(); failedDelete.addAll(cannotDelete); failed.put("changed", failedChange); failed.put("added", failedAdd); failed.put("deleted", failedDelete); listener.disable(); sm.createSession("failed changes"); try { AutoSyncProjectListener.setUpdatesOrFailed(project, failed, "error"); sm.closeSession(); } catch (Exception ex) { log.error("", ex); sm.cancelSession(); } listener.enable(); Utils.guilog("[INFO] There were changes that couldn't be applied. These will be attempted on the next update."); if (!cannotAdd.isEmpty() || !cannotChange.isEmpty()) { failure = true; } } else { listener.disable(); sm.createSession("failed changes"); try { AutoSyncProjectListener.setUpdatesOrFailed(project, null, "error"); sm.closeSession(); } catch (Exception ex) { log.error("", ex); sm.cancelSession(); } listener.enable(); } //show window of what got changed List<ValidationSuite> vss = new ArrayList<ValidationSuite>(); vss.add(suite); if (suite.hasErrors()) Utils.displayValidationWindow(vss, "Delta Sync Log"); //conflicts JSONObject mvResult = new JSONObject(); mvResult.put("elements", webConflictedObjects); ModelValidator mv = new ModelValidator(null, mvResult, false, localConflictedElements, false); try { mv.validate(false, null); } catch (ServerException ex) { } Set<Element> conflictedElements = mv.getDifferentElements(); if (!conflictedElements.isEmpty()) { JSONObject conflictedToSave = new JSONObject(); JSONArray conflictedElementIds = new JSONArray(); for (Element ce: conflictedElements) conflictedElementIds.add(ExportUtility.getElementID(ce)); conflictedToSave.put("elements", conflictedElementIds); Utils.guilog("[INFO] There are potential conflicts between changes from MMS and locally changed elements, please resolve first and rerun update/commit."); listener.disable(); sm.createSession("failed changes"); try { AutoSyncProjectListener.setConflicts(project, conflictedToSave); sm.closeSession(); } catch (Exception ex) { log.error("", ex); sm.cancelSession(); } listener.enable(); failure = true; mv.showWindow(); return; } } else { if (!skipUpdate) Utils.guilog("[INFO] MMS has no updates."); //AutoSyncProjectListener.setLooseEnds(project, null); //AutoSyncProjectListener.setFailed(project, null); } //send local changes if (commit) { Utils.guilog("[INFO] Committing local changes to MMS..."); JSONArray toSendElements = new JSONArray(); Set<String> alreadyAdded = new HashSet<String>(); for (Element e: localAdded.values()) { if (e == null) continue; String id = ExportUtility.getElementID(e); if (id == null) continue; if (alreadyAdded.contains(id)) continue; alreadyAdded.add(id); toSendElements.add(ExportUtility.fillElement(e, null)); } for (Element e: localChanged.values()) { if (e == null) continue; String id = ExportUtility.getElementID(e); if (id == null) continue; if (alreadyAdded.contains(id)) continue; alreadyAdded.add(id); toSendElements.add(ExportUtility.fillElement(e, null)); } JSONObject toSendUpdates = new JSONObject(); toSendUpdates.put("elements", toSendElements); toSendUpdates.put("source", "magicdraw"); if (toSendElements.size() > 100) { } //do foreground? if (!toSendElements.isEmpty()) { Utils.guilog("[INFO] Change requests are added to queue."); OutputQueue.getInstance().offer(new Request(ExportUtility.getPostElementsUrl(), toSendUpdates.toJSONString(), "POST", true, toSendElements.size(), "Sync Changes")); } localAdded.clear(); localChanged.clear(); JSONArray toDeleteElements = new JSONArray(); for (String e: localDeleted.keySet()) { if (ExportUtility.getElementFromID(e) != null) //somehow the model has it, don't delete on server continue; JSONObject toDelete = new JSONObject(); toDelete.put("sysmlid", e); toDeleteElements.add(toDelete); } toSendUpdates.put("elements", toDeleteElements); if (!toDeleteElements.isEmpty()) { Utils.guilog("[INFO] Delete requests are added to queue."); OutputQueue.getInstance().offer(new Request(ExportUtility.getUrlWithWorkspace() + "/elements", toSendUpdates.toJSONString(), "DELETEALL", true, toDeleteElements.size(), "Sync Deletes")); } localDeleted.clear(); if (toDeleteElements.isEmpty() && toSendElements.isEmpty()) Utils.guilog("[INFO] No changes to commit."); if (!toDeleteElements.isEmpty() || !toSendElements.isEmpty() || !toGet.isEmpty()) Utils.guilog("[INFO] Don't forget to save or commit to teamwork and unlock!"); listener.disable(); SessionManager sm = SessionManager.getInstance(); sm.createSession("updates sent"); try { AutoSyncProjectListener.setUpdatesOrFailed(project, null, "update"); sm.closeSession(); } catch (Exception ex) { log.error("", ex); sm.cancelSession(); } listener.enable(); } if (!toGet.isEmpty() && !commit) Utils.guilog("[INFO] Don't forget to save or commit to teamwork and unlock!"); } public boolean getFailure() { return failure; } }
package net.sf.taverna.t2.workbench.views.monitor.progressreport; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import net.sf.taverna.t2.facade.WorkflowInstanceFacade; import net.sf.taverna.t2.facade.WorkflowInstanceFacade.State; import net.sf.taverna.t2.lang.observer.Observable; import net.sf.taverna.t2.lang.observer.Observer; import net.sf.taverna.t2.monitor.MonitorManager; import net.sf.taverna.t2.monitor.MonitorableProperty; import net.sf.taverna.t2.monitor.MonitorManager.AddPropertiesMessage; import net.sf.taverna.t2.monitor.MonitorManager.DeregisterNodeMessage; import net.sf.taverna.t2.monitor.MonitorManager.MonitorMessage; import net.sf.taverna.t2.monitor.MonitorManager.RegisterNodeMessage; import net.sf.taverna.t2.workflowmodel.Dataflow; import net.sf.taverna.t2.workflowmodel.Processor; import net.sf.taverna.t2.workflowmodel.processor.activity.Activity; import org.apache.log4j.Logger; /** * An implementation of the Monitor interface that updates the TreeTable when * MonitorableProperties change. * */ public class WorkflowRunProgressMonitor implements Observer<MonitorMessage> { private static final String STATUS_FINISHED = "Finished"; private static final String STATUS_CANCELLED = "Cancelled"; // Workflow run status label - we can only tell of workflow is running // or is finished from inside this monitor. If workfow run is stopped or // paused - this will be updated form the run-ui. // private JLabel workflowRunStatusLabel; private static Logger logger = Logger.getLogger(WorkflowRunProgressMonitor.class); private static long deregisterDelay = 10000; private static long monitorRate = 1000; private final WorkflowRunProgressTreeTable progressTreeTable; // Map of owning process ids for processors to their corresponding MonitorNodes // (we only create MonitorNodes for processors) private Map<String, WorkflowRunProgressMonitorNode> processorMonitorNodes = new HashMap<String, WorkflowRunProgressMonitorNode>(); // Map of owning process ids to workflow objects (including the processor, // dataflow and facade objects) private Map<String, Object> workflowObjects = Collections.synchronizedMap(new HashMap<String, Object>()); // Map from invocation process ID to start time private static Map<String, Date> activitityInvocationStartTimes = Collections.synchronizedMap(new HashMap<String, Date>()); private static Map<Processor, List<Long>> processorInvocationTimes = Collections.synchronizedMap(new HashMap<Processor, List<Long>>()); //private Map<String, ResultListener> resultListeners = new HashMap<String, ResultListener>(); private Timer updateTimer = new Timer("Progress table monitor update timer", true); private UpdateTask updateTask; // Filter only events for the workflow shown in the progressTreeTable private String filter; private WorkflowInstanceFacade facade; public WorkflowRunProgressMonitor(WorkflowRunProgressTreeTable progressTreeTable, WorkflowInstanceFacade facade) { this.progressTreeTable = progressTreeTable; this.facade = facade; } public void onDispose() { updateTimer.cancel(); updateTask.run(); } @Override protected void finalize() throws Throwable { onDispose(); } public void notify(Observable<MonitorMessage> sender, MonitorMessage message) throws Exception { if (message instanceof RegisterNodeMessage) { RegisterNodeMessage regMessage = (RegisterNodeMessage) message; registerNode(regMessage.getWorkflowObject(), regMessage .getOwningProcess(), regMessage.getProperties()); } else if (message instanceof DeregisterNodeMessage) { deregisterNode(message.getOwningProcess()); } else if (message instanceof AddPropertiesMessage) { AddPropertiesMessage addMessage = (AddPropertiesMessage) message; addPropertiesToNode(addMessage.getOwningProcess(), addMessage .getNewProperties()); } else { logger.warn("Unknown message " + message + " from " + sender); } } private void registerNode(Object workflowObject, String[] owningProcess, Set<MonitorableProperty<?>> properties) { if (filter == null && owningProcess.length == 1) { filter = owningProcess[0]; } // Is this event is for the workflow we are monitoring? // (exclude events for other workflows) if (owningProcess[0].equals(filter)) { String owningProcessId = getOwningProcessId(owningProcess); workflowObjects.put(owningProcessId, workflowObject); if (workflowObject instanceof Processor) { Processor processor = (Processor) workflowObject; processorInvocationTimes.put(processor, new ArrayList<Long>()); WorkflowRunProgressMonitorNode parentMonitorNode = findParentMonitorNode(owningProcess); WorkflowRunProgressMonitorNode monitorNode = new WorkflowRunProgressMonitorNode( processor, owningProcess, properties, progressTreeTable, facade, parentMonitorNode); synchronized(processorMonitorNodes) { processorMonitorNodes.put(owningProcessId, monitorNode); } } else if (workflowObject instanceof Dataflow) { // outermost dataflow if (owningProcess.length == 2) { synchronized (this) { if (updateTask != null) { // updateTask.cancel(); } updateTask = new UpdateTask(); try{ updateTimer.schedule(updateTask, monitorRate, monitorRate); } catch(IllegalStateException ex){ // task seems already cancelled // Do nothing } } } } // This is the beginning of the actual workflow run - the facade object is received else if (workflowObject instanceof WorkflowInstanceFacade) { // WorkflowInstanceFacade facade = (WorkflowInstanceFacade) workflowObject; // ResultListener resultListener = new MonitorResultListener( // getProcessorId(owningProcess)); // facade.addResultListener(resultListener); // resultListeners.put(owningProcessId, resultListener); // if (workflowRunStatusLabel != null){ // workflowRunStatusLabel.setText(STATUS_RUNNING); // workflowRunStatusLabel.setIcon(WorkbenchIcons.workingIcon); } else if (workflowObject instanceof Activity<?>) { activitityInvocationStartTimes.put(owningProcessId, new Date()); } } } private WorkflowRunProgressMonitorNode findParentMonitorNode( String[] owningProcess) { List<String> parentOwningProcess = Arrays.asList(owningProcess); while (!parentOwningProcess.isEmpty()) { // Remove last element parentOwningProcess = parentOwningProcess.subList(0, parentOwningProcess.size()-1); String parentId = getOwningProcessId(parentOwningProcess); synchronized (processorMonitorNodes) { WorkflowRunProgressMonitorNode parentNode = processorMonitorNodes .get(parentId); if (parentNode != null) { return parentNode; } } } return null; } public void deregisterNode(String[] owningProcess) { if (owningProcess[0].equals(filter)) { final String owningProcessId = getOwningProcessId(owningProcess); Object workflowObject = workflowObjects.remove(owningProcessId); if (workflowObject instanceof Processor) { WorkflowRunProgressMonitorNode workflowRunProgressMonitorNode; synchronized(processorMonitorNodes) { workflowRunProgressMonitorNode = processorMonitorNodes.get(owningProcessId); } workflowRunProgressMonitorNode.update(); Date processorFinishDate = new Date(); Date processorStartTime = progressTreeTable.getProcessorStartDate(((Processor) workflowObject)); // For some reason total number of iterations is messed up when we update it // from inside the node, so the final number is set here. // If total number of iterations is 0 that means there was just one invocation. int total = workflowRunProgressMonitorNode.getTotalNumberOfIterations(); total = (total == 0) ? 1 : total; progressTreeTable.setProcessorFinishDate(((Processor) workflowObject), processorFinishDate); progressTreeTable.setProcessorStatus(((Processor) workflowObject), STATUS_FINISHED); } else if (workflowObject instanceof Dataflow) { if (owningProcess.length == 2) { // outermost dataflow finished so schedule a task to cancel // the update task synchronized (this) { if (updateTask != null) { try{ updateTimer.schedule(new TimerTask() { public void run() { updateTask.cancel(); updateTask = null; } }, deregisterDelay); } catch(IllegalStateException ex){ // task seems already cancelled // Do nothing } } } } } else if (workflowObject instanceof WorkflowInstanceFacade) { //final WorkflowInstanceFacade facade = (WorkflowInstanceFacade) workflowObject; WorkflowInstanceFacade instanceFacade = (WorkflowInstanceFacade) workflowObject; // Is this the workflow facade for the outer most workflow? // (If it is the facade for one of the contained nested workflows then the // workflow status should not be set to FINISHED after the nested one has finished // as the main workflow may still be running) if (owningProcess.length == 1){ Date workflowFinishDate = new Date(); Date workflowStartTime = progressTreeTable.getWorkflowStartDate(); progressTreeTable.setWorkflowFinishDate(workflowFinishDate); boolean isCancelled = instanceFacade.getState().equals(State.cancelled); progressTreeTable.setWorkflowStatus(isCancelled ? STATUS_CANCELLED : STATUS_FINISHED); if (workflowStartTime != null){ long averageInvocationTime = (workflowFinishDate.getTime() - workflowStartTime.getTime()); progressTreeTable.setWorkflowInvocationTime(averageInvocationTime); } // if (workflowRunStatusLabel != null){ // workflowRunStatusLabel.setText(STATUS_FINISHED); // workflowRunStatusLabel.setIcon(WorkbenchIcons.greentickIcon); // Stop observing monitor messages as workflow has finished running // This observer may have been already removed (in which case the command // will have no effect) but in the case the workflow has no outputs // we have to do the removing here. MonitorManager.getInstance().removeObserver(this); } } else if (workflowObject instanceof Activity<?>) { Date endTime = new Date(); Date startTime = activitityInvocationStartTimes.remove(owningProcessId); ArrayList<String> owningProcessList = new ArrayList<String>(Arrays.asList(owningProcess)); owningProcessList.remove(owningProcess.length-1); String parentProcessId = getOwningProcessId(owningProcessList); Object parentObject = workflowObjects.get(parentProcessId); if (parentObject instanceof Processor) { Processor processor = (Processor) parentObject; if (startTime != null) { long invocationTime = endTime.getTime() - startTime.getTime(); List<Long> invocationTimes = processorInvocationTimes.get(processor); invocationTimes.add(invocationTime); long totalTime = 0; for (Long time : invocationTimes) { totalTime += time; } if (! invocationTimes.isEmpty()) { long averageInvocationTime = totalTime / invocationTimes.size(); progressTreeTable.setProcessorAverageInvocationTime(processor, averageInvocationTime); } } } } } } public void addPropertiesToNode(String[] owningProcess, Set<MonitorableProperty<?>> newProperties) { if (owningProcess[0].equals(filter)) { WorkflowRunProgressMonitorNode monitorNode; synchronized(processorMonitorNodes) { monitorNode = processorMonitorNodes .get(getOwningProcessId(owningProcess)); } new Exception().printStackTrace(); if (monitorNode != null) { for (MonitorableProperty<?> property : newProperties) { monitorNode.addMonitorableProperty(property); } } } } private static String getOwningProcessId(String[] owningProcess) { return getOwningProcessId(Arrays.asList(owningProcess)); } /** * Converts the owning process array to a string. * * @param owningProcess * the owning process id * @return the owning process as a string */ private static String getOwningProcessId(List<String> owningProcess) { StringBuffer sb = new StringBuffer(); Iterator<String> iterator = owningProcess.iterator(); while (iterator.hasNext()) { String string = iterator.next(); sb.append(string); if (iterator.hasNext()) { sb.append(":"); } } return sb.toString(); } public class UpdateTask extends TimerTask { public void run() { try { List<WorkflowRunProgressMonitorNode> nodes; synchronized(processorMonitorNodes) { nodes = new ArrayList<WorkflowRunProgressMonitorNode>(processorMonitorNodes.values()); } for (WorkflowRunProgressMonitorNode node : nodes) { node.update(); } progressTreeTable.refreshTable(); } catch (RuntimeException ex) { logger.error("UpdateTask update failed", ex); } } } }
package hudson.plugins.cobertura; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.Util; import hudson.model.Action; import hudson.model.BuildListener; import hudson.model.Result; import hudson.model.AbstractBuild; import hudson.model.AbstractItem; import hudson.model.AbstractProject; import hudson.plugins.cobertura.renderers.SourceCodePainter; import hudson.plugins.cobertura.renderers.SourceEncoding; import hudson.plugins.cobertura.targets.CoverageMetric; import hudson.plugins.cobertura.targets.CoverageTarget; import hudson.plugins.cobertura.targets.CoverageResult; import hudson.remoting.VirtualChannel; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import hudson.tasks.Recorder; import java.io.File; import java.io.FilenameFilter; import java.io.InputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import net.sf.json.JSONObject; import org.apache.commons.beanutils.ConvertUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Cobertura {@link Publisher}. * * @author Stephen Connolly */ public class CoberturaPublisher extends Recorder { private final String coberturaReportFile; private final boolean onlyStable; private final boolean failUnhealthy; private final boolean failUnstable; private final boolean autoUpdateHealth; private final boolean autoUpdateStability; private final boolean zoomCoverageChart; private final boolean copyHealth; private final String neighbourJobName; private final int maxNumberOfBuilds; private boolean failNoReports = true; private CoverageTarget healthyTarget; private CoverageTarget unhealthyTarget; private CoverageTarget failingTarget; public static final CoberturaReportFilenameFilter COBERTURA_FILENAME_FILTER = new CoberturaReportFilenameFilter(); private static final Logger logger = Logger .getLogger(CoberturaPublisher.class.getName()); private final SourceEncoding sourceEncoding; /** * @param coberturaReportFile * the report directory * @stapler-constructor */ @DataBoundConstructor public CoberturaPublisher(String coberturaReportFile, boolean onlyStable, boolean failUnhealthy, boolean copyHealth, boolean failUnstable, boolean autoUpdateHealth, boolean autoUpdateStability, boolean zoomCoverageChart, boolean failNoReports, SourceEncoding sourceEncoding, int maxNumberOfBuilds, String neighbourJobName) { this.coberturaReportFile = coberturaReportFile; this.onlyStable = onlyStable; this.failUnhealthy = failUnhealthy; this.copyHealth = copyHealth; this.neighbourJobName = neighbourJobName; this.failUnstable = failUnstable; this.autoUpdateHealth = autoUpdateHealth; this.autoUpdateStability = autoUpdateStability; this.zoomCoverageChart = zoomCoverageChart; this.failNoReports = failNoReports; this.sourceEncoding = sourceEncoding; this.maxNumberOfBuilds = maxNumberOfBuilds; this.healthyTarget = new CoverageTarget(); this.unhealthyTarget = new CoverageTarget(); this.failingTarget = new CoverageTarget(); } /** * Getter for property 'targets'. * * @return Value for property 'targets'. */ public List<CoberturaPublisherTarget> getTargets() { Map<CoverageMetric, CoberturaPublisherTarget> targets = new TreeMap<CoverageMetric, CoberturaPublisherTarget>(); float checker; for (CoverageMetric metric : healthyTarget.getTargets()) { CoberturaPublisherTarget target = targets.get(metric); if (target == null) { target = new CoberturaPublisherTarget(); target.setMetric(metric); } checker = (float) healthyTarget.getTarget(metric) / 100000f; if (checker <= 0.001f) { checker = (float) (Math.round(checker * 100000f)); } target.setHealthy(checker); targets.put(metric, target); } for (CoverageMetric metric : unhealthyTarget.getTargets()) { CoberturaPublisherTarget target = targets.get(metric); if (target == null) { target = new CoberturaPublisherTarget(); target.setMetric(metric); } checker = (float) unhealthyTarget.getTarget(metric) / 100000f; if (checker <= 0.001f) { checker = (float) (Math.round(checker * 100000f)); } target.setUnhealthy(checker); targets.put(metric, target); } for (CoverageMetric metric : failingTarget.getTargets()) { CoberturaPublisherTarget target = targets.get(metric); if (target == null) { target = new CoberturaPublisherTarget(); target.setMetric(metric); } checker = (float) failingTarget.getTarget(metric) / 100000f; if (checker <= 0.001f) { checker = (float) (Math.round(checker * 100000f)); } target.setUnstable(checker); targets.put(metric, target); } List<CoberturaPublisherTarget> result = new ArrayList<CoberturaPublisherTarget>( targets.values()); return result; } /** * Setter for property 'targets'. * * @param targets * Value to set for property 'targets'. */ private void setTargets(List<CoberturaPublisherTarget> targets) { // healthyTarget.clear(); // unhealthyTarget.clear(); // failingTarget.clear(); float rounded; for (CoberturaPublisherTarget target : targets) { if (target.getHealthy() != null) { rounded = (Math.round((float) 100f * target.getHealthy())); rounded = roundDecimalFloat(rounded); healthyTarget.setTarget(target.getMetric(), (int) ((float) 100000f * rounded)); } if (target.getUnhealthy() != null) { rounded = (Math.round((float) 100f * target.getUnhealthy())); rounded = roundDecimalFloat(rounded); unhealthyTarget.setTarget(target.getMetric(), (int) ((float) 100000f * rounded)); } if (target.getUnstable() != null) { rounded = (Math.round((float) 100f * target.getUnstable())); rounded = roundDecimalFloat(rounded); failingTarget.setTarget(target.getMetric(), (int) ((float) 100000f * rounded)); } } } /** * Getter for property 'coberturaReportFile'. * * @return Value for property 'coberturaReportFile'. */ public String getCoberturaReportFile() { return coberturaReportFile; } /** * Which type of build should be considered. * * @return the onlyStable */ public boolean getOnlyStable() { return onlyStable; } public int getMaxNumberOfBuilds() { return maxNumberOfBuilds; } /** * Getter for property 'failUnhealthy'. * * @return Value for property 'failUnhealthy'. */ public boolean getFailUnhealthy() { return failUnhealthy; } public boolean getCopyHealth() { return copyHealth; } public String getNeighbourJobName() { return neighbourJobName; } /** * Getter for property 'failUnstable'. * * @return Value for property 'failUnstable'. */ public boolean getFailUnstable() { return failUnstable; } /** * Getter for property 'autoUpdateHealth'. * * @return Value for property 'autoUpdateHealth'. */ public boolean getAutoUpdateHealth() { return autoUpdateHealth; } /** * Getter for property 'autoUpdateStability'. * * @return Value for property 'autoUpdateStability'. */ public boolean getAutoUpdateStability() { return autoUpdateStability; } public boolean getZoomCoverageChart() { return zoomCoverageChart; } public boolean isFailNoReports() { return failNoReports; } /** * Getter for property 'healthyTarget'. * * @return Value for property 'healthyTarget'. */ public CoverageTarget getHealthyTarget() { return healthyTarget; } /** * Setter for property 'healthyTarget'. * * @param healthyTarget * Value to set for property 'healthyTarget'. */ public void setHealthyTarget(CoverageTarget healthyTarget) { this.healthyTarget = healthyTarget; } /** * Getter for property 'unhealthyTarget'. * * @return Value for property 'unhealthyTarget'. */ public CoverageTarget getUnhealthyTarget() { return unhealthyTarget; } /** * Setter for property 'unhealthyTarget'. * * @param unhealthyTarget * Value to set for property 'unhealthyTarget'. */ public void setUnhealthyTarget(CoverageTarget unhealthyTarget) { this.unhealthyTarget = unhealthyTarget; } /** * Getter for property 'failingTarget'. * * @return Value for property 'failingTarget'. */ public CoverageTarget getFailingTarget() { return failingTarget; } /** * Setter for property 'failingTarget'. * * @param failingTarget * Value to set for property 'failingTarget'. */ public void setFailingTarget(CoverageTarget failingTarget) { this.failingTarget = failingTarget; } /** * Gets the directory where the Cobertura Report is stored for the given * project. */ /* package */ static File getCoberturaReportDir(AbstractItem project) { return new File(project.getRootDir(), "cobertura"); } /** * Gets the directory where the Cobertura Report is stored for the given * project. */ /* package */ static File[] getCoberturaReports(AbstractBuild<?, ?> build) { return build.getRootDir().listFiles(COBERTURA_FILENAME_FILTER); } /** * {@inheritDoc} */ @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { listener.getLogger().println( "[Cobertura] Publishing Cobertura coverage report..."); final FilePath[] moduleRoots = build.getModuleRoots(); final boolean multipleModuleRoots = moduleRoots != null && moduleRoots.length > 1; final FilePath moduleRoot = multipleModuleRoots ? build.getWorkspace() : build.getModuleRoot(); final File buildCoberturaDir = build.getRootDir(); FilePath buildTarget = new FilePath(buildCoberturaDir); FilePath[] reports = new FilePath[0]; try { reports = moduleRoot.act(new ParseReportCallable( coberturaReportFile)); // if the build has failed, then there's not // much point in reporting an error if (build.getResult().isWorseOrEqualTo(Result.FAILURE) && reports.length == 0) { return true; } } catch (IOException e) { Util.displayIOException(e, listener); e.printStackTrace(listener .fatalError("Unable to find coverage results")); build.setResult(Result.FAILURE); } if (reports.length == 0) { String msg = "[Cobertura] No coverage results were found using the pattern '" + coberturaReportFile + "' relative to '" + moduleRoot.getRemote() + "'." + " Did you enter a pattern relative to the correct directory?" + " Did you generate the XML report(s) for Cobertura?"; listener.getLogger().println(msg); if (failNoReports) { build.setResult(Result.FAILURE); } else { listener.getLogger().println( "[Cobertura] Skipped cobertura reports."); } return true; } for (int i = 0; i < reports.length; i++) { final FilePath targetPath = new FilePath(buildTarget, "coverage" + (i == 0 ? "" : i) + ".xml"); try { reports[i].copyTo(targetPath); } catch (IOException e) { Util.displayIOException(e, listener); e.printStackTrace(listener .fatalError("Unable to copy coverage from " + reports[i] + " to " + buildTarget)); build.setResult(Result.FAILURE); } } listener.getLogger() .println("Publishing Cobertura coverage results..."); Set<String> sourcePaths = new HashSet<String>(); CoverageResult result = null; for (File coberturaXmlReport : getCoberturaReports(build)) { try { result = CoberturaCoverageParser.parse(coberturaXmlReport, result, sourcePaths); } catch (IOException e) { Util.displayIOException(e, listener); e.printStackTrace(listener.fatalError("Unable to parse " + coberturaXmlReport)); build.setResult(Result.FAILURE); } } if (result != null) { listener.getLogger().println("Cobertura coverage report found."); result.setOwner(build); final FilePath paintedSourcesPath = new FilePath(new File(build .getProject().getRootDir(), "cobertura")); paintedSourcesPath.mkdirs(); SourceCodePainter painter = new SourceCodePainter( paintedSourcesPath, sourcePaths, result.getPaintedSources(), listener, getSourceEncoding()); moduleRoot.act(painter); final CoberturaBuildAction action = CoberturaBuildAction.load( build, result, healthyTarget, unhealthyTarget, getOnlyStable(), getFailUnhealthy(), getCopyHealth(), getFailUnstable(), getAutoUpdateHealth(), getAutoUpdateStability(), getNeighbourJobName()); build.getActions().add(action); Set<CoverageMetric> failingMetrics = failingTarget .getFailingMetrics(result); if (!failingMetrics.isEmpty()) { listener.getLogger() .println( "Code coverage enforcement failed for the following metrics:"); float oldStabilityPercent; float setStabilityPercent; for (CoverageMetric metric : failingMetrics) { oldStabilityPercent = failingTarget.getObservedPercent( result, metric); setStabilityPercent = failingTarget.getSetPercent(result, metric); listener.getLogger() .println( " " + metric.getName() + "'s stability is " + roundDecimalFloat(oldStabilityPercent * 100f) + " and set mininum stability is " + roundDecimalFloat(setStabilityPercent * 100f) + "."); } if (!getFailUnstable()) { listener.getLogger().println("Setting Build to unstable."); build.setResult(Result.UNSTABLE); } else { listener.getLogger().println( "Failing build due to unstability."); build.setResult(Result.FAILURE); } } if (getFailUnhealthy()) { Set<CoverageMetric> unhealthyMetrics = unhealthyTarget .getFailingMetrics(result); if (!unhealthyMetrics.isEmpty()) { listener.getLogger().println( "Unhealthy for the following metrics:"); float oldHealthyPercent; float setHealthyPercent; for (CoverageMetric metric : unhealthyMetrics) { oldHealthyPercent = unhealthyTarget.getObservedPercent( result, metric); setHealthyPercent = unhealthyTarget.getSetPercent( result, metric); listener.getLogger() .println( " " + metric.getName() + "'s health is " + roundDecimalFloat(oldHealthyPercent * 100f) + " and set minimum health is " + roundDecimalFloat(setHealthyPercent * 100f) + "."); } listener.getLogger().println( "Failing build because it is unhealthy."); build.setResult(Result.FAILURE); } } if (build.getResult() == Result.SUCCESS) { if (getCopyHealth()) { String path = buildCoberturaDir.toString().substring(0, buildCoberturaDir.toString().indexOf("jobs")) + "jobs/" + getNeighbourJobName() + "/config.xml"; setMainJobPercentages(path, result, listener); } else { if (getAutoUpdateHealth()) { setNewPercentages(result, true, listener); } if (getAutoUpdateStability()) { setNewPercentages(result, false, listener); } } } } else { listener.getLogger().println( "No coverage results were successfully parsed. Did you generate " + "the XML report(s) for Cobertura?"); build.setResult(Result.FAILURE); } return true; } /** * Changes unhealthy or unstable percentage fields for ratcheting. */ private void setNewPercentages(CoverageResult result, boolean select, BuildListener listener) { Set<CoverageMetric> healthyMetrics = healthyTarget .getAllMetrics(result); float newPercent; float oldPercent; // copyJobTarget. if (!healthyMetrics.isEmpty()) { for (CoverageMetric metric : healthyMetrics) { newPercent = healthyTarget.getObservedPercent(result, metric); newPercent = (float) (Math.round(newPercent * 100f)); if (select) { oldPercent = unhealthyTarget.getSetPercent(result, metric); oldPercent = (float) (Math.round(oldPercent * 100f)); } else { oldPercent = failingTarget.getSetPercent(result, metric); oldPercent = (float) (Math.round(oldPercent * 100f)); } if (newPercent > oldPercent) { if (select) { unhealthyTarget.setTarget(metric, (int) (newPercent * 1000f)); listener.getLogger().println( " " + metric.getName() + "'s new health minimum is: " + roundDecimalFloat(newPercent)); } else { failingTarget.setTarget(metric, (int) (newPercent * 1000f)); listener.getLogger().println( " " + metric.getName() + "'s new stability minimum is: " + roundDecimalFloat(newPercent)); } } } } } /** * Updates the unhealthy or unstable percentage fields for another job * */ private void setMainJobPercentages(String neighbourJobPath, CoverageResult result, BuildListener listener) { Set<CoverageMetric> healthyMetrics = healthyTarget .getAllMetrics(result); Map<String, Integer> mainJobUnhealthyMetrics = getMainJobMetrics( "unhealthyTarget", listener, neighbourJobPath); Map<String, Integer> mainJobFailingMetrics = getMainJobMetrics( "failingTarget", listener, neighbourJobPath); float newPercent; // copyJobTarget. if (!healthyMetrics.isEmpty()) { for (CoverageMetric metric : healthyMetrics) { newPercent = healthyTarget.getObservedPercent(result, metric); newPercent = (float) (Math.round(newPercent * 100f)); unhealthyTarget .setTarget(metric, (int) (mainJobUnhealthyMetrics .get(metric.toString()) * 1f)); failingTarget .setTarget(metric, (int) (mainJobFailingMetrics .get(metric.toString()) * 1f)); } } } public Map<String, Integer> getMainJobMetrics(String metricsNodeName, BuildListener listener, String neighbourJobPath) { Map<String, Integer> jobMetrics = new HashMap<String, Integer>(); File fXmlFile = new File( neighbourJobPath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); Element node = (Element) doc.getElementsByTagName(metricsNodeName) .item(0); NodeList nlist = node.getElementsByTagName("entry"); for (int temp = 0; temp < nlist.getLength(); temp++) { Node nNode = nlist.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; jobMetrics .put(eElement .getElementsByTagName( "hudson.plugins.cobertura.targets.CoverageMetric") .item(0).getTextContent(), Integer.parseInt(eElement .getElementsByTagName("int") .item(0).getTextContent())); } } } catch (SAXException e) { // Util.displayIOException(e, listener); e.printStackTrace(listener .fatalError("Unable to parse main job file")); } catch (IOException e1) { Util.displayIOException(e1, listener); e1.printStackTrace(listener .fatalError("Unable to parse main job file")); // build.setResult(Result.FAILURE); } catch (ParserConfigurationException e2) { e2.printStackTrace(listener .fatalError("Unable to parse main job file")); } return jobMetrics; } /** * {@inheritDoc} */ @Override public Action getProjectAction(AbstractProject<?, ?> project) { return new CoberturaProjectAction(project, getOnlyStable()); } /** * {@inheritDoc} */ public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.BUILD; } /** * {@inheritDoc} */ @Override public BuildStepDescriptor<Publisher> getDescriptor() { // see Descriptor javadoc for more about what a descriptor is. return DESCRIPTOR; } public SourceEncoding getSourceEncoding() { return sourceEncoding; } /** * Descriptor should be singleton. */ @Extension public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); public static class ParseReportCallable implements FilePath.FileCallable<FilePath[]> { private static final long serialVersionUID = 1L; private final String reportFilePath; public ParseReportCallable(String reportFilePath) { this.reportFilePath = reportFilePath; } public FilePath[] invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { FilePath[] r = new FilePath(f).list(reportFilePath); XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty("javax.xml.stream.supportDTD", false); for (FilePath filePath : r) { InputStream is = null; XMLEventReader reader = null; try { is = filePath.read(); reader = factory.createXMLEventReader(is); while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { StartElement start = (StartElement) event; if (start.getName().getLocalPart() .equals("coverage")) { // This is a cobertura coverage report file break; } else { throw new IOException( filePath + " is not a cobertura coverage report, please check your report pattern"); } } } } catch (XMLStreamException e) { throw new IOException( filePath + " is not an XML file, please check your report pattern"); } finally { try { if (reader != null) { try { reader.close(); } catch (XMLStreamException ex) { } } } finally { IOUtils.closeQuietly(is); } } } return r; } } * See <tt>views/hudson/plugins/cobertura/CoberturaPublisher/*.jelly</tt> * for the actual HTML fragment for the configuration screen. */ public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> { CoverageMetric[] metrics = { CoverageMetric.PACKAGES, CoverageMetric.FILES, CoverageMetric.CLASSES, CoverageMetric.METHOD, CoverageMetric.LINE, CoverageMetric.CONDITIONAL, }; /** * Constructs a new DescriptorImpl. */ DescriptorImpl() { super(CoberturaPublisher.class); } /** * This human readable name is used in the configuration screen. */ public String getDisplayName() { return Messages.CoberturaPublisher_displayName(); } /** * Getter for property 'metrics'. * * @return Value for property 'metrics'. */ public List<CoverageMetric> getMetrics() { return Arrays.asList(metrics); } /** * Getter for property 'defaultTargets'. * * @return Value for property 'defaultTargets'. */ public List<CoberturaPublisherTarget> getDefaultTargets() { List<CoberturaPublisherTarget> result = new ArrayList<CoberturaPublisherTarget>(); result.add(new CoberturaPublisherTarget(CoverageMetric.METHOD, 80f, null, null)); result.add(new CoberturaPublisherTarget(CoverageMetric.LINE, 80f, null, null)); result.add(new CoberturaPublisherTarget(CoverageMetric.CONDITIONAL, 70f, null, null)); return result; } public List<CoberturaPublisherTarget> getTargets( CoberturaPublisher instance) { if (instance == null) { return getDefaultTargets(); } return instance.getTargets(); } /** * {@inheritDoc} */ @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { req.bindParameters(this, "cobertura."); save(); return super.configure(req, formData); } /** * Creates a new instance of {@link CoberturaPublisher} from a submitted * form. */ @Override public CoberturaPublisher newInstance(StaplerRequest req, JSONObject formData) throws FormException { CoberturaPublisher instance = req.bindJSON( CoberturaPublisher.class, formData); ConvertUtils.register(CoberturaPublisherTarget.CONVERTER, CoverageMetric.class); logger.info(req.toString()); List<CoberturaPublisherTarget> targets = req.bindParametersToList( CoberturaPublisherTarget.class, "cobertura.target."); System.out.println(); instance.setTargets(targets); return instance; } @SuppressWarnings("unchecked") @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } } private static class CoberturaReportFilenameFilter implements FilenameFilter { /** * {@inheritDoc} */ public boolean accept(File dir, String name) { // TODO take this out of an anonymous inner class, create a // singleton and use a Regex to match the name return name.startsWith("coverage") && name.endsWith(".xml"); } } public float roundDecimalFloat(Float input) { float rounded = (float) Math.round(input); rounded = rounded / 100f; return rounded; } }
package org.nuxeo.ecm.automation.core.events; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.automation.AutomationService; import org.nuxeo.ecm.automation.OperationContext; import org.nuxeo.ecm.core.event.Event; import org.nuxeo.ecm.core.event.EventContext; import org.nuxeo.ecm.core.event.impl.DocumentEventContext; /** * TODO: This service should be moved in another project. * * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> */ public class EventHandlerRegistry { private static final Log log = LogFactory.getLog(OperationEventListener.class); protected final AutomationService svc; protected Map<String, List<EventHandler>> handlers; protected Map<String, List<EventHandler>> pchandlers; protected volatile Map<String, List<EventHandler>> lookup; protected volatile Map<String, List<EventHandler>> pclookup; public EventHandlerRegistry(AutomationService svc) { this.svc = svc; handlers = new HashMap<String, List<EventHandler>>(); pchandlers = new HashMap<String, List<EventHandler>>(); } public List<EventHandler> getEventHandlers(String eventId) { return lookup().get(eventId); } public List<EventHandler> getPostCommitEventHandlers(String eventId) { return pclookup().get(eventId); } public void putEventHandler(EventHandler handler) { for (String eventId : handler.getEvents()) { putEventHandler(eventId, handler); } } public synchronized void putEventHandler(String eventId, EventHandler handler) { List<EventHandler> handlers = this.handlers.get(eventId); if (handlers == null) { handlers = new ArrayList<EventHandler>(); this.handlers.put(eventId, handlers); } handlers.add(handler); lookup = null; } public void putPostCommitEventHandler(EventHandler handler) { for (String eventId : handler.getEvents()) { putPostCommitEventHandler(eventId, handler); } } public synchronized void putPostCommitEventHandler(String eventId, EventHandler handler) { List<EventHandler> handlers = this.pchandlers.get(eventId); if (handlers == null) { handlers = new ArrayList<EventHandler>(); this.pchandlers.put(eventId, handlers); } handlers.add(handler); pclookup = null; } public synchronized void removePostCommitEventHandler(EventHandler handler) { for (String eventId : handler.getEvents()) { List<EventHandler> handlers = this.pchandlers.get(eventId); if (handlers != null) { Iterator<EventHandler> it = handlers.iterator(); while (it.hasNext()) { EventHandler h = it.next(); // TODO chainId is not really an unique ID for the event // handler... if (h.chainId.equals(handler.chainId)) { it.remove(); break; } } } } pclookup = null; } public synchronized void removeEventHandler(EventHandler handler) { for (String eventId : handler.getEvents()) { List<EventHandler> handlers = this.handlers.get(eventId); if (handlers != null) { Iterator<EventHandler> it = handlers.iterator(); while (it.hasNext()) { EventHandler h = it.next(); // TODO chainId is not really an unique ID for the event // handler... if (h.chainId.equals(handler.chainId)) { it.remove(); break; } } } } lookup = null; } public synchronized void clear() { handlers = new HashMap<String, List<EventHandler>>(); pchandlers = new HashMap<String, List<EventHandler>>(); lookup = null; pclookup = null; } public Map<String, List<EventHandler>> lookup() { Map<String, List<EventHandler>> _lookup = lookup; if (_lookup == null) { synchronized (this) { if (lookup == null) { lookup = new HashMap<String, List<EventHandler>>(handlers); } _lookup = lookup; } } return _lookup; } public Map<String, List<EventHandler>> pclookup() { Map<String, List<EventHandler>> _lookup = pclookup; if (_lookup == null) { synchronized (this) { if (pclookup == null) { pclookup = new HashMap<String, List<EventHandler>>( pchandlers); } _lookup = pclookup; } } return _lookup; } public Set<String> getPostCommitEventNames() { return pclookup().keySet(); } // TODO: impl remove handlers method? or should refactor runtime to be able // to redeploy only using clear() method public void handleEvent(Event event, List<EventHandler> handlers, boolean saveSession) { if (handlers == null || handlers.isEmpty()) { return; // ignore } EventContext ectx = event.getContext(); OperationContext ctx = null; for (EventHandler handler : handlers) { if (ectx instanceof DocumentEventContext) { ctx = new OperationContext(ectx.getCoreSession()); ctx.setInput(((DocumentEventContext) ectx).getSourceDocument()); } else { // not a document event .. the chain must begin with void // operation - session is not available. ctx = new OperationContext(); } ctx.put("Event", event); ctx.setCommit(saveSession); // avoid reentrant events try { if (handler.isEnabled(ctx, ectx)) { // TODO this will save the // session at each // iteration! svc.run(ctx, handler.getChainId()); } } catch (Exception e) { log.error("Failed to handle event " + event.getName() + " using chain: " + handler.getChainId(), e); } } } }
package hudson.plugins.git.util; import hudson.Extension; import hudson.model.TaskListener; import hudson.plugins.git.Branch; import hudson.plugins.git.BranchSpec; import hudson.plugins.git.GitException; import hudson.plugins.git.GitSCM; import hudson.plugins.git.IGitAPI; import hudson.plugins.git.Revision; import org.kohsuke.stapler.DataBoundConstructor; import org.eclipse.jgit.lib.ObjectId; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import static java.util.Collections.emptyList; public class DefaultBuildChooser extends BuildChooser { @DataBoundConstructor public DefaultBuildChooser() { } /** * Determines which Revisions to build. * * If only one branch is chosen and only one repository is listed, then * just attempt to find the latest revision number for the chosen branch. * * If multiple branches are selected or the branches include wildcards, then * use the advanced usecase as defined in the getAdvancedCandidateRevisons * method. * * @throws IOException * @throws GitException */ public Collection<Revision> getCandidateRevisions(boolean isPollCall, String singleBranch, IGitAPI git, TaskListener listener, BuildData data) throws GitException, IOException { verbose(listener,"getCandidateRevisions({0},{1},,,{2}) considering branches to build",isPollCall,singleBranch,data); // if the branch name contains more wildcards then the simple usecase // does not apply and we need to skip to the advanced usecase if (singleBranch == null || singleBranch.contains("*")) return getAdvancedCandidateRevisions(isPollCall,listener,new GitUtils(listener,git),data); // check if we're trying to build a specific commit // this only makes sense for a build, there is no // reason to poll for a commit if (!isPollCall && singleBranch.matches("[0-9a-f]{6,40}")) { try { ObjectId sha1 = git.revParse(singleBranch); Revision revision = new Revision(sha1); revision.getBranches().add(new Branch("detached", sha1)); verbose(listener,"Will build the detached SHA1 {0}",sha1); return Collections.singletonList(revision); } catch (GitException e) { // revision does not exist, may still be a branch // for example a branch called "badface" would show up here verbose(listener, "Not a valid SHA1 {0}", singleBranch); } } // if it doesn't contain '/' then it could be either a tag or an unqualified branch if (!singleBranch.contains("/")) { // the 'branch' could actually be a tag: Set<String> tags = git.getTagNames(singleBranch); if(tags.size() == 0) { // its not a tag, so lets fully qualify the branch String repository = gitSCM.getRepositories().get(0).getName(); singleBranch = repository + "/" + singleBranch; verbose(listener, "{0} is not a tag. Qualifying with the repository {1} a a branch", singleBranch, repository); } } try { ObjectId sha1 = git.revParse(singleBranch); verbose(listener, "rev-parse {0} -> {1}", singleBranch, sha1); // if polling for changes don't select something that has // already been built as a build candidate if (isPollCall && data.hasBeenBuilt(sha1)) { verbose(listener, "{0} has already been built", sha1); return emptyList(); } verbose(listener, "Found a new commit {0} to be built on {1}", sha1, singleBranch); Revision revision = new Revision(sha1); revision.getBranches().add(new Branch(singleBranch, sha1)); return Collections.singletonList(revision); /* // calculate the revisions that are new compared to the last build List<Revision> candidateRevs = new ArrayList<Revision>(); List<ObjectId> allRevs = git.revListAll(); // index 0 contains the newest revision if (data != null && allRevs != null) { Revision lastBuiltRev = data.getLastBuiltRevision(); if (lastBuiltRev == null) { return Collections.singletonList(objectId2Revision(singleBranch, sha1)); } int indexOfLastBuildRev = allRevs.indexOf(lastBuiltRev.getSha1()); if (indexOfLastBuildRev == -1) { // mhmmm ... can happen when branches are switched. return Collections.singletonList(objectId2Revision(singleBranch, sha1)); } List<ObjectId> newRevisionsSinceLastBuild = allRevs.subList(0, indexOfLastBuildRev); // translate list of ObjectIds into list of Revisions for (ObjectId objectId : newRevisionsSinceLastBuild) { candidateRevs.add(objectId2Revision(singleBranch, objectId)); } } if (candidateRevs.isEmpty()) { return Collections.singletonList(objectId2Revision(singleBranch, sha1)); } return candidateRevs; */ } catch (GitException e) { // branch does not exist, there is nothing to build verbose(listener, "Failed to rev-parse: {0}", singleBranch); return emptyList(); } } private Revision objectId2Revision(String singleBranch, ObjectId sha1) { Revision revision = new Revision(sha1); revision.getBranches().add(new Branch(singleBranch, sha1)); return revision; } /** * In order to determine which Revisions to build. * * Does the following : * 1. Find all the branch revisions * 2. Filter out branches that we don't care about from the revisions. * Any Revisions with no interesting branches are dropped. * 3. Get rid of any revisions that are wholly subsumed by another * revision we're considering. * 4. Get rid of any revisions that we've already built. * * NB: Alternate BuildChooser implementations are possible - this * may be beneficial if "only 1" branch is to be built, as much of * this work is irrelevant in that usecase. * @throws IOException * @throws GitException */ private Collection<Revision> getAdvancedCandidateRevisions(boolean isPollCall, TaskListener listener, GitUtils utils, BuildData data) throws GitException, IOException { // 1. Get all the (branch) revisions that exist Collection<Revision> revs = utils.getAllBranchRevisions(); verbose(listener, "Starting with all the branches: {0}", revs); // 2. Filter out any revisions that don't contain any branches that we // actually care about (spec) for (Iterator<Revision> i = revs.iterator(); i.hasNext();) { Revision r = i.next(); // filter out uninteresting branches for (Iterator<Branch> j = r.getBranches().iterator(); j.hasNext();) { Branch b = j.next(); boolean keep = false; for (BranchSpec bspec : gitSCM.getBranches()) { if (bspec.matches(b.getName())) { keep = true; break; } } if (!keep) { verbose(listener, "Ignoring {0} because it doesn''t match branch specifier", b); j.remove(); } } if (r.getBranches().size() == 0) { verbose(listener, "Ignoring {0} because we don''t care about any of the branches that point to it", r); i.remove(); } } verbose(listener, "After branch filtering: {0}", revs); // 3. We only want 'tip' revisions revs = utils.filterTipBranches(revs); verbose(listener, "After non-tip filtering: {0}", revs); // 4. Finally, remove any revisions that have already been built. verbose(listener, "Removing what''s already been built: {0}", data.getBuildsByBranchName()); for (Iterator<Revision> i = revs.iterator(); i.hasNext();) { Revision r = i.next(); if (data.hasBeenBuilt(r.getSha1())) { i.remove(); } } verbose(listener, "After filtering out what''s already been built: {0}", revs); // if we're trying to run a build (not an SCM poll) and nothing new // was found then just run the last build again if (!isPollCall && revs.isEmpty() && data.getLastBuiltRevision() != null) { verbose(listener, "Nothing seems worth building, so falling back to the previously built revision: {0}", data.getLastBuiltRevision()); return Collections.singletonList(data.getLastBuiltRevision()); } return revs; } /** * Write the message to the listener only when the verbose mode is on. */ private void verbose(TaskListener listener, String format, Object... args) { if (GitSCM.VERBOSE) listener.getLogger().println(MessageFormat.format(format,args)); } @Extension public static final class DescriptorImpl extends BuildChooserDescriptor { @Override public String getDisplayName() { return "Default"; } @Override public String getLegacyId() { return "Default"; } } }
package io.fabric8.che.starter.client; import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import io.fabric8.che.starter.exception.ProjectCreationException; import io.fabric8.che.starter.model.DevMachineServer; import io.fabric8.che.starter.model.Project; import io.fabric8.che.starter.model.Workspace; import io.fabric8.che.starter.model.WorkspaceStatus; import io.fabric8.che.starter.template.ProjectTemplate; @Component public class ProjectClient { private static final Logger LOG = LogManager.getLogger(ProjectClient.class); @Value("${che.workspace.start.timeout}") private long workspaceStartTimeout; @Autowired private ProjectTemplate projectTemplate; @Autowired WorkspaceClient workspaceClient; @Async public void createProject(String cheServerURL, String workspaceId, String name, String repo, String branch) throws IOException, ProjectCreationException { // Before we can create a project, we must start the new workspace workspaceClient.startWorkspace(cheServerURL, workspaceId); // Poll until the workspace is started WorkspaceStatus status = workspaceClient.getWorkspaceStatus(cheServerURL, workspaceId); long currentTime = System.currentTimeMillis(); while (!WorkspaceClient.WORKSPACE_STATUS_RUNNING.equals(status.getWorkspaceStatus()) && System.currentTimeMillis() < (currentTime + workspaceStartTimeout)) { try { Thread.sleep(1000); LOG.info("Polling workspace '{}' status...", workspaceId); } catch (InterruptedException e) { LOG.error("Error while polling for workspace status", e); break; } status = workspaceClient.getWorkspaceStatus(cheServerURL, workspaceId); } LOG.info("Workspace '{}' is running", workspaceId); Workspace workspace = workspaceClient.getWorkspace(cheServerURL, workspaceId); String wsAgentUrl = getWsAgentUrl(workspace); // Next we create a new project against workspace agent API Url String url = CheRestEndpoints.CREATE_PROJECT.generateUrl(wsAgentUrl); LOG.info("Creating project against workspace agent URL: {}", url); String jsonTemplate = projectTemplate.createRequest().setName(name).setRepo(repo).setBranch(branch).getJSON(); RestTemplate template = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(jsonTemplate, headers); ResponseEntity<Project[]> response = template.exchange(url, HttpMethod.POST, entity, Project[].class); if (response.getBody().length > 0) { Project p = response.getBody()[0]; LOG.info("Successfully created project {}", p.getName()); } else { LOG.info("Error occurred while creating project {}", name); throw new ProjectCreationException("Error occurred while creating project " + name); } } private String getWsAgentUrl (final Workspace workspace) { return workspace.getRuntime().getDevMachine().getRuntime().getServers().get("4401/tcp").getUrl(); } }
package io.lp0onfire.smtnes.generators.cpu; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import io.lp0onfire.smtnes.CodeGenerator; import io.lp0onfire.smtnes.smt2.*; /** * Execute one CPU cycle, beginning at the conclusion of the previous * memory cycle (or at the start of a reset) and ending the next time the CPU accesses memory. */ public class CPUCycle implements CodeGenerator { @Override public Set<String> getStateVariablesRead() { return new HashSet<>(Arrays.asList( "CPU_A", "CPU_X", "CPU_Y", "CPU_PC", "CPU_SP", "CPU_P", "CPU_CalcAddr", "CPU_TmpAddr", "CPU_BranchOffset", "CPU_DataIn", "CPU_ResetSequence", "CPU_State")); } @Override public Set<String> getStateVariablesWritten() { return new HashSet<>(Arrays.asList( "CPU_A", "CPU_X", "CPU_Y", "CPU_PC", "CPU_SP", "CPU_P", "CPU_CalcAddr", "CPU_TmpAddr", "CPU_BranchOffset", "CPU_AddressBus", "CPU_WriteEnable", "CPU_DataOut", "CPU_ResetSequence", "CPU_State")); } private Symbol A_current; private Symbol X_current; private Symbol Y_current; private Symbol SP_current; private Symbol P_current; private Symbol PC_current; private Symbol CalcAddr_current; private Symbol TmpAddr_current; private Symbol BranchOffset_current; private Symbol AddressBus_current; private Symbol WriteEnable_current; private Symbol DataIn_current; private Symbol ResetSequence_current; private Symbol State_current; private Symbol A_next; private Symbol X_next; private Symbol Y_next; private Symbol SP_next; private Symbol P_next; private Symbol PC_next; private Symbol CalcAddr_next; private Symbol TmpAddr_next; private Symbol BranchOffset_next; private Symbol AddressBus_next; private Symbol WriteEnable_next; private Symbol DataOut_next; private Symbol ResetSequence_next; private Symbol State_next; // helpers for subexpressions private EqualsExpression preserveA() { return new EqualsExpression(A_current, A_next); } private EqualsExpression preserveX() { return new EqualsExpression(X_current, X_next); } private EqualsExpression preserveY() { return new EqualsExpression(Y_current, Y_next); } private EqualsExpression preserveSP() { return new EqualsExpression(SP_current, SP_next); } private EqualsExpression preserveP() { return new EqualsExpression(P_current, P_next); } private EqualsExpression preservePC() { return new EqualsExpression(PC_current, PC_next); } @Override public List<SExpression> generateCode(Map<String, Symbol> inputs, Map<String, Symbol> outputs) { List<SExpression> exprs = new LinkedList<>(); // read input variables A_current = inputs.get("CPU_A"); X_current = inputs.get("CPU_X"); Y_current = inputs.get("CPU_Y"); SP_current = inputs.get("CPU_SP"); P_current = inputs.get("CPU_P"); PC_current = inputs.get("CPU_PC"); CalcAddr_current = inputs.get("CPU_CalcAddr"); TmpAddr_current = inputs.get("CPU_TmpAddr"); BranchOffset_current = inputs.get("CPU_BranchOffset"); AddressBus_current = inputs.get("CPU_AddressBus"); WriteEnable_current = inputs.get("CPU_WriteEnable"); DataIn_current = inputs.get("CPU_DataIn"); ResetSequence_current = inputs.get("CPU_ResetSequence"); State_current = inputs.get("CPU_State"); // declare output variables A_next = outputs.get("CPU_A"); exprs.add(new BitVectorDeclaration(A_next, new Numeral("8"))); X_next = outputs.get("CPU_X"); exprs.add(new BitVectorDeclaration(X_next, new Numeral("8"))); Y_next = outputs.get("CPU_Y"); exprs.add(new BitVectorDeclaration(Y_next, new Numeral("8"))); SP_next = outputs.get("CPU_SP"); exprs.add(new BitVectorDeclaration(SP_next, new Numeral("8"))); P_next = outputs.get("CPU_P"); exprs.add(new BitVectorDeclaration(P_next, new Numeral("8"))); PC_next = outputs.get("CPU_PC"); exprs.add(new BitVectorDeclaration(PC_next, new Numeral("16"))); CalcAddr_next = outputs.get("CPU_CalcAddr"); exprs.add(new BitVectorDeclaration(CalcAddr_next, new Numeral("16"))); TmpAddr_next = outputs.get("CPU_TmpAddr"); exprs.add(new BitVectorDeclaration(TmpAddr_next, new Numeral("16"))); BranchOffset_next = outputs.get("CPU_BranchOffset"); exprs.add(new BitVectorDeclaration(BranchOffset_next, new Numeral("8"))); AddressBus_next = outputs.get("CPU_AddressBus"); exprs.add(new BitVectorDeclaration(AddressBus_next, new Numeral("16"))); WriteEnable_next = outputs.get("CPU_WriteEnable"); exprs.add(new BitVectorDeclaration(WriteEnable_next, new Numeral("1"))); DataOut_next = outputs.get("CPU_DataOut"); exprs.add(new BitVectorDeclaration(DataOut_next, new Numeral("8"))); ResetSequence_next = outputs.get("CPU_ResetSequence"); exprs.add(new BitVectorDeclaration(ResetSequence_next, new Numeral("3"))); State_next = outputs.get("CPU_State"); exprs.add(new BitVectorDeclaration(State_next, new Numeral(Integer.toString(CPUState.getStateWidth())))); exprs.addAll(handleReset()); return exprs; } private List<SExpression> handleReset() { List<SExpression> exprs = new LinkedList<>(); // check for things that happen when CPU_State = Resetting // this corresponds to CPU::Reset() // phase 0: read memory at PC exprs.add(new Assertion(new Implication( new AndExpression(new EqualsExpression(State_current, CPUState.Resetting.toBinaryConstant()), new EqualsExpression(ResetSequence_current, new BinaryConstant("000"))), new AndExpression( preserveA(), preserveX(), preserveY(), preserveSP(), preserveP(), preservePC(), new EqualsExpression(State_next, State_current), new EqualsExpression(AddressBus_next, PC_current), new EqualsExpression(WriteEnable_next, new BinaryConstant("0")), new EqualsExpression(DataOut_next, new BinaryConstant("00000000")), new EqualsExpression(ResetSequence_next, new BinaryConstant("001")) )))); // phase 1: read memory at PC exprs.add(new Assertion(new Implication( new AndExpression(new EqualsExpression(State_current, CPUState.Resetting.toBinaryConstant()), new EqualsExpression(ResetSequence_current, new BinaryConstant("001"))), new AndExpression( preserveA(), preserveX(), preserveY(), preserveSP(), preserveP(), preservePC(), new EqualsExpression(State_next, State_current), new EqualsExpression(AddressBus_next, PC_current), new EqualsExpression(WriteEnable_next, new BinaryConstant("0")), new EqualsExpression(DataOut_next, new BinaryConstant("00000000")), new EqualsExpression(ResetSequence_next, new BinaryConstant("010")) )))); // phase 2: read and decrement SP exprs.add(new Assertion(new Implication( new AndExpression(new EqualsExpression(State_current, CPUState.Resetting.toBinaryConstant()), new EqualsExpression(ResetSequence_current, new BinaryConstant("010"))), new AndExpression( preserveA(), preserveX(), preserveY(), preserveP(), preservePC(), new EqualsExpression(SP_next, new BitVectorSubtractExpression(SP_current, new BinaryConstant("00000001"))), new EqualsExpression(State_next, State_current), new EqualsExpression(AddressBus_next, new BitVectorConcatExpression(new BinaryConstant("00000001"), SP_current)), new EqualsExpression(WriteEnable_next, new BinaryConstant("0")), new EqualsExpression(DataOut_next, new BinaryConstant("00000000")), new EqualsExpression(ResetSequence_next, new BinaryConstant("011")) )))); // phase 3: read and decrement SP exprs.add(new Assertion(new Implication( new AndExpression(new EqualsExpression(State_current, CPUState.Resetting.toBinaryConstant()), new EqualsExpression(ResetSequence_current, new BinaryConstant("011"))), new AndExpression( preserveA(), preserveX(), preserveY(), preserveP(), preservePC(), new EqualsExpression(SP_next, new BitVectorSubtractExpression(SP_current, new BinaryConstant("00000001"))), new EqualsExpression(State_next, State_current), new EqualsExpression(AddressBus_next, new BitVectorConcatExpression(new BinaryConstant("00000001"), SP_current)), new EqualsExpression(WriteEnable_next, new BinaryConstant("0")), new EqualsExpression(DataOut_next, new BinaryConstant("00000000")), new EqualsExpression(ResetSequence_next, new BinaryConstant("100")) )))); // phase 4: read and decrement SP exprs.add(new Assertion(new Implication( new AndExpression(new EqualsExpression(State_current, CPUState.Resetting.toBinaryConstant()), new EqualsExpression(ResetSequence_current, new BinaryConstant("100"))), new AndExpression( preserveA(), preserveX(), preserveY(), preserveP(), preservePC(), new EqualsExpression(SP_next, new BitVectorSubtractExpression(SP_current, new BinaryConstant("00000001"))), new EqualsExpression(State_next, State_current), new EqualsExpression(AddressBus_next, new BitVectorConcatExpression(new BinaryConstant("00000001"), SP_current)), new EqualsExpression(WriteEnable_next, new BinaryConstant("0")), new EqualsExpression(DataOut_next, new BinaryConstant("00000000")), new EqualsExpression(ResetSequence_next, new BinaryConstant("101")) )))); // phase 5: set P[FI] = 1, read 0xFFFC exprs.add(new Assertion(new Implication( new AndExpression(new EqualsExpression(State_current, CPUState.Resetting.toBinaryConstant()), new EqualsExpression(ResetSequence_current, new BinaryConstant("101"))), new AndExpression( preserveA(), preserveX(), preserveY(), preserveSP(), preservePC(), new EqualsExpression(P_next, new BitVectorOrExpression(P_current, new BinaryConstant("00000100"))), new EqualsExpression(State_next, State_current), new EqualsExpression(AddressBus_next, new HexConstant("FFFC")), new EqualsExpression(WriteEnable_next, new BinaryConstant("0")), new EqualsExpression(DataOut_next, new BinaryConstant("00000000")), new EqualsExpression(ResetSequence_next, new BinaryConstant("110")) )))); // phase 6: set PC_low = DataIn, read 0xFFFD exprs.add(new Assertion(new Implication( new AndExpression(new EqualsExpression(State_current, CPUState.Resetting.toBinaryConstant()), new EqualsExpression(ResetSequence_current, new BinaryConstant("110"))), new AndExpression( preserveA(), preserveX(), preserveY(), preserveSP(), preserveP(), new EqualsExpression(PC_next, new BitVectorConcatExpression( new BitVectorExtractExpression(PC_current, new Numeral("15"), new Numeral("8")), DataIn_current)), new EqualsExpression(State_next, State_current), new EqualsExpression(AddressBus_next, new HexConstant("FFFD")), new EqualsExpression(WriteEnable_next, new BinaryConstant("0")), new EqualsExpression(DataOut_next, new BinaryConstant("00000000")), new EqualsExpression(ResetSequence_next, new BinaryConstant("111")) )))); // phase 7: set PC_high = DataIn, set up instruction fetch SExpression nextProgramCounter = new BitVectorConcatExpression( DataIn_current, new BitVectorExtractExpression(PC_current, new Numeral("7"), new Numeral("0"))); exprs.add(new Assertion(new Implication( new AndExpression(new EqualsExpression(State_current, CPUState.Resetting.toBinaryConstant()), new EqualsExpression(ResetSequence_current, new BinaryConstant("111"))), new AndExpression( preserveA(), preserveX(), preserveY(), preserveSP(), preserveP(), new EqualsExpression(PC_next, nextProgramCounter), new EqualsExpression(State_next, CPUState.InstructionFetch.toBinaryConstant()), new EqualsExpression(AddressBus_next, nextProgramCounter), new EqualsExpression(WriteEnable_next, new BinaryConstant("0")), new EqualsExpression(DataOut_next, new BinaryConstant("00000000")), new EqualsExpression(ResetSequence_next, new BinaryConstant("000")) )))); return exprs; } }
package main.java.com.bag.server; import bftsmart.reconfiguration.util.RSAKeyLoader; import bftsmart.tom.MessageContext; import bftsmart.tom.ServiceProxy; import bftsmart.tom.core.messages.TOMMessageType; import bftsmart.tom.util.TOMUtil; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.pool.KryoPool; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import main.java.com.bag.instrumentations.ServerInstrumentation; import main.java.com.bag.operations.IOperation; import main.java.com.bag.database.SparkseeDatabaseAccess; import main.java.com.bag.util.Constants; import main.java.com.bag.util.Log; import main.java.com.bag.util.storage.NodeStorage; import main.java.com.bag.util.storage.RelationshipStorage; import main.java.com.bag.util.storage.SignatureStorage; import org.jetbrains.annotations.NotNull; import java.security.PublicKey; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Class handling server communication in the global cluster. */ public class GlobalClusterSlave extends AbstractRecoverable { /** * Name of the location of the global config. */ private static final String GLOBAL_CONFIG_LOCATION = "global/config"; /** * The wrapper class instance. Used to access the global cluster if possible. */ private final ServerWrapper wrapper; /** * The id of the local cluster. */ private final int id; /** * The internal client used in this server */ private final int idClient; /** * Cache which holds the signatureStorages for the consistency. */ private final Cache<Long, SignatureStorage> signatureStorageCache = Caffeine.newBuilder().build(); /** * The last sent commit, do not put anything under this number in the signature cache. */ private long lastSent = 0; /** * The serviceProxy to establish communication with the other replicas. */ private final ServiceProxy proxy; /** * SignatureStorageCache lock to be sure that we compare correctly. */ private static final Object lock = new Object(); /** * Thread pool for message sending. */ private final ExecutorService service = Executors.newFixedThreadPool(2); /** * Thread pool for message sending. */ private final ExecutorService localDis = Executors.newSingleThreadExecutor(); GlobalClusterSlave(final int id, @NotNull final ServerWrapper wrapper, final ServerInstrumentation instrumentation) { super(id, GLOBAL_CONFIG_LOCATION, wrapper, instrumentation); this.id = id; this.idClient = id + 1000; this.wrapper = wrapper; Log.getLogger().info("Turning on client proxy with id:" + idClient); this.proxy = new ServiceProxy(this.idClient, GLOBAL_CONFIG_LOCATION); Log.getLogger().info("Turned on global cluster with id:" + id); } /** * Every byte array is one request. * * @param message the requests. * @param messageContexts the contexts. * @return the answers of all requests in this batch. */ @Override public byte[][] appExecuteBatch(final byte[][] message, final MessageContext[] messageContexts, final boolean noop) { final KryoPool pool = new KryoPool.Builder(super.getFactory()).softReferences().build(); final Kryo kryo = pool.borrow(); if (messageContexts == null || message == null || message.length != messageContexts.length) { Log.getLogger().error("!!!!!!!!!!!!!!!!!Something is going so badly!!!!!!!!!!!!!!!!!! the message length is != the contxt length"); } for(int i = 0; i < message.length; i++) { Log.getLogger().info("Committed: " + getGlobalSnapshotId() + " consensus: " + messageContexts[i].getConsensusId() + " sequence: " + messageContexts[i].getSequence() + " op: " + messageContexts[i].getOperationId()); } final byte[][] allResults = new byte[message.length][]; for (int i = 0; i < message.length; i++) { if (messageContexts != null && messageContexts[i] != null) { try { final Input input = new Input(message[i]); final String type = kryo.readObject(input, String.class); if (Constants.COMMIT_MESSAGE.equals(type)) { final Long timeStamp = kryo.readObject(input, Long.class); final byte[] result = executeCommit(kryo, input, timeStamp, messageContexts[i]); allResults[i] = result; } else { Log.getLogger().error("Return empty bytes for message type: " + type); allResults[i] = makeEmptyAbortResult(); updateCounts(0, 0, 0, 1); } } catch (final Exception any) { Log.getLogger().error("Any: ", any); } } else { Log.getLogger().error("Received message with empty context!"); allResults[i] = makeEmptyAbortResult(); updateCounts(0, 0, 0, 1); } } pool.release(kryo); return allResults; } @Override void readSpecificData(final Input input, final Kryo kryo) { final int length = kryo.readObject(input, Integer.class); for (int i = 0; i < length; i++) { try { signatureStorageCache.put(kryo.readObject(input, Long.class), kryo.readObject(input, SignatureStorage.class)); } catch (final ClassCastException ex) { Log.getLogger().error("Unable to restore signatureStoreMap entry: " + i + " at server: " + id, ex); } } } @Override public Output writeSpecificData(final Output output, final Kryo kryo) { if (signatureStorageCache == null) { return output; } Log.getLogger().error("Size at global: " + signatureStorageCache.estimatedSize()); final Map<Long, SignatureStorage> copy = signatureStorageCache.asMap(); kryo.writeObject(output, copy.size()); for (final Map.Entry<Long, SignatureStorage> entrySet : copy.entrySet()) { kryo.writeObject(output, entrySet.getKey()); kryo.writeObject(output, entrySet.getValue()); } return output; } /** * Check for conflicts and unpack things for conflict handle check. * * @param kryo the kryo instance. * @param input the input. * @param messageContext the message context. * @return the response. */ private byte[] executeCommit(final Kryo kryo, final Input input, final long timeStamp, final MessageContext messageContext) { Log.getLogger().info("Starting executing: " + "signatures" + " " + "commit" + " " + (getGlobalSnapshotId() + 1) + " " + messageContext.getConsensusId() + " sequence: " + messageContext.getSequence() + " op: " + messageContext.getOperationId()); //Read the inputStream. final List readsSetNodeX = kryo.readObject(input, ArrayList.class); final List readsSetRelationshipX = kryo.readObject(input, ArrayList.class); final List writeSetX = kryo.readObject(input, ArrayList.class); //Create placeHolders. final ArrayList<NodeStorage> readSetNode; final ArrayList<RelationshipStorage> readsSetRelationship; final ArrayList<IOperation> localWriteSet; input.close(); final Output output = new Output(128); kryo.writeObject(output, Constants.COMMIT_RESPONSE); try { readSetNode = (ArrayList<NodeStorage>) readsSetNodeX; readsSetRelationship = (ArrayList<RelationshipStorage>) readsSetRelationshipX; localWriteSet = (ArrayList<IOperation>) writeSetX; } catch (final Exception e) { Log.getLogger().info("Couldn't convert received data to sets. Returning abort", e); kryo.writeObject(output, Constants.ABORT); kryo.writeObject(output, getGlobalSnapshotId()); //Send abort to client and abort final byte[] returnBytes = output.getBuffer(); output.close(); return returnBytes; } if (wrapper.isGloballyVerified() && wrapper.getLocalCluster() != null && !localWriteSet.isEmpty() && wrapper.getLocalClusterSlaveId() == 0) { Log.getLogger().info("Distribute commit to slave!"); distributeCommitToSlave(localWriteSet, Constants.COMMIT, getGlobalSnapshotId(), kryo, readSetNode, readsSetRelationship, messageContext); } /*if (messageContext.getConsensusId() < wrapper.getLastTransactionId()) { kryo.writeObject(output, Constants.COMMIT); kryo.writeObject(output, getGlobalSnapshotId()); final byte[] returnBytes = output.getBuffer(); output.close(); Log.getLogger().error("Old transaction, pulling it: " + getGlobalSnapshotId() + " compared to: " + messageContext.getConsensusId()); return returnBytes; }*/ Log.getLogger().info("Going to check: " + "signatures" + " " + "commit" + " " + (getGlobalSnapshotId() + 1) + " " + messageContext.getConsensusId() + " " + Arrays.toString(localWriteSet.toArray()) + " sequence: " + messageContext.getSequence() + " op: " + messageContext.getOperationId()); if (!ConflictHandler.checkForConflict(super.getGlobalWriteSet(), super.getLatestWritesSet(), new ArrayList<>(localWriteSet), readSetNode, readsSetRelationship, timeStamp, wrapper.getDataBaseAccess(), wrapper.isMultiVersion())) { updateCounts(0, 0, 0, 1); Log.getLogger() .info("Found conflict " + (getGlobalSnapshotId() + 1) + " " + messageContext.getConsensusId() + ", returning abort with timestamp: " + timeStamp + " globalSnapshot at: " + getGlobalSnapshotId() + " and writes: " + Arrays.toString(localWriteSet.toArray()) + " and reads: " + readSetNode.size() + " + " + readsSetRelationship.size()); kryo.writeObject(output, Constants.ABORT); kryo.writeObject(output, getGlobalSnapshotId()); if (!localWriteSet.isEmpty()) { Log.getLogger().info("Aborting of: " + getGlobalSnapshotId() + " localId: " + timeStamp); } //Send abort to client and abort final byte[] returnBytes = output.getBuffer(); output.close(); return returnBytes; } if (!localWriteSet.isEmpty()) { final RSAKeyLoader rsaLoader = new RSAKeyLoader(idClient, GLOBAL_CONFIG_LOCATION, false); super.executeCommit(localWriteSet, rsaLoader, idClient, timeStamp, messageContext.getConsensusId()); Log.getLogger().info("Comitting: " + "signatures" + " " + "commit" + " " + getGlobalSnapshotId() + " " + messageContext.getConsensusId() + " " + Arrays.toString(localWriteSet.toArray()) + " sequence: " + messageContext.getSequence() + " op: " + messageContext.getOperationId()); if (wrapper.getLocalCluster() != null && !wrapper.isGloballyVerified()) { Log.getLogger().info("Sending global: " + getGlobalSnapshotId() + " Consensus: " + messageContext.getConsensusId()); signCommitWithDecisionAndDistribute(localWriteSet, Constants.COMMIT, getGlobalSnapshotId(), kryo, messageContext.getConsensusId()); } } else { updateCounts(0, 0, 1, 0); } kryo.writeObject(output, Constants.COMMIT); kryo.writeObject(output, getGlobalSnapshotId()); final byte[] returnBytes = output.getBuffer(); output.close(); Log.getLogger().info("No conflict found, returning commit with snapShot id: " + getGlobalSnapshotId() + " size: " + returnBytes.length); return returnBytes; } /** * Check for conflicts and unpack things for conflict handle check. * * @param kryo the kryo instance. * @param input the input. * @return the response. */ private byte[] executeReadOnlyCommit(final Kryo kryo, final Input input, final long timeStamp) { //Read the inputStream. final List readsSetNodeX = kryo.readObject(input, ArrayList.class); final List readsSetRelationshipX = kryo.readObject(input, ArrayList.class); final List writeSetX = kryo.readObject(input, ArrayList.class); //Create placeHolders. final ArrayList<NodeStorage> readSetNode; final ArrayList<RelationshipStorage> readsSetRelationship; final ArrayList<IOperation> localWriteSet; input.close(); final Output output = new Output(128); kryo.writeObject(output, Constants.COMMIT_RESPONSE); try { readSetNode = (ArrayList<NodeStorage>) readsSetNodeX; readsSetRelationship = (ArrayList<RelationshipStorage>) readsSetRelationshipX; localWriteSet = (ArrayList<IOperation>) writeSetX; } catch (final Exception e) { Log.getLogger().error("Couldn't convert received data to sets. Returning abort", e); kryo.writeObject(output, Constants.ABORT); kryo.writeObject(output, getGlobalSnapshotId()); //Send abort to client and abort final byte[] returnBytes = output.getBuffer(); output.close(); return returnBytes; } if (!ConflictHandler.checkForConflict(super.getGlobalWriteSet(), super.getLatestWritesSet(), localWriteSet, readSetNode, readsSetRelationship, timeStamp, wrapper.getDataBaseAccess(), wrapper.isMultiVersion())) { updateCounts(0, 0, 0, 1); Log.getLogger() .info("Found conflict, returning abort with timestamp: " + timeStamp + " globalSnapshot at: " + getGlobalSnapshotId() + " and writes: " + localWriteSet.size() + " and reads: " + readSetNode.size() + " + " + readsSetRelationship.size()); kryo.writeObject(output, Constants.ABORT); kryo.writeObject(output, getGlobalSnapshotId()); //Send abort to client and abort final byte[] returnBytes = output.getBuffer(); output.close(); return returnBytes; } updateCounts(0, 0, 1, 0); kryo.writeObject(output, Constants.COMMIT); kryo.writeObject(output, getGlobalSnapshotId()); final byte[] returnBytes = output.getBuffer(); output.close(); Log.getLogger().info("No conflict found, returning commit with snapShot id: " + getGlobalSnapshotId() + " size: " + returnBytes.length); return returnBytes; } /** * Signs the commit, gathers all signatures, * and distributes the commit and decision to the slaves. * * @param localWriteSet the writeset. * @param decision the decision. * @param snapShotId the snapshot. * @param kryo the kryo instance. * @param consensusId the consensus ID. */ private void signCommitWithDecisionAndDistribute(final List<IOperation> localWriteSet, final String decision, final long snapShotId, final Kryo kryo, final int consensusId) { Log.getLogger().info("Sending signed commit to the other global replicas"); final RSAKeyLoader rsaLoader = new RSAKeyLoader(idClient, GLOBAL_CONFIG_LOCATION, false); //Might not be enough, might have to think about increasing the buffer size in the future. final Output output = new Output(0, 100240); kryo.writeObject(output, Constants.SIGNATURE_MESSAGE); kryo.writeObject(output, decision); kryo.writeObject(output, snapShotId); kryo.writeObject(output, localWriteSet); kryo.writeObject(output, consensusId); final byte[] message = output.toBytes(); final byte[] signature; try { signature = TOMUtil.signMessage(rsaLoader.loadPrivateKey(), message); } catch (final Exception e) { Log.getLogger().error("Unable to sign message at server " + getId(), e); return; } synchronized (lock) { SignatureStorage signatureStorage = signatureStorageCache.getIfPresent(snapShotId); if (signatureStorage != null) { if (signatureStorage.getMessage().length != output.toBytes().length) { Log.getLogger().error("Message in signatureStorage: " + signatureStorage.getMessage().length + " message of committing server: " + message.length + "id: " + snapShotId); final Input messageInput = new Input(signatureStorage.getMessage()); try { final String a = kryo.readObject(messageInput, String.class); final String b = kryo.readObject(messageInput, String.class); final long c = kryo.readObject(messageInput, Long.class); final List d = kryo.readObject(messageInput, ArrayList.class); final ArrayList<IOperation> e = (ArrayList<IOperation>) d; final int f = kryo.readObject(messageInput, Integer.class); Log.getLogger().error("Did: " + a + " " + b + " " + c + " " + f + " " + Arrays.toString(e.toArray())); Log.getLogger().error("Has: " + "signatures" + " " + decision + " " + snapShotId + " " + consensusId + " " + Arrays.toString(localWriteSet.toArray())); } catch (final Exception ex) { Log.getLogger().error(ex); } finally { messageInput.close(); } } } else { Log.getLogger().info("Size of message stored is: " + message.length); signatureStorage = new SignatureStorage(getReplica().getReplicaContext().getStaticConfiguration().getF() + 1, message, decision); signatureStorageCache.put(snapShotId, signatureStorage); } signatureStorage.setProcessed(); Log.getLogger().info("Set processed by global cluster: " + snapShotId + " by: " + idClient); signatureStorage.addSignatures(idClient, signature); if (signatureStorage.hasEnough()) { Log.getLogger().info("Sending update to slave signed by all members: " + snapShotId); final Output messageOutput = new Output(100096); kryo.writeObject(messageOutput, Constants.UPDATE_SLAVE); kryo.writeObject(messageOutput, decision); kryo.writeObject(messageOutput, snapShotId); kryo.writeObject(messageOutput, signatureStorage); kryo.writeObject(messageOutput, consensusId); final DistributeMessageThread runnable = new DistributeMessageThread(messageOutput.getBuffer()); service.submit(runnable); messageOutput.close(); signatureStorage.setDistributed(); signatureStorageCache.put(snapShotId, signatureStorage); signatureStorageCache.invalidate(snapShotId); lastSent = snapShotId; } else { signatureStorageCache.put(snapShotId, signatureStorage); } } kryo.writeObject(output, message.length); kryo.writeObject(output, signature.length); output.writeBytes(signature); final GlobalMessageThread messageThread = new GlobalMessageThread(output.getBuffer()); localDis.submit(messageThread); //proxy.sendMessageToTargets(output.getBuffer(), 0, 0, proxy.getViewManager().getCurrentViewProcesses(), TOMMessageType.UNORDERED_REQUEST); output.close(); } /** * Takes the signature of the decision and sends it to the slaves. * * @param localWriteSet the local writeSet. * @param decision the decision. * @param snapShotId the snapshotId. * @param kryo the kryo instance. * @param readSetNode the read set for the nodes. * @param readsSetRelationship the read set for the relationships. * @param context the message context. */ private void distributeCommitToSlave( final List<IOperation> localWriteSet, final String decision, final long snapShotId, final Kryo kryo, final ArrayList<NodeStorage> readSetNode, final ArrayList<RelationshipStorage> readsSetRelationship, final MessageContext context) { //Might not be enough, might have to think about increasing the buffer size in the future. final Output output = new Output(0, 100240); kryo.writeObject(output, Constants.SIGNATURE_MESSAGE); kryo.writeObject(output, decision); kryo.writeObject(output, snapShotId); kryo.writeObject(output, localWriteSet); kryo.writeObject(output, readSetNode); kryo.writeObject(output, readsSetRelationship); kryo.writeObject(output, context.getConsensusId()); final byte[] message = output.toBytes(); final byte[] signature; signature = context.getProof().iterator().next().getValue(); final SignatureStorage signatureStorage = new SignatureStorage(getReplica().getReplicaContext().getStaticConfiguration().getF() + 1, message, decision); signatureStorage.setProcessed(); Log.getLogger().info("Set processed by global cluster: " + snapShotId + " by: " + idClient); signatureStorage.addSignatures(idClient, signature); Log.getLogger().info("Sending update to slave signed by all members: " + snapShotId); final Output messageOutput = new Output(100096); kryo.writeObject(messageOutput, Constants.UPDATE_SLAVE); kryo.writeObject(messageOutput, decision); kryo.writeObject(messageOutput, snapShotId); kryo.writeObject(messageOutput, signatureStorage); kryo.writeObject(messageOutput, context.getConsensusId()); Log.getLogger().info("Starting thread to update to slave signed by all members: " + snapShotId); final DistributeMessageThread runnable = new DistributeMessageThread(messageOutput.getBuffer()); service.submit(runnable); messageOutput.close(); signatureStorage.setDistributed(); lastSent = snapShotId; Log.getLogger().info("Finished to update to slave signed by all members: " + snapShotId); } /** * Handle a signature message. * * @param input the message. * @param messageContext the context. * @param kryo the kryo object. */ private void handleSignatureMessage(final Input input, final MessageContext messageContext, final Kryo kryo) { //Our own message. if (idClient == messageContext.getSender()) { return; } final byte[] buffer = input.getBuffer(); final String decision = kryo.readObject(input, String.class); final Long snapShotId = kryo.readObject(input, Long.class); final List writeSet = kryo.readObject(input, ArrayList.class); final int consensusId = kryo.readObject(input, Integer.class); final ArrayList<IOperation> localWriteSet; synchronized (lock) { if (lastSent > snapShotId) { final SignatureStorage tempStorage = signatureStorageCache.getIfPresent(snapShotId); if (tempStorage == null || tempStorage.isDistributed()) { signatureStorageCache.invalidate(snapShotId); return; } } try { localWriteSet = (ArrayList<IOperation>) writeSet; } catch (final ClassCastException e) { Log.getLogger().error("Couldn't convert received signature message.", e); return; } Log.getLogger().info("Server: " + id + " Received message to sign with snapShotId: " + snapShotId + " of Server " + messageContext.getSender() + " and decision: " + decision + " and a writeSet of the length of: " + localWriteSet.size()); final int messageLength = kryo.readObject(input, Integer.class); final int signatureLength = kryo.readObject(input, Integer.class); final byte[] signature = input.readBytes(signatureLength); //Not required anymore. input.close(); final RSAKeyLoader rsaLoader = new RSAKeyLoader(messageContext.getSender(), GLOBAL_CONFIG_LOCATION, false); final PublicKey key; try { key = rsaLoader.loadPublicKey(); } catch (final Exception e) { Log.getLogger().error("Unable to load public key on server " + id + " sent by server " + messageContext.getSender(), e); return; } final byte[] message = new byte[messageLength]; System.arraycopy(buffer, 0, message, 0, messageLength); final boolean signatureMatches = TOMUtil.verifySignature(key, message, signature); if (signatureMatches) { storeSignedMessage(snapShotId, signature, messageContext, decision, message, writeSet, consensusId); return; } Log.getLogger().error("Signature doesn't match of message, throwing message away." + id + ":" + messageContext.getSender() + ": " + message + "/" + signature); } } @Override public byte[] appExecuteUnordered(final byte[] bytes, final MessageContext messageContext) { Log.getLogger().info("Received unordered message at global replica"); final KryoPool pool = new KryoPool.Builder(getFactory()).softReferences().build(); final Kryo kryo = pool.borrow(); final Input input = new Input(bytes); final String messageType = kryo.readObject(input, String.class); Output output = new Output(1, 804800); byte[] returnValue; try { switch (messageType) { case Constants.READ_MESSAGE: Log.getLogger().info("Received Node read message"); try { kryo.writeObject(output, Constants.READ_MESSAGE); output = handleNodeRead(input, kryo, output, messageContext.getSender()); } catch (final Exception t) { Log.getLogger().error("Error on " + Constants.READ_MESSAGE + ", returning empty read", t); output.close(); output = makeEmptyReadResponse(Constants.READ_MESSAGE, kryo); } break; case Constants.RELATIONSHIP_READ_MESSAGE: Log.getLogger().info("Received Relationship read message"); try { kryo.writeObject(output, Constants.READ_MESSAGE); output = handleRelationshipRead(input, kryo, output, messageContext.getSender()); } catch (final Exception t) { Log.getLogger().error("Error on " + Constants.RELATIONSHIP_READ_MESSAGE + ", returning empty read", t); output = makeEmptyReadResponse(Constants.RELATIONSHIP_READ_MESSAGE, kryo); } break; case Constants.SIGNATURE_MESSAGE: if (wrapper.getLocalCluster() != null) { handleSignatureMessage(input, messageContext, kryo); } break; case Constants.REGISTER_GLOBALLY_MESSAGE: Log.getLogger().info("Received register globally message"); output.close(); input.close(); pool.release(kryo); return handleRegisteringSlave(input, kryo); case Constants.COMMIT: Log.getLogger().info("Received commit message: " + input.getBuffer().length); if (wrapper.getDataBaseAccess() instanceof SparkseeDatabaseAccess) { input.close(); pool.release(kryo); return new byte[] {0}; } final byte[] result; result = handleReadOnlyCommit(input, kryo); input.close(); pool.release(kryo); Log.getLogger().info("Return it to client, size: " + result.length); return result; default: Log.getLogger().error("Incorrect operation sent unordered to the server"); break; } returnValue = output.getBuffer(); } finally { output.close(); } Log.getLogger().info("Return it to client, size: " + returnValue.length); input.close(); output.close(); pool.release(kryo); return returnValue; } private byte[] handleReadOnlyCommit(final Input input, final Kryo kryo) { final Long timeStamp = kryo.readObject(input, Long.class); return executeReadOnlyCommit(kryo, input, timeStamp); } /** * This message comes from the local cluster. * Will respond true if it can register. * Message which handles slaves registering at the global cluster. * * @param kryo the kryo instance. * @param input the message. * @return the message in bytes. */ @SuppressWarnings("squid:S2095") private byte[] handleRegisteringSlave(final Input input, final Kryo kryo) { final int localClusterID = kryo.readObject(input, Integer.class); final int newPrimary = kryo.readObject(input, Integer.class); final int oldPrimary = kryo.readObject(input, Integer.class); final ServiceProxy localProxy = new ServiceProxy(1000 + oldPrimary, "local" + localClusterID); final Output output = new Output(512); kryo.writeObject(output, Constants.REGISTER_GLOBALLY_CHECK); kryo.writeObject(output, newPrimary); final byte[] result = localProxy.invokeUnordered(output.getBuffer()); final Output nextOutput = new Output(512); kryo.writeObject(output, Constants.REGISTER_GLOBALLY_REPLY); final Input answer = new Input(result); if (Constants.REGISTER_GLOBALLY_REPLY.equals(answer.readString())) { kryo.writeObject(nextOutput, answer.readBoolean()); } final byte[] returnBuffer = nextOutput.getBuffer(); nextOutput.close(); answer.close(); localProxy.close(); output.close(); return returnBuffer; //remove currentView and edit system.config //If alright send the result to all remaining global clusters so that they update themselves. } /** * Store the signed message on the server. * If n-f messages arrived send it to client. * * @param snapShotId the snapShotId as key. * @param signature the signature * @param context the message context. * @param decision the decision. * @param message the message. * @param consensusId the consensus id. */ private void storeSignedMessage( final Long snapShotId, final byte[] signature, @NotNull final MessageContext context, final String decision, final byte[] message, final List<IOperation> writeSet, final int consensusId) { final SignatureStorage signatureStorage; final KryoPool pool = new KryoPool.Builder(super.getFactory()).softReferences().build(); final Kryo kryo = pool.borrow(); final SignatureStorage tempStorage = signatureStorageCache.getIfPresent(snapShotId); signatureStorageCache.invalidate(snapShotId); if (tempStorage == null) { signatureStorage = new SignatureStorage(super.getReplica().getReplicaContext().getStaticConfiguration().getF() + 1, message, decision); Log.getLogger().info("Replica: " + id + " did not have the transaction prepared. Might be slow or corrupted, message size stored: " + message.length); } else { signatureStorage = tempStorage; } if (signatureStorage.getMessage().length != message.length) { final Input messageInput = new Input(signatureStorage.getMessage()); try { final String a = kryo.readObject(messageInput, String.class); final String b = kryo.readObject(messageInput, String.class); final long c = kryo.readObject(messageInput, Long.class); final List d = kryo.readObject(messageInput, ArrayList.class); final ArrayList<IOperation> e = (ArrayList<IOperation>) d; final int f = kryo.readObject(messageInput, Integer.class); Log.getLogger().error("Did: " + a + " " + b + " " + c + " " + f + " " + Arrays.toString(e.toArray())); Log.getLogger().error("Has: " + "signatures" + " " + decision + " " + snapShotId + " " + consensusId + " " + Arrays.toString(writeSet.toArray())); } catch (final Exception ex) { Log.getLogger().error(ex); } finally { messageInput.close(); } } if (!decision.equals(signatureStorage.getDecision())) { Log.getLogger().error("Replica: " + id + " did receive a different decision of replica: " + context.getSender() + ". Might be corrupted."); return; } signatureStorage.addSignatures(context.getSender(), signature); Log.getLogger().info("Adding signature to signatureStorage, has: " + signatureStorage.getSignatures().size() + " is: " + signatureStorage.isProcessed() + " by: " + context.getSender()); if (signatureStorage.hasEnough()) { Log.getLogger().info("Sending update to slave signed by all members: " + snapShotId); if (signatureStorage.isProcessed()) { final Output messageOutput = new Output(100096); kryo.writeObject(messageOutput, Constants.UPDATE_SLAVE); kryo.writeObject(messageOutput, decision); kryo.writeObject(messageOutput, snapShotId); kryo.writeObject(messageOutput, signatureStorage); kryo.writeObject(messageOutput, consensusId); final DistributeMessageThread runnable = new DistributeMessageThread(messageOutput.getBuffer()); service.submit(runnable); messageOutput.close(); pool.release(kryo); lastSent = snapShotId; signatureStorage.setDistributed(); } } if (!signatureStorage.isDistributed()) { signatureStorageCache.put(snapShotId, signatureStorage); } } @Override public void putIntoWriteSet(final long currentSnapshot, final List<IOperation> localWriteSet) { super.putIntoWriteSet(currentSnapshot, localWriteSet); if (wrapper.getLocalCluster() != null) { wrapper.getLocalCluster().putIntoWriteSet(currentSnapshot, localWriteSet); } } /** * Invoke a message to the global cluster. * * @param input the input object. * @return the response. */ Output invokeGlobally(final Input input) { return new Output(proxy.invokeOrdered(input.getBuffer())); } /** * Closes the global cluster and his code. */ public void close() { super.terminate(); proxy.close(); } private class DistributeMessageThread implements Runnable { private final byte[] message; DistributeMessageThread(final byte[] message) { this.message = message; } @Override public void run() { updateSlave(message); } /** * Update the slave with a transaction. * * @param message the message to propagate. */ private void updateSlave(final byte[] message) { if (wrapper.getLocalCluster() != null) { Log.getLogger().info("Notifying local cluster!"); wrapper.getLocalCluster().propagateUpdate(message); } } } private class GlobalMessageThread implements Runnable { private final byte[] message; GlobalMessageThread(final byte[] message) { this.message = message; } @Override public void run() { update(message); } /** * Update the slave with a transaction. * * @param message the message to propagate. */ private void update(final byte[] message) { while (proxy.invokeUnordered(message) == null) { Log.getLogger().warn("Couldn't distribute the message in the global cluster"); } } } }
package mcjty.rftoolsdim.network; import mcjty.lib.network.PacketHandler; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.relauncher.Side; public class RFToolsDimMessages { public static SimpleNetworkWrapper INSTANCE; public static void registerNetworkMessages(SimpleNetworkWrapper net) { INSTANCE = net; // Server side net.registerMessage(PacketGetDimensionEnergy.Handler.class, PacketGetDimensionEnergy.class, PacketHandler.nextID(), Side.SERVER); // Client side net.registerMessage(PacketRegisterDimensions.Handler.class, PacketRegisterDimensions.class, PacketHandler.nextID(), Side.CLIENT); net.registerMessage(PacketReturnEnergy.Handler.class, PacketReturnEnergy.class, PacketHandler.nextID(), Side.CLIENT); net.registerMessage(PacketSyncDimensionInfo.Handler.class, PacketSyncDimensionInfo.class, PacketHandler.nextID(), Side.CLIENT); net.registerMessage(PacketSyncRules.Handler.class, PacketSyncRules.class, PacketHandler.nextID(), Side.CLIENT); } }
package me.corsin.javatools.reflect; // Project : Ever WebService // Package : com.ever.wsframework.utils // ReflectionUtils.java // Author : Simon CORSIN <simoncorsin@gmail.com> import me.corsin.javatools.misc.Pair; import org.apache.commons.lang3.ClassUtils; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.util.ArrayList; import java.util.List; public class ReflectionUtils { // VARIABLES // CONSTRUCTORS // METHODS public static Object newInstance(String className, Object ... parameters) { try { Class<?> objClass = Class.forName(className); Constructor<?> constructor = getConstructor(objClass, parameters); if (constructor != null) { return constructor.newInstance(parameters); } } catch (Exception e) { } return null; } public static boolean setField(Object object, Field field, Object value) { return setField(object, field.getName(), value); } public static boolean setPublicField(Object object, String fieldName, Object value) { Class<?> objectClass = object.getClass(); Field field; try { field = objectClass.getField(fieldName); field.set(object, value); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /* * Set a field using reflection */ public static boolean setField(Object object, String fieldName, Object value) { char c = fieldName.charAt(0); if (c >= 'a' && c <= 'z') { c -= 'a' - 'A'; fieldName = c + fieldName.substring(1); } String methodName = "set" + fieldName; Class<?>[] returnType = new Class<?>[1]; Class<?> objectClass = object.getClass(); Method getMethod = getMethod(objectClass, "get" + fieldName); if (getMethod == null) { getMethod = getMethod(objectClass, "is" + fieldName); } if (getMethod == null) { return false; } returnType[0] = getMethod.getReturnType(); return silentInvoke(object, methodName, returnType, value); } public static Object getField(Object object, String fieldName) { String propertyName = fieldName; char c = fieldName.charAt(0); if (c >= 'a' && c <= 'z') { c -= 'a' - 'A'; fieldName = c + fieldName.substring(1); } Class<?> objectClass = object.getClass(); Method getMethod = getMethod(objectClass, "get" + fieldName); if (getMethod == null) { getMethod = getMethod(objectClass, "is" + fieldName); } if (getMethod == null) { getMethod = getMethod(objectClass, propertyName); } if (getMethod == null) { throw new RuntimeException("No getter found for property " + propertyName + " on class " + objectClass.getSimpleName()); } return invoke(object, getMethod); } public static Method getMethod(Class<?> aClass, String methodName, Class<?> ... args) { try { return aClass.getMethod(methodName, args); } catch (Exception e) { return null; } } public static Constructor<?> getConstructor(Class<?> cls, Object ... parameters) { Constructor<?> constructor = null; for (Constructor<?> classMethod : cls.getConstructors()) { Class<?>[] parametersType = classMethod.getParameterTypes(); boolean match = false; if (parametersType.length == parameters.length) { match = true; for (int i = 0, length = parametersType.length; i < length; i++) { if (parameters[i] != null) { if (!parametersType[i].isAssignableFrom(parameters[i].getClass())) { match = false; break; } } } } if (match) { constructor = classMethod; break; } } return constructor; } public static Method getMethodThatMatchesParameters(Class<?> cls, String methodName, Object ... parameters) { Method method = null; for (Method classMethod : cls.getMethods()) { if (classMethod.getName().equals(methodName)) { Class<?>[] parametersType = classMethod.getParameterTypes(); boolean match = false; if (parametersType.length == parameters.length) { match = true; for (int i = 0, length = parametersType.length; i < length; i++) { if (parameters[i] != null) { Class<?> parameterClass = parameters[i].getClass(); Class<?> methodParameterClass = parametersType[i]; if (!ClassUtils.isAssignable(parameterClass, methodParameterClass, true)) { match = false; break; } } } } if (match) { method = classMethod; break; } } } return method; } /** * Silently invoke the specified methodName using reflection. * @param object * @param methodName * @param parameters * @return true if the invoke was successful */ public static Object invoke(Object object, String methodName, Object ... parameters) { Method method = getMethodThatMatchesParameters(object.getClass(), methodName, parameters); if (method != null) { try { return method.invoke(object, parameters); } catch (IllegalAccessException e) { throw new RuntimeException("Unable to invoke method", e); } catch (IllegalArgumentException e) { throw new RuntimeException("Unable to invoke method", e); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException)e.getCause(); } throw new RuntimeException(e.getCause()); } } else { throw new RuntimeException("No method that matches [" + methodName + "] for class " + object.getClass().getSimpleName()); } } public static boolean silentInvoke(Object object, String methodName, Class<?>[] parameterTypes, Object ... parameters) { try { Method method = object.getClass().getMethod(methodName, parameterTypes); method.invoke(object, parameters); return true; } catch (Exception e) { return false; } } public static Object invoke(Object object, Method method, Object ... parameters) { try { return method.invoke(object, parameters); } catch (Exception e) { return null; } } @SuppressWarnings("unchecked") public static <T extends Annotation> Pair<Method, T>[] getMethodsWithAnnotation(Class<?> cls, Class<T> annotationCls) { List<Pair<Method, T>> methods = new ArrayList<Pair<Method, T>>(); for (Method method : cls.getMethods()) { T annotation = method.getAnnotation(annotationCls); if (annotation != null) { methods.add(new Pair<Method, T>(method, annotation)); } } return methods.toArray(new Pair[methods.size()]); } public static Class<?> getGenericTypeParameter(Class<?> aClass, Class<?> genericClass, int index) { List<Class<?>> classes = new ArrayList<>(); Class<?> currentCls = aClass; while (currentCls != null && currentCls != genericClass) { classes.add(currentCls); currentCls = currentCls.getSuperclass(); } Class<?> managedClass = null; for (int i = classes.size() - 1; i >= 0 && managedClass == null; i Class<?> cls = classes.get(i); if (cls.getGenericSuperclass() instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType)cls.getGenericSuperclass(); if (type.getActualTypeArguments().length > index) { Type typeArgument = type.getActualTypeArguments()[index]; if (typeArgument instanceof Class) { managedClass = (Class<?>)typeArgument; } } } } return managedClass; } // GETTERS/SETTERS }
package net.aeronica.libs.mml.core; import java.util.ArrayList; import java.util.List; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTreeProperty; import net.aeronica.libs.mml.core.MMLParser.AnoteContext; import net.aeronica.libs.mml.core.MMLParser.BandContext; import net.aeronica.libs.mml.core.MMLParser.InstContext; import net.aeronica.libs.mml.core.MMLParser.LenContext; /** * Transforms MML into a set of data structures that can be used to generate * MIDI, or other formats. * * @author Paul Boese * */ public abstract class MMLTransformBase extends MMLBaseListener { StateInst instState; StatePart partState; /** annotate parse tree for tied note processing */ ParseTreeProperty<Integer> midiNotes = new ParseTreeProperty<Integer>(); ParseTreeProperty<Long> noteRestLengths = new ParseTreeProperty<Long>(); ParseTreeProperty<Integer> mmlVolumes = new ParseTreeProperty<Integer>(); ParseTreeProperty<Long> startTicks = new ParseTreeProperty<Long>(); Integer getMidiNote(ParserRuleContext ctx) {return ctx != null ? midiNotes.get(ctx) : null;} void saveMidiNote(ParserRuleContext ctx, int midiNote) {midiNotes.put(ctx, midiNote);} long getNoteRestLength(ParserRuleContext ctx) {return noteRestLengths.get(ctx);}; void saveNoteRestLength(ParserRuleContext ctx, long length) {noteRestLengths.put(ctx, length);} long getStartTicks(ParserRuleContext ctx) {return startTicks.get(ctx);} void saveStartTicks(ParserRuleContext ctx, long length) {startTicks.put(ctx, length);} int getMMLVolume(ParserRuleContext ctx) {return mmlVolumes.get(ctx);} void saveMMLVolume(ParserRuleContext ctx, int volume) {mmlVolumes.put(ctx, volume);} /** MObject - store the parse results for later conversion to the desired format */ List<MObject> mObject = new ArrayList<MObject>(); void addMObject(MObject mmo) {mObject.add(mmo);} MObject getMObject(int index) {return mObject.get(index);} public MMLTransformBase(float fakeVolume) { partState = new StatePart(); instState = new StateInst(); } /** * <code> * long durationTicks(int mmlNoteLength, boolean dottedLEN) {<br> * <blockquote>double ppq = 480.0d;<br> * double dot = dottedLEN ? 15.0d : 10.0d;<br> * return (long) (((4.0d / (double) mmlNoteLength) * <br> * (dot) / 10.0d) * ppq);</blockquote> * }</blockquote><br> * </code><br> * * @param mmlNoteLength * @param dottedLEN * @return */ public abstract long durationTicks(int mmlNoteLength, boolean dottedLEN); /** * * <code> void processMObjects(List &lt;IMObjects&gt; mObjects) {<br> * <blockquote>IMObjects.Type type;<br> * <blockquote> for(int i=0; i < mmlObjects.size(); i++) {<br> * <blockquote> System.out.println(getMObject(i));<br> * switch (getMMLObject(i).getType()) {<br> * case INST_BEGIN: {<br> * <blockquote> MmlInstBegin mmo = (MmlInstBegin) getMObject(i);<br> * // Nothing to do in reality<br> * break;<br> * }<br> * </blockquote> case TEMPO: {<br> * <blockquote> MmlTempo mmo = (MmlTempo) getMObject(i);<br> * currentTempo = mmo.getTempo();<br> * tracks[0].add(createTempoMetaEvent(currentTempo,<br> * mmo.getTicksStart()+ticksOffset));<br> * break;<br> * }</blockquote></blockquote><br> * . . .<br> * </blockquote> }</blockquote><br> * * @param mObjects */ public abstract void processMObjects(List<MObject> mObject); @Override public void enterInst(InstContext ctx) { instState.init(); partState.init(); addMObject(new MObject.MObjectBuilder(MObject.Type.INST_BEGIN).build()); } @Override public void exitInst(InstContext ctx) { instState.collectDurationTicks(partState.getRunningTicks()); addMObject(new MObject.MObjectBuilder(MObject.Type.INST_END).cumulativeTicks(partState.getRunningTicks()).build()); } @Override public void enterPart(MMLParser.PartContext ctx) { instState.collectDurationTicks(partState.getRunningTicks()); addMObject(new MObject.MObjectBuilder(MObject.Type.PART).cumulativeTicks(partState.getRunningTicks()).build()); partState.init(); } @Override public void exitBand(BandContext ctx) { addMObject(new MObject.MObjectBuilder(MObject.Type.DONE).longestPartTicks(instState.getLongestDurationTicks()).build()); processMObjects(mObject); } @Override public void enterOctave(MMLParser.OctaveContext ctx) { if (ctx.OCTAVE() != null) { char c = (char) ctx.OCTAVE().getText().charAt(0); switch (c) { case '<': partState.downOctave(); break; case '>': partState.upOctave(); break; } } } @Override public void enterTied(MMLParser.TiedContext ctx) {partState.setTied(true);} @Override public void exitTied(MMLParser.TiedContext ctx) { partState.setTied(false); List<StructTiedNotes> tiedNotes = new ArrayList<StructTiedNotes>(); StructTiedNotes tiedNote = null; boolean isTied = false; long lengthTicks = 0; int noteLeft = 0; int noteRight = 0; AnoteContext ctxL = null; AnoteContext ctxR = null; List<AnoteContext> listAnotes = ctx.anote(); int count = listAnotes.size(); // LEFT for (int i = 1; i < count; i++) { ctxL = ctx.anote(i - 1); ctxR = ctx.anote(i); noteLeft = getMidiNote(ctxL); noteRight = getMidiNote(ctxR); // Initial LEFT if (!isTied) { tiedNote = new StructTiedNotes(); lengthTicks = 0; tiedNote.volume = getMMLVolume(ctxL); tiedNote.startingTicks = getStartTicks(ctxL); tiedNote.midiNote = noteLeft; } if (noteLeft == noteRight) { // sum LEFTS lengthTicks += getNoteRestLength(ctxL); isTied = true; } else { lengthTicks += getNoteRestLength(ctxL); tiedNote.lengthTicks = lengthTicks; tiedNote.volume = getMMLVolume(ctxL); tiedNotes.add(tiedNote); addMObject(new MObject.MObjectBuilder(MObject.Type.NOTE) .midiNote(tiedNote.midiNote) .startingTicks(tiedNote.startingTicks) .lengthTicks(lengthTicks) .volume(tiedNote.volume) .text(ctxL.getText()) .build()); isTied = false; } } // LAST RIGHT if (isTied) { lengthTicks += getNoteRestLength(ctxR); tiedNote.lengthTicks = lengthTicks; tiedNotes.add(tiedNote); addMObject(new MObject.MObjectBuilder(MObject.Type.NOTE) .midiNote(tiedNote.midiNote) .startingTicks(tiedNote.startingTicks) .lengthTicks(lengthTicks) .volume(tiedNote.volume) .text(ctx.getText()) .build()); } else { // LAST LONELY RIGHT NOTE tiedNote = new StructTiedNotes(); tiedNote.startingTicks = getStartTicks(ctxR); lengthTicks = getNoteRestLength(ctxR); tiedNote.volume = getMMLVolume(ctxR); tiedNote.midiNote = noteRight; tiedNote.lengthTicks = lengthTicks; tiedNotes.add(tiedNote); addMObject(new MObject.MObjectBuilder(MObject.Type.NOTE) .midiNote(tiedNote.midiNote) .startingTicks(tiedNote.startingTicks) .lengthTicks(lengthTicks) .volume(tiedNote.volume) .text(ctxR.getText()) .build()); } } @Override public void enterNote(MMLParser.NoteContext ctx) { int mmlDuration = partState.getMMLLength(); int volume = partState.getVolume(); long startingTicks = partState.getRunningTicks(); boolean dot = partState.isDotted(); boolean tied = partState.isTied(); int rawNote = Integer.valueOf(ctx.NOTE().getText().toUpperCase().charAt(0)); int midiNote = MMLUtil.getMIDINote(rawNote, partState.getOctave()); if (ctx.ACC() != null) { char c = (char) ctx.ACC().getText().charAt(0); switch (c) { case '+': case ' midiNote++; break; case '-': midiNote break; } } if (ctx.INT() != null) { mmlDuration = Integer.valueOf(ctx.INT().getText()); dot = false; } if (!ctx.DOT().isEmpty()) { dot = true; } long length = durationTicks(mmlDuration, dot); if (!tied) { addMObject(new MObject.MObjectBuilder(MObject.Type.NOTE) .midiNote(midiNote) .startingTicks(startingTicks) .lengthTicks(length) .volume(volume) .text(ctx.getText()) .build()); } partState.accumulateTicks(length); /** annotate parse tree for tied note processing */ saveStartTicks(ctx.getParent(), startingTicks); saveNoteRestLength(ctx.getParent(), length); saveMidiNote(ctx.getParent(), midiNote); saveMMLVolume(ctx.getParent(), volume); } @Override public void enterMidi(MMLParser.MidiContext ctx) { int mmlLength = partState.getMMLLength(); int volume = partState.getVolume(); long startingTicks = partState.getRunningTicks(); boolean dot = partState.isDotted(); boolean tied = partState.isTied(); int midiNote = 0; if (ctx.INT() != null) { // XXX: "n#" format is not played correctly. One octave too low. CF Issue #6. Add 12 to fix. midiNote = Integer.valueOf(ctx.INT().getText()) + 12; } long lengthTicks = durationTicks(mmlLength, dot); if (!tied) { addMObject(new MObject.MObjectBuilder(MObject.Type.NOTE) .midiNote(midiNote) .startingTicks(startingTicks) .lengthTicks(lengthTicks) .volume(volume) .text(ctx.getText()) .build()); } partState.accumulateTicks(lengthTicks); /** annotate parse tree for tied note processing */ saveStartTicks(ctx.getParent(), startingTicks); saveNoteRestLength(ctx.getParent(), lengthTicks); saveMidiNote(ctx.getParent(), midiNote); saveMMLVolume(ctx.getParent(), volume); } @Override public void enterRest(MMLParser.RestContext ctx) { int mmlLength = partState.getMMLLength(); long startingTicks = partState.getRunningTicks(); boolean dot = partState.isDotted(); if (ctx.INT() != null) { mmlLength = Integer.valueOf(ctx.INT().getText()); dot = false; } if (!ctx.DOT().isEmpty()) { dot = true; } long lengthTicks = durationTicks(mmlLength, dot); partState.accumulateTicks(lengthTicks); saveStartTicks(ctx.getParent(), startingTicks); saveNoteRestLength(ctx, lengthTicks); saveMMLVolume(ctx, partState.getVolume()); addMObject(new MObject.MObjectBuilder(MObject.Type.REST) .startingTicks(startingTicks) .lengthTicks(lengthTicks) .build()); } @Override public void enterCmd(MMLParser.CmdContext ctx) { if (ctx.INT() == null) return; char c = (char) ctx.CMD().getText().toUpperCase().charAt(0); int value = Integer.valueOf(ctx.INT().getText()); switch (c) { case 'I': { instState.setInstrument(value); addMObject(new MObject.MObjectBuilder(MObject.Type.INST) .instrument(instState.getInstrument()) .startingTicks(partState.getRunningTicks()) .build()); } break; case 'O': partState.setOctave(value); break; case 'T': { instState.setTempo(value); addMObject(new MObject.MObjectBuilder(MObject.Type.TEMPO) .tempo(instState.getTempo()) .startingTicks(partState.getRunningTicks()) .build()); } break; case 'V': partState.setVolume(value); break; } } @Override public void enterLen(LenContext ctx) { if (ctx.INT() == null) return; boolean dotted = false; // char c = (char) ctx.LEN().getText().toUpperCase().charAt(0); int value = Integer.valueOf(ctx.INT().getText()); if (!ctx.DOT().isEmpty()) { dotted = true; } partState.setMMLLength(value, dotted); } }