answer
stringlengths
17
10.2M
package io.quarkus.creator.phase.augment; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.nio.file.CopyOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; 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 java.util.concurrent.Callable; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.BiFunction; import org.eclipse.microprofile.config.Config; import org.jboss.logging.Logger; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import io.quarkus.bootstrap.BootstrapDependencyProcessingException; import io.quarkus.bootstrap.model.AppDependency; import io.quarkus.bootstrap.resolver.AppModelResolver; import io.quarkus.bootstrap.util.IoUtils; import io.quarkus.bootstrap.util.ZipUtils; import io.quarkus.builder.BuildResult; import io.quarkus.creator.AppCreationPhase; import io.quarkus.creator.AppCreator; import io.quarkus.creator.AppCreatorException; import io.quarkus.creator.config.reader.MappedPropertiesHandler; import io.quarkus.creator.config.reader.PropertiesHandler; import io.quarkus.creator.outcome.OutcomeProviderRegistration; import io.quarkus.creator.phase.curate.CurateOutcome; import io.quarkus.deployment.ApplicationArchive; import io.quarkus.deployment.ApplicationInfoUtil; import io.quarkus.deployment.ClassOutput; import io.quarkus.deployment.QuarkusAugmentor; import io.quarkus.deployment.QuarkusClassWriter; import io.quarkus.deployment.builditem.ApplicationArchivesBuildItem; import io.quarkus.deployment.builditem.BytecodeTransformerBuildItem; import io.quarkus.deployment.builditem.MainClassBuildItem; import io.quarkus.deployment.builditem.substrate.SubstrateOutputBuildItem; import io.quarkus.gizmo.NullWriter; import io.smallrye.config.PropertiesConfigSource; import io.smallrye.config.SmallRyeConfigProviderResolver; /** * This phase consumes {@link io.quarkus.creator.phase.curate.CurateOutcome} and processes * user application and its dependency classes for phases that generate a runnable application. * * @author Alexey Loubyansky */ public class AugmentPhase implements AppCreationPhase<AugmentPhase>, AugmentOutcome { private static final Logger log = Logger.getLogger(AugmentPhase.class); private static final String APPLICATION_INFO_PROPERTIES = "application-info.properties"; private static final String META_INF = "META-INF"; private Path outputDir; private Path appClassesDir; private Path transformedClassesDir; private Path wiringClassesDir; private Path generatedSourcesDir; private Path configDir; private Map<Path, Set<String>> transformedClassesByJar; /** * Output directory for the outcome of this phase. * If not set by the user the work directory of the creator * will be used instead. * * @param outputDir output directory for this phase * @return this phase instance */ public AugmentPhase setOutputDir(Path outputDir) { this.outputDir = outputDir; return this; } /** * Directory containing application classes. If none is set by the user, * the creation process has to be initiated with an application JAR which * will be unpacked into classes directory in the creator's work directory. * * @param appClassesDir directory for application classes * @return this phase instance */ public AugmentPhase setAppClassesDir(Path appClassesDir) { this.appClassesDir = appClassesDir; return this; } /** * Directory containing transformed application classes. If none is set by * the user, transformed-classes directory will be created in the work * directory of the creator. * * @param transformedClassesDir directory for transformed application classes * @return this phase instance */ public AugmentPhase setTransformedClassesDir(Path transformedClassesDir) { this.transformedClassesDir = transformedClassesDir; return this; } /** * The directory for generated classes. If none is set by the user, * wiring-classes directory will be created in the work directory of the creator. * * @param wiringClassesDir directory for generated classes * @return this phase instance */ public AugmentPhase setWiringClassesDir(Path wiringClassesDir) { this.wiringClassesDir = wiringClassesDir; return this; } /** * Directory containing the configuration files. * * @param configDir directory the configuration files (application.properties) * @return this phase instance */ public AugmentPhase setConfigDir(Path configDir) { this.configDir = configDir; return this; } /** * The directory for generated source files. If none is set, then * no source file generation will be done. * * @param generatedSourcesDir the directory for generated source files * @return this phase instance */ public AugmentPhase setGeneratedSourcesDir(final Path generatedSourcesDir) { this.generatedSourcesDir = generatedSourcesDir; return this; } @Override public Path getAppClassesDir() { return appClassesDir; } @Override public Path getTransformedClassesDir() { return transformedClassesDir; } @Override public Path getWiringClassesDir() { return wiringClassesDir; } @Override public Path getConfigDir() { return configDir; } @Override public Map<Path, Set<String>> getTransformedClassesByJar() { return transformedClassesByJar; } @Override public void register(OutcomeProviderRegistration registration) throws AppCreatorException { registration.provides(AugmentOutcome.class); } @Override public void provideOutcome(AppCreator ctx) throws AppCreatorException { final CurateOutcome appState = ctx.resolveOutcome(CurateOutcome.class); outputDir = outputDir == null ? ctx.getWorkPath() : IoUtils.mkdirs(outputDir); if (appClassesDir == null) { appClassesDir = outputDir.resolve("classes"); Path appJar = appState.getAppArtifact().getPath(); try { ZipUtils.unzip(appJar, appClassesDir); } catch (IOException e) { throw new AppCreatorException("Failed to unzip " + appJar, e); } final Path metaInf = appClassesDir.resolve(META_INF); IoUtils.recursiveDelete(metaInf.resolve("maven")); IoUtils.recursiveDelete(metaInf.resolve("INDEX.LIST")); IoUtils.recursiveDelete(metaInf.resolve("MANIFEST.MF")); IoUtils.recursiveDelete(metaInf.resolve(APPLICATION_INFO_PROPERTIES)); } ApplicationInfoUtil.writeApplicationInfoProperties(appState.getAppArtifact(), appClassesDir); //lets default to appClassesDir for now if (configDir == null) configDir = appClassesDir; else { //if we use gradle we copy the configDir contents to appClassesDir try { if (!Files.isSameFile(configDir, appClassesDir)) { Files.walkFileTree(configDir, new CopyDirVisitor(configDir, appClassesDir, StandardCopyOption.REPLACE_EXISTING)); } } catch (IOException e) { throw new AppCreatorException("Failed while copying files from " + configDir + " to " + appClassesDir, e); } } transformedClassesDir = IoUtils .mkdirs(transformedClassesDir == null ? outputDir.resolve("transformed-classes") : transformedClassesDir); wiringClassesDir = IoUtils.mkdirs(wiringClassesDir == null ? outputDir.resolve("wiring-classes") : wiringClassesDir); doProcess(appState); ctx.pushOutcome(AugmentOutcome.class, this); } private void doProcess(CurateOutcome appState) throws AppCreatorException { //first lets look for some config, as it is not on the current class path //and we need to load it to run the build process Path config = configDir.resolve("application.properties"); if (Files.exists(config)) { try { Config built = SmallRyeConfigProviderResolver.instance().getBuilder() .addDefaultSources() .addDiscoveredConverters() .addDiscoveredSources() .withSources(new PropertiesConfigSource(config.toUri().toURL())).build(); SmallRyeConfigProviderResolver.instance().registerConfig(built, Thread.currentThread().getContextClassLoader()); } catch (Exception e) { throw new RuntimeException(e); } } final AppModelResolver depResolver = appState.getArtifactResolver(); List<AppDependency> appDeps; try { appDeps = appState.getEffectiveModel().getAllDependencies(); } catch (BootstrapDependencyProcessingException e) { throw new AppCreatorException("Failed to resolve application build classpath", e); } URLClassLoader runnerClassLoader = null; try { // we need to make sure all the deployment artifacts are on the class path final List<URL> cpUrls = new ArrayList<>(appDeps.size() + 1); cpUrls.add(appClassesDir.toUri().toURL()); for (AppDependency appDep : appDeps) { final Path resolvedDep = depResolver.resolve(appDep.getArtifact()); cpUrls.add(resolvedDep.toUri().toURL()); } runnerClassLoader = new URLClassLoader(cpUrls.toArray(new URL[cpUrls.size()]), getClass().getClassLoader()); final Path wiringClassesDirectory = wiringClassesDir; ClassOutput classOutput = new ClassOutput() { @Override public void writeClass(boolean applicationClass, String className, byte[] data) throws IOException { String location = className.replace('.', File.separatorChar); final Path p = wiringClassesDirectory.resolve(location + ".class"); Files.createDirectories(p.getParent()); try (OutputStream out = Files.newOutputStream(p)) { out.write(data); } } @Override public void writeResource(String name, byte[] data) throws IOException { final Path p = wiringClassesDirectory.resolve(name); Files.createDirectories(p.getParent()); try (OutputStream out = Files.newOutputStream(p)) { out.write(data); } } @Override public Writer writeSource(final String className) { String location = className.replace('.', '/'); final Path basePath = AugmentPhase.this.generatedSourcesDir; if (basePath == null) return NullWriter.INSTANCE; final Path path = basePath.resolve("gizmo").resolve(location + ".zig"); try { Files.createDirectories(path.getParent()); return Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException e) { throw new IllegalStateException("Failed to write source file", e); } } }; ClassLoader old = Thread.currentThread().getContextClassLoader(); BuildResult result; try { Thread.currentThread().setContextClassLoader(runnerClassLoader); QuarkusAugmentor.Builder builder = QuarkusAugmentor.builder(); builder.setRoot(appClassesDir); builder.setClassLoader(runnerClassLoader); builder.setOutput(classOutput); builder.addFinal(BytecodeTransformerBuildItem.class) .addFinal(ApplicationArchivesBuildItem.class) .addFinal(MainClassBuildItem.class) .addFinal(SubstrateOutputBuildItem.class); result = builder.build().run(); } finally { Thread.currentThread().setContextClassLoader(old); } final List<BytecodeTransformerBuildItem> bytecodeTransformerBuildItems = result .consumeMulti(BytecodeTransformerBuildItem.class); transformedClassesByJar = new HashMap<>(); if (!bytecodeTransformerBuildItems.isEmpty()) { ApplicationArchivesBuildItem appArchives = result.consume(ApplicationArchivesBuildItem.class); final Map<String, List<BiFunction<String, ClassVisitor, ClassVisitor>>> bytecodeTransformers = new HashMap<>( bytecodeTransformerBuildItems.size()); for (BytecodeTransformerBuildItem i : bytecodeTransformerBuildItems) { bytecodeTransformers.computeIfAbsent(i.getClassToTransform(), (h) -> new ArrayList<>()) .add(i.getVisitorFunction()); } // now copy all the contents to the runner jar // we also record if any additional archives needed transformation // when we copy these archives we will remove the problematic classes final ExecutorService executorPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); final ConcurrentLinkedDeque<Future<FutureEntry>> transformed = new ConcurrentLinkedDeque<>(); try { ClassLoader transformCl = runnerClassLoader; for (Map.Entry<String, List<BiFunction<String, ClassVisitor, ClassVisitor>>> entry : bytecodeTransformers .entrySet()) { String className = entry.getKey(); ApplicationArchive archive = appArchives.containingArchive(entry.getKey()); if (archive != null) { List<BiFunction<String, ClassVisitor, ClassVisitor>> visitors = entry.getValue(); String classFileName = className.replace(".", "/") + ".class"; Path path = archive.getChildPath(classFileName); transformedClassesByJar.computeIfAbsent(archive.getArchiveLocation(), (a) -> new HashSet<>()) .add(classFileName); transformed.add(executorPool.submit(new Callable<FutureEntry>() { @Override public FutureEntry call() throws Exception { ClassLoader old = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(transformCl); if (Files.size(path) > Integer.MAX_VALUE) { throw new RuntimeException( "Can't process class files larger than Integer.MAX_VALUE bytes"); } ClassReader cr = new ClassReader(Files.readAllBytes(path)); ClassWriter writer = new QuarkusClassWriter(cr, ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); ClassVisitor visitor = writer; for (BiFunction<String, ClassVisitor, ClassVisitor> i : visitors) { visitor = i.apply(className, visitor); } cr.accept(visitor, 0); return new FutureEntry(writer.toByteArray(), classFileName); } finally { Thread.currentThread().setContextClassLoader(old); } } })); } else { log.warnf("Cannot transform %s as it's containing application archive could not be found.", entry.getKey()); } } } finally { executorPool.shutdown(); } if (!transformed.isEmpty()) { for (Future<FutureEntry> i : transformed) { final FutureEntry res = i.get(); final Path classFile = transformedClassesDir.resolve(res.location); Files.createDirectories(classFile.getParent()); try (OutputStream out = Files.newOutputStream(classFile)) { IoUtils.copy(out, new ByteArrayInputStream(res.data)); } } } } } catch (Exception e) { throw new AppCreatorException("Failed to augment application classes", e); } finally { if (runnerClassLoader != null) { try { runnerClassLoader.close(); } catch (IOException e) { log.warn("Failed to close runner classloader", e); } } } } private static final class FutureEntry { final byte[] data; final String location; private FutureEntry(byte[] data, String location) { this.data = data; this.location = location; } } @Override public String getConfigPropertyName() { return "augment"; } @Override public PropertiesHandler<AugmentPhase> getPropertiesHandler() { return new MappedPropertiesHandler<AugmentPhase>() { @Override public AugmentPhase getTarget() { return AugmentPhase.this; } } .map("output", (AugmentPhase t, String value) -> t.setOutputDir(Paths.get(value))) .map("classes", (AugmentPhase t, String value) -> t.setAppClassesDir(Paths.get(value))) .map("transformed-classes", (AugmentPhase t, String value) -> t.setTransformedClassesDir(Paths.get(value))) .map("wiring-classes", (AugmentPhase t, String value) -> t.setWiringClassesDir(Paths.get(value))) .map("config", (AugmentPhase t, String value) -> t.setConfigDir(Paths.get(value))); } public static class CopyDirVisitor extends SimpleFileVisitor<Path> { private final Path fromPath; private final Path toPath; private final CopyOption copyOption; public CopyDirVisitor(Path fromPath, Path toPath, CopyOption copyOption) { this.fromPath = fromPath; this.toPath = toPath; this.copyOption = copyOption; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path targetPath = toPath.resolve(fromPath.relativize(dir)); if (!Files.exists(targetPath)) { Files.createDirectory(targetPath); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, toPath.resolve(fromPath.relativize(file)), copyOption); return FileVisitResult.CONTINUE; } } }
// SelectAll.java package imagej.core.plugins.display; import imagej.data.display.DataView; import imagej.data.display.ImageDisplay; import imagej.data.display.OverlayView; import imagej.ext.menu.MenuConstants; import imagej.ext.plugin.ImageJPlugin; import imagej.ext.plugin.Menu; import imagej.ext.plugin.Parameter; import imagej.ext.plugin.Plugin; /** * Selects all of the overlays linked to the given display. * * @author Lee Kamentsky */ @Plugin(menu = { @Menu(label = MenuConstants.EDIT_LABEL, weight = MenuConstants.EDIT_WEIGHT, mnemonic = MenuConstants.EDIT_MNEMONIC), @Menu(label = "Selection", mnemonic = 's'), @Menu(label = "Select All", mnemonic = 'a', accelerator = "control a", weight = 4) }, headless = true) public class SelectAll implements ImageJPlugin { @Parameter private ImageDisplay display; @Override public void run() { for (final DataView view : display) { if (view instanceof OverlayView) { view.setSelected(true); } } } public ImageDisplay getDisplay() { return display; } public void setDisplay(final ImageDisplay display) { this.display = display; } }
package us.kbase.auth; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.security.InvalidKeyException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; import java.security.SignatureException; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPublicKey; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMReader; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; /** * A fairly simple Auth service client for KBase, intended (at least initially) for use with GLAMM. * Usage: * * AuthUser user = AuthService.login(user, password); * if (AuthService.validateToken(user.getToken())) { * // There's a valid token! Return the valid user, or just the token, and move along. * } * * Thus, this provides code for a user to log in to KBase, retrieve a valid Auth token, and * optionally validate it. * * @author wjriehl */ public class AuthService { private static String AUTH_URL = "https: private static String AUTH_LOGIN_PATH = "/Sessions/Login"; /** * Logs in a user and returns an AuthUser object, which is more or less a POJO containing basic user attributes, * along with the generated AuthToken. * * @param user * @param pw * @return an AuthUser that has been successfully logged in. * @throws AuthException if the credentials are invalid, or if there is a problem communicating with the server. */ public static AuthUser login(String userName, String password) throws AuthException { // This is the data that will be POSTed to the service. // By default (not sure if we *really* need to change it), it fetches all the fields. try { String dataStr = "user_id=" + URLEncoder.encode(userName, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8") + "&cookie=1&fields=user_id,name,email,groups,kbase_sessionid,token,verified,opt_in,system_admin"; return fetchUser(dataStr); } catch (UnsupportedEncodingException e) { throw new RuntimeException("An unexpected URL encoding exception occurred: " + e.getLocalizedMessage()); } } /** * Given a token for a logged in user, returns the AuthUser object representing that user's profile. * * @param token * @return an AuthUser associated with the given token. * @throws AuthException if the token is malformed or invalid, or if an error occurs while communicating * with the server. */ public static AuthUser getUserFromToken(String token) throws AuthException { String dataStr = "token=" + token + "&fields=user_id,name,email,groups,kbase_sessionid,token,verified,opt_in,system_admin"; return fetchUser(dataStr); } /** * Given an AuthToken object for a logged in user, this returns the AuthUser object representing that user's * profile. * * @param token * @return an AuthUser associated with the given token. * @throws AuthException */ public static AuthUser getUserFromToken(AuthToken token) throws AuthException { String dataStr = "token=" + token.toString() + "&fields=user_id,name,email,groups,kbase_sessionid,token,verified,opt_in,system_admin"; return fetchUser(dataStr); } /** * Given a data str, describing URL-encoded fields for the auth server, this attempts to authenticate the user * with KBase servers. * * @param dataStr * @return an AuthUser that has been authenticated with KBase * @throws AuthException if the auth credentials are invalid or if the login URL is incorrect. */ private static AuthUser fetchUser(String dataStr) throws AuthException { // Start with a null user - if the mapper fails for some reason, we know it's // still null (and not uninitialized), and can throw a proper exception. AuthUser user = null; try { // Build the connection project and set it up. HttpsURLConnection conn = (HttpsURLConnection) new URL(AUTH_URL + AUTH_LOGIN_PATH).openConnection(); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(dataStr.getBytes().length)); conn.setRequestProperty("Content-Language", "en-US"); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // Write out the POST data. DataOutputStream writer = new DataOutputStream(conn.getOutputStream()); writer.writeBytes(dataStr); writer.flush(); writer.close(); // If we don't have a happy response code, throw an exception. int responseCode = conn.getResponseCode(); if (responseCode != 200) { conn.disconnect(); throw new AuthException("Login failed! Server responded with code " + responseCode + " " + conn.getResponseMessage()); } /** Encoding the HTTP response into JSON format */ BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); user = new ObjectMapper().readValue(br, AuthUser.class); br.close(); conn.disconnect(); } catch (UnsupportedEncodingException e) { throw new RuntimeException("An unexpected encoding exception occurred: " + e.getLocalizedMessage()); } catch (MalformedURLException e) { throw new AuthException("An exception occurred while connecting to the auth service URL: " + e.getLocalizedMessage()); } catch (IOException e) { throw new AuthException("An exception occurred while parsing authentication results: " + e.getLocalizedMessage()); } // In the end, return the user. if (user == null) { // if still null, throw an exception throw new AuthException("Unable to construct a user object from login results!"); } return user; } /** * Given a String representation of an auth token, this validates it against its source in Globus Online. * * @param tokenStr the token string retrieved from KBase * @return true if the token's valid, false otherwise * @throw AuthException if there is a problem parsing the token or the server response, or if the token's * verification URL is invalid. */ public static boolean validateToken(String tokenStr) throws AuthException { try { AuthToken token = new AuthToken(tokenStr); return validateToken(token); } catch (IOException e) { throw new AuthException("An error occurred while parsing your token: " + e.getLocalizedMessage()); } } /** * This validates a KBase Auth token, and returns true or if valid or false if not. * * It works in a few steps: * 1. Check the token format, throw IOException if the format's wrong. * 2. Extract the 'token' part and the signature. * 3. Get the public key from the 'SigningSubject' part of the token. * 4. Do the sha1-RSA comparison. * 5. Return the result of the comparison * * Most of this is taken from KBaseAuthValidateToken.java, written by Shuchu Han, as part of the Persistent Store code. * So, thanks! * * @param token * @return true if the token's valid, false otherwise * @throws AuthException if there is a parsing problem with either the token or the server response, or if the token's * verification URL is invalid. */ public static boolean validateToken(AuthToken token) throws AuthException { boolean result = false; try { /** now HTTPS the SigningSubject of input Token */ URL validationUrl = new URL(token.getSigningSubject()); // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; // Ignore differences between given hostname and certificate hostname HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hv); /** make the request to Authentication server */ HttpsURLConnection conn = (HttpsURLConnection) validationUrl.openConnection(); InputStream in = conn.getInputStream(); /** Encoding the HTTP response into JSON format */ BufferedReader br = new BufferedReader(new InputStreamReader(in)); ObjectMapper m = new ObjectMapper(); JsonNode jn = m.readTree(br); JsonNode jd = jn.get("pubkey"); in.close(); conn.disconnect(); /** now get the public key and do the verify */ Security.addProvider(new BouncyCastleProvider()); PEMReader pemReader = new PEMReader(new StringReader(jd.getTextValue().replace("\\n","\n"))); RSAPublicKey pubKey = (RSAPublicKey) pemReader.readObject(); pemReader.close(); Signature s = Signature.getInstance("SHA1withRSA"); s.initVerify(pubKey); /** update the data * * SHA-1 (and all other hashing algorithms) return binary data. That means that (in Java) they produce a byte[]. * That byte array does not represent any specific characters, which means you can't simply turn it into a String * like you did.If you need a String, then you have to format that byte[] in a way that can be represented as * a String (otherwise, just keep the byte[] around).Two common ways of representing arbitrary byte[] as printable * characters are BASE64 or simple hex-Strings (i.e. representing each byte by two hexadecimal digits). * It looks like you're trying to produce a hex-String. There's also another pitfall: if you want to get the SHA-1 * of a Java String, then you need to convert that String to a byte[] first (as the input of SHA-1 is a byte[] as well). * If you simply use myString.getBytes() as you showed, then it will use the platform default encoding and as such * will be dependent on the environment you run it in (for example it could return different data based on the * language/locale setting of your OS).A better solution is to specify the encoding to use for the String-to-byte[] * conversion like this: myString.getBytes("UTF-8"). Choosing UTF-8 (or another encoding that can represent every * unicode character) is the safest choice here. */ byte[] sig_data_byte = token.getTokenData().getBytes("UTF-8"); s.update(sig_data_byte); /** * The equivalent of Perl 's pack "H*", $vartoconvert in Java is : * javax.xml.bind.DatatypeConverter.parseHexBinary(hexadecimalString);. * For more information on this, I think it is recommended to read * DatatypeConverter class' reference from JavaDocs. */ byte[] sig_byte = javax.xml.bind.DatatypeConverter.parseHexBinary(token.getSignature()); /** verification of signature*/ result = s.verify(sig_byte); } catch (SignatureException e) { throw new RuntimeException("An unexpected error occurred while verifying the auth token"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("An unexpected error occurred while verifying the auth token: " + e.getLocalizedMessage()); } catch (MalformedURLException e) { throw new AuthException("An error occurred while using the token's verification URL: " + e.getLocalizedMessage()); } catch (IOException e) { throw new AuthException("An error occurred while retrieving the token signature"); } catch (KeyManagementException e) { throw new RuntimeException("An unexpected error occurred while initializing the SSL trust mechanism."); } catch (InvalidKeyException e) { throw new AuthException("An error occurred while parsing the public key for the token."); } return result; } /** * Disables SSL certificate validation. * * Once upon a time, we had issues getting the KBase SSL certificate renewed. This isn't a big deal for a web * user - just click through the "Hey, this isn't valid!" page. But going over https would make the Java * HttpsURLConnection have a tizzy fit. * * Running this method tells the HttpsURLConnection to ignore any certificate validation errors in any subsequent * calls. So if the certificate has errors in the future, run this method before doing any service calls. * * e.g. * <code> * AuthService.disableCertificateValidation(); * AuthService.login(<<credentials>>); * </code> */ @SuppressWarnings("unused") private static void disableCertificateValidation() { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hv); } catch (Exception e) {} } /** * Returns the current URL to which the service is pointing. * @return the current URL for the service */ public static String getServiceUrl() { return AUTH_URL; } public static void setServiceUrl(String url) { if (url != null && url.length() > 0 && url.startsWith("http")) AUTH_URL = url; } // Main for testing. // TODO - make some JUnit tests. public static void main(String[] args) { try { AuthUser user = AuthService.login("kbasetest", "@Suite525"); boolean validated = AuthService.validateToken(user.getToken()); System.out.println(user.toString() + "\nValidated token? " + validated); AuthUser user2 = AuthService.getUserFromToken(user.getToken().toString()); System.out.println(user2.toString()); System.out.println(user2.getToken().getTokenData()); System.out.println(user2.getToken().isExpired()); } catch (AuthException e) { // handle IOException System.out.println(e.getLocalizedMessage()); } } }
package com.github.weisj.darklaf.ui.splitpane; import com.github.weisj.darklaf.decorators.LayoutManagerDelegate; import javax.swing.*; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicSplitPaneDivider; import javax.swing.plaf.basic.BasicSplitPaneUI; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * @author Jannis Weis */ public class DarkSplitPaneUI extends BasicSplitPaneUI implements PropertyChangeListener { private static final int DIVIDER_DRAG_SIZE = 10; private static final int DIVIDER_DRAG_OFFSET = 5; private Style style; private Color dividerLine; protected DarkSplitPaneUI(final Style style) { this.style = style; } public static ComponentUI createUI(final JComponent c) { return new DarkSplitPaneUI(Style.get(UIManager.getString("SplitPane.defaultDividerStyle"))); } @Override public void installUI(final JComponent c) { super.installUI(c); splitPane.setContinuousLayout(true); splitPane.setComponentZOrder(getDivider(), 0); } @Override protected void installDefaults() { super.installDefaults(); dividerLine = UIManager.getColor("SplitPane.dividerLineColor"); } @Override protected void installListeners() { super.installListeners(); splitPane.addPropertyChangeListener(this); } @Override public void uninstallUI(final JComponent c) { if (splitPane.getLayout() instanceof LayoutManagerDelegate) { splitPane.setLayout(null); } super.uninstallUI(c); divider = null; } @Override protected void uninstallListeners() { super.uninstallListeners(); splitPane.removePropertyChangeListener(this); } @Override public BasicSplitPaneDivider createDefaultDivider() { if (style == Style.GRIP) { return new DarkSplitPaneDivider(this); } else { return new ThinDivider(this); } } @Override protected void resetLayoutManager() { super.resetLayoutManager(); splitPane.setLayout(new LayoutManagerDelegate(splitPane.getLayout()) { @Override public void layoutContainer(final Container parent) { super.layoutContainer(parent); if (style != Style.GRIP) { Rectangle bounds = getDivider().getBounds(); if (getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { bounds.x -= DIVIDER_DRAG_OFFSET; bounds.width = DIVIDER_DRAG_SIZE; } else { bounds.y -= DIVIDER_DRAG_OFFSET; bounds.height = DIVIDER_DRAG_SIZE; } getDivider().setBounds(bounds); } } }); } @Override public void propertyChange(final PropertyChangeEvent evt) { String key = evt.getPropertyName(); if ("JSplitPane.style".equals(key)) { Object val = evt.getNewValue(); Style oldStyle = style; if (Style.INVISIBLE.name.equals(val)) { style = Style.INVISIBLE; } else if (Style.LINE.name.equals(val)) { style = Style.LINE; } else { style = Style.GRIP; } if (oldStyle != style) { if (style == Style.GRIP || oldStyle == Style.GRIP) { splitPane.setUI(new DarkSplitPaneUI(style)); } else { splitPane.doLayout(); } } } else if ("orientation".equals(key)) { splitPane.doLayout(); } } protected Color getDividerLineColor() { return dividerLine; } private enum Style { GRIP("grip"), LINE("line"), INVISIBLE("invisible"); final private String name; Style(final String name) { this.name = name; } static Style get(final String style) { try { return valueOf(style.toLowerCase()); } catch (IllegalArgumentException e) { return GRIP; } } } private final class ThinDivider extends BasicSplitPaneDivider { private ThinDivider(final BasicSplitPaneUI ui) { super(ui); } @Override public int getDividerSize() { return style == Style.LINE ? 1 : 0; } @Override public void paint(final Graphics g) { if (style == Style.LINE) { g.setColor(getDividerLineColor()); if (orientation == JSplitPane.HORIZONTAL_SPLIT) { g.drawLine(DIVIDER_DRAG_OFFSET, 0, DIVIDER_DRAG_OFFSET, getHeight()); } else { g.drawLine(0, DIVIDER_DRAG_OFFSET, getWidth(), DIVIDER_DRAG_OFFSET); } } } @Override public boolean contains(final Point p) { if (!isEnabled()) return false; return super.contains(p); } @Override protected void dragDividerTo(final int location) { super.dragDividerTo(location + DIVIDER_DRAG_OFFSET); } @Override protected void finishDraggingTo(final int location) { super.finishDraggingTo(location + DIVIDER_DRAG_OFFSET); } } }
package jolie.net; import java.io.IOException; import java.net.URISyntaxException; import jolie.ExecutionThread; import jolie.Interpreter; import jolie.SessionListener; import jolie.SessionThread; import jolie.State; import jolie.lang.Constants; import jolie.lang.Constants.OperationType; import jolie.lang.parse.ast.types.TypeDefinition; import jolie.net.ports.OutputPort; import jolie.process.OneWayProcess; import jolie.runtime.FaultException; import jolie.runtime.VariablePath; import jolie.process.Process; import jolie.process.RequestResponseProcess; import jolie.process.SequentialProcess; import jolie.runtime.OneWayOperation; import jolie.runtime.RequestResponseOperation; import jolie.runtime.typing.OneWayTypeDescription; import jolie.runtime.typing.RequestResponseTypeDescription; import jolie.runtime.typing.TypeCheckingException; /** * An AggregatedOperation instance contains information about an operation that is aggregated by an input port. * @author Fabrizio Montesi */ public abstract class AggregatedOperation { private static class CourierOneWayAggregatedOperation extends AggregatedOperation { private final OneWayOperation operation; private final Process courierProcess; private final VariablePath inputVariablePath; public CourierOneWayAggregatedOperation( OneWayOperation operation, VariablePath inputVariablePath, Process courierProcess ) { super( operation.id() ); this.operation = operation; this.inputVariablePath = inputVariablePath; this.courierProcess = courierProcess; } public OperationType type() { return OperationType.ONE_WAY; } public void runAggregationBehaviour( final CommMessage requestMessage, final CommChannel channel ) throws IOException, URISyntaxException { Interpreter interpreter = Interpreter.getInstance(); try { operation.requestType().check( requestMessage.value() ); ExecutionThread initThread = Interpreter.getInstance().initThread(); try { initThread.join(); } catch( InterruptedException e ) { throw new IOException( e ); } State state = initThread.state().clone(); Process p = new SequentialProcess( new Process[] { new OneWayProcess( operation, inputVariablePath ).receiveMessage( new SessionMessage( requestMessage, channel ), state ), courierProcess }); SessionThread t = new SessionThread( p, state, initThread ); final FaultException[] f = new FaultException[1]; f[0] = null; t.addSessionListener( new SessionListener() { public void onSessionExecuted( SessionThread session ) {} public void onSessionError( SessionThread session, FaultException fault ) { // We need to send the acknowledgement if ( fault.faultName().equals( "CorrelationError" ) || fault.faultName().equals( "IOException" ) || fault.faultName().equals( "TypeMismatch" ) ) { synchronized( f ) { f[0] = fault; } } else { Interpreter.getInstance().logSevere( "Courier session for operation " + operation.id() + " has thrown fault " + fault.faultName() + ", which cannot be forwarded to the caller. Forwarding IOException." ); synchronized( f ) { f[0] = new FaultException( jolie.lang.Constants.IO_EXCEPTION_FAULT_NAME, fault.faultName() ); } } } } ); t.start(); try { t.join(); } catch( InterruptedException e ) {} synchronized( f ) { if ( f[0] == null ) { // We need to send the acknowledgement channel.send( CommMessage.createEmptyResponse( requestMessage ) ); } else { channel.send( CommMessage.createFaultResponse( requestMessage, f[0] ) ); } } } catch( TypeCheckingException e ) { interpreter.logWarning( "TypeMismatch for received message (input operation " + operation.id() + "): " + e.getMessage() ); try { channel.send( CommMessage.createFaultResponse( requestMessage, new FaultException( jolie.lang.Constants.TYPE_MISMATCH_FAULT_NAME, e.getMessage() ) ) ); } catch( IOException ioe ) { Interpreter.getInstance().logSevere( ioe ); } } finally { channel.disposeForInput(); } } @Override public RequestResponseTypeDescription getRequestResponseTypeDescription() { return null; } @Override public OneWayTypeDescription getOneWayTypeDescription() { return operation.getOneWayTypeDescription(); } } private static class CourierRequestResponseAggregatedOperation extends AggregatedOperation { private final RequestResponseOperation operation; private final Process courierProcess; private final VariablePath inputVariablePath; private final VariablePath outputVariablePath; public CourierRequestResponseAggregatedOperation( RequestResponseOperation operation, VariablePath inputVariablePath, VariablePath outputVariablePath, Process courierProcess ) { super( operation.id() ); this.operation = operation; this.inputVariablePath = inputVariablePath; this.outputVariablePath = outputVariablePath; this.courierProcess = courierProcess; } public OperationType type() { return OperationType.REQUEST_RESPONSE; } public void runAggregationBehaviour( final CommMessage requestMessage, final CommChannel channel ) throws IOException, URISyntaxException { Interpreter interpreter = Interpreter.getInstance(); try { operation.requestType().check( requestMessage.value() ); ExecutionThread initThread = Interpreter.getInstance().initThread(); try { initThread.join(); } catch( InterruptedException e ) { throw new IOException( e ); } State state = initThread.state().clone(); Process p = new RequestResponseProcess( operation, inputVariablePath, outputVariablePath, courierProcess ) .receiveMessage( new SessionMessage( requestMessage, channel ), state ); new SessionThread( p, state, initThread ).start(); } catch( TypeCheckingException e ) { interpreter.logWarning( "Received message TypeMismatch (input operation " + operation.id() + "): " + e.getMessage() ); try { channel.send( CommMessage.createFaultResponse( requestMessage, new FaultException( jolie.lang.Constants.TYPE_MISMATCH_FAULT_NAME, e.getMessage() ) ) ); } catch( IOException ioe ) { Interpreter.getInstance().logSevere( ioe ); } } finally { channel.disposeForInput(); } } @Override public RequestResponseTypeDescription getRequestResponseTypeDescription() { return operation.typeDescription(); } @Override public OneWayTypeDescription getOneWayTypeDescription() { return null; } } private static class DirectAggregatedOperation extends AggregatedOperation { private final OutputPort outputPort; private final Constants.OperationType type; private final String name; public DirectAggregatedOperation( String name, Constants.OperationType type, OutputPort outputPort ) { super( name ); this.type = type; this.outputPort = outputPort; this.name = name; } public OperationType type() { return type; } public void runAggregationBehaviour( CommMessage requestMessage, CommChannel channel ) throws IOException, URISyntaxException { // Aggregation input /*if ( type == OperationType.ONE_WAY ) { CommChannel oChannel = outputPort.getCommChannel(); oChannel.send( requestMessage ); oChannel.release(); } else {*/ CommChannel oChannel = outputPort.getNewCommChannel(); oChannel.setRedirectionChannel( channel ); oChannel.setRedirectionMessageId( requestMessage.id() ); try { oChannel.send( outputPort.getResourceUpdatedMessage( requestMessage ) ); oChannel.setToBeClosed( false ); oChannel.disposeForInput(); } catch( IOException e ) { channel.send( CommMessage.createFaultResponse( requestMessage, new FaultException( e ) ) ); channel.disposeForInput(); } } @Override public RequestResponseTypeDescription getRequestResponseTypeDescription() { if ( type.equals( Constants.OperationType.ONE_WAY ) ) { return null; } else { return outputPort.getInterface().requestResponseOperations().get( name ); } } @Override public OneWayTypeDescription getOneWayTypeDescription() { if ( type.equals( Constants.OperationType.REQUEST_RESPONSE ) ) { return null; } else { return outputPort.getInterface().oneWayOperations().get( name ); } } } private final String name; private AggregatedOperation( String name ) { this.name = name; } public static AggregatedOperation createDirect( String name, Constants.OperationType type, OutputPort outputPort ) { return new DirectAggregatedOperation( name, type, outputPort ); } public static AggregatedOperation createWithCourier( OneWayOperation operation, VariablePath inputVariablePath, Process courierProcess ) { return new CourierOneWayAggregatedOperation( operation, inputVariablePath, courierProcess ); } public static AggregatedOperation createWithCourier( RequestResponseOperation operation, VariablePath inputVariablePath, VariablePath outputVariablePath, Process courierProcess ) { return new CourierRequestResponseAggregatedOperation( operation, inputVariablePath, outputVariablePath, courierProcess ); } /** * Returns the operation type of this operation * @return the operation type of this operation * @see OperationType */ public abstract OperationType type(); /** * Returns the TypeDefinition of the response message * @return the type definition of the response message. */ public abstract RequestResponseTypeDescription getRequestResponseTypeDescription(); /** * Returns the TypeDefinition of the request message * @return the type definition of the request message. */ public abstract OneWayTypeDescription getOneWayTypeDescription(); /** * Returns the name of this operation. * @return the name of this operation. */ public String name() { return name; } public abstract void runAggregationBehaviour( CommMessage requestMessage, CommChannel channel ) throws IOException, URISyntaxException; }
package org.openecard.crypto.tls; import org.openecard.crypto.tls.auth.DynamicAuthentication; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; import javax.annotation.Nonnull; import org.openecard.bouncycastle.crypto.tls.AlertLevel; import org.openecard.bouncycastle.crypto.tls.CipherSuite; import org.openecard.bouncycastle.crypto.tls.HashAlgorithm; import org.openecard.bouncycastle.crypto.tls.NamedCurve; import org.openecard.bouncycastle.crypto.tls.PSKTlsClient; import org.openecard.bouncycastle.crypto.tls.ProtocolVersion; import org.openecard.bouncycastle.crypto.tls.SignatureAlgorithm; import org.openecard.bouncycastle.crypto.tls.SignatureAndHashAlgorithm; import org.openecard.bouncycastle.crypto.tls.TlsAuthentication; import org.openecard.bouncycastle.crypto.tls.TlsCipherFactory; import org.openecard.bouncycastle.crypto.tls.TlsECCUtils; import org.openecard.bouncycastle.crypto.tls.TlsExtensionsUtils; import org.openecard.bouncycastle.crypto.tls.TlsPSKIdentity; import org.openecard.bouncycastle.crypto.tls.TlsUtils; import org.openecard.common.OpenecardProperties; import org.openecard.crypto.tls.auth.ContextAware; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * PSK TLS client also implementing the ClientCertTlsClient interface. <br/> * If not modified, the TlsAuthentication instance returned by {@link #getAuthentication()} is of type * {@link DynamicAuthentication} without further modifications. * * @author Tobias Wich */ public class ClientCertPSKTlsClient extends PSKTlsClient implements ClientCertTlsClient { private static final Logger logger = LoggerFactory.getLogger(ClientCertPSKTlsClient.class); private final String host; private TlsAuthentication tlsAuth; /** * Create a ClientCertPSKTlsClient for the given parameters. * * @param pskId PSK to use for this connection. * @param host Host or IP address. Value must not be null. * @param doSni Control whether the server should send the SNI Header in the Client Hello. */ public ClientCertPSKTlsClient(@Nonnull TlsPSKIdentity pskId, @Nonnull String host, boolean doSni) { super(pskId); if (doSni) { setServerName(host); } boolean tls1 = Boolean.valueOf(OpenecardProperties.getProperty("legacy.tls1")); setMinimumVersion(tls1 ? ProtocolVersion.TLSv10 : ProtocolVersion.TLSv11); this.host = host; } /** * Create a ClientCertPSKTlsClient for the given parameters. * * @param tcf Cipher factory to use in this client. * @param pskId PSK to use for this connection. * @param host Host or IP address. Value must not be null. * @param doSni Control whether the server should send the SNI Header in the Client Hello. */ public ClientCertPSKTlsClient(@Nonnull TlsCipherFactory tcf, @Nonnull TlsPSKIdentity pskId, @Nonnull String host, boolean doSni) { super(tcf, pskId); if (doSni) { setServerName(host); } boolean tls1 = Boolean.valueOf(OpenecardProperties.getProperty("legacy.tls1")); setMinimumVersion(tls1 ? ProtocolVersion.TLSv10 : ProtocolVersion.TLSv11); this.host = host; } @Override public int[] getCipherSuites() { return new int[] { // recommended ciphers from TR-02102-2 sec. 3.3.1 CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, // this cipher suite does not work with the governikus eID server, so it is excluded here // CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, // must have according to TR-03124-1 sec. 4.4 CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA, }; } @Override public synchronized TlsAuthentication getAuthentication() throws IOException { if (tlsAuth == null) { tlsAuth = new DynamicAuthentication(host); } if (tlsAuth instanceof ContextAware) { ((ContextAware) tlsAuth).setContext(context); } return tlsAuth; } @Override public synchronized void setAuthentication(TlsAuthentication tlsAuth) { this.tlsAuth = tlsAuth; } @Override public Hashtable getClientExtensions() throws IOException { Hashtable clientExtensions = super.getClientExtensions(); clientExtensions = TlsExtensionsUtils.ensureExtensionsInitialised(clientExtensions); // code taken from AbstractTlsClient, if that should ever change modify it here too if (TlsECCUtils.containsECCCipherSuites(getCipherSuites())) { this.namedCurves = new int[] { // required parameters TR-03116-4 sec. 4.1.4 NamedCurve.secp224r1, NamedCurve.secp256r1, NamedCurve.brainpoolP256r1, // other possible parameters TR-02102-2 sec. 3.6 NamedCurve.secp384r1, NamedCurve.brainpoolP384r1, NamedCurve.brainpoolP512r1, }; TlsECCUtils.addSupportedEllipticCurvesExtension(clientExtensions, namedCurves); } // overwrite hash and signature algorithms if (TlsUtils.isSignatureAlgorithmsExtensionAllowed(clientVersion)) { short[] hashAlgorithms = new short[]{ HashAlgorithm.sha512, HashAlgorithm.sha384, HashAlgorithm.sha256, HashAlgorithm.sha224, HashAlgorithm.sha1 }; short[] signatureAlgorithms = new short[]{ SignatureAlgorithm.rsa, SignatureAlgorithm.ecdsa }; this.supportedSignatureAlgorithms = new Vector(); for (int i = 0; i < hashAlgorithms.length; ++i) { for (int j = 0; j < signatureAlgorithms.length; ++j) { this.supportedSignatureAlgorithms.addElement(new SignatureAndHashAlgorithm(hashAlgorithms[i], signatureAlgorithms[j])); } } clientExtensions = TlsExtensionsUtils.ensureExtensionsInitialised(clientExtensions); TlsUtils.addSignatureAlgorithmsExtension(clientExtensions, supportedSignatureAlgorithms); } return clientExtensions; } @Override public void notifySecureRenegotiation(boolean secureRenegotiation) throws IOException { // allow renegotiation } @Override public void notifyAlertRaised(short alertLevel, short alertDescription, String message, Throwable cause) { TlsError error = new TlsError(alertLevel, alertDescription, message, cause); if (alertLevel == AlertLevel.warning && logger.isInfoEnabled()) { logger.info("TLS warning sent."); if (logger.isDebugEnabled()) { logger.info(error.toString(), cause); } else { logger.info(error.toString()); } } else if (alertLevel == AlertLevel.fatal) { logger.error("TLS error sent."); logger.error(error.toString(), cause); } super.notifyAlertRaised(alertLevel, alertDescription, message, cause); } @Override public void notifyAlertReceived(short alertLevel, short alertDescription) { TlsError error = new TlsError(alertLevel, alertDescription); if (alertLevel == AlertLevel.warning && logger.isInfoEnabled()) { logger.info("TLS warning received."); logger.info(error.toString()); } else if (alertLevel == AlertLevel.fatal) { logger.error("TLS error received."); logger.error(error.toString()); } super.notifyAlertReceived(alertLevel, alertDescription); } }
package fr.treeptik.cloudunit.controller; import fr.treeptik.cloudunit.dto.*; import fr.treeptik.cloudunit.exception.CheckException; import fr.treeptik.cloudunit.exception.ServiceException; import fr.treeptik.cloudunit.model.Application; import fr.treeptik.cloudunit.model.Status; import fr.treeptik.cloudunit.model.User; import fr.treeptik.cloudunit.service.ApplicationService; import fr.treeptik.cloudunit.service.DockerService; import fr.treeptik.cloudunit.service.FileService; import fr.treeptik.cloudunit.utils.AuthentificationUtils; import fr.treeptik.cloudunit.utils.FilesUtils; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.repository.query.Param; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Locale; @Controller @RequestMapping("/file") public class FileController { private static final long serialVersionUID = 1L; private final transient Logger logger = LoggerFactory .getLogger(FileController.class); @Inject private FileService fileService; @Inject private DockerService dockerService; @Inject private ApplicationService applicationService; @Inject private AuthentificationUtils authentificationUtils; private Locale locale = Locale.ENGLISH; /** * @param containerId * @param path * @return * @throws ServiceException * @throws CheckException */ @RequestMapping(value = "/container/{containerId}/path/{path}", method = RequestMethod.GET) @ResponseBody @ResponseStatus(HttpStatus.OK) public List<FileUnit> listByContainerIdAndPath( @PathVariable String containerId, @PathVariable String path) throws ServiceException, CheckException { if (logger.isDebugEnabled()) { logger.debug("containerId:" + containerId); logger.debug("path:" + path); } path = convertPathFromUI(path); List<FileUnit> fichiers = fileService.listByContainerIdAndPath( containerId, path); return fichiers; } /** * Upload a file into a container * * @return * @throws IOException * @throws ServiceException * @throws CheckException */ @RequestMapping(value = "/container/{containerId}/application/{applicationName}/path/{path}", method = RequestMethod.POST, consumes = {"multipart/form-data"}) @ResponseBody @ResponseStatus(HttpStatus.OK) public JsonResponse uploadFileToContainer( @RequestPart("file") MultipartFile fileUpload, @PathVariable final String containerId, @PathVariable final String applicationName, @PathVariable final String path, HttpServletRequest request, HttpServletResponse response) throws IOException, ServiceException, CheckException { if (logger.isDebugEnabled()) { logger.debug("-- CALL UPLOAD FILE TO CONTAINER FS --"); logger.debug("applicationName = " + applicationName); logger.debug("containerId = " + containerId); logger.debug("pathFile = " + path); } User user = authentificationUtils.getAuthentificatedUser(); Application application = applicationService.findByNameAndUser(user, applicationName); // We must be sure there is no running action before starting new one this.authentificationUtils.canStartNewAction(user, application, locale); // Application is now pending applicationService.setStatus(application, Status.PENDING); if (application != null) { File file = File.createTempFile("upload-", FilesUtils.setSuffix(fileUpload.getOriginalFilename())); //File file = new File(fileUpload.getOriginalFilename()); fileUpload.transferTo(file); try { fileService.sendFileToContainer(applicationName, containerId, file, fileUpload.getOriginalFilename(), path); } catch (ServiceException e) { StringBuilder msgError = new StringBuilder(); msgError.append("Error during file upload : " + file); msgError.append("containerId : " + containerId); msgError.append("applicationName : " + applicationName); msgError.append(e.getMessage()); return new HttpErrorServer(msgError.toString()); } finally { // in all case, the error during file upload cannot be critical. // We prefer to set the application in started mode applicationService.setStatus(application, Status.START); if (file != null) { file.delete(); } } } return new HttpOk(); } /** * Delete resources (files and folders) into a container for a path * * @param containerId * @param applicationName * @param path * @return * @throws ServiceException * @throws CheckException * @throws IOException */ @RequestMapping(value = "/container/{containerId}/application/{applicationName}/path/{path:.*}", method = RequestMethod.DELETE) @ResponseBody public JsonResponse deleteResourcesIntoContainer( @PathVariable final String containerId, @PathVariable final String applicationName, @PathVariable String path) throws ServiceException, CheckException, IOException { if (logger.isDebugEnabled()) { logger.debug("containerId:" + containerId); logger.debug("applicationName:" + applicationName); logger.debug("path:" + path); } path = convertPathFromUI(path); User user = authentificationUtils.getAuthentificatedUser(); Application application = applicationService.findByNameAndUser(user, applicationName); fileService .deleteFilesFromContainer(applicationName, containerId, path); return new HttpOk(); } /** * Delete resources (files and folders) into a container for a path * * @param containerId * @param applicationName * @param path * @return * @throws ServiceException * @throws CheckException * @throws IOException */ @RequestMapping(value = "/container/{containerId}/application/{applicationName}/path/{path:.*}", method = RequestMethod.POST) public @ResponseBody JsonResponse createDirectory( @PathVariable final String containerId, @PathVariable final String applicationName, @PathVariable String path) throws ServiceException, CheckException, IOException { if (logger.isDebugEnabled()) { logger.debug("containerId:" + containerId); logger.debug("applicationName:" + applicationName); logger.debug("path:" + path); } System.out.println(" System.out.println("/file/container/" + containerId + "/application/" + applicationName + "/path/" + path); System.out.println(" fileService.createDirectory(applicationName, containerId, path); return new HttpOk(); } /** * Unzip content file into Container * * @param containerId * @param applicationName * @param path * @param fileName * @param request * @param response * @throws ServiceException * @throws CheckException * @throws IOException * @returnoriginalName */ @RequestMapping(value = "/unzip/container/{containerId}/application/{applicationName}/path/{path}/fileName/{fileName:.*}", method = RequestMethod.PUT) public void unzipFileIntoContainer( @PathVariable final String containerId, @PathVariable final String applicationName, @PathVariable String path, @PathVariable final String fileName, HttpServletRequest request, HttpServletResponse response) throws ServiceException, CheckException, IOException { if (logger.isDebugEnabled()) { logger.debug("containerId:" + containerId); logger.debug("applicationName:" + applicationName); logger.debug("fileName:" + fileName); } String command = null; if (FileUnit.tar().test(fileName)) { command = "tar xvf " + convertPathFromUI(path) + "/" + fileName + " -C " + convertPathFromUI(path); } else if (FileUnit.tar().test(fileName)) { command = "unzip " + convertPathFromUI(path); } else { throw new RuntimeException("Cannot decompress this file. Extension is not right : " + fileName); } logger.debug(command); String commandExec = dockerService.exec(containerId, command); if (commandExec != null) { logger.debug(commandExec); } else { logger.error("No content for : " + command); } } /** * Display content file from a container * * @param containerId * @param applicationName * @param path * @param fileName * @param request * @param response * @throws ServiceException * @throws CheckException * @throws IOException * @returnoriginalName */ @RequestMapping(value = "/content/container/{containerId}/application/{applicationName}/path/{path}/fileName/{fileName:.*}", method = RequestMethod.POST) public void saveContentFileIntoContainer( @PathVariable final String containerId, @PathVariable final String applicationName, @PathVariable String path, @PathVariable final String fileName, @RequestBody FileContent fileContent, HttpServletRequest request, HttpServletResponse response) throws ServiceException, CheckException, IOException { if (logger.isDebugEnabled()) { logger.debug("containerId:" + containerId); logger.debug("applicationName:" + applicationName); logger.debug("fileName:" + fileName); logger.debug("fileContent: " + fileContent); } User user = authentificationUtils.getAuthentificatedUser(); Application application = applicationService.findByNameAndUser(user, applicationName); // We must be sure there is no running action before starting new one this.authentificationUtils.canStartNewAction(user, application, locale); // Application is now pending applicationService.setStatus(application, Status.PENDING); if (application != null) { File file = File.createTempFile("upload", "tmp"); FileUtils.write(file, fileContent.getFileContent()); try { fileService.sendFileToContainer(applicationName, containerId, file, fileName, path); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } catch (ServiceException e) { StringBuilder msgError = new StringBuilder(); msgError.append("Error during file upload : " + file); msgError.append("containerId : " + containerId); msgError.append("applicationName : " + applicationName); msgError.append(e.getMessage()); } finally { // in all case, the error during file upload cannot be critical. // We prefer to set the application in started mode applicationService.setStatus(application, Status.START); if (file != null) { file.delete(); } } } } /** * Display content file from a container * * @param containerId * @param applicationName * @param path * @param fileName * @param request * @param response * @throws ServiceException * @throws CheckException * @throws IOException * @returnoriginalName */ @RequestMapping(value = "/content/container/{containerId}/application/{applicationName}/path/{path}/fileName/{fileName:.*}", method = RequestMethod.GET) public void displayContentFileFromContainer( @PathVariable final String containerId, @PathVariable final String applicationName, @PathVariable String path, @PathVariable final String fileName, HttpServletRequest request, HttpServletResponse response) throws ServiceException, CheckException, IOException { if (logger.isDebugEnabled()) { logger.debug("containerId:" + containerId); logger.debug("applicationName:" + applicationName); logger.debug("fileName:" + fileName); } String command = "cat " + convertPathFromUI(path) + "/" + fileName; logger.debug(command); String contentFile = dockerService.exec(containerId, command); if (contentFile != null) { logger.debug(contentFile); response.setContentType("text/plain"); Writer writer = response.getWriter(); writer.write(contentFile); writer.close(); } else { logger.error("No content for : " + command); } } /** * Download a file into a container * * @param containerId * @param applicationName * @param path * @param fileName * @param request * @param response * @throws ServiceException * @throws CheckException * @throws IOException * @returnoriginalName */ @RequestMapping(value = "/container/{containerId}/application/{applicationName}/path/{path}/fileName/{fileName:.*}", method = RequestMethod.GET) public void downloadFileFromContainer( @PathVariable final String containerId, @PathVariable final String applicationName, @PathVariable String path, @PathVariable final String fileName, HttpServletRequest request, HttpServletResponse response) throws ServiceException, CheckException, IOException { if (logger.isDebugEnabled()) { logger.debug("containerId:" + containerId); logger.debug("applicationName:" + applicationName); logger.debug("fileName:" + fileName); } User user = authentificationUtils.getAuthentificatedUser(); Application application = applicationService.findByNameAndUser(user, applicationName); // We must be sure there is no running action before starting new one this.authentificationUtils.canStartNewAction(user, application, locale); File file = File.createTempFile("previousDownload", FilesUtils.setSuffix(fileName)); path = convertPathFromUI(path); File fileFromContainer = fileService.getFileFromContainer(applicationName, containerId, file, fileName, path); BufferedReader br = new BufferedReader(new FileReader(fileFromContainer)); if (br.readLine() == null) { file = File.createTempFile(fileName, ""); // put an empty space for empty file FileUtils.write(file, " "); } response.reset(); String mimeType = URLConnection.guessContentTypeFromName(file.getName()); String contentDisposition = String.format("attachment; filename=%s", fileName); int fileSize = Long.valueOf(file.length()).intValue(); response.setContentType(mimeType); response.setHeader("Content-Disposition", contentDisposition); response.setContentLength(fileSize); response.setHeader("Content-Description", "File Transfer"); response.setCharacterEncoding("binary"); Path path2 = Paths.get(file.getAbsolutePath()); byte[] data = Files.readAllBytes(path2); try (OutputStream stream = response.getOutputStream()) { stream.write(data); stream.flush(); // commits response! stream.close(); } catch (IOException ex) { // clean error handling } file.delete(); } private String convertPathFromUI(String path) { if (path != null) { path = path.replaceAll("____", "/"); path = path.replaceAll("__", "/"); } return path; } }
package org.eclipse.birt.data.engine.impl; import java.util.Collection; import java.util.Iterator; import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression; import org.eclipse.birt.data.engine.api.querydefn.FilterDefinition; import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition; import org.eclipse.birt.data.engine.api.querydefn.InputParameterBinding; import org.eclipse.birt.data.engine.api.querydefn.OdaDataSetDesign; import org.eclipse.birt.data.engine.api.querydefn.OdaDataSourceDesign; import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition; import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression; import org.eclipse.birt.data.engine.api.querydefn.SortDefinition; /** * A utility function * The toString method dump all non-empty fields of the given object */ public final class LogUtil { public static String toString( Object source ) { if ( source instanceof Collection ){ return toString_Collection(source); } else if(source instanceof FilterDefinition){ return toString_FilterDefinition(source); } else if(source instanceof ConditionalExpression){ return toString_ConditionalExpression(source); } else if(source instanceof ScriptExpression){ return toString_ScriptExpression(source); } else if(source instanceof InputParameterBinding){ return toString_InputParameterBinding(source); } else if(source instanceof GroupDefinition){ return toString_GroupDefinition(source); } else if(source instanceof SortDefinition){ return toString_SortDefinition(source); } else if(source instanceof QueryDefinition){ return toString_QueryDefinition(source); } else if(source instanceof OdaDataSetDesign){ return toString_OdaDataSetDesign(source); } else if(source instanceof OdaDataSourceDesign){ return toString_OdaDataSourceDesign(source); } else if(source == null) return "null"; else return source.toString(); } private static String toString_Collection(Object source){ StringBuffer stringBuffer= new StringBuffer(); Iterator iterator = ( (Collection) source ).iterator( ); while ( iterator.hasNext( ) ) { stringBuffer.append( toString( iterator.next( ) ) + ", \r\n\t" ); } String str = stringBuffer.toString( ); if ( str.endsWith( "\t" ) ) { str = str.substring( 0, str.length( ) - 5 ); } return str; } private static String toString_FilterDefinition(Object source){ return "FilterDefinition("+toString(((FilterDefinition)source).getExpression())+")"; } private static String toString_ConditionalExpression(Object source){ StringBuffer stringBuffer= new StringBuffer("ConditionalExpression("); ConditionalExpression conditionalExpression = (ConditionalExpression)source; stringBuffer.append( "Operator : "+conditionalExpression.getOperator()+", " ); stringBuffer.append( "Expression : "+toString(conditionalExpression.getExpression())+", " ); if ( !isEmpty(conditionalExpression.getOperand1( )) ) stringBuffer.append( "Operand1 : "+toString(conditionalExpression.getOperand1())+", " ); if ( !isEmpty(conditionalExpression.getOperand2( ))) stringBuffer.append( "Operand2 : "+toString(conditionalExpression.getOperand2())+")" ); return stringBuffer.toString( ); } private static String toString_ScriptExpression(Object source){ return "ScriptExpression(Text:"+((ScriptExpression)source).getText()+")"; } private static String toString_InputParameterBinding( Object source ) { InputParameterBinding inputParameterBinding =(InputParameterBinding)source; StringBuffer stringBuffer = new StringBuffer( "InputParameterBinding(" ); if ( !isEmpty(inputParameterBinding.getName())) stringBuffer.append( "Name : " +inputParameterBinding.getName()+", " ); stringBuffer.append( "Position : " +inputParameterBinding.getPosition()+", " ); stringBuffer.append( "Expression : " + toString(inputParameterBinding.getExpr()) ); stringBuffer.append( ")" ); return stringBuffer.toString( ); } private static String toString_SortDefinition(Object source){ SortDefinition sort = (SortDefinition)source; StringBuffer stringBuffer = new StringBuffer( "SortDefinition(" ); if ( !isEmpty(sort.getColumn())) stringBuffer.append( "Column : " + sort.getColumn( )+", " ); if ( !isEmpty(sort.getExpression())) stringBuffer.append( "getExpression : " + sort.getExpression( )+", " ); stringBuffer.append( "SortDirection : " + sort.getSortDirection( ) +")"); return stringBuffer.toString( ); } private static String toString_GroupDefinition(Object source){ GroupDefinition group = (GroupDefinition)source; StringBuffer stringBuffer = new StringBuffer( "GroupDefinition(" ); if ( !isEmpty( group.getName( ) ) ) stringBuffer.append( "Name : " + group.getName( )+", " ); if ( !isEmpty( group.getKeyColumn( ) ) ) stringBuffer.append( "KeyColumn : " + group.getKeyColumn( )+", " ); if ( !isEmpty( group.getKeyExpression( ) ) ) stringBuffer.append( "KeyExpression : " + group.getKeyExpression( )+", " ); stringBuffer.append( "SortDirection : " + group.getSortDirection( )+", " ); if ( !isEmpty( group.getAfterExpressions( ) ) ) stringBuffer.append( "AfterExpressions : " + toString(group.getAfterExpressions( ))+", " ); if ( !isEmpty( group.getBeforeExpressions( ) ) ) stringBuffer.append( "BeforeExpressions : " + toString(group.getBeforeExpressions( ))+", " ); if ( !isEmpty( group.getRowExpressions( ) ) ) stringBuffer.append( "RowExpressions : " + toString(group.getRowExpressions( ))+", " ); stringBuffer.append( "Interval : " + group.getInterval( )+", " ); stringBuffer.append( "IntervalRange : " + group.getIntervalRange( )+", " ); if ( !isEmpty( group.getIntervalStart( ) ) ) stringBuffer.append( "IntervalStart : " + group.getIntervalStart( )+", " ); if ( !isEmpty( group.getSubqueries( ) ) ) stringBuffer.append( "Subqueries : " + toString(group.getSubqueries( ))+", " ); if ( !isEmpty( group.getSorts( ) ) ) stringBuffer.append( "Sorts : " + toString(group.getSorts( ))+", " ); if ( !isEmpty( group.getFilters( ) ) ) stringBuffer.append( "Filters : " + toString(group.getFilters( )) ); stringBuffer.append(")"); return stringBuffer.toString(); } private static String toString_QueryDefinition(Object source){ QueryDefinition querySpec = (QueryDefinition)source; StringBuffer stringBuffer = new StringBuffer("QueryDefinition("); stringBuffer.append( "DataSetName : "+querySpec.getDataSetName()+"\r\n" ); if ( !isEmpty( querySpec.getAfterExpressions( ) ) ) stringBuffer.append( "AfterExpressions : " + LogUtil.toString( querySpec.getAfterExpressions( ) ) + "\r\n" ); if ( !isEmpty( querySpec.getBeforeExpressions( ) ) ) stringBuffer.append( "BeforeExpressions : "+LogUtil.toString(querySpec.getBeforeExpressions())+"\r\n" ); if ( !isEmpty( querySpec.getRowExpressions( ) ) ) stringBuffer.append( "RowExpressions : "+LogUtil.toString(querySpec.getRowExpressions())+"\r\n" ); if ( !isEmpty( querySpec.getParentQuery( ) ) ) stringBuffer.append( "ParentQuery : "+LogUtil.toString(querySpec.getParentQuery())+"\r\n" ); if ( !isEmpty( querySpec.getSubqueries( ) ) ) stringBuffer.append( "Subqueries : "+LogUtil.toString(querySpec.getSubqueries())+"\r\n" ); stringBuffer.append( "MaxRows : "+querySpec.getMaxRows()+"\r\n" ); if ( !isEmpty( querySpec.getColumnProjection( ) ) ) stringBuffer.append( "ColumnProjection : "+querySpec.getColumnProjection()+"\r\n" ); if ( !isEmpty( querySpec.getGroups( ) ) ) stringBuffer.append( "Groups : "+LogUtil.toString(querySpec.getGroups())+"\r\n" ); if ( !isEmpty( querySpec.getFilters( ) ) ) stringBuffer.append( "Filters : " + LogUtil.toString( querySpec.getFilters( ) ) + "\r\n" ); if ( !isEmpty( querySpec.getSorts( ) ) ) stringBuffer.append( "Sorts : "+LogUtil.toString(querySpec.getSorts())+"\r\n" ); if ( !isEmpty( querySpec.getInputParamBindings( ) ) ) stringBuffer.append( "InputParamBindings : "+LogUtil.toString(querySpec.getInputParamBindings())+")\r\n" ); return stringBuffer.toString(); } private static String toString_OdaDataSetDesign(Object source){ OdaDataSetDesign dataSet = (OdaDataSetDesign)source; StringBuffer stringBuffer= new StringBuffer("OdaDataSetDesign("); //BaseDataSetDesign if ( !isEmpty( dataSet.getName( ) ) ) stringBuffer.append( "Name : " + dataSet.getName( ) + "\r\n" ); if ( !isEmpty( dataSet.getDataSourceName( ) ) ) stringBuffer.append( "DataSourceName : "+dataSet.getDataSourceName()+"\r\n" ); if ( !isEmpty( dataSet.getAfterCloseScript( ) ) ) stringBuffer.append( "AfterCloseScript : "+dataSet.getAfterCloseScript()+"\r\n" ); if ( !isEmpty( dataSet.getAfterOpenScript( ) ) ) stringBuffer.append( "AfterOpenScript : "+dataSet.getAfterOpenScript()+"\r\n" ); if ( !isEmpty( dataSet.getBeforeCloseScript( ) ) ) stringBuffer.append( "BeforeCloseScript : "+dataSet.getBeforeCloseScript()+"\r\n" ); if ( !isEmpty( dataSet.getBeforeOpenScript( ) ) ) stringBuffer.append( "BeforeOpenScript : "+dataSet.getBeforeOpenScript()+"\r\n" ); if ( !isEmpty( dataSet.getOnFetchScript( ) ) ) stringBuffer.append( "OnFetchScript : "+dataSet.getOnFetchScript()+"\r\n" ); if ( !isEmpty( dataSet.getComputedColumns( ) ) ) stringBuffer.append( "ComputedColumns : "+ toString(dataSet.getComputedColumns())+"\r\n" ); if ( !isEmpty( dataSet.getFilters( ) ) ) stringBuffer.append( "Filters : "+ toString(dataSet.getFilters())+"\r\n" ); if ( !isEmpty( dataSet.getParameters( ) ) ) stringBuffer.append( "Parameters : "+ toString(dataSet.getParameters())+"\r\n" ); if ( !isEmpty( dataSet.getInputParamBindings( ) ) ) stringBuffer.append( "InputParamBindings : "+ toString(dataSet.getInputParamBindings())+"\r\n" ); if ( !isEmpty( dataSet.getResultSetHints( ) ) ) stringBuffer.append( "ResultSetHints : "+ toString(dataSet.getResultSetHints())+"\r\n" ); //OdaDataSetDesign if ( !isEmpty( dataSet.getDataSetType( ) ) ) stringBuffer.append( "DataSetType : "+dataSet.getDataSetType()+"\r\n" ); if ( !isEmpty( dataSet.getPrimaryResultSetName( ) ) ) stringBuffer.append( "PrimaryResultSetName : "+dataSet.getPrimaryResultSetName()+"\r\n" ); if ( !isEmpty( dataSet.getQueryScript( ) ) ) stringBuffer.append( "QueryScript : "+dataSet.getQueryScript()+"\r\n" ); if ( !isEmpty( dataSet.getQueryText( ) ) ) stringBuffer.append( "QueryText : "+dataSet.getQueryText()+"\r\n" ); if ( !isEmpty( dataSet.getPrivateProperties( ) ) ) stringBuffer.append( "PrivateProperties : "+toString(dataSet.getPrivateProperties())+"\r\n" ); if ( !isEmpty( dataSet.getPublicProperties( ) ) ) stringBuffer.append( "PublicProperties : "+toString(dataSet.getPublicProperties())+"\r\n" ); stringBuffer.append( ")" ); return stringBuffer.toString(); } private static String toString_OdaDataSourceDesign(Object source){ OdaDataSourceDesign dataSource = (OdaDataSourceDesign)source; StringBuffer stringBuffer= new StringBuffer("OdaDataSourceDesign("); //BaseDataSourceDesign if ( !isEmpty( dataSource.getName( ) ) ) stringBuffer.append( "Name : "+dataSource.getName()+"\r\n" ); if ( !isEmpty( dataSource.getAfterCloseScript( ) ) ) stringBuffer.append( "AfterCloseScript : "+dataSource.getAfterCloseScript()+"\r\n" ); if ( !isEmpty( dataSource.getAfterOpenScript( ) ) ) stringBuffer.append( "AfterOpenScript : "+dataSource.getAfterOpenScript()+"\r\n" ); if ( !isEmpty( dataSource.getBeforeCloseScript( ) ) ) stringBuffer.append( "BeforeCloseScript : "+dataSource.getBeforeCloseScript()+"\r\n" ); if ( !isEmpty( dataSource.getBeforeOpenScript( ) ) ) stringBuffer.append( "BeforeOpenScript : "+dataSource.getBeforeOpenScript()+"\r\n" ); //OdaDataSourceDesign if ( !isEmpty( dataSource.getDriverName( ) ) ) stringBuffer.append( "DriverName : "+dataSource.getDriverName()+"\r\n" ); if ( !isEmpty( dataSource.getPrivateProperties( ) ) ) stringBuffer.append( "PrivateProperties : "+dataSource.getPrivateProperties()+"\r\n" ); if ( !isEmpty( dataSource.getPublicProperties( ) ) ) stringBuffer.append( "PublicProperties : "+dataSource.getPublicProperties()+"\r\n" ); stringBuffer.append( ")" ); return stringBuffer.toString(); } private static boolean isEmpty( Object source ) { if ( source == null || "".equals( toString( source ) ) ) return true; else return false; } }
package tests.wurstscript.tests; import de.peeeq.wurstscript.ast.FunctionCall; import de.peeeq.wurstscript.ast.WurstModel; import de.peeeq.wurstscript.parser.WPos; import de.peeeq.wurstscript.utils.Utils; import org.testng.annotations.Test; public class PositionTests extends WurstScriptTest { @Test public void testFuncCallPos() { WurstModel model = testScript("blub", false, String.join(System.lineSeparator(), "package Test", "function foo() returns int", " return foo()", "" )); FunctionCall c = (FunctionCall) Utils.getAstElementAtPos(model.get(0), 3, 12, false); WPos pos = c.attrErrorPos(); System.out.println("pos = " + pos.getLine()); System.out.println("pos = " + pos.getStartColumn()); System.out.println("pos = " + pos.getEndColumn()); } }
package com.almende.dialog.adapter; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.znerd.xmlenc.XMLOutputter; import com.almende.dialog.LogLevel; import com.almende.dialog.Settings; import com.almende.dialog.accounts.AdapterConfig; import com.almende.dialog.adapter.tools.Broadsoft; import com.almende.dialog.agent.AdapterAgent; import com.almende.dialog.model.Answer; import com.almende.dialog.model.MediaProperty.MediaPropertyKey; import com.almende.dialog.model.MediaProperty.MediumType; import com.almende.dialog.model.Question; import com.almende.dialog.model.Session; import com.almende.dialog.model.ddr.DDRRecord; import com.almende.dialog.util.DDRUtils; import com.almende.dialog.util.ServerUtils; import com.almende.dialog.util.TimeUtils; import com.almende.util.myBlobstore.MyBlobStore; import com.askfast.commons.entity.AccountType; import com.askfast.commons.utils.PhoneNumberUtils; import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat; @Path("/vxml/") public class VoiceXMLRESTProxy { protected static final Logger log = Logger.getLogger(VoiceXMLRESTProxy.class.getName()); protected static final com.almende.dialog.Logger dialogLog = new com.almende.dialog.Logger(); private static final int LOOP_DETECTION=10; private static final String DTMFGRAMMAR="dtmf2hash"; private static final String PLAY_TRIAL_AUDIO_KEY = "playTrialAccountAudio"; private static final int MAX_RETRIES=1; protected String TIMEOUT_URL="timeout"; protected String EXCEPTION_URL="exception"; private String host = ""; public static void killSession(Session session){ AdapterConfig config = session.getAdapterConfig(); if(config!=null) { Broadsoft bs = new Broadsoft(config); bs.endCall(session.getExternalSession()); } } /** * @Deprecated. Use broadcast calling mechanism instead. <br> * {@link VoiceXMLRESTProxy#dial(Map, String, String, AdapterConfig) * dial} method * * @param address * @param url * @param config * @return */ @Deprecated public static String dial(String address, String url, AdapterConfig config) { try { address = PhoneNumberUtils.formatNumber(address, PhoneNumberFormat.E164); } catch (Exception e) { log.severe(String.format("Phonenumber: %s is not valid", address)); return ""; } //avoid multiple calls to be made to the same number, from the same adapter. Session session = Session.getSession(Session.getSessionKey(config, address)); if(session != null) { String responseMessage = checkIfCallAlreadyInSession(address, config, session); if(responseMessage != null) { return responseMessage; } else { //recreate a fresh session session.drop(); session = Session.getOrCreateSession(config, address); } } else { session = Session.getOrCreateSession(config, address); } session.killed = false; session.setStartUrl(url); session.setDirection("outbound"); session.setRemoteAddress(address); session.setType(AdapterAgent.ADAPTER_TYPE_BROADSOFT); Question question = Question.fromURL(url, config.getConfigId(), address, config.getMyAddress(), session.getDdrRecordId(), session.getKey()); session.setQuestion(question); session.storeSession(); dialogLog.log(LogLevel.INFO, config, String.format("Call started from: %s to: %s", config.getMyAddress(), address), session); Broadsoft bs = new Broadsoft(config); bs.startSubscription(); String extSession = bs.startCall(address + "@outbound", session); session.setExternalSession(extSession); session.storeSession(); return session.getKey(); } /** * initiates a call to all the numbers in the addressNameMap and returns a * Map of <adress, SessionKey> * @return */ public static HashMap<String, String> dial( Map<String, String> addressNameMap, String url, String senderName, AdapterConfig config ) throws Exception { HashMap<String, String> resultSessionMap = new HashMap<String, String>(); // If it is a broadcast don't provide the remote address because it is deceiving. String loadAddress = ""; if(addressNameMap.size()==1) loadAddress = addressNameMap.keySet().iterator().next(); //fetch the question Question question = Question.fromURL( url, config.getConfigId(), loadAddress, config.getMyAddress(), null, null ); for ( String address : addressNameMap.keySet() ) { try { String formattedAddress = PhoneNumberUtils.formatNumber( address, PhoneNumberFormat.E164 ); //avoid multiple calls to be made to the same number, from the same adapter. Session session = Session.getSession(Session.getSessionKey(config, formattedAddress)); if(session != null) { String responseMessage = checkIfCallAlreadyInSession(formattedAddress, config, session); if(responseMessage != null) { resultSessionMap.put(formattedAddress, responseMessage); continue; } else { //recreate a fresh session session.drop(); session = Session.getOrCreateSession(config, formattedAddress); } } else { session = Session.getOrCreateSession(config, formattedAddress); } session.killed=false; session.setStartUrl(url); session.setDirection("outbound"); session.setRemoteAddress(formattedAddress); session.setType(AdapterAgent.ADAPTER_TYPE_BROADSOFT); session.setAdapterID(config.getConfigId()); session.setQuestion( question ); dialogLog.log(LogLevel.INFO, session.getAdapterConfig(), String.format("Outgoing call from: %s to: %s", session.getLocalAddress(), formattedAddress), session); String extSession = ""; if ( !ServerUtils.isInUnitTestingEnvironment() ) { Broadsoft bs = new Broadsoft( config ); String subscriptiion = bs.startSubscription(); log.info(String.format("Calling subscription complete. Message: %s. Starting call.. ", subscriptiion)); extSession = bs.startCall( formattedAddress + "@outbound", session ); } session.setExternalSession( extSession ); session.storeSession(); resultSessionMap.put( formattedAddress, session.getKey() ); } catch ( Exception e ) { log.severe( String.format( "Phonenumber: %s is not valid", address ) ); } } return resultSessionMap; } public static ArrayList<String> getActiveCalls(AdapterConfig config) { Broadsoft bs = new Broadsoft(config); return bs.getActiveCalls(); } public static ArrayList<String> getActiveCallsInfo(AdapterConfig config) { Broadsoft bs = new Broadsoft(config); return bs.getActiveCallsInfo(); } public static boolean killActiveCalls(AdapterConfig config) { Broadsoft bs = new Broadsoft(config); return bs.killActiveCalls(); } @Path("dtmf2hash") @GET @Produces("application/srgs+xml") public Response getDTMF2Hash(@QueryParam("minlength") String minLength, @QueryParam("maxlength") String maxLength) { minLength = (minLength != null && !minLength.isEmpty()) ? minLength : "1"; maxLength = (maxLength != null && !maxLength.isEmpty()) ? maxLength : ""; String repeat = minLength.equals( maxLength ) ? minLength : (minLength + "-" + maxLength); String result = "<?xml version=\"1.0\"?> "+ "<grammar mode=\"dtmf\" version=\"1.0\" xmlns:xsi=\"http: "<rule id=\"digit\"> "+ "<one-of> "+ "<item> 0 </item> "+ "<item> 1 </item> "+ "<item> 2 </item> "+ "<item> 3 </item> "+ "<item> 4 </item> "+ "<item> 5 </item> "+ "<item> 6 </item> "+ "<item> 7 </item> "+ "<item> 8 </item> "+ "<item> 9 </item> "+ "<item> * </item> "+ "</one-of> "+ "</rule> "+ "<rule id=\"untilHash\" scope=\"public\"> "+ "<one-of> "+ "<item repeat=\"" + repeat + "\"><ruleref uri=\"#digit\"/></item> "+ "<item> # </item> "+ "</one-of> "+ "</rule> "+ "</grammar> "; return Response.ok(result).build(); } @Path("new") @GET @Produces("application/voicexml") public Response getNewDialog(@QueryParam("direction") String direction,@QueryParam("remoteID") String remoteID,@QueryParam("localID") String localID, @Context UriInfo ui) { log.info("call started:"+direction+":"+remoteID+":"+localID); this.host=ui.getBaseUri().toString().replace(":80", ""); AdapterConfig config = AdapterConfig.findAdapterConfig(AdapterAgent.ADAPTER_TYPE_BROADSOFT, localID); String formattedRemoteId = remoteID; //format the remote number try { formattedRemoteId = PhoneNumberUtils.formatNumber( remoteID.split( "@" )[0], PhoneNumberFormat.E164 ); } catch ( Exception e1 ) { log.severe( "Remote number formatting failed: "+ remoteID.split( "@" )[0] ); } String sessionKey = AdapterAgent.ADAPTER_TYPE_BROADSOFT+"|"+localID+"|"+ formattedRemoteId; Session session = Session.getSession(sessionKey); String url = ""; if ( session != null && direction.equalsIgnoreCase("outbound")) { url = session.getStartUrl(); dialogLog.log(LogLevel.INFO, config, String.format("Outgoing Call from: %s to: %s", config.getMyAddress(), formattedRemoteId), session); } else if(direction.equals("inbound")) { //create a session for incoming only session = Session.getOrCreateSession(config, formattedRemoteId); url = config.getURLForInboundScenario(); Broadsoft bs = new Broadsoft( config ); bs.startSubscription(); dialogLog.log(LogLevel.INFO, config, String.format("Incoming Call received from: %s at: %s", formattedRemoteId, config.getMyAddress()), session); } if(session != null) { session.setStartUrl( url ); session.setDirection( direction ); session.setRemoteAddress( formattedRemoteId ); session.setType( AdapterAgent.ADAPTER_TYPE_BROADSOFT ); session.setAccountId( config.getOwner() ); session.setAdapterID( config.getConfigId() ); } else { log.severe(String.format("Session %s not found", sessionKey)); return null; } Question question = session.getQuestion(); if(question == null) { question = Question.fromURL(url, session.getAdapterConfig().getConfigId(), formattedRemoteId, localID, session.getDdrRecordId(), session.getKey()); } session.setQuestion(question); if (session.getQuestion() != null) { //play trial account audio if the account is trial if(config.getAccountType() != null && config.getAccountType().equals(AccountType.TRIAL)){ session.getExtras().put(PLAY_TRIAL_AUDIO_KEY, "true"); } //create ddr record DDRRecord ddrRecord = null; try { if (direction.equalsIgnoreCase("outbound")) { ddrRecord = DDRUtils.createDDRRecordOnOutgoingCommunication(config, formattedRemoteId, 1, url); } else { ddrRecord = DDRUtils.createDDRRecordOnIncomingCommunication(config, formattedRemoteId, 1, url); } session.setDdrRecordId( ddrRecord != null ? ddrRecord.getId() : null); ddrRecord.addAdditionalInfo(Session.TRACKING_TOKEN_KEY, session.getTrackingToken()); } catch (Exception e) { String errorMessage = String.format("Creating DDR records failed. Direction: %s for adapterId: %s with address: %s remoteId: %s and localId: %s", direction, config.getConfigId(), config.getMyAddress(), formattedRemoteId, localID); log.severe(errorMessage); dialogLog.severe(config.getConfigId(), errorMessage, ddrRecord != null ? ddrRecord.getId() : null, sessionKey); } finally { ddrRecord.createOrUpdate(); session.storeSession(); } return handleQuestion( question, config, formattedRemoteId, sessionKey ); } else { return Response.ok().build(); } } @Path( "answer" ) @GET @Produces( "application/voicexml+xml" ) public Response answer( @QueryParam( "questionId" ) String question_id, @QueryParam( "answerId" ) String answer_id, @QueryParam( "answerInput" ) String answer_input, @QueryParam( "sessionKey" ) String sessionKey, @Context UriInfo ui ) { try { answer_input = answer_input != null ? URLDecoder.decode( answer_input, "UTF-8" ) : answer_input; } catch ( UnsupportedEncodingException e ) { log.warning( String.format( "Answer input decode failed for: %s", answer_input) ); } this.host = ui.getBaseUri().toString().replace( ":80", "" ); String reply = "<vxml><exit/></vxml>"; Session session = Session.getSession( sessionKey ); if ( session != null ) { Question question = session.getQuestion(); if ( question != null ) { String responder = session.getRemoteAddress(); if ( session.killed ) { log.warning( "session is killed" ); return Response.status( Response.Status.BAD_REQUEST ).build(); } dialogLog.log(LogLevel.INFO, session.getAdapterConfig(), String.format("Answer input: %s from: %s to question: %s", answer_input, session.getRemoteAddress(), question.getQuestion_expandedtext()), session); String answerForQuestion = question.getQuestion_expandedtext(); question = question.answer( responder, session.getAdapterConfig().getConfigId(), answer_id, answer_input, sessionKey ); //reload the session session = Session.getSession( sessionKey ); session.setQuestion( question ); session.storeSession(); //check if ddr is in session. save the answer in the ddr if(session.getDdrRecordId() != null) { try { DDRRecord ddrRecord = DDRRecord.getDDRRecord(session.getDdrRecordId(), session.getAccountId()); if(ddrRecord != null) { ddrRecord.addAdditionalInfo(DDRRecord.ANSWER_INPUT_KEY + ":" + answerForQuestion, answer_input); ddrRecord.createOrUpdateWithLog(); } } catch (Exception e) { } } return handleQuestion( question, session.getAdapterConfig(), responder, sessionKey ); } else { log.warning( "No question found in session!" ); } } else { log.warning( "No session found for: " + sessionKey ); dialogLog.severe(null, "No session found!", session); } return Response.ok( reply ).build(); } @Path( "timeout" ) @GET @Produces( "application/voicexml+xml" ) public Response timeout( @QueryParam( "questionId" ) String question_id, @QueryParam( "sessionKey" ) String sessionKey ) throws Exception { String reply = "<vxml><exit/></vxml>"; Session session = Session.getSession( sessionKey ); if ( session != null ) { Question question = session.getQuestion(); String responder = session.getRemoteAddress(); if ( session.killed ) { return Response.status( Response.Status.BAD_REQUEST ).build(); } dialogLog.log(LogLevel.INFO, session.getAdapterConfig(), String.format("Timeout from: %s for question: %s", responder, question.getQuestion_expandedtext()), session); HashMap<String,Object> extras = new HashMap<String, Object>(); extras.put( "sessionKey", sessionKey ); question = question.event( "timeout", "No answer received", extras, responder ); session.setQuestion( question ); if (question != null) { String retryLimit = question.getMediaPropertyValue(MediumType.BROADSOFT, MediaPropertyKey.RETRY_LIMIT); retryLimit = retryLimit != null ? retryLimit : String.valueOf(Question.DEFAULT_MAX_QUESTION_LOAD); Integer retryCount = session.getRetryCount(); retryCount = retryCount != null ? retryCount : 0; if (retryCount < Integer.parseInt(retryLimit)) { session.setRetryCount(++retryCount); } else { //hangup so set question to null question = null; } } else { log.warning("No question found for this session :"+ sessionKey); } session.storeSession(); return handleQuestion( question, session.getAdapterConfig(), responder, sessionKey ); } else { log.warning("Strange that no session is found for: "+ sessionKey); } return Response.ok( reply ).build(); } @Path("exception") @GET @Produces("application/voicexml+xml") public Response exception(@QueryParam("questionId") String question_id, @QueryParam("sessionKey") String sessionKey) { String reply = "<vxml><exit/></vxml>"; Session session = Session.getSession(sessionKey); if (session != null && session.getQuestion() != null) { Question question = session.getQuestion(); String responder = session.getRemoteAddress(); if (session.killed) { return Response.status(Response.Status.BAD_REQUEST).build(); } dialogLog.log(LogLevel.INFO, session.getAdapterConfig(), String.format("Wrong answer received from: %s for question: %s", responder, question.getQuestion_expandedtext()), session); HashMap<String, String> extras = new HashMap<String, String>(); extras.put("sessionKey", sessionKey); question = question.event("exception", "Wrong answer received", extras, responder); //reload the session session = Session.getSession(sessionKey); session.setQuestion(question); session.storeSession(); return handleQuestion(question, session.getAdapterConfig(), responder, sessionKey); } return Response.ok(reply).build(); } /** * hang up a call based on the session. * * @param session if null, doesnt trigger an hangup event. Also expects a question to be there in this session, or atleast a * startURL from where the question can be fetched. * @return * @throws Exception */ public Response hangup(Session session) throws Exception { if (session != null) { log.info("call hangup with:" + session.getDirection() + ":" + session.getRemoteAddress() + ":" + session.getLocalAddress()); if (session.getQuestion() == null) { Question question = Question.fromURL(session.getStartUrl(), session.getAdapterConfig().getConfigId(), session.getRemoteAddress(), session.getLocalAddress(), session.getDdrRecordId(), session.getKey()); session.setQuestion(question); } if (session.getQuestion() != null && !isEventTriggered("hangup", session)) { HashMap<String, Object> timeMap = getTimeMap(session.getStartTimestamp(), session.getAnswerTimestamp(), session.getReleaseTimestamp()); timeMap.put("referredCalledId", session.getExtras().get("referredCalledId")); timeMap.put("sessionKey", session.getKey()); if(session.getExtras() != null && !session.getExtras().isEmpty()) { timeMap.putAll(session.getExtras()); } Response hangupResponse = handleQuestion(null, session.getAdapterConfig(), session.getRemoteAddress(), session.getKey()); session.getQuestion().event("hangup", "Hangup", timeMap, session.getRemoteAddress()); dialogLog.log(LogLevel.INFO, session.getAdapterConfig(), String.format("Call hungup from: %s", session.getRemoteAddress()), session); return hangupResponse; } else { log.info("no question received"); } } return Response.ok("").build(); } /** * used to trigger answered event unlike {@link VoiceXMLRESTProxy#answer(String, String, String, String, UriInfo)} * @return * @throws Exception */ public Response answered( String direction, String remoteID, String localID, String startTime, String answerTime) throws Exception { log.info( "call answered with:" + direction + "_" + remoteID + "_" + localID ); String sessionKey = AdapterAgent.ADAPTER_TYPE_BROADSOFT+"|"+localID+"|"+remoteID.split( "@outbound" )[0]; //ignore the @outbound suffix Session session = Session.getSession(sessionKey); //for direction = transfer (redirect event), json should not be null //make sure that the answered call is not triggered twice if (session != null && session.getQuestion() != null && !isEventTriggered("answered", session)) { String responder = session.getRemoteAddress(); String referredCalledId = session.getExtras().get("referredCalledId"); HashMap<String, Object> timeMap = getTimeMap(startTime, answerTime, null); timeMap.put("referredCalledId", referredCalledId); timeMap.put("sessionKey", sessionKey); session.getQuestion().event("answered", "Answered", timeMap, responder); dialogLog.log(LogLevel.INFO, session.getAdapterConfig(), String.format("Call from: %s answered by: %s", session.getLocalAddress(), responder), session); } return Response.ok( "" ).build(); } @Path("cc") @POST public Response receiveCCMessage(String xml) { log.info("Received cc: "+xml); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8"))); Node subscriberId = dom.getElementsByTagName("subscriberId").item(0); AdapterConfig config = AdapterConfig.findAdapterConfigByUsername(subscriberId.getTextContent()); Node eventData = dom.getElementsByTagName("eventData").item(0); // check if incall event if(eventData.getChildNodes().getLength()>1) { Node call = eventData.getChildNodes().item(1); Node personality = null; Node callState = null; Node remoteParty = null; Node releaseCause = null; Node answerTime = null; Node releaseTime = null; Node startTime = null; for ( int i = 0; i < call.getChildNodes().getLength(); i++ ) { Node node = call.getChildNodes().item( i ); if ( node.getNodeName().equals( "personality" ) ) { personality = node; } else if ( node.getNodeName().equals( "callState" ) ) { callState = node; } else if ( node.getNodeName().equals( "remoteParty" ) ) { remoteParty = node; } else if ( node.getNodeName().equals( "releaseCause" ) ) { releaseCause = node; } else if ( node.getNodeName().equals( "startTime" ) ) { startTime = node; } else if ( node.getNodeName().equals( "answerTime" ) ) { answerTime = node; } else if ( node.getNodeName().equals( "releaseTime" ) ) { releaseTime = node; } } if(callState!=null && callState.getNodeName().equals("callState")) { // Check if call if ( callState.getTextContent().equals( "Released" ) || callState.getTextContent().equals( "Active" ) ) { String startTimeString = startTime != null ? startTime.getTextContent() : null; String answerTimeString = answerTime != null ? answerTime.getTextContent() : null; String releaseTimeString = releaseTime != null ? releaseTime.getTextContent() : null; // Check if a sip or network call String type=""; String address=""; String fullAddress = ""; for(int i=0; i<remoteParty.getChildNodes().getLength();i++) { Node rpChild = remoteParty.getChildNodes().item(i); if(rpChild.getNodeName().equals("address")) { address=rpChild.getTextContent(); }else if(rpChild.getNodeName().equals("callType")) { type=rpChild.getTextContent(); } } fullAddress = new String(address); // Check if session can be matched to call if(type.equals("Network") || type.equals("Group") || type.equals("Unknown")) { address = address.replace("tel:", "").replace("sip:", ""); log.info("Going to format phone number: "+address); String[] addressArray = address.split("@"); try { address = PhoneNumberUtils.formatNumber(addressArray[0], null); if(addressArray.length > 1) { address += "@" + addressArray[1]; } } catch (Exception e) { log.severe(String.format("Could not format phonenumber: %s", addressArray[0])); } String sessionKey = AdapterAgent.ADAPTER_TYPE_BROADSOFT+"|"+config.getMyAddress()+"|"+ addressArray[0]; Session session = Session.getSession(sessionKey); if (session != null) { log.info("Session key: " + sessionKey); String direction = "inbound"; if (personality.getTextContent().equals("Originator") && !address.contains("outbound")) { //address += "@outbound"; direction = "transfer"; log.info("Transfer detected????"); //when the receiver hangs up, an active callstate is also triggered. // but the releaseCause is also set to Temporarily Unavailable if (callState.getTextContent().equals("Active")) { if (releaseCause == null || (releaseCause != null && !releaseCause.getTextContent().equalsIgnoreCase("Temporarily Unavailable") && !releaseCause .getTextContent() .equalsIgnoreCase("User Not Found"))) { session.setDirection(direction); session.setAnswerTimestamp(answerTimeString); session.setStartTimestamp(startTimeString); if (session.getQuestion() == null) { Question questionFromIncomingCall = Session .getQuestionFromDifferentSession(config.getConfigId(), "inbound", "referredCalledId", session.getRemoteAddress()); if (questionFromIncomingCall != null) { session.setQuestion(questionFromIncomingCall); session.storeSession(); } } session.storeSession(); answered(direction, address, config.getMyAddress(), startTimeString, answerTimeString); } //a reject from the remote user. initiate a hangup event // else{ // //drop the session first and then call hangup // return hangup(session); } } else if (personality.getTextContent().equals("Originator")) { log.info("Outbound detected?????"); direction = "outbound"; } else if (personality.getTextContent().equals("Click-to-Dial")) { log.info("CTD hangup detected?????"); direction = "outbound"; //TODO: move this to internal mechanism to check if call is started! if (releaseCause.getTextContent().equals("Server Failure")) { log.severe("Need to restart the call!!!! ReleaseCause: " + releaseCause.getTextContent()); int retry = session.getRetryCount() != null ? session.getRetryCount() : 0; if (retry < MAX_RETRIES) { Broadsoft bs = new Broadsoft(config); String extSession = bs.startCall(address, session); log.info("Restarted call extSession: " + extSession); retry++; session.setRetryCount(retry); } else { // TODO: Send mail to support!!! log.severe("Retries failed!!!"); } } else if (releaseCause.getTextContent().equals("Request Failure")) { log.severe("Restart call?? ReleaseCause: " + releaseCause.getTextContent()); int retry = session.getRetryCount() != null ? session.getRetryCount() : 0; if (retry < MAX_RETRIES) { Broadsoft bs = new Broadsoft(config); String extSession = bs.startCall(address, session); log.info("Restarted call extSession: " + extSession); retry++; session.setRetryCount(retry); } else { // TODO: Send mail to support!!! log.severe("Retries failed!!!"); } } } //store or update the session session.storeSession(); if (callState.getTextContent().equals("Released")) { boolean callReleased = false; if (session != null && direction != "transfer" && !personality.getTextContent().equals("Terminator") && fullAddress.startsWith("tel:")) { log.info("SESSSION FOUND!! SEND HANGUP!!!"); callReleased = true; } else { if (personality.getTextContent().equals("Originator") && fullAddress.startsWith("sip:")) { if (session.getAnswerTimestamp() == null && session.getStartTimestamp() != null && session.getReleaseTimestamp() != null) { callReleased = true; } log.info(String.format("Probably a disconnect of a sip. %s hangup event", callReleased ? "calling" : "not calling")); } else if (personality.getTextContent().equals("Originator") && fullAddress.startsWith("tel:")) { log.info("Probably a disconnect of a redirect. call hangup event"); callReleased = true; } else if (personality.getTextContent().equals("Terminator")) { log.info("No session for this inbound?????"); callReleased = true; } else { log.info("What the hell was this?????"); log.info("Session already ended?"); } } //update session with call timings if (callReleased) { //sometimes answerTimeStamp is only given in the ACTIVE ccxml String answerTimestamp = session.getAnswerTimestamp(); answerTimeString = (answerTimestamp != null && answerTimeString == null) ? answerTimestamp : answerTimeString; session.setAnswerTimestamp(answerTimeString); session.setStartTimestamp(startTimeString); session.setReleaseTimestamp(releaseTimeString); session.setDirection(direction); session.setRemoteAddress(address); session.setLocalAddress(config.getMyAddress()); session.storeSession(); log.info(String.format("Call ended. session updated: %s", ServerUtils.serialize(session))); //flush the keys if ddrProcessing was successful if (DDRUtils.stopDDRCosts(session.getKey(), true)) { session.drop(); } hangup(session); } } } } else { log.warning("Can't handle hangup of type: "+type+" (yet)"); } } } } else { Node eventName = dom.getElementsByTagName("eventName").item(0); if(eventName!=null && eventName.getTextContent().equals("SubscriptionTerminatedEvent")) { Broadsoft bs = new Broadsoft(config); bs.startSubscription(); log.info("Start a new dialog"); } log.info("Received a subscription update!"); } } catch (Exception e) { log.severe("Something failed: "+ e.getMessage()); e.printStackTrace(); } return Response.ok("").build(); } @GET @Path( "tts/{textForSpeech}" ) public Response redirectToSpeechEngine( @PathParam( "textForSpeech" ) String textForSpeech, @QueryParam( "hl" ) @DefaultValue( "nl-nl" ) String language, @QueryParam( "c" ) @DefaultValue( "wav" ) String contentType, @QueryParam( "r" ) @DefaultValue( "0" ) String speed, @QueryParam( "f" ) @DefaultValue( "8khz_8bit_mono" ) String format, @Context HttpServletRequest req, @Context HttpServletResponse resp ) throws IOException, URISyntaxException { String ttsURL = getTTSURL( textForSpeech, language, contentType, speed, format ); return Response.seeOther( new URI( ttsURL ) ).build(); } /** * simple endpoint for repeating a question based on its session and question id * @param sessionKey * @param questionId * @return * @throws Exception */ @GET @Path( "retry" ) public Response retryQuestion( @QueryParam( "sessionKey" ) String sessionKey ) throws Exception { Session session = Session.getSession( sessionKey ); if(session.getQuestion() != null) { return handleQuestion(session.getQuestion(), session.getAdapterConfig(), session.getRemoteAddress(), sessionKey); } return Response.ok( "" ).build(); } public class Return { ArrayList<String> prompts; Question question; public Return(ArrayList<String> prompts, Question question) { this.prompts = prompts; this.question = question; } } public Return formQuestion(Question question, String adapterID, String address, String ddrRecordId, String sessionKey) { ArrayList<String> prompts = new ArrayList<String>(); for (int count = 0; count <= LOOP_DETECTION; count++) { if (question == null) break; log.info("Going to form question of type: " + question.getType()); if (question.getType() == null) { question = null; break; } String preferred_language = question.getPreferred_language(); question.setPreferred_language(preferred_language); String qText = question.getQuestion_text(); if (qText != null && !qText.equals("")) prompts.add(qText); if (question.getType().equalsIgnoreCase("closed")) { for (Answer ans : question.getAnswers()) { String answer = ans.getAnswer_text(); if (answer != null && !answer.equals("")) prompts.add(answer); } break; //Jump from forloop } else if (question.getType().equalsIgnoreCase("comment")) { //question = question.answer(null, adapterID, null, null); break; } else if (question.getType().equalsIgnoreCase("referral")) { if (question.getUrl() != null && !question.getUrl().startsWith("tel:")) { question = Question.fromURL(question.getUrl(), adapterID, address, ddrRecordId, sessionKey); //question = question.answer(null, null, null); // break; } else { // Break out because we are going to reconnect break; } } else { break; //Jump from forloop (open questions, etc.) } } return new Return(prompts, question); } protected String renderComment(Question question,ArrayList<String> prompts, String sessionKey){ String handleTimeoutURL = "timeout"; String handleExceptionURL = "exception"; String redirectTimeoutProperty = question.getMediaPropertyValue( MediumType.BROADSOFT, MediaPropertyKey.TIMEOUT ); //assign a default timeout if one is not specified String redirectTimeout = redirectTimeoutProperty != null ? redirectTimeoutProperty : "40s"; if(!redirectTimeout.endsWith("s")) { log.warning("Redirect timeout must be end with 's'. E.g. 40s. Found: "+ redirectTimeout); redirectTimeout += "s"; } String redirectTypeProperty = question.getMediaPropertyValue( MediumType.BROADSOFT, MediaPropertyKey.TYPE ); String redirectType = redirectTypeProperty != null ? redirectTypeProperty.toLowerCase() : "bridge"; if(!redirectType.equals("blind") && !redirectType.equals("bridge")) { log.warning("Redirect must be blind or bridge. Found: "+ redirectTimeout); redirectTypeProperty = "bridge"; } StringWriter sw = new StringWriter(); try { XMLOutputter outputter = new XMLOutputter(sw, "UTF-8"); outputter.declaration(); outputter.startTag("vxml"); outputter.attribute("version", "2.1"); outputter.attribute("xmlns", "http: outputter.startTag("form"); if (question != null && question.getType().equalsIgnoreCase("referral")){ outputter.startTag("transfer"); outputter.attribute("name", "thisCall"); outputter.attribute("dest", question.getUrl()); if(redirectType.equals("bridge")) { outputter.attribute("bridge","true"); } else { outputter.attribute("bridge","false"); } outputter.attribute("connecttimeout",redirectTimeout); for (String prompt : prompts){ outputter.startTag("prompt"); outputter.startTag("audio"); outputter.attribute("src", prompt); outputter.endTag(); outputter.endTag(); } outputter.startTag("filled"); outputter.startTag("if"); outputter.attribute("cond", "thisCall=='noanswer'"); outputter.startTag("goto"); outputter.attribute("next", handleTimeoutURL+"?questionId="+question.getQuestion_id()+"&sessionKey="+URLEncoder.encode(sessionKey, "UTF-8")); outputter.endTag(); outputter.startTag("elseif"); outputter.attribute("cond", "thisCall=='busy' || thisCall=='network_busy'"); outputter.endTag(); outputter.startTag("goto"); outputter.attribute("next", handleExceptionURL+"?questionId="+question.getQuestion_id()+"&sessionKey="+URLEncoder.encode(sessionKey, "UTF-8")); outputter.endTag(); outputter.startTag("else"); outputter.endTag(); outputter.startTag("goto"); outputter.attribute("next", getAnswerUrl()+"?questionId="+question.getQuestion_id()+"&sessionKey="+URLEncoder.encode(sessionKey, "UTF-8")); outputter.endTag(); outputter.endTag(); outputter.endTag(); outputter.endTag(); } else { outputter.startTag("block"); for (String prompt : prompts){ outputter.startTag("prompt"); outputter.startTag("audio"); outputter.attribute("src", prompt); outputter.endTag(); outputter.endTag(); } if(question!=null) { outputter.startTag("goto"); outputter.attribute("next", getAnswerUrl()+"?questionId="+question.getQuestion_id()+"&sessionKey="+URLEncoder.encode(sessionKey, "UTF-8")); outputter.endTag(); } outputter.endTag(); } outputter.endTag(); outputter.endTag(); outputter.endDocument(); } catch (Exception e) { log.severe("Exception in creating question XML: "+ e.toString()); } return sw.toString(); } private String renderClosedQuestion(Question question, ArrayList<String> prompts, String sessionKey) { ArrayList<Answer> answers = question.getAnswers(); String handleTimeoutURL = "timeout"; StringWriter sw = new StringWriter(); try { XMLOutputter outputter = new XMLOutputter(sw, "UTF-8"); outputter.declaration(); outputter.startTag("vxml"); outputter.attribute("version", "2.1"); outputter.attribute("xmlns", "http: //remove the termchar operator when # is found in the answer for (Answer answer : answers) { if (answers.size() > 11 || (answer.getAnswer_text() != null && answer.getAnswer_text().contains("dtmfKey: outputter.startTag("property"); outputter.attribute("name", "termchar"); outputter.attribute("value", ""); outputter.endTag(); break; } } String noAnswerTimeout = question.getMediaPropertyValue(MediumType.BROADSOFT, MediaPropertyKey.TIMEOUT); //assign a default timeout if one is not specified noAnswerTimeout = noAnswerTimeout != null ? noAnswerTimeout : "10s"; if (!noAnswerTimeout.endsWith("s")) { log.warning("No answer timeout must end with 's'. E.g. 10s. Found: " + noAnswerTimeout); noAnswerTimeout += "s"; } outputter.startTag("property"); outputter.attribute("name", "timeout"); outputter.attribute("value", noAnswerTimeout); outputter.endTag(); outputter.startTag("menu"); for (String prompt : prompts) { outputter.startTag("prompt"); outputter.startTag("audio"); outputter.attribute("src", prompt); outputter.endTag(); outputter.endTag(); } for (int cnt = 0; cnt < answers.size(); cnt++) { Integer dtmf = cnt + 1; String dtmfValue = dtmf.toString(); if (answers.get(cnt).getAnswer_text() != null && answers.get(cnt).getAnswer_text().startsWith("dtmfKey: dtmfValue = answers.get(cnt).getAnswer_text().replace("dtmfKey://", "").trim(); } else { if (dtmf == 10) { // 10 translates into 0 dtmfValue = "0"; } else if (dtmf == 11) { dtmfValue = "*"; } else if (dtmf == 12) { dtmfValue = " } else if (dtmf > 12) { break; } } outputter.startTag("choice"); outputter.attribute("dtmf", dtmfValue); outputter.attribute("next", getAnswerUrl() + "?questionId=" + question.getQuestion_id() + "&answerId=" + answers.get(cnt).getAnswer_id() + "&answerInput=" + URLEncoder.encode(dtmfValue, "UTF-8") + "&sessionKey=" + URLEncoder.encode(sessionKey, "UTF-8")); outputter.endTag(); } outputter.startTag("noinput"); outputter.startTag("goto"); outputter.attribute("next", handleTimeoutURL + "?questionId=" + question.getQuestion_id() + "&sessionKey=" + URLEncoder.encode(sessionKey, "UTF-8")); outputter.endTag(); outputter.endTag(); outputter.startTag("nomatch"); outputter.startTag("goto"); outputter.attribute("next", getAnswerUrl() + "?questionId=" + question.getQuestion_id() + "&answerId=-1&sessionKey=" + URLEncoder.encode(sessionKey, "UTF-8")); outputter.endTag(); outputter.endTag(); outputter.endTag(); outputter.endTag(); outputter.endDocument(); } catch (Exception e) { log.severe("Exception in creating question XML: " + e.toString()); } return sw.toString(); } protected String renderOpenQuestion(Question question,ArrayList<String> prompts,String sessionKey) { String handleTimeoutURL = "/vxml/timeout"; StringWriter sw = new StringWriter(); try { XMLOutputter outputter = new XMLOutputter(sw, "UTF-8"); outputter.declaration(); outputter.startTag("vxml"); outputter.attribute("version", "2.1"); outputter.attribute("xmlns", "http: // Check if media property type equals audio // if so record audio message, if not record dtmf input String typeProperty = question.getMediaPropertyValue( MediumType.BROADSOFT, MediaPropertyKey.TYPE ); if(typeProperty!=null && typeProperty.equalsIgnoreCase("audio")) { renderVoiceMailQuestion( question, prompts, sessionKey, outputter ); } else { //see if a dtmf length is defined in the question String dtmfMinLength = question.getMediaPropertyValue( MediumType.BROADSOFT, MediaPropertyKey.ANSWER_INPUT_MIN_LENGTH ); dtmfMinLength = dtmfMinLength != null ? dtmfMinLength : ""; String dtmfMaxLength = question.getMediaPropertyValue( MediumType.BROADSOFT, MediaPropertyKey.ANSWER_INPUT_MAX_LENGTH ); dtmfMaxLength = dtmfMaxLength != null ? dtmfMaxLength : ""; String noAnswerTimeout = question.getMediaPropertyValue( MediumType.BROADSOFT, MediaPropertyKey.TIMEOUT ); String retryLimit = question.getMediaPropertyValue( MediumType.BROADSOFT, MediaPropertyKey.RETRY_LIMIT ); //assign a default timeout if one is not specified noAnswerTimeout = noAnswerTimeout != null ? noAnswerTimeout : "5s"; if(!noAnswerTimeout.endsWith("s")) { log.warning("No answer timeout must end with 's'. E.g. 10s. Found: "+ noAnswerTimeout); noAnswerTimeout += "s"; } outputter.startTag("var"); outputter.attribute("name","answerInput"); outputter.endTag(); outputter.startTag("var"); outputter.attribute("name","questionId"); outputter.attribute("expr", "'"+question.getQuestion_id()+"'"); outputter.endTag(); outputter.startTag("var"); outputter.attribute("name","sessionKey"); outputter.attribute("expr", "'"+sessionKey+"'"); outputter.endTag(); outputter.startTag("form"); outputter.startTag( "property" ); outputter.attribute( "name", "timeout" ); outputter.attribute( "value", noAnswerTimeout ); outputter.endTag(); outputter.startTag("field"); outputter.attribute("name", "answer"); outputter.startTag("grammar"); outputter.attribute("mode", "dtmf"); outputter.attribute( "src", DTMFGRAMMAR + "?minlength=" + dtmfMinLength + "&maxlength=" + dtmfMaxLength ); outputter.attribute("type", "application/srgs+xml"); outputter.endTag(); for (String prompt: prompts){ outputter.startTag("prompt"); outputter.startTag("audio"); outputter.attribute("src", prompt); outputter.endTag(); outputter.endTag(); } outputter.startTag( "noinput" ); outputter.startTag( "goto" ); if ( retryLimit == null ) { outputter.attribute( "next", handleTimeoutURL + "?questionId=" + question.getQuestion_id() + "&sessionKey=" + URLEncoder.encode(sessionKey, "UTF-8") ); } else { Integer retryCount = Question.getRetryCount( sessionKey ); if ( retryCount < Integer.parseInt( retryLimit ) ) { outputter.attribute( "next", "/retry" + "?questionId=" + question.getQuestion_id() + "&sessionKey=" + URLEncoder.encode(sessionKey, "UTF-8") ); Question.updateRetryCount( sessionKey ); } else { Question.flushRetryCount( sessionKey ); } } outputter.endTag(); outputter.endTag(); outputter.startTag("filled"); outputter.startTag("assign"); outputter.attribute("name", "answerInput"); outputter.attribute("expr", "answer$.utterance.replace(' ','','g')"); outputter.endTag(); outputter.startTag("submit"); outputter.attribute("next", getAnswerUrl()); outputter.attribute("namelist","answerInput questionId sessionKey"); outputter.endTag(); outputter.startTag("clear"); outputter.attribute("namelist", "answerInput answer"); outputter.endTag(); outputter.endTag(); outputter.endTag(); outputter.endTag(); } outputter.endTag(); outputter.endDocument(); } catch (Exception e) { log.severe("Exception in creating open question XML: "+ e.toString()); } return sw.toString(); } /** renders/updates the xml for recording an audio and posts it to the user on the callback * @param question * @param prompts * @param sessionKey * @param outputter * @throws IOException * @throws UnsupportedEncodingException */ protected void renderVoiceMailQuestion(Question question, ArrayList<String> prompts, String sessionKey, XMLOutputter outputter) throws IOException, UnsupportedEncodingException { //assign a default voice mail length if one is not specified String voiceMessageLengthProperty = question.getMediaPropertyValue(MediumType.BROADSOFT, MediaPropertyKey.VOICE_MESSAGE_LENGTH); voiceMessageLengthProperty = voiceMessageLengthProperty != null ? voiceMessageLengthProperty : "15s"; if (!voiceMessageLengthProperty.endsWith("s")) { log.warning("Voicemail length must be end with 's'. E.g. 40s. Found: " + voiceMessageLengthProperty); voiceMessageLengthProperty += "s"; } String dtmfTerm = question.getMediaPropertyValue(MediumType.BROADSOFT, MediaPropertyKey.DTMF_TERMINATE); dtmfTerm = dtmfTerm != null ? dtmfTerm : "true"; String voiceMailBeep = question.getMediaPropertyValue(MediumType.BROADSOFT, MediaPropertyKey.VOICE_MESSAGE_BEEP); voiceMailBeep = voiceMailBeep != null ? voiceMailBeep : "true"; // Fetch the upload url //String host = this.host.replace("rest/", ""); String uuid = UUID.randomUUID().toString(); String filename = uuid + ".wav"; String storedAudiofile = host + "download/" + filename; MyBlobStore store = new MyBlobStore(); String uploadURL = store.createUploadUrl(filename, "/dialoghandler/rest/download/audio.vxml"); outputter.startTag("form"); outputter.attribute("id", "ComposeMessage"); outputter.startTag("record"); outputter.attribute("name", "file"); outputter.attribute("beep", voiceMailBeep); outputter.attribute("maxtime", voiceMessageLengthProperty); outputter.attribute("dtmfterm", dtmfTerm); //outputter.attribute("finalsilence", "3s"); for (String prompt : prompts){ outputter.startTag("prompt"); outputter.attribute("timeout", "5s"); outputter.startTag("audio"); outputter.attribute("src", prompt); outputter.endTag(); outputter.endTag(); } outputter.startTag("noinput"); for (String prompt : prompts){ outputter.startTag("prompt"); outputter.startTag("audio"); outputter.attribute("src", prompt); outputter.endTag(); outputter.endTag(); } /*outputter.startTag("goto"); outputter.attribute("next", handleTimeoutURL+"?question_id="+question.getQuestion_id()+"&sessionKey="+sessionKey); outputter.endTag();*/ outputter.endTag(); outputter.endTag(); outputter.startTag("subdialog"); outputter.attribute("name", "saveWav"); outputter.attribute("src", uploadURL); outputter.attribute("namelist", "file"); outputter.attribute("method", "post"); outputter.attribute("enctype", "multipart/form-data"); outputter.startTag("filled"); outputter.startTag("if"); outputter.attribute("cond", "saveWav.response='SUCCESS'"); outputter.startTag("goto"); outputter.attribute("next", getAnswerUrl() + "?questionId=" + question.getQuestion_id() + "&sessionKey=" + URLEncoder.encode(sessionKey, "UTF-8") + "&answerInput=" + URLEncoder.encode(storedAudiofile, "UTF-8")); outputter.endTag(); outputter.startTag("else"); outputter.endTag(); for (String prompt : prompts){ outputter.startTag("prompt"); outputter.startTag("audio"); outputter.attribute("src", prompt); outputter.endTag(); outputter.endTag(); } outputter.endTag(); outputter.endTag(); } private Response handleQuestion(Question question, AdapterConfig adapterConfig, String remoteID, String sessionKey) { String result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><vxml version=\"2.1\" xmlns=\"http: Return res = formQuestion(question, adapterConfig.getConfigId(), remoteID, null, sessionKey); if (question != null && !question.getType().equalsIgnoreCase("comment")) question = res.question; Session session = Session.getSession(sessionKey); //if the adapter is a trial adapter, add a introductory node if (session != null && "true".equals(session.getExtras().get(PLAY_TRIAL_AUDIO_KEY))) { res.prompts = res.prompts != null ? res.prompts : new ArrayList<String>(); String trialAudioURL = getTrialAudioURL(question.getPreferred_language()); res.prompts.add(0, trialAudioURL); session.getExtras().put(PLAY_TRIAL_AUDIO_KEY, "false"); } log.info("question formed at handleQuestion is: " + ServerUtils.serializeWithoutException(question)); log.info("prompts formed at handleQuestion is: " + res.prompts); if (question != null) { question.generateIds(); session.setQuestion(question); session.setRemoteAddress(remoteID); session.storeSession(); //convert all text prompts to speech if (res.prompts != null) { String language = question.getPreferred_language().contains("-") ? question.getPreferred_language() : "nl-nl"; String ttsSpeedProperty = question.getMediaPropertyValue(MediumType.BROADSOFT, MediaPropertyKey.TSS_SPEED); ttsSpeedProperty = ttsSpeedProperty != null ? ttsSpeedProperty : "0"; ArrayList<String> promptsCopy = new ArrayList<String>(); for (String prompt : res.prompts) { if (!prompt.startsWith("dtmfKey: if (!prompt.endsWith(".wav")) { promptsCopy.add(getTTSURL(prompt, language, "wav", ttsSpeedProperty, null)); } else { promptsCopy.add(prompt); } } } res.prompts = promptsCopy; } if (question.getType().equalsIgnoreCase("closed")) { result = renderClosedQuestion(question, res.prompts, sessionKey); } else if (question.getType().equalsIgnoreCase("open")) { result = renderOpenQuestion(question, res.prompts, sessionKey); } else if (question.getType().equalsIgnoreCase("referral")) { if (question.getUrl() != null && question.getUrl().startsWith("tel:")) { // added for release0.4.2 to store the question in the session, //for triggering an answered event log.info(String.format("current session key before referral is: %s and remoteId %s", sessionKey, remoteID)); try { String redirectedId = PhoneNumberUtils .formatNumber(question.getUrl().replace("tel:", ""), null); //update url with formatted redirecteId. RFC3966 returns format tel:<blabla> as expected question.setUrl(PhoneNumberUtils.formatNumber(redirectedId, PhoneNumberFormat.RFC3966)); //store the remoteId as its lost while trying to trigger the answered event HashMap<String, String> extras = new HashMap<String, String>(); extras.put("referredCalledId", redirectedId); session.getExtras().putAll(extras); session.setQuestion(question); session.setRemoteAddress(remoteID); //create a new ddr record and session to catch the redirect Session referralSession = Session.getOrCreateSession(adapterConfig, redirectedId); if (session.getDirection() != null) { DDRRecord ddrRecord = DDRUtils.createDDRRecordOnOutgoingCommunication(adapterConfig, redirectedId, 1, question.getUrl()); ddrRecord.addAdditionalInfo(Session.TRACKING_TOKEN_KEY, session.getTrackingToken()); ddrRecord.createOrUpdate(); referralSession.setDdrRecordId(ddrRecord.getId()); referralSession.setDirection(session.getDirection()); referralSession.setTrackingToken(session.getTrackingToken()); } referralSession.setQuestion(session.getQuestion()); referralSession.storeSession(); session.storeSession(); } catch (Exception e) { log.severe(String.format("Phonenumber: %s is not valid", question.getUrl().replace("tel:", ""))); } result = renderComment(question, res.prompts, sessionKey); } } else if (res.prompts.size() > 0) { result = renderComment(question, res.prompts, sessionKey); } } else if (res.prompts.size() > 0) { result = renderComment(null, res.prompts, sessionKey); } else { log.info("Going to hangup? So clear Session?"); } log.info("Sending xml: " + result); return Response.ok(result).build(); } protected String getAnswerUrl() { return "answer"; } /** * @param startTime * @param answerTime * @param releaseTime * @return */ private HashMap<String, Object> getTimeMap( String startTime, String answerTime, String releaseTime ) { HashMap<String, Object> timeMap = new HashMap<String, Object>(); timeMap.put( "startTime", startTime ); timeMap.put( "answerTime", answerTime ); timeMap.put( "releaseTime", releaseTime ); return timeMap; } /** * returns the TTS URL from tts.ask-fast * * @param textForSpeech * @param language * @param contentType * @return */ private String getTTSURL( String textForSpeech, String language, String contentType, String speed, String format ) { speed = (speed != null && !speed.isEmpty()) ? speed : "0"; contentType = (contentType != null && !contentType.isEmpty()) ? contentType : "wav"; format = (format != null && !format.isEmpty()) ? format : "8khz_8bit_mono"; try { textForSpeech = URLEncoder.encode( textForSpeech.replace( "text://", "" ), "UTF-8").replace( "+", "%20" ); } catch ( UnsupportedEncodingException e ) { e.printStackTrace(); log.severe( e.getLocalizedMessage() ); } return "http://tts.ask-fast.com/api/parse?text=" + textForSpeech + "&lang=" + language + "&codec=" + contentType + "&speed=" + speed + "&format=" + format + "&type=.wav"; } /** * returns the baseURL for the audio of the trial account * @return * @throws Exception */ private String getTrialAudioURL(String language) { String agentURL = "http://" + Settings.HOST + "/dialoghandler"; if (language != null && (language.equals("nl") || language.equals("nl-nl"))) { agentURL += "/nl_trial_message.wav"; } else { agentURL += "/en_trial_message.wav"; } return agentURL; } /** * method checks with broadsoft if the session is already in place. If it is * place, it returns at error message. * * @param address * @param config * @param session * @return error message is the call is already in place. else returns null */ private static String checkIfCallAlreadyInSession(String address, AdapterConfig config, Session session) { log.warning(String.format("Existing session %s. Will check with provider if its actually true", session.getKey())); if (config != null) { Broadsoft broadsoft = new Broadsoft(config); ArrayList<String> activeCallsXML = broadsoft.getActiveCallsInfo(); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); for (String activeCallXML : activeCallsXML) { Document dom; dom = db.parse(new ByteArrayInputStream(activeCallXML.getBytes("UTF-8"))); Node addressNode = dom.getElementsByTagName("address").item(0); if (addressNode != null && addressNode.getFirstChild().getNodeValue().contains(address)) { return String.format("Session already active: %s. Cannot initiate new call!!", session.getKey()); } } } catch (Exception e) { log.severe(String.format("Session: %s found in ASK-Fast, but error occured whle trying to check status at provider end. Message: %s", session.getKey(), e.getMessage())); } } return null; } /** * check if for this session an * @param eventName * @param session * @return */ private static boolean isEventTriggered(String eventName, Session session) { if (session != null) { if (session.getExtras().get("event_" + eventName) != null) { String timestamp = TimeUtils.getStringFormatFromDateTime(Long.parseLong(session.getExtras() .get("event_" + eventName)), null); log.warning(eventName + "event already triggered before for this session at: " + timestamp); return true; } else { session.getExtras().put("event_" + eventName, String.valueOf(TimeUtils.getServerCurrentTimeInMillis())); session.storeSession(); } } return false; } }
package com.jme3.scene.plugins.blender.textures; import com.jme3.asset.AssetInfo; import java.awt.color.ColorSpace; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import jme3tools.converters.ImageToAwt; import jme3tools.converters.RGB565; import com.jme3.asset.AssetManager; import com.jme3.asset.AssetNotFoundException; import com.jme3.asset.BlenderKey; import com.jme3.asset.BlenderKey.FeaturesToLoad; import com.jme3.asset.GeneratedTextureKey; import com.jme3.asset.TextureKey; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.plugins.blender.AbstractBlenderHelper; import com.jme3.scene.plugins.blender.BlenderContext; import com.jme3.scene.plugins.blender.BlenderContext.LoadedFeatureDataType; import com.jme3.scene.plugins.blender.exceptions.BlenderFileException; import com.jme3.scene.plugins.blender.file.FileBlockHeader; import com.jme3.scene.plugins.blender.file.Pointer; import com.jme3.scene.plugins.blender.file.Structure; import com.jme3.scene.plugins.blender.textures.generating.TextureGeneratorFactory; import com.jme3.scene.plugins.blender.textures.io.PixelIOFactory; import com.jme3.scene.plugins.blender.textures.io.PixelInputOutput; import com.jme3.texture.Image; import com.jme3.texture.Image.Format; import com.jme3.texture.Texture; import com.jme3.texture.Texture.MinFilter; import com.jme3.texture.Texture.WrapMode; import com.jme3.texture.Texture2D; import com.jme3.util.BufferUtils; /** * A class that is used in texture calculations. * * @author Marcin Roguski */ public class TextureHelper extends AbstractBlenderHelper { private static final Logger LOGGER = Logger.getLogger(TextureHelper.class.getName()); // texture types public static final int TEX_NONE = 0; public static final int TEX_CLOUDS = 1; public static final int TEX_WOOD = 2; public static final int TEX_MARBLE = 3; public static final int TEX_MAGIC = 4; public static final int TEX_BLEND = 5; public static final int TEX_STUCCI = 6; public static final int TEX_NOISE = 7; public static final int TEX_IMAGE = 8; public static final int TEX_PLUGIN = 9; public static final int TEX_ENVMAP = 10; public static final int TEX_MUSGRAVE = 11; public static final int TEX_VORONOI = 12; public static final int TEX_DISTNOISE = 13; public static final int TEX_POINTDENSITY = 14; public static final int TEX_VOXELDATA = 15; private TextureGeneratorFactory textureGeneratorFactory; /** * This constructor parses the given blender version and stores the result. * It creates noise generator and texture generators. * * @param blenderVersion * the version read from the blend file * @param fixUpAxis * a variable that indicates if the Y asxis is the UP axis or not */ public TextureHelper(String blenderVersion, boolean fixUpAxis) { super(blenderVersion, false); textureGeneratorFactory = new TextureGeneratorFactory(blenderVersion); } /** * This class returns a texture read from the file or from packed blender * data. The returned texture has the name set to the value of its blender * type. * * @param tex * texture structure filled with data * @param blenderContext * the blender context * @return the texture that can be used by JME engine * @throws BlenderFileException * this exception is thrown when the blend file structure is * somehow invalid or corrupted */ public Texture getTexture(Structure tex, Structure mTex, BlenderContext blenderContext) throws BlenderFileException { Texture result = (Texture) blenderContext.getLoadedFeature(tex.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_FEATURE); if (result != null) { return result; } int type = ((Number) tex.getFieldValue("type")).intValue(); switch (type) { case TEX_IMAGE:// (it is first because probably this will be most commonly used) Pointer pImage = (Pointer) tex.getFieldValue("ima"); if (pImage.isNotNull()) { Structure image = pImage.fetchData(blenderContext.getInputStream()).get(0); Image loadedImage = this.loadImage(image, blenderContext); if(loadedImage != null) { result = new Texture2D(loadedImage); this.applyColorbandAndColorFactors(tex, result.getImage(), blenderContext); } } break; case TEX_CLOUDS: case TEX_WOOD: case TEX_MARBLE: case TEX_MAGIC: case TEX_BLEND: case TEX_STUCCI: case TEX_NOISE: case TEX_MUSGRAVE: case TEX_VORONOI: case TEX_DISTNOISE: result = new GeneratedTexture(tex, mTex, textureGeneratorFactory.createTextureGenerator(type), blenderContext); break; case TEX_NONE:// No texture, do nothing break; case TEX_POINTDENSITY: case TEX_VOXELDATA: case TEX_PLUGIN: case TEX_ENVMAP: LOGGER.log(Level.WARNING, "Unsupported texture type: {0} for texture: {1}", new Object[] { type, tex.getName() }); break; default: throw new BlenderFileException("Unknown texture type: " + type + " for texture: " + tex.getName()); } if (result != null) { result.setName(tex.getName()); result.setWrap(WrapMode.Repeat); //decide if the mipmaps will be generated switch(blenderContext.getBlenderKey().getMipmapGenerationMethod()) { case ALWAYS_GENERATE: result.setMinFilter(MinFilter.Trilinear); break; case NEVER_GENERATE: break; case GENERATE_WHEN_NEEDED: int imaflag = ((Number) tex.getFieldValue("imaflag")).intValue(); if((imaflag & 0x04) != 0) { result.setMinFilter(MinFilter.Trilinear); } break; default: throw new IllegalStateException("Unknown mipmap generation method: " + blenderContext.getBlenderKey().getMipmapGenerationMethod()); } if (type != TEX_IMAGE) {// only generated textures should have this key result.setKey(new GeneratedTextureKey(tex.getName())); } blenderContext.addLoadedFeatures(tex.getOldMemoryAddress(), tex.getName(), tex, result); } return result; } /** * This method converts the given texture into normal-map texture. * * @param source * the source texture * @param strengthFactor * the normal strength factor * @return normal-map texture */ public Image convertToNormalMapTexture(Image source, float strengthFactor) { BufferedImage sourceImage = ImageToAwt.convert(source, false, false, 0); BufferedImage heightMap = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_INT_ARGB); BufferedImage bumpMap = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_INT_ARGB); ColorConvertOp gscale = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null); gscale.filter(sourceImage, heightMap); Vector3f S = new Vector3f(); Vector3f T = new Vector3f(); Vector3f N = new Vector3f(); for (int x = 0; x < bumpMap.getWidth(); ++x) { for (int y = 0; y < bumpMap.getHeight(); ++y) { // generating bump pixel S.x = 1; S.y = 0; S.z = strengthFactor * this.getHeight(heightMap, x + 1, y) - strengthFactor * this.getHeight(heightMap, x - 1, y); T.x = 0; T.y = 1; T.z = strengthFactor * this.getHeight(heightMap, x, y + 1) - strengthFactor * this.getHeight(heightMap, x, y - 1); float den = (float) Math.sqrt(S.z * S.z + T.z * T.z + 1); N.x = -S.z; N.y = -T.z; N.z = 1; N.divideLocal(den); // setting thge pixel in the result image bumpMap.setRGB(x, y, this.vectorToColor(N.x, N.y, N.z)); } } ByteBuffer byteBuffer = BufferUtils.createByteBuffer(source.getWidth() * source.getHeight() * 3); ImageToAwt.convert(bumpMap, Format.RGB8, byteBuffer); return new Image(Format.RGB8, source.getWidth(), source.getHeight(), byteBuffer); } /** * This method decompresses the given image. If the given image is already * decompressed nothing happens and it is simply returned. * * @param image * the image to decompress * @return the decompressed image */ public Image decompress(Image image) { Format format = image.getFormat(); int depth = image.getDepth(); if(depth == 0) { depth = 1; } ArrayList<ByteBuffer> dataArray = new ArrayList<ByteBuffer>(depth); int[] sizes = image.getMipMapSizes() != null ? image.getMipMapSizes() : new int[1]; int[] newMipmapSizes = image.getMipMapSizes() != null ? new int[image.getMipMapSizes().length] : null; for (int dataLayerIndex = 0; dataLayerIndex < depth; ++dataLayerIndex) { ByteBuffer data = image.getData(dataLayerIndex); data.rewind(); if(sizes.length == 1) { sizes[0] = data.remaining(); } float widthToHeightRatio = image.getWidth() / image.getHeight();//this should always be constant for each mipmap List<DDSTexelData> texelDataList = new ArrayList<DDSTexelData>(sizes.length); int maxPosition = 0, resultSize = 0; for(int sizeIndex=0;sizeIndex<sizes.length;++sizeIndex) { maxPosition += sizes[sizeIndex]; DDSTexelData texelData = new DDSTexelData(sizes[sizeIndex], widthToHeightRatio, format); texelDataList.add(texelData); switch (format) { case DXT1:// BC1 case DXT1A: while (data.position() < maxPosition) { TexturePixel[] colors = new TexturePixel[] { new TexturePixel(), new TexturePixel(), new TexturePixel(), new TexturePixel() }; short c0 = data.getShort(); short c1 = data.getShort(); int col0 = RGB565.RGB565_to_ARGB8(c0); int col1 = RGB565.RGB565_to_ARGB8(c1); colors[0].fromARGB8(col0); colors[1].fromARGB8(col1); if (col0 > col1) { // creating color2 = 2/3color0 + 1/3color1 colors[2].fromPixel(colors[0]); colors[2].mult(2); colors[2].add(colors[1]); colors[2].divide(3); // creating color3 = 1/3color0 + 2/3color1; colors[3].fromPixel(colors[1]); colors[3].mult(2); colors[3].add(colors[0]); colors[3].divide(3); } else { // creating color2 = 1/2color0 + 1/2color1 colors[2].fromPixel(colors[0]); colors[2].add(colors[1]); colors[2].mult(0.5f); colors[3].fromARGB8(0); } int indexes = data.getInt();// 4-byte table with color indexes in decompressed table texelData.add(colors, indexes); } break; case DXT3:// BC2 while (data.position() < maxPosition) { TexturePixel[] colors = new TexturePixel[] { new TexturePixel(), new TexturePixel(), new TexturePixel(), new TexturePixel() }; long alpha = data.getLong(); float[] alphas = new float[16]; long alphasIndex = 0; for (int i = 0; i < 16; ++i) { alphasIndex |= i << i * 4; byte a = (byte) ((alpha >> i * 4 & 0x0F) << 4); alphas[i] = a >= 0 ? a / 255.0f : 1.0f - ~a / 255.0f; } short c0 = data.getShort(); short c1 = data.getShort(); int col0 = RGB565.RGB565_to_ARGB8(c0); int col1 = RGB565.RGB565_to_ARGB8(c1); colors[0].fromARGB8(col0); colors[1].fromARGB8(col1); // creating color2 = 2/3color0 + 1/3color1 colors[2].fromPixel(colors[0]); colors[2].mult(2); colors[2].add(colors[1]); colors[2].divide(3); // creating color3 = 1/3color0 + 2/3color1; colors[3].fromPixel(colors[1]); colors[3].mult(2); colors[3].add(colors[0]); colors[3].divide(3); int indexes = data.getInt();// 4-byte table with color indexes in decompressed table texelData.add(colors, indexes, alphas, alphasIndex); } break; case DXT5:// BC3 float[] alphas = new float[8]; while (data.position() < maxPosition) { TexturePixel[] colors = new TexturePixel[] { new TexturePixel(), new TexturePixel(), new TexturePixel(), new TexturePixel() }; alphas[0] = data.get() * 255.0f; alphas[1] = data.get() * 255.0f; long alphaIndices = data.get() | data.get() << 8 | data.get() << 16 | data.get() << 24 | data.get() << 32 | data.get() << 40; if (alphas[0] > alphas[1]) {// 6 interpolated alpha values. alphas[2] = (6 * alphas[0] + alphas[1]) / 7; alphas[3] = (5 * alphas[0] + 2 * alphas[1]) / 7; alphas[4] = (4 * alphas[0] + 3 * alphas[1]) / 7; alphas[5] = (3 * alphas[0] + 4 * alphas[1]) / 7; alphas[6] = (2 * alphas[0] + 5 * alphas[1]) / 7; alphas[7] = (alphas[0] + 6 * alphas[1]) / 7; } else { alphas[2] = (4 * alphas[0] + alphas[1]) * 0.2f; alphas[3] = (3 * alphas[0] + 2 * alphas[1]) * 0.2f; alphas[4] = (2 * alphas[0] + 3 * alphas[1]) * 0.2f; alphas[5] = (alphas[0] + 4 * alphas[1]) * 0.2f; alphas[6] = 0; alphas[7] = 1; } short c0 = data.getShort(); short c1 = data.getShort(); int col0 = RGB565.RGB565_to_ARGB8(c0); int col1 = RGB565.RGB565_to_ARGB8(c1); colors[0].fromARGB8(col0); colors[1].fromARGB8(col1); // creating color2 = 2/3color0 + 1/3color1 colors[2].fromPixel(colors[0]); colors[2].mult(2); colors[2].add(colors[1]); colors[2].divide(3); // creating color3 = 1/3color0 + 2/3color1; colors[3].fromPixel(colors[1]); colors[3].mult(2); colors[3].add(colors[0]); colors[3].divide(3); int indexes = data.getInt();// 4-byte table with color indexes in decompressed table texelData.add(colors, indexes, alphas, alphaIndices); } break; default: throw new IllegalStateException("Unknown compressed format: " + format); } newMipmapSizes[sizeIndex] = texelData.getSizeInBytes(); resultSize += texelData.getSizeInBytes(); } byte[] bytes = new byte[resultSize]; int offset = 0; byte[] pixelBytes = new byte[4]; for(DDSTexelData texelData : texelDataList) { for (int i = 0; i < texelData.getPixelWidth(); ++i) { for (int j = 0; j < texelData.getPixelHeight(); ++j) { if(texelData.getRGBA8(i, j, pixelBytes)) { bytes[offset + (j * texelData.getPixelWidth() + i) * 4] = pixelBytes[0]; bytes[offset + (j * texelData.getPixelWidth() + i) * 4 + 1] = pixelBytes[1]; bytes[offset + (j * texelData.getPixelWidth() + i) * 4 + 2] = pixelBytes[2]; bytes[offset + (j * texelData.getPixelWidth() + i) * 4 + 3] = pixelBytes[3]; } else { break; } } } offset += texelData.getSizeInBytes(); } dataArray.add(BufferUtils.createByteBuffer(bytes)); } Image result = depth > 1 ? new Image(Format.RGBA8, image.getWidth(), image.getHeight(), depth, dataArray) : new Image(Format.RGBA8, image.getWidth(), image.getHeight(), dataArray.get(0)); if(newMipmapSizes != null) { result.setMipMapSizes(newMipmapSizes); } return result; } /** * This method returns the height represented by the specified pixel in the * given texture. The given texture should be a height-map. * * @param image * the height-map texture * @param x * pixel's X coordinate * @param y * pixel's Y coordinate * @return height reprezented by the given texture in the specified location */ protected int getHeight(BufferedImage image, int x, int y) { if (x < 0) { x = 0; } else if (x >= image.getWidth()) { x = image.getWidth() - 1; } if (y < 0) { y = 0; } else if (y >= image.getHeight()) { y = image.getHeight() - 1; } return image.getRGB(x, y) & 0xff; } /** * This method transforms given vector's coordinates into ARGB color (A is * always = 255). * * @param x * X factor of the vector * @param y * Y factor of the vector * @param z * Z factor of the vector * @return color representation of the given vector */ protected int vectorToColor(float x, float y, float z) { int r = Math.round(255 * (x + 1f) / 2f); int g = Math.round(255 * (y + 1f) / 2f); int b = Math.round(255 * (z + 1f) / 2f); return (255 << 24) + (r << 16) + (g << 8) + b; } /** * This class returns a texture read from the file or from packed blender * data. * * @param image * image structure filled with data * @param blenderContext * the blender context * @return the texture that can be used by JME engine * @throws BlenderFileException * this exception is thrown when the blend file structure is * somehow invalid or corrupted */ protected Image loadImage(Structure image, BlenderContext blenderContext) throws BlenderFileException { LOGGER.log(Level.FINE, "Fetching texture with OMA = {0}", image.getOldMemoryAddress()); Image result = (Image) blenderContext.getLoadedFeature(image.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_FEATURE); if (result == null) { String texturePath = image.getFieldValue("name").toString(); Pointer pPackedFile = (Pointer) image.getFieldValue("packedfile"); if (pPackedFile.isNull()) { LOGGER.log(Level.INFO, "Reading texture from file: {0}", texturePath); result = this.loadImageFromFile(texturePath, blenderContext); } else { LOGGER.info("Packed texture. Reading directly from the blend file!"); Structure packedFile = pPackedFile.fetchData(blenderContext.getInputStream()).get(0); Pointer pData = (Pointer) packedFile.getFieldValue("data"); FileBlockHeader dataFileBlock = blenderContext.getFileBlock(pData.getOldMemoryAddress()); blenderContext.getInputStream().setPosition(dataFileBlock.getBlockPosition()); ImageLoader imageLoader = new ImageLoader(); // Should the texture be flipped? It works for sinbad .. result = imageLoader.loadImage(blenderContext.getInputStream(), dataFileBlock.getBlockPosition(), true); } if (result != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Adding image {0} to the loaded features with OMA = {1}", new Object[] { texturePath, image.getOldMemoryAddress() }); } blenderContext.addLoadedFeatures(image.getOldMemoryAddress(), image.getName(), image, result); } } return result; } /** * This method creates the affine transform that is used to transform a * triangle defined by one UV coordinates into a triangle defined by * different UV's. * * @param source * source UV coordinates * @param dest * target UV coordinates * @param sourceSize * the width and height of the source image * @param targetSize * the width and height of the target image * @return affine transform to transform one triangle to another */ public AffineTransform createAffineTransform(Vector2f[] source, Vector2f[] dest, int[] sourceSize, int[] targetSize) { float x11 = source[0].getX() * sourceSize[0]; float x12 = source[0].getY() * sourceSize[1]; float x21 = source[1].getX() * sourceSize[0]; float x22 = source[1].getY() * sourceSize[1]; float x31 = source[2].getX() * sourceSize[0]; float x32 = source[2].getY() * sourceSize[1]; float y11 = dest[0].getX() * targetSize[0]; float y12 = dest[0].getY() * targetSize[1]; float y21 = dest[1].getX() * targetSize[0]; float y22 = dest[1].getY() * targetSize[1]; float y31 = dest[2].getX() * targetSize[0]; float y32 = dest[2].getY() * targetSize[1]; float a1 = ((y11 - y21) * (x12 - x32) - (y11 - y31) * (x12 - x22)) / ((x11 - x21) * (x12 - x32) - (x11 - x31) * (x12 - x22)); float a2 = ((y11 - y21) * (x11 - x31) - (y11 - y31) * (x11 - x21)) / ((x12 - x22) * (x11 - x31) - (x12 - x32) * (x11 - x21)); float a3 = y11 - a1 * x11 - a2 * x12; float a4 = ((y12 - y22) * (x12 - x32) - (y12 - y32) * (x12 - x22)) / ((x11 - x21) * (x12 - x32) - (x11 - x31) * (x12 - x22)); float a5 = ((y12 - y22) * (x11 - x31) - (y12 - y32) * (x11 - x21)) / ((x12 - x22) * (x11 - x31) - (x12 - x32) * (x11 - x21)); float a6 = y12 - a4 * x11 - a5 * x12; return new AffineTransform(a1, a4, a2, a5, a3, a6); } /** * This method returns the proper pixel position on the image. * * @param pos * the relative position (value of range <0, 1> (both inclusive)) * @param size * the size of the line the pixel lies on (width, heigth or * depth) * @return the integer index of the pixel on the line of the specified width */ public int getPixelPosition(float pos, int size) { float pixelWidth = 1 / (float) size; pos *= size; int result = (int) pos; // here is where we repair floating point operations errors :) if (Math.abs(result - pos) > pixelWidth) { ++result; } return result; } /** * This method returns subimage of the give image. The subimage is * constrained by the rectangle coordinates. The source image is unchanged. * * @param image * the image to be subimaged * @param minX * minimum X position * @param minY * minimum Y position * @param maxX * maximum X position * @param maxY * maximum Y position * @return a part of the given image */ public Image getSubimage(Image image, int minX, int minY, int maxX, int maxY) { if (minY > maxY) { throw new IllegalArgumentException("Minimum Y value is higher than maximum Y value!"); } if (minX > maxX) { throw new IllegalArgumentException("Minimum Y value is higher than maximum Y value!"); } if (image.getData().size() > 1) { throw new IllegalArgumentException("Only flat images are allowed for subimage operation!"); } if (image.getMipMapSizes() != null) { LOGGER.warning("Subimaging image with mipmaps is not yet supported!"); } int width = maxX - minX; int height = maxY - minY; ByteBuffer data = BufferUtils.createByteBuffer(width * height * (image.getFormat().getBitsPerPixel() >> 3)); Image result = new Image(image.getFormat(), width, height, data); PixelInputOutput pixelIO = PixelIOFactory.getPixelIO(image.getFormat()); TexturePixel pixel = new TexturePixel(); for (int x = minX; x < maxX; ++x) { for (int y = minY; y < maxY; ++y) { pixelIO.read(image, 0, pixel, x, y); pixelIO.write(result, 0, pixel, x - minX, y - minY); } } return result; } /** * This method applies the colorband and color factors to image type * textures. If there is no colorband defined for the texture or the color * factors are all equal to 1.0f then no changes are made. * * @param tex * the texture structure * @param image * the image that will be altered if necessary * @param blenderContext * the blender context */ private void applyColorbandAndColorFactors(Structure tex, Image image, BlenderContext blenderContext) { float rfac = ((Number) tex.getFieldValue("rfac")).floatValue(); float gfac = ((Number) tex.getFieldValue("gfac")).floatValue(); float bfac = ((Number) tex.getFieldValue("bfac")).floatValue(); float[][] colorBand = new ColorBand(tex, blenderContext).computeValues(); int depth = image.getDepth() == 0 ? 1 : image.getDepth(); if (colorBand != null) { TexturePixel pixel = new TexturePixel(); PixelInputOutput imageIO = PixelIOFactory.getPixelIO(image.getFormat()); for (int layerIndex = 0; layerIndex < depth; ++layerIndex) { for (int x = 0; x < image.getWidth(); ++x) { for (int y = 0; y < image.getHeight(); ++y) { imageIO.read(image, layerIndex, pixel, x, y); int colorbandIndex = (int) (pixel.alpha * 1000.0f); pixel.red = colorBand[colorbandIndex][0] * rfac; pixel.green = colorBand[colorbandIndex][1] * gfac; pixel.blue = colorBand[colorbandIndex][2] * bfac; pixel.alpha = colorBand[colorbandIndex][3]; imageIO.write(image, layerIndex, pixel, x, y); } } } } else if (rfac != 1.0f || gfac != 1.0f || bfac != 1.0f) { TexturePixel pixel = new TexturePixel(); PixelInputOutput imageIO = PixelIOFactory.getPixelIO(image.getFormat()); for (int layerIndex = 0; layerIndex < depth; ++layerIndex) { for (int x = 0; x < image.getWidth(); ++x) { for (int y = 0; y < image.getHeight(); ++y) { imageIO.read(image, layerIndex, pixel, x, y); pixel.red *= rfac; pixel.green *= gfac; pixel.blue *= bfac; imageIO.write(image, layerIndex, pixel, x, y); } } } } } /** * This method loads the textre from outside the blend file. * * @param name * the path to the image * @param blenderContext * the blender context * @return the loaded image or null if the image cannot be found */ protected Image loadImageFromFile(String name, BlenderContext blenderContext) { if (!name.contains(".")) { return null; // no extension means not a valid image } AssetManager assetManager = blenderContext.getAssetManager(); name = name.replaceAll("\\\\", "\\/"); Image result = null; List<String> assetNames = new ArrayList<String>(); if (name.startsWith(" String relativePath = name.substring(2); // augument the path with blender key path BlenderKey blenderKey = blenderContext.getBlenderKey(); int idx = blenderKey.getName().lastIndexOf('/'); String blenderAssetFolder = blenderKey.getName().substring(0, idx != -1 ? idx : 0); assetNames.add(blenderAssetFolder + '/' + relativePath); } else {// use every path from the asset name to the root (absolute // path) String[] paths = name.split("\\/"); StringBuilder sb = new StringBuilder(paths[paths.length - 1]);// the asset name assetNames.add(paths[paths.length - 1]); for (int i = paths.length - 2; i >= 0; --i) { sb.insert(0, '/'); sb.insert(0, paths[i]); assetNames.add(0, sb.toString()); } } // now try to locate the asset for (String assetName : assetNames) { try { TextureKey key = new TextureKey(assetName); key.setGenerateMips(true); key.setAsCube(false); AssetInfo info = assetManager.locateAsset(key); if(info != null){ Texture texture = assetManager.loadTexture(key); result = texture.getImage();//get only the image break;// if no exception is thrown then accept the located asset // and break the loop } } catch (AssetNotFoundException e) { LOGGER.fine(e.getLocalizedMessage()); } } return result; } @Override public boolean shouldBeLoaded(Structure structure, BlenderContext blenderContext) { return (blenderContext.getBlenderKey().getFeaturesToLoad() & FeaturesToLoad.TEXTURES) != 0; } }
package com.jme3.scene.plugins.blender.textures; import com.jme3.asset.AssetInfo; import java.awt.color.ColorSpace; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import jme3tools.converters.ImageToAwt; import jme3tools.converters.RGB565; import com.jme3.asset.AssetManager; import com.jme3.asset.AssetNotFoundException; import com.jme3.asset.BlenderKey; import com.jme3.asset.BlenderKey.FeaturesToLoad; import com.jme3.asset.GeneratedTextureKey; import com.jme3.asset.TextureKey; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.plugins.blender.AbstractBlenderHelper; import com.jme3.scene.plugins.blender.BlenderContext; import com.jme3.scene.plugins.blender.BlenderContext.LoadedFeatureDataType; import com.jme3.scene.plugins.blender.exceptions.BlenderFileException; import com.jme3.scene.plugins.blender.file.FileBlockHeader; import com.jme3.scene.plugins.blender.file.Pointer; import com.jme3.scene.plugins.blender.file.Structure; import com.jme3.scene.plugins.blender.textures.generating.TextureGeneratorFactory; import com.jme3.scene.plugins.blender.textures.io.PixelIOFactory; import com.jme3.scene.plugins.blender.textures.io.PixelInputOutput; import com.jme3.texture.Image; import com.jme3.texture.Image.Format; import com.jme3.texture.Texture; import com.jme3.texture.Texture.MinFilter; import com.jme3.texture.Texture.WrapMode; import com.jme3.texture.Texture2D; import com.jme3.util.BufferUtils; /** * A class that is used in texture calculations. * * @author Marcin Roguski */ public class TextureHelper extends AbstractBlenderHelper { private static final Logger LOGGER = Logger.getLogger(TextureHelper.class.getName()); // texture types public static final int TEX_NONE = 0; public static final int TEX_CLOUDS = 1; public static final int TEX_WOOD = 2; public static final int TEX_MARBLE = 3; public static final int TEX_MAGIC = 4; public static final int TEX_BLEND = 5; public static final int TEX_STUCCI = 6; public static final int TEX_NOISE = 7; public static final int TEX_IMAGE = 8; public static final int TEX_PLUGIN = 9; public static final int TEX_ENVMAP = 10; public static final int TEX_MUSGRAVE = 11; public static final int TEX_VORONOI = 12; public static final int TEX_DISTNOISE = 13; public static final int TEX_POINTDENSITY = 14; public static final int TEX_VOXELDATA = 15; private TextureGeneratorFactory textureGeneratorFactory; /** * This constructor parses the given blender version and stores the result. * It creates noise generator and texture generators. * * @param blenderVersion * the version read from the blend file * @param fixUpAxis * a variable that indicates if the Y asxis is the UP axis or not */ public TextureHelper(String blenderVersion, boolean fixUpAxis) { super(blenderVersion, false); textureGeneratorFactory = new TextureGeneratorFactory(blenderVersion); } /** * This class returns a texture read from the file or from packed blender * data. The returned texture has the name set to the value of its blender * type. * * @param tex * texture structure filled with data * @param blenderContext * the blender context * @return the texture that can be used by JME engine * @throws BlenderFileException * this exception is thrown when the blend file structure is * somehow invalid or corrupted */ public Texture getTexture(Structure tex, Structure mTex, BlenderContext blenderContext) throws BlenderFileException { Texture result = (Texture) blenderContext.getLoadedFeature(tex.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_FEATURE); if (result != null) { return result; } int type = ((Number) tex.getFieldValue("type")).intValue(); switch (type) { case TEX_IMAGE:// (it is first because probably this will be most commonly used) Pointer pImage = (Pointer) tex.getFieldValue("ima"); if (pImage.isNotNull()) { Structure image = pImage.fetchData(blenderContext.getInputStream()).get(0); Texture loadedTexture = this.loadTexture(image, blenderContext); if(loadedTexture != null) { result = loadedTexture; this.applyColorbandAndColorFactors(tex, result.getImage(), blenderContext); } } break; case TEX_CLOUDS: case TEX_WOOD: case TEX_MARBLE: case TEX_MAGIC: case TEX_BLEND: case TEX_STUCCI: case TEX_NOISE: case TEX_MUSGRAVE: case TEX_VORONOI: case TEX_DISTNOISE: result = new GeneratedTexture(tex, mTex, textureGeneratorFactory.createTextureGenerator(type), blenderContext); break; case TEX_NONE:// No texture, do nothing break; case TEX_POINTDENSITY: case TEX_VOXELDATA: case TEX_PLUGIN: case TEX_ENVMAP: LOGGER.log(Level.WARNING, "Unsupported texture type: {0} for texture: {1}", new Object[] { type, tex.getName() }); break; default: throw new BlenderFileException("Unknown texture type: " + type + " for texture: " + tex.getName()); } if (result != null) { result.setName(tex.getName()); result.setWrap(WrapMode.Repeat); //decide if the mipmaps will be generated switch(blenderContext.getBlenderKey().getMipmapGenerationMethod()) { case ALWAYS_GENERATE: result.setMinFilter(MinFilter.Trilinear); break; case NEVER_GENERATE: break; case GENERATE_WHEN_NEEDED: int imaflag = ((Number) tex.getFieldValue("imaflag")).intValue(); if((imaflag & 0x04) != 0) { result.setMinFilter(MinFilter.Trilinear); } break; default: throw new IllegalStateException("Unknown mipmap generation method: " + blenderContext.getBlenderKey().getMipmapGenerationMethod()); } if (type != TEX_IMAGE) {// only generated textures should have this key result.setKey(new GeneratedTextureKey(tex.getName())); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Adding texture {0} to the loaded features with OMA = {1}", new Object[] { result.getName(), tex.getOldMemoryAddress() }); } blenderContext.addLoadedFeatures(tex.getOldMemoryAddress(), tex.getName(), tex, result); } return result; } /** * This method converts the given texture into normal-map texture. * * @param source * the source texture * @param strengthFactor * the normal strength factor * @return normal-map texture */ public Image convertToNormalMapTexture(Image source, float strengthFactor) { BufferedImage sourceImage = ImageToAwt.convert(source, false, false, 0); BufferedImage heightMap = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_INT_ARGB); BufferedImage bumpMap = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_INT_ARGB); ColorConvertOp gscale = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null); gscale.filter(sourceImage, heightMap); Vector3f S = new Vector3f(); Vector3f T = new Vector3f(); Vector3f N = new Vector3f(); for (int x = 0; x < bumpMap.getWidth(); ++x) { for (int y = 0; y < bumpMap.getHeight(); ++y) { // generating bump pixel S.x = 1; S.y = 0; S.z = strengthFactor * this.getHeight(heightMap, x + 1, y) - strengthFactor * this.getHeight(heightMap, x - 1, y); T.x = 0; T.y = 1; T.z = strengthFactor * this.getHeight(heightMap, x, y + 1) - strengthFactor * this.getHeight(heightMap, x, y - 1); float den = (float) Math.sqrt(S.z * S.z + T.z * T.z + 1); N.x = -S.z; N.y = -T.z; N.z = 1; N.divideLocal(den); // setting thge pixel in the result image bumpMap.setRGB(x, y, this.vectorToColor(N.x, N.y, N.z)); } } ByteBuffer byteBuffer = BufferUtils.createByteBuffer(source.getWidth() * source.getHeight() * 3); ImageToAwt.convert(bumpMap, Format.RGB8, byteBuffer); return new Image(Format.RGB8, source.getWidth(), source.getHeight(), byteBuffer); } /** * This method decompresses the given image. If the given image is already * decompressed nothing happens and it is simply returned. * * @param image * the image to decompress * @return the decompressed image */ public Image decompress(Image image) { Format format = image.getFormat(); int depth = image.getDepth(); if(depth == 0) { depth = 1; } ArrayList<ByteBuffer> dataArray = new ArrayList<ByteBuffer>(depth); int[] sizes = image.getMipMapSizes() != null ? image.getMipMapSizes() : new int[1]; int[] newMipmapSizes = image.getMipMapSizes() != null ? new int[image.getMipMapSizes().length] : null; for (int dataLayerIndex = 0; dataLayerIndex < depth; ++dataLayerIndex) { ByteBuffer data = image.getData(dataLayerIndex); data.rewind(); if(sizes.length == 1) { sizes[0] = data.remaining(); } float widthToHeightRatio = image.getWidth() / image.getHeight();//this should always be constant for each mipmap List<DDSTexelData> texelDataList = new ArrayList<DDSTexelData>(sizes.length); int maxPosition = 0, resultSize = 0; for(int sizeIndex=0;sizeIndex<sizes.length;++sizeIndex) { maxPosition += sizes[sizeIndex]; DDSTexelData texelData = new DDSTexelData(sizes[sizeIndex], widthToHeightRatio, format); texelDataList.add(texelData); switch (format) { case DXT1:// BC1 case DXT1A: while (data.position() < maxPosition) { TexturePixel[] colors = new TexturePixel[] { new TexturePixel(), new TexturePixel(), new TexturePixel(), new TexturePixel() }; short c0 = data.getShort(); short c1 = data.getShort(); int col0 = RGB565.RGB565_to_ARGB8(c0); int col1 = RGB565.RGB565_to_ARGB8(c1); colors[0].fromARGB8(col0); colors[1].fromARGB8(col1); if (col0 > col1) { // creating color2 = 2/3color0 + 1/3color1 colors[2].fromPixel(colors[0]); colors[2].mult(2); colors[2].add(colors[1]); colors[2].divide(3); // creating color3 = 1/3color0 + 2/3color1; colors[3].fromPixel(colors[1]); colors[3].mult(2); colors[3].add(colors[0]); colors[3].divide(3); } else { // creating color2 = 1/2color0 + 1/2color1 colors[2].fromPixel(colors[0]); colors[2].add(colors[1]); colors[2].mult(0.5f); colors[3].fromARGB8(0); } int indexes = data.getInt();// 4-byte table with color indexes in decompressed table texelData.add(colors, indexes); } break; case DXT3:// BC2 while (data.position() < maxPosition) { TexturePixel[] colors = new TexturePixel[] { new TexturePixel(), new TexturePixel(), new TexturePixel(), new TexturePixel() }; long alpha = data.getLong(); float[] alphas = new float[16]; long alphasIndex = 0; for (int i = 0; i < 16; ++i) { alphasIndex |= i << i * 4; byte a = (byte) ((alpha >> i * 4 & 0x0F) << 4); alphas[i] = a >= 0 ? a / 255.0f : 1.0f - ~a / 255.0f; } short c0 = data.getShort(); short c1 = data.getShort(); int col0 = RGB565.RGB565_to_ARGB8(c0); int col1 = RGB565.RGB565_to_ARGB8(c1); colors[0].fromARGB8(col0); colors[1].fromARGB8(col1); // creating color2 = 2/3color0 + 1/3color1 colors[2].fromPixel(colors[0]); colors[2].mult(2); colors[2].add(colors[1]); colors[2].divide(3); // creating color3 = 1/3color0 + 2/3color1; colors[3].fromPixel(colors[1]); colors[3].mult(2); colors[3].add(colors[0]); colors[3].divide(3); int indexes = data.getInt();// 4-byte table with color indexes in decompressed table texelData.add(colors, indexes, alphas, alphasIndex); } break; case DXT5:// BC3 float[] alphas = new float[8]; while (data.position() < maxPosition) { TexturePixel[] colors = new TexturePixel[] { new TexturePixel(), new TexturePixel(), new TexturePixel(), new TexturePixel() }; alphas[0] = data.get() * 255.0f; alphas[1] = data.get() * 255.0f; long alphaIndices = data.get() | data.get() << 8 | data.get() << 16 | data.get() << 24 | data.get() << 32 | data.get() << 40; if (alphas[0] > alphas[1]) {// 6 interpolated alpha values. alphas[2] = (6 * alphas[0] + alphas[1]) / 7; alphas[3] = (5 * alphas[0] + 2 * alphas[1]) / 7; alphas[4] = (4 * alphas[0] + 3 * alphas[1]) / 7; alphas[5] = (3 * alphas[0] + 4 * alphas[1]) / 7; alphas[6] = (2 * alphas[0] + 5 * alphas[1]) / 7; alphas[7] = (alphas[0] + 6 * alphas[1]) / 7; } else { alphas[2] = (4 * alphas[0] + alphas[1]) * 0.2f; alphas[3] = (3 * alphas[0] + 2 * alphas[1]) * 0.2f; alphas[4] = (2 * alphas[0] + 3 * alphas[1]) * 0.2f; alphas[5] = (alphas[0] + 4 * alphas[1]) * 0.2f; alphas[6] = 0; alphas[7] = 1; } short c0 = data.getShort(); short c1 = data.getShort(); int col0 = RGB565.RGB565_to_ARGB8(c0); int col1 = RGB565.RGB565_to_ARGB8(c1); colors[0].fromARGB8(col0); colors[1].fromARGB8(col1); // creating color2 = 2/3color0 + 1/3color1 colors[2].fromPixel(colors[0]); colors[2].mult(2); colors[2].add(colors[1]); colors[2].divide(3); // creating color3 = 1/3color0 + 2/3color1; colors[3].fromPixel(colors[1]); colors[3].mult(2); colors[3].add(colors[0]); colors[3].divide(3); int indexes = data.getInt();// 4-byte table with color indexes in decompressed table texelData.add(colors, indexes, alphas, alphaIndices); } break; default: throw new IllegalStateException("Unknown compressed format: " + format); } newMipmapSizes[sizeIndex] = texelData.getSizeInBytes(); resultSize += texelData.getSizeInBytes(); } byte[] bytes = new byte[resultSize]; int offset = 0; byte[] pixelBytes = new byte[4]; for(DDSTexelData texelData : texelDataList) { for (int i = 0; i < texelData.getPixelWidth(); ++i) { for (int j = 0; j < texelData.getPixelHeight(); ++j) { if(texelData.getRGBA8(i, j, pixelBytes)) { bytes[offset + (j * texelData.getPixelWidth() + i) * 4] = pixelBytes[0]; bytes[offset + (j * texelData.getPixelWidth() + i) * 4 + 1] = pixelBytes[1]; bytes[offset + (j * texelData.getPixelWidth() + i) * 4 + 2] = pixelBytes[2]; bytes[offset + (j * texelData.getPixelWidth() + i) * 4 + 3] = pixelBytes[3]; } else { break; } } } offset += texelData.getSizeInBytes(); } dataArray.add(BufferUtils.createByteBuffer(bytes)); } Image result = depth > 1 ? new Image(Format.RGBA8, image.getWidth(), image.getHeight(), depth, dataArray) : new Image(Format.RGBA8, image.getWidth(), image.getHeight(), dataArray.get(0)); if(newMipmapSizes != null) { result.setMipMapSizes(newMipmapSizes); } return result; } /** * This method returns the height represented by the specified pixel in the * given texture. The given texture should be a height-map. * * @param image * the height-map texture * @param x * pixel's X coordinate * @param y * pixel's Y coordinate * @return height reprezented by the given texture in the specified location */ protected int getHeight(BufferedImage image, int x, int y) { if (x < 0) { x = 0; } else if (x >= image.getWidth()) { x = image.getWidth() - 1; } if (y < 0) { y = 0; } else if (y >= image.getHeight()) { y = image.getHeight() - 1; } return image.getRGB(x, y) & 0xff; } /** * This method transforms given vector's coordinates into ARGB color (A is * always = 255). * * @param x * X factor of the vector * @param y * Y factor of the vector * @param z * Z factor of the vector * @return color representation of the given vector */ protected int vectorToColor(float x, float y, float z) { int r = Math.round(255 * (x + 1f) / 2f); int g = Math.round(255 * (y + 1f) / 2f); int b = Math.round(255 * (z + 1f) / 2f); return (255 << 24) + (r << 16) + (g << 8) + b; } /** * This class returns a texture read from the file or from packed blender * data. * * @param imageStructure * image structure filled with data * @param blenderContext * the blender context * @return the texture that can be used by JME engine * @throws BlenderFileException * this exception is thrown when the blend file structure is * somehow invalid or corrupted */ protected Texture loadTexture(Structure imageStructure, BlenderContext blenderContext) throws BlenderFileException { LOGGER.log(Level.FINE, "Fetching texture with OMA = {0}", imageStructure.getOldMemoryAddress()); Texture result = null; Image im = (Image) blenderContext.getLoadedFeature(imageStructure.getOldMemoryAddress(), LoadedFeatureDataType.LOADED_FEATURE); if (im == null) { String texturePath = imageStructure.getFieldValue("name").toString(); Pointer pPackedFile = (Pointer) imageStructure.getFieldValue("packedfile"); if (pPackedFile.isNull()) { LOGGER.log(Level.INFO, "Reading texture from file: {0}", texturePath); result = this.loadImageFromFile(texturePath, blenderContext); } else { LOGGER.info("Packed texture. Reading directly from the blend file!"); Structure packedFile = pPackedFile.fetchData(blenderContext.getInputStream()).get(0); Pointer pData = (Pointer) packedFile.getFieldValue("data"); FileBlockHeader dataFileBlock = blenderContext.getFileBlock(pData.getOldMemoryAddress()); blenderContext.getInputStream().setPosition(dataFileBlock.getBlockPosition()); ImageLoader imageLoader = new ImageLoader(); // Should the texture be flipped? It works for sinbad .. result = new Texture2D(imageLoader.loadImage(blenderContext.getInputStream(), dataFileBlock.getBlockPosition(), true)); } } else { result = new Texture2D(im); } return result; } /** * This method creates the affine transform that is used to transform a * triangle defined by one UV coordinates into a triangle defined by * different UV's. * * @param source * source UV coordinates * @param dest * target UV coordinates * @param sourceSize * the width and height of the source image * @param targetSize * the width and height of the target image * @return affine transform to transform one triangle to another */ public AffineTransform createAffineTransform(Vector2f[] source, Vector2f[] dest, int[] sourceSize, int[] targetSize) { float x11 = source[0].getX() * sourceSize[0]; float x12 = source[0].getY() * sourceSize[1]; float x21 = source[1].getX() * sourceSize[0]; float x22 = source[1].getY() * sourceSize[1]; float x31 = source[2].getX() * sourceSize[0]; float x32 = source[2].getY() * sourceSize[1]; float y11 = dest[0].getX() * targetSize[0]; float y12 = dest[0].getY() * targetSize[1]; float y21 = dest[1].getX() * targetSize[0]; float y22 = dest[1].getY() * targetSize[1]; float y31 = dest[2].getX() * targetSize[0]; float y32 = dest[2].getY() * targetSize[1]; float a1 = ((y11 - y21) * (x12 - x32) - (y11 - y31) * (x12 - x22)) / ((x11 - x21) * (x12 - x32) - (x11 - x31) * (x12 - x22)); float a2 = ((y11 - y21) * (x11 - x31) - (y11 - y31) * (x11 - x21)) / ((x12 - x22) * (x11 - x31) - (x12 - x32) * (x11 - x21)); float a3 = y11 - a1 * x11 - a2 * x12; float a4 = ((y12 - y22) * (x12 - x32) - (y12 - y32) * (x12 - x22)) / ((x11 - x21) * (x12 - x32) - (x11 - x31) * (x12 - x22)); float a5 = ((y12 - y22) * (x11 - x31) - (y12 - y32) * (x11 - x21)) / ((x12 - x22) * (x11 - x31) - (x12 - x32) * (x11 - x21)); float a6 = y12 - a4 * x11 - a5 * x12; return new AffineTransform(a1, a4, a2, a5, a3, a6); } /** * This method returns the proper pixel position on the image. * * @param pos * the relative position (value of range <0, 1> (both inclusive)) * @param size * the size of the line the pixel lies on (width, heigth or * depth) * @return the integer index of the pixel on the line of the specified width */ public int getPixelPosition(float pos, int size) { float pixelWidth = 1 / (float) size; pos *= size; int result = (int) pos; // here is where we repair floating point operations errors :) if (Math.abs(result - pos) > pixelWidth) { ++result; } return result; } /** * This method returns subimage of the give image. The subimage is * constrained by the rectangle coordinates. The source image is unchanged. * * @param image * the image to be subimaged * @param minX * minimum X position * @param minY * minimum Y position * @param maxX * maximum X position * @param maxY * maximum Y position * @return a part of the given image */ public Image getSubimage(Image image, int minX, int minY, int maxX, int maxY) { if (minY > maxY) { throw new IllegalArgumentException("Minimum Y value is higher than maximum Y value!"); } if (minX > maxX) { throw new IllegalArgumentException("Minimum Y value is higher than maximum Y value!"); } if (image.getData().size() > 1) { throw new IllegalArgumentException("Only flat images are allowed for subimage operation!"); } if (image.getMipMapSizes() != null) { LOGGER.warning("Subimaging image with mipmaps is not yet supported!"); } int width = maxX - minX; int height = maxY - minY; ByteBuffer data = BufferUtils.createByteBuffer(width * height * (image.getFormat().getBitsPerPixel() >> 3)); Image result = new Image(image.getFormat(), width, height, data); PixelInputOutput pixelIO = PixelIOFactory.getPixelIO(image.getFormat()); TexturePixel pixel = new TexturePixel(); for (int x = minX; x < maxX; ++x) { for (int y = minY; y < maxY; ++y) { pixelIO.read(image, 0, pixel, x, y); pixelIO.write(result, 0, pixel, x - minX, y - minY); } } return result; } /** * This method applies the colorband and color factors to image type * textures. If there is no colorband defined for the texture or the color * factors are all equal to 1.0f then no changes are made. * * @param tex * the texture structure * @param image * the image that will be altered if necessary * @param blenderContext * the blender context */ private void applyColorbandAndColorFactors(Structure tex, Image image, BlenderContext blenderContext) { float rfac = ((Number) tex.getFieldValue("rfac")).floatValue(); float gfac = ((Number) tex.getFieldValue("gfac")).floatValue(); float bfac = ((Number) tex.getFieldValue("bfac")).floatValue(); float[][] colorBand = new ColorBand(tex, blenderContext).computeValues(); int depth = image.getDepth() == 0 ? 1 : image.getDepth(); if (colorBand != null) { TexturePixel pixel = new TexturePixel(); PixelInputOutput imageIO = PixelIOFactory.getPixelIO(image.getFormat()); for (int layerIndex = 0; layerIndex < depth; ++layerIndex) { for (int x = 0; x < image.getWidth(); ++x) { for (int y = 0; y < image.getHeight(); ++y) { imageIO.read(image, layerIndex, pixel, x, y); int colorbandIndex = (int) (pixel.alpha * 1000.0f); pixel.red = colorBand[colorbandIndex][0] * rfac; pixel.green = colorBand[colorbandIndex][1] * gfac; pixel.blue = colorBand[colorbandIndex][2] * bfac; pixel.alpha = colorBand[colorbandIndex][3]; imageIO.write(image, layerIndex, pixel, x, y); } } } } else if (rfac != 1.0f || gfac != 1.0f || bfac != 1.0f) { TexturePixel pixel = new TexturePixel(); PixelInputOutput imageIO = PixelIOFactory.getPixelIO(image.getFormat()); for (int layerIndex = 0; layerIndex < depth; ++layerIndex) { for (int x = 0; x < image.getWidth(); ++x) { for (int y = 0; y < image.getHeight(); ++y) { imageIO.read(image, layerIndex, pixel, x, y); pixel.red *= rfac; pixel.green *= gfac; pixel.blue *= bfac; imageIO.write(image, layerIndex, pixel, x, y); } } } } } /** * This method loads the textre from outside the blend file. * * @param name * the path to the image * @param blenderContext * the blender context * @return the loaded image or null if the image cannot be found */ protected Texture loadImageFromFile(String name, BlenderContext blenderContext) { if (!name.contains(".")) { return null; // no extension means not a valid image } AssetManager assetManager = blenderContext.getAssetManager(); name = name.replaceAll("\\\\", "\\/"); Texture result = null; List<String> assetNames = new ArrayList<String>(); if (name.startsWith(" String relativePath = name.substring(2); // augument the path with blender key path BlenderKey blenderKey = blenderContext.getBlenderKey(); int idx = blenderKey.getName().lastIndexOf('/'); String blenderAssetFolder = blenderKey.getName().substring(0, idx != -1 ? idx : 0); assetNames.add(blenderAssetFolder + '/' + relativePath); } else {// use every path from the asset name to the root (absolute // path) String[] paths = name.split("\\/"); StringBuilder sb = new StringBuilder(paths[paths.length - 1]);// the asset name assetNames.add(paths[paths.length - 1]); for (int i = paths.length - 2; i >= 0; --i) { sb.insert(0, '/'); sb.insert(0, paths[i]); assetNames.add(0, sb.toString()); } } // now try to locate the asset for (String assetName : assetNames) { try { TextureKey key = new TextureKey(assetName); key.setGenerateMips(true); key.setAsCube(false); AssetInfo info = assetManager.locateAsset(key); if(info != null){ Texture texture = assetManager.loadTexture(key); result = texture;//get only the image break;// if no exception is thrown then accept the located asset // and break the loop } } catch (AssetNotFoundException e) { LOGGER.fine(e.getLocalizedMessage()); } } return result; } @Override public boolean shouldBeLoaded(Structure structure, BlenderContext blenderContext) { return (blenderContext.getBlenderKey().getFeaturesToLoad() & FeaturesToLoad.TEXTURES) != 0; } }
package guitests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; import javafx.scene.input.KeyCode; import seedu.address.logic.commands.SelectCommand; import seedu.address.ui.CommandBox; public class CommandBoxTest extends AddressBookGuiTest { private static final String COMMAND_THAT_SUCCEEDS = SelectCommand.COMMAND_WORD + " 3"; private static final String COMMAND_THAT_FAILS = "invalid command"; private GuiRobot guiRobot = new GuiRobot(); private ArrayList<String> defaultStyleOfCommandBox; private ArrayList<String> errorStyleOfCommandBox; @Before public void setUp() { defaultStyleOfCommandBox = new ArrayList<>(commandBox.getStyleClass()); assertFalse("CommandBox default style classes should not contain error style class.", defaultStyleOfCommandBox.contains(CommandBox.ERROR_STYLE_CLASS)); // build style class for error errorStyleOfCommandBox = new ArrayList<>(defaultStyleOfCommandBox); errorStyleOfCommandBox.add(CommandBox.ERROR_STYLE_CLASS); } @Test public void commandBox_startingWithSuccessfulCommand() { assertBehaviorForSuccessfulCommand(); assertBehaviorForFailedCommand(); } @Test public void commandBox_startingWithFailedCommand() { assertBehaviorForFailedCommand(); assertBehaviorForSuccessfulCommand(); // verify that style is changed correctly even after multiple consecutive successful/failed commands assertBehaviorForSuccessfulCommand(); assertBehaviorForFailedCommand(); assertBehaviorForFailedCommand(); assertBehaviorForSuccessfulCommand(); } @Test public void commandBox_handleKeyPress() { commandBox.runCommand(COMMAND_THAT_FAILS); assertEquals(errorStyleOfCommandBox, commandBox.getStyleClass()); guiRobot.push(KeyCode.ESCAPE); assertEquals(errorStyleOfCommandBox, commandBox.getStyleClass()); guiRobot.push(KeyCode.A); guiRobot.pauseForHuman(); assertEquals(defaultStyleOfCommandBox, commandBox.getStyleClass()); } @Test public void handleKeyPress_startingWithUp() { // empty history assertInputHistory(KeyCode.UP, ""); assertInputHistory(KeyCode.DOWN, ""); // one command commandBox.runCommand(COMMAND_THAT_SUCCEEDS); assertInputHistory(KeyCode.UP, COMMAND_THAT_SUCCEEDS); assertInputHistory(KeyCode.DOWN, ""); // two commands commandBox.runCommand(COMMAND_THAT_FAILS); assertInputHistory(KeyCode.UP, COMMAND_THAT_SUCCEEDS); assertInputHistory(KeyCode.UP, COMMAND_THAT_SUCCEEDS); assertInputHistory(KeyCode.DOWN, COMMAND_THAT_FAILS); assertInputHistory(KeyCode.DOWN, ""); assertInputHistory(KeyCode.DOWN, ""); assertInputHistory(KeyCode.UP, COMMAND_THAT_FAILS); // insert command in the middle of retrieving previous commands guiRobot.push(KeyCode.UP); String thirdCommand = "list"; commandBox.runCommand(thirdCommand); assertInputHistory(KeyCode.UP, thirdCommand); assertInputHistory(KeyCode.UP, COMMAND_THAT_FAILS); assertInputHistory(KeyCode.UP, COMMAND_THAT_SUCCEEDS); assertInputHistory(KeyCode.DOWN, COMMAND_THAT_FAILS); assertInputHistory(KeyCode.DOWN, thirdCommand); assertInputHistory(KeyCode.DOWN, ""); } @Test public void handleKeyPress_startingWithDown() { // empty history assertInputHistory(KeyCode.DOWN, ""); assertInputHistory(KeyCode.UP, ""); // one command commandBox.runCommand(COMMAND_THAT_SUCCEEDS); assertInputHistory(KeyCode.DOWN, ""); assertInputHistory(KeyCode.UP, COMMAND_THAT_SUCCEEDS); // two commands commandBox.runCommand(COMMAND_THAT_FAILS); assertInputHistory(KeyCode.DOWN, ""); assertInputHistory(KeyCode.UP, COMMAND_THAT_FAILS); // insert command in the middle of retrieving previous commands guiRobot.push(KeyCode.UP); String thirdCommand = "list"; commandBox.runCommand(thirdCommand); assertInputHistory(KeyCode.DOWN, ""); assertInputHistory(KeyCode.UP, thirdCommand); } /** * Runs a command that fails, then verifies that * - the return value of runCommand(...) is false, * - the text remains, * - the command box has only one ERROR_STYLE_CLASS, with other style classes untouched. */ private void assertBehaviorForFailedCommand() { assertFalse(commandBox.runCommand(COMMAND_THAT_FAILS)); assertEquals(COMMAND_THAT_FAILS, commandBox.getCommandInput()); assertEquals(errorStyleOfCommandBox, commandBox.getStyleClass()); } /** * Runs a command that succeeds, then verifies that * - the return value of runCommand(...) is true, * - the text is cleared, * - the command box does not have any ERROR_STYLE_CLASS, with style classes the same as default. */ private void assertBehaviorForSuccessfulCommand() { assertTrue(commandBox.runCommand(COMMAND_THAT_SUCCEEDS)); assertEquals("", commandBox.getCommandInput()); assertEquals(defaultStyleOfCommandBox, commandBox.getStyleClass()); } /** * Pushes {@code keycode} and checks that the input in the {@code commandBox} equals to {@code expectedCommand}. */ private void assertInputHistory(KeyCode keycode, String expectedCommand) { guiRobot.push(keycode); assertEquals(expectedCommand, commandBox.getCommandInput()); } }
package integration; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import org.openqa.selenium.Cookie; import org.openqa.selenium.WebElement; import org.testng.Assert; import org.testng.ITestContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.coveros.selenified.Selenified; import com.coveros.selenified.Locator; import com.coveros.selenified.application.App; public class ActionGetIT extends Selenified { @BeforeClass(alwaysRun = true) public void beforeClass(ITestContext test) { // set the base URL for the tests here setTestSite(this, test, "http://172.31.2.65/"); // set the author of the tests here setAuthor(this, test, "Max Saperstone\n<br/>max.saperstone@coveros.com"); // set the version of the tests or of the software, possibly with a // dynamic check setVersion(this, test, "0.0.1"); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getBrowser method") public void getBrowserTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions if (app.getBrowser().equals("NONE")) { app.getOutputFile().addError(); } // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getCapabilities method") public void getCapabilitiesTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions if (app.getCapabilities().equals(null)) { app.getOutputFile().addError(); } // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "cookie", "virtual" }, description = "An integration test to check the getCookie method") public void getCookieTest() throws IOException, ParseException { // the cookie date String dateval = "2019-12-18T12:00:00"; DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("UTC")); // use this object to manipulate the app App app = this.apps.get(); // perform some actions Cookie cookie = app.get().cookie("cookie"); Assert.assertEquals(cookie, new Cookie("cookie", "cookietest", "/", df.parse(dateval))); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "cookie", "virtual" }, description = "An integration negative test to check the getCookie method") public void negativeGetCookieTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions Cookie cookie = app.get().cookie("badcookie"); Assert.assertNull(cookie); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "cookie", "virtual" }, description = "An integration test to check the getCookieValue method") public void getCookieValueTest() throws IOException, ParseException { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String cookie = app.get().cookieValue("cookie"); Assert.assertEquals(cookie, "cookietest"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "cookie", "virtual" }, description = "An integration negative test to check the getCookieValue method") public void negativeGetCookieValueTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String cookie = app.get().cookieValue("badcookie"); Assert.assertNull(cookie); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "cookie", "virtual" }, description = "An integration test to check the getCookiePath method") public void getCookiePathTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String cookie = app.get().cookiePath("cookie"); Assert.assertEquals(cookie, "/"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "cookie", "virtual" }, description = "An integration negative test to check the getCookiePath method") public void negativeGetCookiePathTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String cookie = app.get().cookiePath("badcookie"); Assert.assertNull(cookie); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "cookie", "virtual" }, description = "An integration test to check the getCookieDomain method") public void getCookieDomainTest(ITestContext context) { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String cookie = app.get().cookieDomain("cookie"); Assert.assertEquals(cookie, getTestSite(this.getClass().getName(), context).split("/")[2].split(":")[0]); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "cookie", "virtual" }, description = "An integration negative test to check the getCookieDomain method") public void negativeGetCookieDomainTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String cookie = app.get().cookieDomain("badcookie"); Assert.assertNull(cookie); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "cookie", "virtual" }, description = "An integration test to check the getCookieExpiration method") public void getCookieExpirationTest() throws IOException, ParseException { // the cookie date String dateval = "2019-12-18T12:00:00"; DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("UTC")); // use this object to manipulate the app App app = this.apps.get(); // perform some actions Date cookie = app.get().cookieExpiration("cookie"); Assert.assertEquals(cookie, df.parse(dateval)); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "cookie", "virtual" }, description = "An integration negative test to check the getCookieExpiration method") public void negativeGetCookieExpirationTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions Date cookie = app.get().cookieExpiration("badcookie"); Assert.assertNull(cookie); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectOptions method") public void getSelectOptionsTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String[] options = app.newElement(Locator.NAME, "car_list").get().selectOptions(); Assert.assertEquals(options, new String[] { "Volvo", "Saab", "Mercedes", "Audi" }); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectOptions method") public void getSelectOptionsNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String[] options = app.newElement(Locator.NAME, "non-existent-name", 0).get().selectOptions(); Assert.assertNull(options); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectOptions method") public void getSelectValuesTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String[] options = app.newElement(Locator.NAME, "car_list").get().selectValues(); Assert.assertEquals(options, new String[] { "volvo", "saab", "mercedes", "audi" }); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectOptions method") public void getSelectValuesNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String[] options = app.newElement(Locator.NAME, "non-existent-name", 0).get().selectValues(); Assert.assertNull(options); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getNumOfSelectOptions method") public void getNumOfSelectOptionsTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions int options = app.newElement(Locator.NAME, "car_list").get().numOfSelectOptions(); Assert.assertEquals(options, 4); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getNumOfSelectOptions method") public void getNumOfSelectOptionsNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions int options = app.newElement(Locator.NAME, "non-existent-name", 0).get().numOfSelectOptions(); Assert.assertEquals(options, 0); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getNumOfTableRows method") public void getNumOfTableRowsTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions int rows = app.newElement(Locator.ID, "table").get().numOfTableRows(); Assert.assertEquals(rows, 7); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getNumOfTableRows method") public void getNumOfTableRowsNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions int rows = app.newElement(Locator.ID, "non-existent-name", 0).get().numOfTableRows(); Assert.assertEquals(rows, 0); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getNumOfTableColumns method") public void getNumOfTableColumnsTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions int columns = app.newElement(Locator.ID, "table").get().numOfTableColumns(); Assert.assertEquals(columns, 4); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getNumOfTableColumns method") public void getNumOfTableColumnsNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions int columns = app.newElement(Locator.ID, "non-existent-name", 0).get().numOfTableColumns(); Assert.assertEquals(columns, 0); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableRow method") public void getTableRowTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions List<WebElement> row = app.newElement(Locator.ID, "table").get().tableRow(1); Assert.assertEquals(row.size(), 4); Assert.assertEquals(row.get(0).getText(), "President"); Assert.assertEquals(row.get(1).getText(), "Alfreds Futterkiste"); Assert.assertEquals(row.get(2).getText(), "Maria Anders"); Assert.assertEquals(row.get(3).getText(), "Germany"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableRow method") public void getTableRowNoRowTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions List<WebElement> row = app.newElement(Locator.ID, "table", 0).get().tableRow(99); Assert.assertEquals(row, new ArrayList<>()); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableRow method") public void getTableRowNotTableTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions List<WebElement> row = app.newElement(Locator.ID, "input_box", 0).get().tableRow(1); Assert.assertNull(row); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableRow method") public void getTableRowNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions List<WebElement> row = app.newElement(Locator.ID, "non-existent-name").get().tableRow(1); Assert.assertNull(row); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableRow method") public void getTableRowsTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions List<WebElement> rows = app.newElement(Locator.ID, "table", 1).get().tableRows(); Assert.assertEquals(rows.size(), 7); Assert.assertTrue(rows.get(0).getText().matches("Company\\s*Contact\\s*Country")); Assert.assertTrue( rows.get(1).getText().matches("President\\s*Alfreds\\s*Futterkiste\\s*Maria\\s*Anders\\s*Germany")); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableRow method") public void getTableRowsNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions List<WebElement> rows = app.newElement(Locator.ID, "non-existent-name", 1).get().tableRows(); Assert.assertNull(rows); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableColumn method") public void getTableColumnTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions List<WebElement> column = app.newElement(Locator.ID, "table").get().tableColumn(1); Assert.assertEquals(column.size(), 7); Assert.assertEquals(column.get(0).getText(), "Company"); Assert.assertEquals(column.get(1).getText(), "Alfreds Futterkiste"); Assert.assertEquals(column.get(2).getText(), "Centro comercial Moctezuma"); Assert.assertEquals(column.get(3).getText(), "Ernst Handel"); Assert.assertEquals(column.get(4).getText(), "Island Trading"); Assert.assertEquals(column.get(5).getText(), "Laughing Bacchus Winecellars"); Assert.assertEquals(column.get(6).getText(), "Magazzini Alimentari Riuniti"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableColumn method") public void getTableColumnNoColumnTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions List<WebElement> column = app.newElement(Locator.ID, "table", 0).get().tableColumn(99); Assert.assertEquals(column, new ArrayList<>()); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableColumn method") public void getTableColumnNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions List<WebElement> column = app.newElement(Locator.ID, "non-existent-name").get().tableColumn(1); Assert.assertNull(column); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableColumn method") public void getTableColumnNotTableTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions List<WebElement> column = app.newElement(Locator.ID, "transparent_input").get().tableColumn(1); Assert.assertNull(column); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableColumn method") public void getTableColumnsTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions List<List<WebElement>> columns = app.newElement(Locator.ID, "table", 1).get().tableColumns(); Assert.assertEquals(columns.size(), 4); Assert.assertEquals(columns.get(1).get(0).getText(), "Company"); Assert.assertEquals(columns.get(1).get(1).getText(), "Alfreds Futterkiste"); Assert.assertEquals(columns.get(1).get(2).getText(), "Centro comercial Moctezuma"); Assert.assertEquals(columns.get(1).get(3).getText(), "Ernst Handel"); Assert.assertEquals(columns.get(1).get(4).getText(), "Island Trading"); Assert.assertEquals(columns.get(1).get(5).getText(), "Laughing Bacchus Winecellars"); Assert.assertEquals(columns.get(1).get(6).getText(), "Magazzini Alimentari Riuniti"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableColumn method") public void getTableColumnsNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions List<List<WebElement>> columns = app.newElement(Locator.ID, "non-existent-name", 1).get().tableColumns(); Assert.assertNull(columns); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableCell method") public void getTableCellTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions WebElement cell = app.newElement(Locator.ID, "table").get().tableCell(1, 1); Assert.assertEquals(cell.getText(), "Alfreds Futterkiste"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableCell method") public void getTableCellNoCellWideTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions WebElement cell = app.newElement(Locator.ID, "table", 0).get().tableCell(1, 99); Assert.assertNull(cell); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableCell method") public void getTableCellNoCellLongTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions WebElement cell = app.newElement(Locator.ID, "table").get().tableCell(99, 1); Assert.assertNull(cell); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableCell method") public void getTableCellNoCellTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions WebElement cell = app.newElement(Locator.ID, "table").get().tableCell(99, 99); Assert.assertNull(cell); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getTableCell method") public void getTableCellNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions WebElement cell = app.newElement(Locator.ID, "non-existent-name").get().tableCell(1, 1); Assert.assertNull(cell); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectedText method") public void getSelectedTextTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String text = app.newElement(Locator.ID, "car_list").get().selectedOption(); Assert.assertEquals(text, "Volvo"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectedText method") public void getSelectedTextNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String text = app.newElement(Locator.ID, "non-existent-name", 0).get().selectedOption(); Assert.assertNull(text); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectedText method") public void getSelectedTextNotSelectTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String text = app.newElement(Locator.ID, "table").get().selectedOption(); Assert.assertNull(text); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectedTexts method") public void getSelectedTextsTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String[] text = app.newElement(Locator.ID, "car_list").get().selectedOptions(); Assert.assertEquals(text, new String[] { "Volvo" }); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectedTexts method") public void getSelectedTextsNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String[] text = app.newElement(Locator.ID, "non-existent-name", 0).get().selectedOptions(); Assert.assertNull(text); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectedTexts method") public void getSelectedTextsNotSelectTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String[] text = app.newElement(Locator.ID, "table").get().selectedOptions(); Assert.assertNull(text); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectedValue method") public void getSelectedValueTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String value = app.newElement(Locator.ID, "car_list").get().selectedValue(); Assert.assertEquals(value, "volvo"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectedValue method") public void getSelectedValueNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String value = app.newElement(Locator.ID, "non-existent-name", 0).get().selectedValue(); Assert.assertNull(value); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectedValue method") public void getSelectedValueNotSelectTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String value = app.newElement(Locator.ID, "table").get().selectedValue(); Assert.assertNull(value); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectedValues method") public void getSelectedValuesTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String[] value = app.newElement(Locator.ID, "car_list").get().selectedValues(); Assert.assertEquals(value, new String[] { "volvo" }); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectedValues method") public void getSelectedValuesNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String[] value = app.newElement(Locator.ID, "non-existent-name", 0).get().selectedValues(); Assert.assertNull(value); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getSelectedValues method") public void getSelectedValuesNotSelectTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String[] value = app.newElement(Locator.ID, "table").get().selectedValues(); Assert.assertNull(value); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getText method") public void getTextTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String text = app.newElement(Locator.ID, "disable_click").get().text(); Assert.assertEquals(text, "Click me to Disable/Enable a html button"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getText method") public void getTextNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String text = app.newElement(Locator.ID, "non-existent-name", 0).get().text(); Assert.assertNull(text); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getValue method") public void getValueTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String text = app.newElement(Locator.ID, "input_box").get().value(); Assert.assertEquals(text, ""); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getValue method") public void getValueNotInputTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String text = app.newElement(Locator.ID, "disable_click", 0).get().value(); Assert.assertNull(text); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getValue method") public void getValueNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String text = app.newElement(Locator.ID, "non-existent-name").get().value(); Assert.assertNull(text); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get" }, description = "An integration test to check the getCss method") public void getCssTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String css = app.newElement(Locator.ID, "disable_click").get().css("display"); Assert.assertEquals(css, "block"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get" }, description = "An integration test to check the getCss method") public void getCssWonkyTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String css = app.newElement(Locator.ID, "disable_click", 0).get().css("some-bad-css-attribute"); Assert.assertEquals(css, ""); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get" }, description = "An integration test to check the getCss method") public void getCssNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String css = app.newElement(Locator.ID, "non-existent-name").get().css("display"); Assert.assertNull(css); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getAttribute method") public void getAttributeTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String attribute = app.newElement(Locator.ID, "disable_click").get().attribute("class"); Assert.assertEquals(attribute, "click"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getAttribute method") public void getAttributeWonkyTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String attribute = app.newElement(Locator.ID, "disable_click", 0).get().attribute("some-bad-attribute"); Assert.assertNull(attribute); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getAttribute method") public void getAttributeNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String attribute = app.newElement(Locator.ID, "non-existent-name").get().attribute("display"); Assert.assertNull(attribute); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get" }, description = "An integration test to check the getAllAttribute method") public void getAllAttributeTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions Map<String, String> attributes = app.newElement(Locator.ID, "disable_click").get().allAttributes(); Map<String, String> expected = new HashMap<>(); expected.put("id", "disable_click"); expected.put("class", "click"); Assert.assertEquals(attributes, expected); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get" }, description = "An integration test to check the getAllAttribute method") public void getAllAttributeNoneTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions Map<String, String> attributes = app.newElement(Locator.TAGNAME, "thead", 0).get().allAttributes(); Map<String, String> expected = new HashMap<>(); Assert.assertEquals(attributes, expected); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "A negative integration test to check the getAllAttribute method") public void getAllAttributeNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions Map<String, String> attributes = app.newElement(Locator.ID, "non-existent-name").get().allAttributes(); Assert.assertEquals(attributes, new HashMap<>()); // verify 0 issue finish(); } @Test(groups = { "integration", "actions", "get" }, description = "An integration test to check the getEval method") public void getEvalTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String location = (String) app.get().eval("document.location"); Assert.assertNull(location); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get" }, description = "An integration test to check the getEval method") public void getElementEvalTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String location = (String) app.newElement(Locator.ID, "disable_click", 0).get().eval("document.location"); Assert.assertNull(location); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get" }, description = "A negative integration test to check the getEval method") public void getElementEvalNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions String location = (String) app.newElement(Locator.ID, "non-existent-name").get().eval("document.location"); Assert.assertNull(location); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get" }, description = "An integration test to check the getPrompt method") public void getPromptTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions app.newElement(Locator.ID, "prompt_button").click(); String prompt = app.get().prompt(); Assert.assertEquals(prompt, "What do you think?"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get" }, description = "A integration negative test to check the getPrompt method") public void negativeGetPromptTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions app.get().prompt(); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get" }, description = "An integration test to check the getConfirmation method") public void getConfirmationTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions app.newElement(Locator.ID, "confirm_button").click(); String confirm = app.get().confirmation(); Assert.assertEquals(confirm, "Is this not great?"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get" }, description = "An integration negative test to check the getConfirmation method") public void negativeGetConfirmationTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions app.get().confirmation(); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get" }, description = "An integration test to check the getAlert method") public void getAlertTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions app.newElement(Locator.ID, "disable_click").click(); app.newElement(Locator.ID, "alert_button").click(); String alert = app.get().alert(); Assert.assertEquals(alert, "Enabled!"); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get" }, description = "An integration negative test to check the getAlert method") public void negativeGetAlertTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions app.get().alert(); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getHtmlSource method") public void getHtmlSourceTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions app.newElement(Locator.ID, "submit_button", 0).click(); String source = app.get().htmlSource(); Assert.assertTrue(source.contains("You're on the next page")); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getElementMatchCount method") public void getElementMatchCountTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions Assert.assertEquals(app.newElement(Locator.ID, "submit_button").get().matchCount(), 1); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration test to check the getElementMatchCount method") public void getElementMatchCountMultipleTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions Assert.assertEquals(app.newElement(Locator.CLASSNAME, "overlay").get().matchCount(), 3); // verify no issues finish(); } @Test(groups = { "integration", "actions", "get", "virtual" }, description = "An integration negative test to check the getElementMatchCount method") public void getElementMatchCountNotExistTest() { // use this object to manipulate the app App app = this.apps.get(); // perform some actions Assert.assertEquals(app.newElement(Locator.ID, "non-existent-name").get().matchCount(), 0); // verify no issues finish(); } }
package io.javalin; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.List; import java.util.Random; import org.junit.Ignore; import org.junit.Test; import io.javalin.builder.CookieBuilder; import io.javalin.core.util.Util; import com.mashape.unirest.http.HttpMethod; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; public class TestResponse extends _UnirestBaseTest { private String MY_BODY = "" + "This is my body, and I live in it. It's 31 and 6 months old. " + "It's changed a lot since it was new. It's done stuff it wasn't built to do. " + "I often try to fill if up with wine. - Tim Minchin"; @Test public void test_resultString() throws Exception { app.get("/hello", ctx -> ctx.status(418) .result(MY_BODY) .header("X-HEADER-1", "my-header-1") .header("X-HEADER-2", "my-header-2")); HttpResponse<String> response = call(HttpMethod.GET, "/hello"); assertThat(response.getStatus(), is(418)); assertThat(response.getBody(), is(MY_BODY)); assertThat(response.getHeaders().getFirst("X-HEADER-1"), is("my-header-1")); assertThat(response.getHeaders().getFirst("X-HEADER-2"), is("my-header-2")); } @Test public void test_resultStream() throws Exception { byte[] buf = new byte[65537]; // big and not on a page boundary new Random().nextBytes(buf); app.get("/stream", ctx -> ctx.result(new ByteArrayInputStream(buf))); HttpResponse<String> response = call(HttpMethod.GET, "/stream"); ByteArrayOutputStream bout = new ByteArrayOutputStream(); assertThat(Util.INSTANCE.copyStream(response.getRawBody(), bout), is((long) buf.length)); assertThat(buf, equalTo(bout.toByteArray())); } @Test public void test_redirect() throws Exception { app.get("/hello", ctx -> ctx.redirect("/hello-2")); app.get("/hello-2", ctx -> ctx.result("Redirected")); assertThat(GET_body("/hello"), is("Redirected")); } @Test public void test_redirectWithStatus() throws Exception { app.get("/hello", ctx -> ctx.redirect("/hello-2", 302)); app.get("/hello-2", ctx -> ctx.result("Redirected")); Unirest.setHttpClient(noRedirectClient); // disable redirects HttpResponse<String> response = call(HttpMethod.GET, "/hello"); assertThat(response.getStatus(), is(302)); Unirest.setHttpClient(defaultHttpClient); // re-enable redirects response = call(HttpMethod.GET, "/hello"); assertThat(response.getBody(), is("Redirected")); } @Test public void test_createCookie() throws Exception { app.post("/create-cookies", ctx -> ctx.cookie("name1", "value1").cookie("name2", "value2")); HttpResponse<String> response = call(HttpMethod.POST, "/create-cookies"); List<String> cookies = response.getHeaders().get("Set-Cookie"); assertThat(cookies, hasItem("name1=value1")); assertThat(cookies, hasItem("name2=value2")); } @Test public void test_deleteCookie() throws Exception { app.post("/create-cookie", ctx -> ctx.cookie("name1", "value1")); app.post("/delete-cookie", ctx -> ctx.removeCookie("name1")); HttpResponse<String> response = call(HttpMethod.POST, "/create-cookies"); List<String> cookies = response.getHeaders().get("Set-Cookie"); assertThat(cookies, is(nullValue())); } @Test @Ignore("Interferes with TestRequest#test_getMultipleCookies on Travis for some reason...") public void test_cookieBuilder() throws Exception { app.post("/create-cookie", ctx -> { ctx.cookie(CookieBuilder.cookieBuilder("Test", "Tast")); }); HttpResponse<String> response = call(HttpMethod.POST, "/create-cookie"); List<String> cookies = response.getHeaders().get("Set-Cookie"); assertThat(cookies, hasItem("Test=Tast")); } }
package org.jtrfp.trcl; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.core.TRFactory; import org.jtrfp.trcl.obj.Positionable; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class CameraIT { protected Camera subject; protected Positionable[] zeroPositionables; @Before public void setUp() throws Exception { subject = new Camera(); zeroPositionables = new Positionable[2]; for(int i=0; i<2; i++){ Positionable pos = mock(Positionable.class); when(pos.getPosition()).thenReturn(new double[]{0,0,0}); zeroPositionables[i]=pos; } } @After public void tearDown() throws Exception { } //@Test public void testEmpty() { assertTrue(subject.getRelevancePairs() .isEmpty()); assertTrue(subject.getFlatRelevanceCollection().isEmpty()); assertTrue(subject.getRelevanceCollections() .isEmpty()); } //@Test public void testAddEmptyGrid(){ SpacePartitioningGrid<Positionable> spg = new SpacePartitioningGrid<Positionable>(){}; subject.addGrid(spg); assertTrue(subject.getRelevancePairs() .isEmpty()); assertTrue(subject.getFlatRelevanceCollection().isEmpty()); assertTrue(subject.getRelevanceCollections() .isEmpty()); } private void singleThreadExecutorBarrier(ExecutorService ex){ try{ex.submit(new Runnable(){public void run(){}}).get();} catch(ExecutionException e){Assert.fail(e.getLocalizedMessage());} catch(InterruptedException e){Assert.fail(e.getLocalizedMessage());} } // @Test public void testAddSingleCubeGridChangePosition(){//Use of Executors has broken this test. subject.setPosition(new Vector3D(0,0,0)); SpacePartitioningGrid<Positionable> spg = new SpacePartitioningGrid<Positionable>(){}; //spg.activate(); spg.add(zeroPositionables[0]);spg.add(zeroPositionables[1]); subject.addGrid(spg); singleThreadExecutorBarrier(World.relevanceExecutor); subject.setPosition(new Vector3D(0,0,0)); subject.notifyPositionChange(); singleThreadExecutorBarrier(World.relevanceExecutor); assertFalse(subject.getRelevancePairs() .isEmpty()); assertFalse(subject.getFlatRelevanceCollection().isEmpty()); assertFalse(subject.getRelevanceCollections() .isEmpty()); subject.setPosition(new Vector3D(TRFactory.mapSquareSize*20*7,TRFactory.mapSquareSize*20*7,TRFactory.mapSquareSize*20*7)); subject.notifyPositionChange(); singleThreadExecutorBarrier(World.relevanceExecutor); assertTrue(subject.getRelevancePairs() .isEmpty()); assertTrue(subject.getRelevanceCollections() .isEmpty()); assertTrue(subject.getFlatRelevanceCollection().isEmpty()); } //@Test public void testAddSingleCubeGridVisibleEverywhere(){//Use of Executors has broken this test SpacePartitioningGrid<Positionable> spg = new SpacePartitioningGrid<Positionable>(){}; //spg.activate(); Positionable[] vePositionables = new Positionable[2]; for(int i=0; i<2; i++){ Positionable pos=mock(Positionable.class); when(pos.getPosition()).thenReturn(new double[]{Double.NaN,Double.NaN,Double.NaN}); vePositionables[i]=pos; } spg.add(vePositionables[0]);spg.add(vePositionables[1]); subject.addGrid(spg); subject.setPosition(new Vector3D(0,0,0)); subject.notifyPositionChange(); singleThreadExecutorBarrier(World.relevanceExecutor); assertFalse(subject.getRelevancePairs() .isEmpty()); assertFalse(subject.getFlatRelevanceCollection().isEmpty()); assertFalse(subject.getRelevanceCollections() .isEmpty()); subject.setPosition(new Vector3D(TRFactory.mapSquareSize*20*7,TRFactory.mapSquareSize*20*7,TRFactory.mapSquareSize*20*7)); subject.notifyPositionChange(); singleThreadExecutorBarrier(World.relevanceExecutor); assertFalse(subject.getRelevancePairs() .isEmpty()); assertFalse(subject.getRelevanceCollections() .isEmpty()); assertFalse(subject.getFlatRelevanceCollection().isEmpty()); }//end testAddSingleCubeGridVisibleEverywhere() }//end CameraTest
package graphene.dao.es; import graphene.dao.DataSourceListDAO; import graphene.dao.DocumentBuilder; import graphene.model.idl.G_BoundedRange; import graphene.model.idl.G_CallBack; import graphene.model.idl.G_Constraint; import graphene.model.idl.G_DataAccess; import graphene.model.idl.G_DateRange; import graphene.model.idl.G_DirectionFilter; import graphene.model.idl.G_Entity; import graphene.model.idl.G_EntityQuery; import graphene.model.idl.G_LevelOfDetail; import graphene.model.idl.G_Link; import graphene.model.idl.G_LinkEntityTypeFilter; import graphene.model.idl.G_LinkTag; import graphene.model.idl.G_PropertyDescriptors; import graphene.model.idl.G_PropertyMatchDescriptor; import graphene.model.idl.G_PropertyType; import graphene.model.idl.G_SearchResult; import graphene.model.idl.G_SearchResults; import graphene.model.idl.G_SymbolConstants; import graphene.model.idl.G_TransactionResults; import graphene.model.idlhelper.PropertyMatchDescriptorHelper; import graphene.model.idlhelper.QueryHelper; import graphene.model.idlhelper.SingletonRangeHelper; import graphene.util.StringUtils; import graphene.util.stats.TimeReporter; import graphene.util.validator.ValidationUtils; import io.searchbox.client.JestResult; import io.searchbox.core.Count; import io.searchbox.core.CountResult; import io.searchbox.core.Delete; import io.searchbox.core.Index; import io.searchbox.core.Search; import io.searchbox.core.Search.Builder; import io.searchbox.core.SearchScroll; import io.searchbox.indices.CreateIndex; import io.searchbox.indices.IndicesExists; import io.searchbox.params.Parameters; import io.searchbox.params.SearchType; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import org.apache.avro.AvroRemoteException; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.ioc.annotations.Symbol; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.joda.time.DateTime; import org.slf4j.Logger; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; /** * This is a basic class that you can use to communicate with ElasticSearch * through Jest, which does the talking over REST. * * The benefit of using Jest over the ElasticSearchAPI directly, is that you are * not bound to a specific version of the ElasticSearch API. (i.e. Changes at * the REST level happen much less frequently, and you have greater flexibility * with using multiple ElasticSearch versions at customer sites) * * @author djue * */ public class BasicESDAO implements G_DataAccess { /** * Use this flag if you want to supply an es string query that will go * directly into a SearchSourceBuilder. */ public static final String ESQUERY = "_esquery"; public static final String ESFIELDS = "_esfields"; public static final String ESTYPE = "_estype"; private static final int MAX_TO_GET_AT_ONCE = 1000000; private static final int PAGESIZE = 200; public static final String ESID = "_esid"; public static final String ESBOOST = "_esboost"; /* * can reuse, share globally; */ protected static ObjectMapper mapper = new ObjectMapper(); public static ArrayNode getListOfHitsFromResult(final JestResult jestResult) throws JsonParseException, JsonMappingException, IOException { final JsonNode rootNode = mapper.readValue(jestResult.getJsonString(), JsonNode.class); final List<JsonNode> hits = rootNode.get("hits").findValues("hits"); final ArrayNode actualListOfHits = (ArrayNode) hits.get(0); return actualListOfHits; } private String index; protected Logger logger; protected ESRestAPIConnection c; protected String auth = null; protected String type = "_all"; @Inject @Symbol(JestModule.ES_READ_DELAY_MS) protected long ES_READ_DELAY_MS; @Inject @Symbol(JestModule.ES_DEFAULT_TIMEOUT) protected String defaultESTimeout; @Inject @Symbol(G_SymbolConstants.DEFAULT_MAX_SEARCH_RESULTS) protected long defaultMaxSearchResults; @Inject @Symbol(JestModule.ES_SERVER) private String host; @Inject private DataSourceListDAO dao; @Inject private DocumentBuilder db; private final String minimumShouldMatchRule = "1<30%"; static final String DATE_FORMAT = "yyyy-MM-dd"; protected BoolQueryBuilder buildBooleanConstraints(final PropertyMatchDescriptorHelper pmdh, BoolQueryBuilder bool) { final String key = pmdh.getKey(); final G_Constraint constraint = pmdh.getConstraint(); boolean constraintUsed = false; boolean createdNew = false; if (bool == null) { bool = QueryBuilders.boolQuery(); createdNew = true; } String[] fieldArray = new String[1]; fieldArray[0] = key; final Map<String, ArrayList<String>> fieldMappings = dao.getFieldMappings(); if (ValidationUtils.isValid(fieldMappings)) { final ArrayList<String> specificFields = fieldMappings.get(key); if (specificFields != null) { fieldArray = specificFields.toArray(new String[specificFields.size()]); } else { logger.warn("Could not find specific fields for the key " + pmdh.getKey()); } // Try the singleton range first if (ValidationUtils.isValid(pmdh.getSingletonRange())) { final String text = (String) pmdh.getSingletonRange().getValue(); switch (constraint) { case EQUALS: for (final String sf : fieldArray) { bool = bool.must(QueryBuilders.matchPhraseQuery(sf, text)); constraintUsed = true; } break; case CONTAINS: bool = bool.should(QueryBuilders.multiMatchQuery(text, fieldArray)); constraintUsed = true; break; case STARTS_WITH: for (final String sf : fieldArray) { bool = bool.should(QueryBuilders.prefixQuery(sf, text.toLowerCase())); constraintUsed = true; } break; case NOT: for (final String sf : fieldArray) { bool = bool.mustNot(QueryBuilders.matchPhraseQuery(sf, text)); constraintUsed = true; } break; case LIKE: bool = bool.must(QueryBuilders.fuzzyLikeThisQuery(fieldArray).likeText(text)); constraintUsed = true; break; default: break; } } else if (ValidationUtils.isValid(pmdh.getListRange())) { for (final Object text : pmdh.getListRange().getValues()) { switch (constraint) { case EQUALS: bool = bool.must(QueryBuilders.matchPhraseQuery(key, text)); constraintUsed = true; break; case CONTAINS: bool = bool.should(QueryBuilders.multiMatchQuery(text, fieldArray)); // bool = bool.should(QueryBuilders.matchPhraseQuery(key, text)); constraintUsed = true; break; case STARTS_WITH: bool = bool.must(QueryBuilders.matchPhrasePrefixQuery(key, text)); constraintUsed = true; break; case NOT: bool = bool.mustNot(QueryBuilders.matchPhraseQuery(key, text)); constraintUsed = true; break; default: break; } } } else if (ValidationUtils.isValid(pmdh.getBoundedRange())) { final G_BoundedRange br = pmdh.getBoundedRange(); // Enumerate any specific fields that this range can apply to. String[] rangeFieldArray = new String[1]; rangeFieldArray[0] = key; final ArrayList<String> specificRangeFields = dao.getRangeMappings().get(pmdh.getKey()); if (specificRangeFields != null) { rangeFieldArray = specificRangeFields.toArray(new String[specificRangeFields.size()]); } else { logger.warn("Could not find specific fields for the key " + pmdh.getKey()); } Object start = null; Object end = null; if (br.getStart() != null) { switch (pmdh.getType()) { case LONG: start = br.getStart(); break; case STRING: start = br.getStart().toString(); break; case DATE: final DateTime dt = (DateTime) br.getStart(); start = dt.toString(DATE_FORMAT); break; default: break; } } if (br.getEnd() != null) { switch (pmdh.getType()) { case LONG: end = br.getEnd(); break; case STRING: end = br.getEnd().toString(); break; case DATE: final DateTime dt = (DateTime) br.getEnd(); end = dt.toString(DATE_FORMAT); break; default: break; } } for (final String sf : rangeFieldArray) { if (ValidationUtils.isValid(start, end)) { bool = bool.should(QueryBuilders.rangeQuery(sf).from(start).to(end)); constraintUsed = true; } else if (ValidationUtils.isValid(start)) { bool = bool.should(QueryBuilders.rangeQuery(sf).gt(start)); constraintUsed = true; } else if (ValidationUtils.isValid(end)) { bool = bool.should(QueryBuilders.rangeQuery(sf).lt(end)); constraintUsed = true; } } } else { logger.error("Unknown range type for " + pmdh); } } else { logger.error("No field mappings available"); } if ((constraintUsed == false) && (createdNew == true)) { // boolean was created but not used. bool = null; } return bool; } protected io.searchbox.core.Search.Builder buildSearchAction(final G_EntityQuery pq) { final Set<String> esTypes = new HashSet<String>(); final Set<String> esFields = new HashSet<String>(); final Set<String> esNotFields = new HashSet<String>(); final Set<String> esIds = new HashSet<String>(); SearchSourceBuilder ssb = new SearchSourceBuilder(); if (ValidationUtils.isValid(pq) && ValidationUtils.isValid(pq.getPropertyMatchDescriptors())) { BoolQueryBuilder bool = null; String queryString = null; for (final G_PropertyMatchDescriptor d : pq.getPropertyMatchDescriptors()) { final PropertyMatchDescriptorHelper pmdh = PropertyMatchDescriptorHelper.from(d); if (ValidationUtils.isValid(pmdh)) { final String key = pmdh.getKey(); if (key.equals(ESTYPE)) { if (ValidationUtils.isValid(pmdh.getSingletonRange())) { if (ValidationUtils.isValid(pmdh.getSingletonRange().getValue()) && pmdh.getSingletonRange().getType().equals(G_PropertyType.STRING)) { esTypes.add((String) pmdh.getSingletonRange().getValue()); } } else if (ValidationUtils.isValid(pmdh.getListRange()) && ValidationUtils.isValid(pmdh.getListRange().getValues()) && pmdh.getListRange().getType().equals(G_PropertyType.STRING)) { for (final Object t : pmdh.getListRange().getValues()) { esTypes.add((String) t); } } logger.debug("Types are now " + StringUtils.coalesc(", ", esTypes.toArray())); } else if (key.equals(ESID)) { if (ValidationUtils.isValid(pmdh.getSingletonRange())) { if (ValidationUtils.isValid(pmdh.getSingletonRange().getValue()) && pmdh.getSingletonRange().getType().equals(G_PropertyType.STRING)) { esIds.add((String) pmdh.getSingletonRange().getValue()); } } else if (ValidationUtils.isValid(pmdh.getListRange()) && ValidationUtils.isValid(pmdh.getListRange().getValues()) && pmdh.getListRange().getType().equals(G_PropertyType.STRING)) { for (final Object t : pmdh.getListRange().getValues()) { esIds.add((String) t); } } logger.debug("Adding id, ids are now " + StringUtils.coalesc("", esIds.toArray())); } else if (key.equals(ESFIELDS)) { // TODO: Finish up the logic here, because ES has a // different meaning of searching by field, versus // excluding it in the return value if (ValidationUtils.isValid(pmdh.getSingletonRange())) { if (ValidationUtils.isValid(pmdh.getSingletonRange().getValue()) && pmdh.getSingletonRange().getType().equals(G_PropertyType.STRING)) { if (d.getInclude()) { esFields.add((String) pmdh.getSingletonRange().getValue()); } else { esNotFields.add((String) pmdh.getSingletonRange().getValue()); } } } else if (ValidationUtils.isValid(pmdh.getListRange()) && ValidationUtils.isValid(pmdh.getListRange().getValues()) && pmdh.getListRange().getType().equals(G_PropertyType.STRING)) { for (final Object t : pmdh.getListRange().getValues()) { if (d.getInclude()) { logger.debug("Adding field " + t); esFields.add((String) t); } else { logger.debug("Do not include field " + t); esNotFields.add((String) t); } } } } else if (key.equals(ESQUERY)) { if (ValidationUtils.isValid(pmdh.getSingletonRange()) && ValidationUtils.isValid(pmdh.getSingletonRange().getValue()) && pmdh.getSingletonRange().getType().equals(G_PropertyType.STRING)) { logger.debug("Setting custom query " + pmdh.getSingletonRange().getValue()); queryString = (String) pmdh.getSingletonRange().getValue(); } } else if (key.equals(ESBOOST)) { if (ValidationUtils.isValid(pmdh.getSingletonRange()) && ValidationUtils.isValid(pmdh.getSingletonRange().getValue()) && pmdh.getSingletonRange().getType().equals(G_PropertyType.STRING)) { logger.debug("WIP: Setting boost custom query " + pmdh.getSingletonRange().getValue()); // not working yet } } else { bool = buildBooleanConstraints(pmdh, bool); } } else { logger.error("Key or Value was not valid for " + pmdh.toString()); } }// end looping over pmdhs if (queryString != null) { logger.debug("We encountered a custom query so we will use that"); } else if (bool != null) { logger.debug("Using a boolean query with rule " + minimumShouldMatchRule); bool.minimumShouldMatch(minimumShouldMatchRule); queryString = bool.toString(); } else if (esIds.size() > 0) { logger.debug("Using an id filter query instead"); queryString = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.termsFilter("_id", esIds)).toString(); } else { logger.debug("Using an matchAllQuery instead"); queryString = QueryBuilders.matchAllQuery().toString(); } ssb = ssb.query(queryString); /* * This is available as long as we don't do scan. */ // ssb = ssb.sort("_id"); logger.debug(ssb.toString()); } final io.searchbox.core.Search.Builder action = new Search.Builder(ssb.toString()).setParameter("timeout", defaultESTimeout); if (ValidationUtils.isValid(pq.getTargetSchema())) { action.addIndex(pq.getTargetSchema()); logger.debug("adding specified index: " + pq.getTargetSchema()); } else if (ValidationUtils.isValid(c.getIndexName())) { action.addIndex(c.getIndexName()); logger.debug("adding default index: " + c.getIndexName()); } else { logger.error("No index to set in query, check your es.properties to set a search index."); } if (ValidationUtils.isValid(esTypes)) { action.addType(esTypes); logger.debug("adding types: " + esTypes.toArray()); } action.setParameter(Parameters.SIZE, pq.getMaxResult()); logger.debug("We built query " + action.build().toString()); return action; } public long count() { final G_PropertyMatchDescriptor pmdh = G_PropertyMatchDescriptor.newBuilder() .setConstraint(G_Constraint.CONTAINS).setKey(ESTYPE) .setSingletonRange(new SingletonRangeHelper(type, G_PropertyType.STRING)).build(); final G_EntityQuery q = new QueryHelper(pmdh); return count(q); } @Override public long count(final G_EntityQuery pq) { long longCount = 0l; try { final io.searchbox.core.Count.Builder action = new Count.Builder() .setParameter("timeout", defaultESTimeout); if (ValidationUtils.isValid(pq) && ValidationUtils.isValid(pq.getPropertyMatchDescriptors())) { pq.getPropertyMatchDescriptors().get(0); BoolQueryBuilder bool = null; for (final G_PropertyMatchDescriptor d : pq.getPropertyMatchDescriptors()) { if (ValidationUtils.isValid(d)) { final PropertyMatchDescriptorHelper pmdh = PropertyMatchDescriptorHelper.from(d); final String key = pmdh.getKey(); if (key.equals(ESTYPE)) { if (ValidationUtils.isValid(pmdh.getSingletonRange())) { final String type = (String) pmdh.getSingletonRange().getValue(); action.addType(type); logger.debug("added type: " + type); } else if (ValidationUtils.isValid(pmdh.getListRange())) { action.addType((Collection<? extends String>) pmdh.getListRange()); } } else { bool = buildBooleanConstraints(pmdh, bool); } } } SearchSourceBuilder ssb = new SearchSourceBuilder(); if (bool != null) { ssb = ssb.query(bool); } else { ssb = ssb.query(QueryBuilders.matchAllQuery()); } logger.debug(ssb.toString()); action.query(ssb.toString()); if (ValidationUtils.isValid(pq.getTargetSchema())) { action.addIndex(pq.getTargetSchema()); logger.debug("adding specified index: " + pq.getTargetSchema()); } else if (ValidationUtils.isValid(c.getIndexName())) { action.addIndex(c.getIndexName()); logger.debug("adding default index: " + c.getIndexName()); } else { logger.error("No index to set in query, check your es.properties to set a search index."); } } final CountResult result = c.getClient().execute(action.build()); longCount = result.getCount().longValue(); return longCount; } catch (final Exception e) { logger.error("performCount Could not connect to one of the external resources needed for your request: " + e.getMessage()); } logger.debug("Found a count of: " + longCount); return longCount; } public void createIndex(final String indexName) throws Exception { logger.debug("Creating index " + indexName + " with client " + c.getClient().toString()); // create new index (if u have this in elasticsearch.yml and prefer // those defaults, then leave this out final ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder(); settings.put("number_of_shards", 3); settings.put("number_of_replicas", 0); final JestResult execute = c.getClient().execute( new CreateIndex.Builder(indexName).settings(settings.build().getAsMap()) .setParameter("timeout", defaultESTimeout).build()); logger.debug(execute.toString()); } public boolean delete(final String id) { boolean success = false; try { final JestResult result = c.getClient().execute( (new Delete.Builder(id)).index(index).type(type).setParameter("timeout", defaultESTimeout).build()); success = result.isSucceeded(); if (success) { logger.debug("Successfully deleted id " + id); } else { logger.error("Could not delete id '" + id + "' : " + result.getJsonString()); } } catch (final Exception e) { logger.error("delete " + e.getMessage()); } return success; } protected void deleteIndex(final String indexName) throws Exception { c.deleteIndex(indexName); } public boolean exists(final String id) { final String query = new SearchSourceBuilder().query( QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.termFilter("_id", id))) .toString(); try { final CountResult result = c.getClient().execute( new Count.Builder().query(query).addIndex(index).addType(type) .setParameter("timeout", defaultESTimeout).build()); logger.debug("Exists found count " + result.getCount()); return (result.getCount() > 0); } catch (final Exception e) { logger.error("Error determining existence " + e.getMessage()); } logger.error("Error determining existence "); return false; } @Override public Map<String, List<G_Entity>> getAccounts(final List<String> entities) throws AvroRemoteException { // TODO Auto-generated method stub return null; } @Override public G_SearchResults getAll(final long offset, final long maxResults) throws AvroRemoteException { // TODO Auto-generated method stub return null; } public JestResult getAllResults() { final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchAllQuery()).size(MAX_TO_GET_AT_ONCE); final Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(index).addType(type) .setParameter("timeout", defaultESTimeout).build(); logger.debug(searchSourceBuilder.toString()); JestResult result = new JestResult(null); try { result = c.getClient().execute(search); } catch (final Exception e) { logger.error("Get all: " + e.getMessage()); } return result; } @Override public G_TransactionResults getAllTransactions(final G_EntityQuery q) throws AvroRemoteException { // TODO Auto-generated method stub return null; } public JestResult getByField(final String field, final String value) { JestResult result = new JestResult(null); if (ValidationUtils.isValid(field, value)) { final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); // Use the match phrase query so it doesn't tokenize the value. searchSourceBuilder.query(QueryBuilders.matchPhraseQuery(field, value)); final Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(index).addType(type) .setParameter("timeout", defaultESTimeout).build(); logger.debug(searchSourceBuilder.toString()); try { result = c.getClient().execute(search); } catch (final Exception e) { logger.error("Problem getting by field: " + field + " value: " + value, e.getMessage()); } } else { logger.error("A null field or value was provided."); } return result; } public JestResult getByJoinFields(final String field1, final String value1, final String field2, final String value2) { final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery(field1, value1)) .must(QueryBuilders.matchQuery(field2, value2))); final Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(index).addType(type) .setParameter("timeout", defaultESTimeout).build(); JestResult result = new JestResult(null); try { result = c.getClient().execute(search); } catch (final Exception e) { logger.error("User Roles for user: " + e.getMessage()); } return result; } @Override public G_PropertyDescriptors getDescriptors() throws AvroRemoteException { // TODO Auto-generated method stub return null; } @Override public List<G_Entity> getEntities(final List<String> entities, final G_LevelOfDetail levelOfDetail) throws AvroRemoteException { // TODO Auto-generated method stub return null; } @Override public Map<String, List<G_Link>> getFlowAggregation(final List<String> entities, final List<String> focusEntities, final G_DirectionFilter direction, final G_LinkEntityTypeFilter entityType, final G_LinkTag tag, final G_DateRange date) throws AvroRemoteException { // TODO Auto-generated method stub return null; } public String getIdByFirstHit(final JestResult jr) { String id = null; try { id = getListOfHitsFromResult(jr).get(0).get("_id").asText(); } catch (final Exception e) { logger.error("Problem getting id from first hit: ", e); } return id; } public String getIndex() { return index; } public long getModifiedTime() { return DateTime.now().getMillis(); } @Override public double getReadiness() throws AvroRemoteException { // TODO Auto-generated method stub return 0; } /** * When given just the id. Uses default index and no types for this dao. * * @param id * @return */ protected JestResult getResultsById(final String id) { // DONT use _all for type when searching by id. return getResultsById(id, index, null); } /** * When given the id and a type (that is not _all). Uses default index for * this dao. * * @param id * @param type * @return */ protected JestResult getResultsById(final String id, final String type) { return getResultsById(id, index, type); } /** * When given an id a type and an index. * * @param id * @param customIndex * @param customType * @return */ protected JestResult getResultsById(final String id, final String customIndex, final String customType) { final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.termFilter("_id", id))); final Builder sb = new Search.Builder(searchSourceBuilder.toString()).setParameter("timeout", defaultESTimeout); logger.debug(searchSourceBuilder.toString()); if (ValidationUtils.isValid(customIndex)) { sb.addIndex(customIndex); } else { // sb.addIndex("_all"); } if (ValidationUtils.isValid(customType)) { sb.addType(customType); } JestResult result = new JestResult(null); try { final Search search = sb.build(); logger.debug("Using schema " + customIndex); logger.debug("Using type " + customType); result = c.getClient().execute(search); logger.debug(result.getJsonString()); } catch (final Exception e) { logger.error("getResultsById: " + e.getMessage()); } return result; } public JestResult getSpecifiedFields(final String... field) { JestResult result = new JestResult(null); final SearchSourceBuilder ssb = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()) .size(MAX_TO_GET_AT_ONCE).sort("_id"); if (ValidationUtils.isValid(field)) { ssb.fields(field); } final Search search = new Search.Builder(ssb.toString()).addIndex(index).addType(type) .setParameter("timeout", defaultESTimeout).build(); logger.debug(ssb.toString()); try { result = c.getClient().execute(search); } catch (final Exception e) { logger.error("Problem getting by ids with field: " + field, e.getMessage()); } return result; } @Override public Map<String, List<G_Link>> getTimeSeriesAggregation(final List<String> entities, final List<String> focusEntities, final G_LinkTag tag, final G_DateRange date) throws AvroRemoteException { // TODO Auto-generated method stub return null; } public String getType() { return type; } public boolean indexExists() { boolean success = false; if (!ValidationUtils.isValid(index)) { logger.warn("Index variable was not initialized! Cannot check for existence."); } else { try { final JestResult result = c.getClient().execute(new IndicesExists.Builder(index).build()); success = result.isSucceeded(); } catch (final Exception e) { logger.error("indexExists " + e.getMessage()); } } return success; } public void initialize() { logger.debug("Initializing index " + index + " and type " + type); if (ValidationUtils.isValid(index)) { if (indexExists()) { logger.debug("Index " + index + " already exists. This is fine."); } else { try { createIndex(index); } catch (final Exception e) { logger.error("Problem initializing index: " + index, e); } } } else { logger.error("Could not check for existance of index because index variable was not defined."); } } @Override public boolean isReady() throws AvroRemoteException { // TODO Auto-generated method stub return false; } @Override public boolean performCallback(final long offset, final long maxResults, final G_CallBack cb, final G_EntityQuery pq) { JestResult jestResult = new JestResult(null); try { final boolean scrolling = false; if (scrolling) { io.searchbox.core.Search.Builder action = buildSearchAction(pq); final Search build = action.build(); action.addIndex(pq.getTargetSchema()); action.setParameter(Parameters.SEARCH_TYPE, SearchType.SCAN); action = action.setParameter(Parameters.SIZE, maxResults); action = action.setParameter(Parameters.SCROLL, "1m"); /** * Make a search object first. */ jestResult = c.getClient().execute(action.build()); // The first query will not have any results, just the scroll id if (jestResult.isSucceeded()) { logger.debug("execution completed (expected no results, just setting up scroll)"); // logger.debug(jestResult.getJsonString()); int currentResultSize = 0; int pageNumber = 1; do { final String scrollId = jestResult.getJsonObject().get("_scroll_id").getAsString(); logger.debug("Next scroll id is " + scrollId); final SearchScroll scroll = new SearchScroll.Builder(scrollId, "1m").build(); final TimeReporter tr = new TimeReporter("Executing scroll " + pageNumber, logger); jestResult = c.getClient().execute(scroll); tr.logAsCompleted(); // Get the next scroll id final ArrayNode actualListOfHits = getListOfHitsFromResult(jestResult); currentResultSize = actualListOfHits.size(); for (int i = 0; i < actualListOfHits.size(); i++) { final JsonNode currentHit = actualListOfHits.get(i); if (ValidationUtils.isValid(currentHit)) { final G_SearchResult sr = db.buildSearchResultFromDocument(i, currentHit, pq); cb.execute(sr, pq); } } logger.debug("finished scrolling page # " + pageNumber++ + " which had " + currentResultSize + " hits."); } while (currentResultSize > 0); } else { logger.error("Scroll failed with " + jestResult.getErrorMessage()); } } else { // Not scrolling io.searchbox.core.Search.Builder action = buildSearchAction(pq); // action.setParameter(Parameters.SEARCH_TYPE, SearchType.SCAN) action.addIndex(pq.getTargetSchema()); action = action.setParameter(Parameters.SIZE, maxResults); // The first query will not have any results, just the scroll id int currentResultSize = 0; // int pageNumber = 0; jestResult = c.getClient().execute(action.build()); // logger.debug(jestResult.getJsonString()); final JsonNode rootNode = mapper.readValue(jestResult.getJsonString(), JsonNode.class); final JsonNode outerHits = rootNode.get("hits"); if (outerHits == null) { currentResultSize = 0; logger.warn("Found 0 results"); } else { final List<JsonNode> hits = outerHits.findValues("hits"); final ArrayNode actualListOfHits = (ArrayNode) hits.get(0); currentResultSize = actualListOfHits.size(); logger.debug("Found " + currentResultSize + " results"); for (int i = 0; i < actualListOfHits.size(); i++) { final JsonNode currentHit = actualListOfHits.get(i); if (ValidationUtils.isValid(currentHit)) { /** * TODO: To improve speed, let's make a second * callback option that takes an Object. From there * the documentBuilder will have access to the raw * object for a short while, and it can pull out the * id of the document so see if we've already run * through it, BEFORE doing the expensive casting to * DTO object. */ final G_SearchResult sr = db.buildSearchResultFromDocument(i, currentHit, pq); // logger.debug("Executing callback with sr = " + cb.execute(sr, pq); } } logger.debug("finished executing on " + currentResultSize + " hits."); } } } catch (final Exception e) { e.printStackTrace(); } return true; } public void recreateIndex() { try { deleteIndex(index); } catch (final Exception e) { logger.error("recreateIndex " + e.getMessage()); } try { createIndex(index); } catch (final Exception e) { logger.error("recreateIndex " + e.getMessage()); } } /** * * @param g * @param id * @param indexName * @param type * @param useDelay * @return the id used by the saved object. */ @Override public String saveObject(final Object g, final String id, final String indexName, final String type, final boolean useDelay) { Index saveAction; if (!ValidationUtils.isValid(id)) { // saving without an id. saveAction = new Index.Builder(g).index(indexName).type(type).setParameter("timeout", defaultESTimeout) .build(); } else { // saving with a given id. saveAction = new Index.Builder(g).index(indexName).id(id).type(type) .setParameter("timeout", defaultESTimeout).build(); } String generatedId = null; try { final JestResult result = c.getClient().execute(saveAction); final Object oid = result.getValue("_id"); if (ValidationUtils.isValid(oid)) { generatedId = oid.toString(); if (useDelay && (ES_READ_DELAY_MS > 0)) { Thread.sleep(ES_READ_DELAY_MS); } } else { logger.error("Error getting saved object's id: " + result.getJsonString()); generatedId = null; } } catch (ExecutionException | InterruptedException | IOException e) { logger.error("saveObject " + e.getMessage()); } catch (final Exception e) { logger.error("saveObject " + e.getMessage()); } return generatedId; } @Override public G_SearchResults search(final G_EntityQuery pq) throws AvroRemoteException { // TODO Auto-generated method stub return null; } public void setIndex(final String index) { this.index = index; } @Override public Void setReady(final boolean b) throws AvroRemoteException { // TODO Auto-generated method stub return null; } public void setType(final String type) { this.type = type; } }
import java.io.IOException; import java.util.Arrays; public class GradientDescent { public static void main(String[] args) throws IOException { Symbol symbol = new Symbol("LVS"); int FUTURE_DAYS = 10; int NUM_POINTS = 10; int TEST_SET = 20; double[][] data = new double[NUM_POINTS][symbol.getFeatures(0).length]; double[] future = new double[NUM_POINTS]; double[] theta = new double[data[0].length]; // Add features to inputs and future price to outputs for (int i = 0; i < NUM_POINTS; i++) { data[i] = symbol.getFeatures(i + TEST_SET); future[i] = symbol.getAdjClose(i + TEST_SET - FUTURE_DAYS).doubleValue(); } theta = getWeights(data, future, theta, .0001, 1000); int test = 3; System.out.println("Actual: " + future[test]); System.out.println("Prediction: " + (theta[0] + (theta[1] * data[test][1]))); } public static double[] getWeights(double[][] inputs, double[] outputs, double[] theta, double alpha, int numIters) { int m = outputs.length; int numFeatures = inputs[0].length; for (int i = 0; i < numIters; i++) { // Calculate predictions double[] predictions = new double[m]; for (int j = 0; j < m; j++) { // multiply each feature of data by its weight, sum, and then put in predictions for (int k = 0; k < numFeatures; k++) { predictions[j] += inputs[j][k] * theta[k]; } } // Calculate error double[] errorSums = new double[numFeatures]; for (int j = 0; j < numFeatures; j++) { for (int k = 0; k < m; k++) { errorSums[j] += (predictions[k] - outputs[k]) * inputs[k][j]; } } for (int j = 0; j < numFeatures; j++) { theta[j] -= alpha * (1.0 / m) * errorSums[j]; } // System.out.println(Arrays.toString(theta)); } return theta; } }
package xal.app.mtv; import javax.swing.*; import javax.swing.event.*; import java.awt.event.*; import java.net.*; import java.io.*; import xal.extension.application.*; import xal.extension.application.smf.*; /** * The main program for the xio app. * @author J. Galambos * */ public class Main extends ApplicationAdaptor { public Main() {url = null;} public Main(String str) { try{ url = new URL(str); } catch (MalformedURLException exception) { System.err.println(exception); } } public String[] readableDocumentTypes() { return new String[] {"mtv"}; } public String[] writableDocumentTypes() { return new String[] {"mtv"}; } /** this returns a new document to start working with */ public XalDocument newEmptyDocument() { MTVDocument md; // even if url == null, use it. A default accelerator will be created. return md = new MTVDocument(url); } public XalDocument newDocument(java.net.URL theUrl) { MTVDocument md = new MTVDocument(theUrl); return md; } public String applicationName() { return "mtv"; } /** The url to use to create the startup document with */ private URL url; /** * Register actions for the Special menu items */ public void customizeCommands(Commander commander) { } /** The main method of the application. */ static public void main(String[] args) { try { URL[] urls = new URL[args.length]; for ( int index = 0 ; index < args.length ; index++ ) { urls[index] = new File(args[index]).toURI().toURL(); } AcceleratorApplication.launch(new Main(), urls ); } catch(Exception exception) { System.err.println( exception.getMessage() ); exception.printStackTrace(); Application.displayApplicationError("Launch Exception", "Launch Exception", exception); System.exit(-1); } } }
package org.helianto.user.repository; import java.io.Serializable; import org.helianto.core.def.ActivityState; /** * User read adapter. * * @author mauriciofernandesdecastro */ public class UserReadAdapter implements Serializable { private static final long serialVersionUID = 1L; private int userId; private int userGroupId; private int contextId; private int entityId; private int identityId; private String userKey; private String userName; private char userState; private Character userGender; /** * Constructor. * * @param userId * @param contextId * @param entityId * @param identityId * @param userKey * @param userName * @param userState */ public UserReadAdapter(int userId, int contextId, int entityId, int identityId , String userKey, String userName, char userState) { super(); this.userId = userId; this.contextId = contextId; this.entityId = entityId; this.identityId = identityId; this.userKey = userKey; this.userName = userName; this.userState = userState; } /** * Constructor. * * @param userId * @param userGroupId * @param userKey * @param userName * @param userState * @param userGender */ public UserReadAdapter(int userId, int userGroupId, String userKey, String userName, Character userState, Character userGender) { super(); this.userId = userId; this.userGroupId = userGroupId; this.userKey = userKey; this.userName = userName; this.userState = userState; this.userGender = userGender; } public int getUserId() { return userId; } public int getUserGroupId() { return userGroupId; } public int getContextId() { return contextId; } public int getEntityId() { return entityId; } public int getIdentityId() { return identityId; } public String getUserKey() { return userKey; } public String getUserName() { return userName; } public boolean isAccountNonExpired() { // TODO include expirationDate in User return true; } public char getUserState() { return userState; } public boolean isAccountNonLocked() { if (getUserState()==ActivityState.ACTIVE.getValue()) { return true; } return false; } public Character getUserGender() { return userGender; } }
/* * Cordova ZeroConf Plugin * * ZeroConf plugin for Cordova/Phonegap * by Sylvain Brejeon */ package net.becvert.cordova; import android.net.wifi.WifiManager; import android.os.Build; import android.util.Log; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.apache.cordova.PluginResult.Status; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.lang.reflect.Method; import java.net.InetAddress; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.jmdns.JmDNS; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener; public class ZeroConf extends CordovaPlugin implements ServiceListener { private static final String TAG = "ZeroConf"; WifiManager.MulticastLock lock; private JmDNS publisher; private JmDNS browser; private String hostname; private Map<String, CallbackContext> callbacks = new HashMap<String, CallbackContext>(); // publisher public static final String ACTION_REGISTER = "register"; public static final String ACTION_UNREGISTER = "unregister"; public static final String ACTION_STOP = "stop"; // browser public static final String ACTION_WATCH = "watch"; public static final String ACTION_UNWATCH = "unwatch"; public static final String ACTION_CLOSE = "close"; @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); WifiManager wifi = (WifiManager) this.cordova.getActivity() .getSystemService(android.content.Context.WIFI_SERVICE); lock = wifi.createMulticastLock("ZeroConfPluginLock"); lock.setReferenceCounted(true); lock.acquire(); hostname = getHostName("android"); Log.v(TAG, "Initialized"); } @Override public void onDestroy() { super.onDestroy(); if (publisher != null) { try { publisher.close(); } catch (IOException e) { e.printStackTrace(); } finally { publisher = null; } } if (browser != null) { try { browser.close(); } catch (IOException e) { e.printStackTrace(); } finally { browser = null; callbacks = null; } } if (lock != null) { lock.release(); lock = null; } } @Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) { if (ACTION_REGISTER.equals(action)) { final String type = args.optString(0); final String domain = args.optString(1); final String name = args.optString(2); final int port = args.optInt(3); final JSONObject props = args.optJSONObject(4); Log.d(TAG, "Register " + type + domain); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { ServiceInfo service = register(type, domain, name, port, props); JSONObject status = new JSONObject(); status.put("action", "registered"); status.put("service", jsonifyService(service)); Log.d(TAG, "Sending result: " + status.toString()); PluginResult result = new PluginResult(PluginResult.Status.OK, status); callbackContext.sendPluginResult(result); } catch (IOException | JSONException e) { e.printStackTrace(); callbackContext.error("Registration of " + type + domain + " with name " + name + " failed"); } } }); } else if (ACTION_UNREGISTER.equals(action)) { final String type = args.optString(0); final String domain = args.optString(1); final String name = args.optString(2); Log.d(TAG, "Unregister " + type + domain); if (publisher != null) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { unregister(type, domain, name); callbackContext.success("Unregistered " + type + domain + " with name " + name); } }); } } else if (ACTION_STOP.equals(action)) { Log.d(TAG, "Stop"); if (publisher != null) { final JmDNS p = publisher; publisher = null; cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { p.close(); callbackContext.success("Publisher did stop"); } catch (IOException e) { e.printStackTrace(); callbackContext.error("Publisher did not stop properly"); } } }); } } else if (ACTION_WATCH.equals(action)) { final String type = args.optString(0); final String domain = args.optString(1); Log.d(TAG, "Watch " + type + domain); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { watch(type, domain); } catch (IOException e) { e.printStackTrace(); callbackContext.error("Could not watch " + type + domain); } } }); PluginResult result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); callbacks.put(type + domain, callbackContext); } else if (ACTION_UNWATCH.equals(action)) { final String type = args.optString(0); final String domain = args.optString(1); Log.d(TAG, "Unwatch " + type + domain); if (browser != null) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { unwatch(type, domain); callbackContext.success("Stopped watching " + type + domain); } }); PluginResult result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(false); callbacks.remove(type + domain); } } else if (ACTION_CLOSE.equals(action)) { Log.d(TAG, "Close"); if (browser != null) { final JmDNS b = browser; browser = null; cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { b.close(); callbackContext.success("Browser did close"); } catch (IOException e) { e.printStackTrace(); callbackContext.error("Browser did not close properly"); } } }); callbacks.clear(); } } else { Log.e(TAG, "Invalid action: " + action); callbackContext.error("Invalid action: " + action); return false; } return true; } private ServiceInfo register(String type, String domain, String name, int port, JSONObject props) throws IOException, JSONException { if (publisher == null) { publisher = JmDNS.create(null, hostname); } HashMap<String, String> txtRecord = new HashMap<String, String>(); if (props != null) { Iterator<String> iter = props.keys(); while (iter.hasNext()) { String key = iter.next(); txtRecord.put(key, props.getString(key)); } } ServiceInfo service = ServiceInfo.create(type + domain, name, port, 0, 0, txtRecord); publisher.registerService(service); return service; } private void unregister(String type, String domain, String name) { if (publisher == null) { return; } ServiceInfo serviceInfo = publisher.getServiceInfo(type + domain, name); if (serviceInfo != null) { publisher.unregisterService(serviceInfo); } } private void watch(String type, String domain) throws IOException { if (browser == null) { browser = JmDNS.create(null, hostname); } browser.addServiceListener(type + domain, this); ServiceInfo[] services = browser.list(type + domain); for (ServiceInfo service : services) { sendCallback("added", service); } } private void unwatch(String type, String domain) { if (browser != null) { browser.removeServiceListener(type + domain, this); } } @Override public void serviceResolved(ServiceEvent ev) { Log.d(TAG, "Resolved"); sendCallback("added", ev.getInfo()); } @Override public void serviceRemoved(ServiceEvent ev) { Log.d(TAG, "Removed"); sendCallback("removed", ev.getInfo()); } @Override public void serviceAdded(ServiceEvent event) { Log.d(TAG, "Added"); // Force serviceResolved to be called again if (browser != null) { browser.requestServiceInfo(event.getType(), event.getName(), 1); } } public void sendCallback(String action, ServiceInfo service) { CallbackContext callbackContext = callbacks.get(service.getType()); if (callbackContext == null) { return; } JSONObject status = new JSONObject(); try { status.put("action", action); status.put("service", jsonifyService(service)); } catch (JSONException e) { e.printStackTrace(); callbackContext.error("Error while jsonifying service " + service.getType()); return; } Log.d(TAG, "Sending result: " + status.toString()); PluginResult result = new PluginResult(PluginResult.Status.OK, status); result.setKeepCallback(true); callbackContext.sendPluginResult(result); } public static JSONObject jsonifyService(ServiceInfo service) throws JSONException { JSONObject obj = new JSONObject(); String domain = service.getDomain() + "."; obj.put("domain", domain); obj.put("type", service.getType().replace(domain, "")); obj.put("name", service.getName()); obj.put("port", service.getPort()); obj.put("hostname", service.getServer()); JSONArray addresses = new JSONArray(); InetAddress[] inetAddresses = service.getInetAddresses(); for (int i = 0; i < inetAddresses.length; i++) { if (inetAddresses[i] != null) { addresses.put(inetAddresses[i].getHostAddress()); } } obj.put("addresses", addresses); JSONObject props = new JSONObject(); Enumeration<String> names = service.getPropertyNames(); while (names.hasMoreElements()) { String name = names.nextElement(); props.put(name, service.getPropertyString(name)); } obj.put("txtRecord", props); return obj; } public static String getHostName(String defValue) { try { Method getString = Build.class.getDeclaredMethod("getString", String.class); getString.setAccessible(true); return getString.invoke(null, "net.hostname").toString(); } catch (Exception ex) { return defValue; } } }
package jp.satorufujiwara.player.ima; import com.google.ads.interactivemedia.v3.api.AdDisplayContainer; import com.google.ads.interactivemedia.v3.api.AdErrorEvent; import com.google.ads.interactivemedia.v3.api.AdEvent; import com.google.ads.interactivemedia.v3.api.AdsLoader; import com.google.ads.interactivemedia.v3.api.AdsManager; import com.google.ads.interactivemedia.v3.api.AdsManagerLoadedEvent; import com.google.ads.interactivemedia.v3.api.AdsRequest; import com.google.ads.interactivemedia.v3.api.ImaSdkFactory; import com.google.ads.interactivemedia.v3.api.ImaSdkSettings; import com.google.ads.interactivemedia.v3.api.player.ContentProgressProvider; import com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer; import com.google.ads.interactivemedia.v3.api.player.VideoProgressUpdate; import android.content.Context; import android.net.Uri; import android.text.TextUtils; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import jp.satorufujiwara.player.VideoSource; import jp.satorufujiwara.player.VideoTexturePresenter; import jp.satorufujiwara.player.assets.AssetsVideoSource; public class AdPlayerController { private boolean isAdDisplayed = false; private boolean isAdPlaying = false; private final VideoAdPlayer videoAdPlayer; private final ContentProgressProvider contentProgressProvider; private final ViewGroup adUiContainer; private final ImaSdkFactory sdkFactory; private final AdsLoader adsLoader; private final List<VideoAdPlayer.VideoAdPlayerCallback> adCallbacks = new ArrayList<>(1); private final List<AdEvent.AdEventListener> adEventListeners = new ArrayList<>(); private final List<AdErrorEvent.AdErrorListener> adErrorListeners = new ArrayList<>(); private AdsManager adsManager; private OnResumeContentListener resumeContentListener; private OnPauseContentListener pauseContentListener; public static Builder builder(final Context context) { return new Builder(context); } AdPlayerController(final Context context, final String language, final String userAgent, final VideoTexturePresenter videoTexturePresenter, final ViewGroup adUiContainer) { this.adUiContainer = adUiContainer; videoAdPlayer = new VideoAdPlayer() { @Override public void playAd() { isAdDisplayed = true; videoTexturePresenter.play(); } @Override public void loadAd(String url) { isAdDisplayed = true; videoTexturePresenter.setSource(createVideoSourceFrom(url, userAgent)); videoTexturePresenter.prepare(); } @Override public void stopAd() { videoTexturePresenter.stop(); videoTexturePresenter.release(); } @Override public void pauseAd() { videoTexturePresenter.pause(); } @Override public void resumeAd() { playAd(); } @Override public void addCallback(VideoAdPlayerCallback videoAdPlayerCallback) { adCallbacks.add(videoAdPlayerCallback); } @Override public void removeCallback(VideoAdPlayerCallback videoAdPlayerCallback) { adCallbacks.remove(videoAdPlayerCallback); } @Override public VideoProgressUpdate getAdProgress() { if (!isAdDisplayed || videoTexturePresenter.getDuration() <= 0) { return VideoProgressUpdate.VIDEO_TIME_NOT_READY; } return new VideoProgressUpdate(videoTexturePresenter.getCurrentPosition(), videoTexturePresenter.getDuration()); } }; videoAdPlayer.addCallback(new VideoAdPlayer.VideoAdPlayerCallback() { @Override public void onPlay() { if (!isAdDisplayed) { return; } for (VideoAdPlayer.VideoAdPlayerCallback callback : adCallbacks) { callback.onPlay(); } } @Override public void onVolumeChanged(int i) { if (!isAdDisplayed) { return; } for (VideoAdPlayer.VideoAdPlayerCallback callback : adCallbacks) { callback.onVolumeChanged(i); } } @Override public void onPause() { if (!isAdDisplayed) { return; } for (VideoAdPlayer.VideoAdPlayerCallback callback : adCallbacks) { callback.onPause(); } } @Override public void onResume() { if (!isAdDisplayed) { return; } for (VideoAdPlayer.VideoAdPlayerCallback callback : adCallbacks) { callback.onResume(); } } @Override public void onEnded() { if (!isAdDisplayed) { return; } for (VideoAdPlayer.VideoAdPlayerCallback callback : adCallbacks) { callback.onEnded(); } } @Override public void onError() { if (!isAdDisplayed) { return; } for (VideoAdPlayer.VideoAdPlayerCallback callback : adCallbacks) { callback.onError(); } } }); contentProgressProvider = new ContentProgressProvider() { @Override public VideoProgressUpdate getContentProgress() { if (isAdDisplayed || videoTexturePresenter.getDuration() <= 0) { return VideoProgressUpdate.VIDEO_TIME_NOT_READY; } return new VideoProgressUpdate(videoTexturePresenter.getCurrentPosition(), videoTexturePresenter.getDuration()); } }; ImaSdkSettings imaSdkSettings = new ImaSdkSettings(); imaSdkSettings.setLanguage(language); sdkFactory = ImaSdkFactory.getInstance(); adsLoader = sdkFactory.createAdsLoader(context, imaSdkSettings); adsLoader.addAdErrorListener(new AdErrorEvent.AdErrorListener() { /** * An event raised when there is an error loading or playing ads. */ @Override public void onAdError(AdErrorEvent adErrorEvent) { requestResumeContent(); } }); adsLoader.addAdsLoadedListener(new AdsLoader.AdsLoadedListener() { /** * An event raised when ads are successfully loaded from the ad server via AdsLoader. */ @Override public void onAdsManagerLoaded(AdsManagerLoadedEvent adsManagerLoadedEvent) { adsManager = adsManagerLoadedEvent.getAdsManager(); adsManager.addAdErrorListener(new AdErrorEvent.AdErrorListener() { /** * An event raised when there is an error loading or playing ads. */ @Override public void onAdError(AdErrorEvent adErrorEvent) { requestResumeContent(); } }); adsManager.addAdEventListener(new AdEvent.AdEventListener() { @Override public void onAdEvent(AdEvent adEvent) { switch (adEvent.getType()) { case LOADED: adsManager.start(); break; case CONTENT_PAUSE_REQUESTED: requestPauseContent(); break; case CONTENT_RESUME_REQUESTED: requestResumeContent(); break; case PAUSED: isAdPlaying = false; break; case RESUMED: isAdPlaying = true; break; case ALL_ADS_COMPLETED: if (adsManager != null) { adsManager.destroy(); adsManager = null; } break; default: break; } } }); for (AdEvent.AdEventListener l : adEventListeners) { adsManager.addAdEventListener(l); } adEventListeners.clear(); for (AdErrorEvent.AdErrorListener l : adErrorListeners) { adsManager.addAdErrorListener(l); } adErrorListeners.clear(); adsManager.init(); } }); } public void requestAndPlayAds(final String adTagUrl) { if (TextUtils.isEmpty(adTagUrl)) { requestResumeContent(); return; } if (adsManager != null) { adsManager.destroy(); } adsLoader.contentComplete(); final AdDisplayContainer container = sdkFactory.createAdDisplayContainer(); container.setPlayer(videoAdPlayer); container.setAdContainer(adUiContainer); // Set up spots for companions. // CompanionAdSlot companionAdSlot = mSdkFactory.createCompanionAdSlot(); // companionAdSlot.setContainer(mCompanionViewGroup); // companionAdSlot.setSize(728, 90); // ArrayList<CompanionAdSlot> companionAdSlots = new ArrayList<CompanionAdSlot>(); // companionAdSlots.add(companionAdSlot); // mAdDisplayContainer.setCompanionSlots(companionAdSlots); final AdsRequest request = sdkFactory.createAdsRequest(); request.setAdTagUrl(adTagUrl); request.setAdDisplayContainer(container); request.setContentProgressProvider(contentProgressProvider); adsLoader.requestAds(request); } public boolean isAdPlaying() { return isAdPlaying; } public void pause() { if (adsManager != null && isAdDisplayed) { adsManager.pause(); } } public void resume() { if (adsManager != null && isAdDisplayed) { adsManager.resume(); } } public VideoAdPlayer getVideoAdPlayer() { return videoAdPlayer; } public void addAdEventListener(final AdEvent.AdEventListener l) { if (adsManager == null) { adEventListeners.add(l); } else { adsManager.addAdEventListener(l); } } public void addAdErrorListener(final AdErrorEvent.AdErrorListener l) { adsLoader.addAdErrorListener(l); if (adsManager == null) { adErrorListeners.add(l); } else { adsManager.addAdErrorListener(l); } } public void setOnResumeContentListener(final OnResumeContentListener l) { resumeContentListener = l; } public void setOnPauseContentListener(final OnPauseContentListener l) { pauseContentListener = l; } private VideoSource createVideoSourceFrom(String url, String userAgent) { return AssetsVideoSource .newBuilder(Uri.parse(url), userAgent) .bufferSegmentSize(16 * 1024) .bufferSegmentCount(128) .build(); } private void requestResumeContent() { isAdDisplayed = false; isAdPlaying = false; if (resumeContentListener != null) { resumeContentListener.onResumeContentRequested(); } } private void requestPauseContent() { isAdPlaying = true; if (pauseContentListener != null) { pauseContentListener.onPauseContentRequested(); } } public interface OnResumeContentListener { void onResumeContentRequested(); } public interface OnPauseContentListener { void onPauseContentRequested(); } public static class Builder { private final Context context; private VideoTexturePresenter videoTexturePresenter; private ViewGroup adUiContainer; private String language = "en"; private String userAgent = "UserAgent"; public Builder(Context context) { this.context = context; } public Builder setVideoTexturePresenter(final VideoTexturePresenter videoTexturePresenter) { this.videoTexturePresenter = videoTexturePresenter; return this; } public Builder setAdUiContainer(final ViewGroup adUiContainer) { this.adUiContainer = adUiContainer; return this; } public Builder setLanguage(final String language) { this.language = language; return this; } public Builder setUserAgent(final String userAgent) { this.userAgent = userAgent; return this; } public AdPlayerController create() { if (context == null) { throw new RuntimeException("Context must not be null."); } if (videoTexturePresenter == null) { throw new RuntimeException("VideoTexturePresenter must not be null."); } if (adUiContainer == null) { throw new RuntimeException("AdUiContainer must not be null."); } return new AdPlayerController(context, language, userAgent, videoTexturePresenter, adUiContainer); } } }
// package package org.mskcc.cbio.importer.io.internal; // imports import org.mskcc.cbio.importer.*; import org.mskcc.cbio.importer.model.*; import org.mskcc.cbio.portal.scripts.*; import org.mskcc.cbio.portal.dao.*; import org.mskcc.cbio.portal.model.CancerStudy; import org.mskcc.cbio.importer.util.*; import org.mskcc.cbio.portal.model.CopyNumberSegmentFile; import org.mskcc.cbio.importer.converter.internal.MethylationConverterImpl; import org.mskcc.cbio.liftover.Hg18ToHg19; import org.mskcc.cbio.oncotator.OncotateTool; import org.mskcc.cbio.mutassessor.MutationAssessorTool; import org.apache.commons.io.*; import org.apache.commons.io.filefilter.*; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.logging.*; import org.apache.commons.compress.compressors.gzip.GzipUtils; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.springframework.beans.factory.annotation.Value; import java.io.*; import java.util.*; import java.net.URL; import java.util.regex.*; import java.lang.reflect.Constructor; import java.util.zip.GZIPInputStream; /** * Class which implements the FileUtils interface. */ class FileUtilsImpl implements org.mskcc.cbio.importer.FileUtils { // used in unzip method private static int BUFFER = 2048; // our logger private static Log LOG = LogFactory.getLog(FileUtilsImpl.class); // ref to config private Config config; // ref to caseids private CaseIDs caseIDs; // location of lift over binary private String liftoverBinary; @Value("${liftover_binary}") public void setLiftOverBinary(String property) { this.liftoverBinary = property; } public String getLiftOverBinary() { return MetadataUtils.getCanonicalPath(liftoverBinary); } // location of lift over chain private String liftoverChain; @Value("${liftover_chain_file}") public void setLiftOverChain(String property) { this.liftoverChain = property; } public String getLiftOverChain() { return MetadataUtils.getCanonicalPath(liftoverChain); } public FileUtilsImpl(Config config, CaseIDs caseIDs) { // set members this.config = config; this.caseIDs = caseIDs; } @Override public String getMD5Digest(File file) throws Exception { if (LOG.isInfoEnabled()) { LOG.info("getMD5Digest(): " + file.getCanonicalPath()); } String toReturn = ""; InputStream is = org.apache.commons.io.FileUtils.openInputStream(file); try { toReturn = DigestUtils.md5Hex(is); } finally { IOUtils.closeQuietly(is); } // outta here return toReturn; } @Override public String getPrecomputedMD5Digest(File file) throws Exception { if (LOG.isInfoEnabled()) { LOG.info("getPrecomputedMD5Digest(): " + file.getCanonicalPath()); } String toReturn = ""; LineIterator it = org.apache.commons.io.FileUtils.lineIterator(file); try { while (it.hasNext()) { String content = it.nextLine(); if (content.split(" ").length == 2) { toReturn = content.split(" ")[0].toUpperCase(); } } } finally { LineIterator.closeQuietly(it); } // outta here return toReturn; } @Override public void makeDirectory(File directory) throws Exception { org.apache.commons.io.FileUtils.forceMkdir(directory); } @Override public boolean directoryIsEmpty(File directory) throws Exception { return (listFiles(directory, null, true).isEmpty()); } @Override public void deleteDirectory(File directory) throws Exception { org.apache.commons.io.FileUtils.deleteDirectory(directory); } @Override public void deleteFile(File file) throws Exception { if (file.exists()) org.apache.commons.io.FileUtils.forceDelete(file); } @Override public Collection<File> listFiles(File directory, String[] extensions, boolean recursive) throws Exception { return org.apache.commons.io.FileUtils.listFiles(directory, extensions, recursive); } @Override public Collection<String> listFiles(File directory, String wildcard) throws Exception { ArrayList toReturn = new ArrayList<String>(); IOFileFilter filter = new WildcardFileFilter(wildcard); if (directory.exists()) { for (File file : org.apache.commons.io.FileUtils.listFiles(directory, filter, null)) { toReturn.add(file.getCanonicalPath()); } } return toReturn; } @Override public List<DataMatrix> getDataMatrices(ImportDataRecord importDataRecord, DataMatrix methylationCorrelation) throws Exception { List<DataMatrix> dataMatrices = new ArrayList<DataMatrix>(); if (LOG.isInfoEnabled()) { LOG.info("getDataMatrices(): " + importDataRecord); } // determine path to file (does override file exist?) String fileCanonicalPath = importDataRecord.getCanonicalPathToData(); // data can be compressed if (GzipUtils.isCompressedFilename(fileCanonicalPath.toLowerCase())) { if (LOG.isInfoEnabled()) { LOG.info("getDataMatrices(): processing file: " + fileCanonicalPath); } dataMatrices.addAll(getDataMatricesFromArchive(importDataRecord, methylationCorrelation)); } else { if (LOG.isInfoEnabled()) { LOG.info("getDataMatrices(): processing file: " + fileCanonicalPath); } File dataFile = new File(fileCanonicalPath); InputStream is = org.apache.commons.io.FileUtils.openInputStream(dataFile); DataMatrix m = getDataMatrix(dataFile.getName(), is, methylationCorrelation); if (m != null) { dataMatrices.add(m); } IOUtils.closeQuietly(is); } // outta here return dataMatrices; } @Override public List<String> getMissingCaseListFilenames(String rootDirectory, CancerStudyMetadata cancerStudyMetadata) throws Exception { ArrayList toReturn = new ArrayList<String>(); String caseListDirectory = (rootDirectory + File.separator + cancerStudyMetadata.getStudyPath() + File.separator + "case_lists"); for (CaseListMetadata caseListMetadata : config.getCaseListMetadata(Config.ALL)) { String caseListFilename = caseListDirectory + File.separator + caseListMetadata.getCaseListFilename(); File caseListFile = new File(caseListFilename); if (!caseListFile.exists()) toReturn.add(caseListFilename); } return toReturn; } @Override public void generateCaseLists(boolean overwrite, boolean strict, String stagingDirectory, CancerStudyMetadata cancerStudyMetadata) throws Exception { // iterate over case lists for (CaseListMetadata caseListMetadata : config.getCaseListMetadata(Config.ALL)) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), processing cancer study: " + cancerStudyMetadata + ", case list: " + caseListMetadata.getCaseListFilename()); } File caseListFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), "case_lists", caseListMetadata.getCaseListFilename()); if (caseListFile.exists() && !overwrite) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), caseListFile exists and overwrite is false, skipping caselist..."); } continue; } // how many staging files are we working with? String[] stagingFilenames = null; // setup union/intersection bools boolean unionCaseList = caseListMetadata.getStagingFilenames().contains(CaseListMetadata.CASE_LIST_UNION_DELIMITER); boolean intersectionCaseList = caseListMetadata.getStagingFilenames().contains(CaseListMetadata.CASE_LIST_INTERSECTION_DELIMITER); // union (like all cases) if (unionCaseList) { stagingFilenames = caseListMetadata.getStagingFilenames().split("\\" + CaseListMetadata.CASE_LIST_UNION_DELIMITER); } // intersection (like complete or cna-seq) else if (intersectionCaseList) { stagingFilenames = caseListMetadata.getStagingFilenames().split("\\" + CaseListMetadata.CASE_LIST_INTERSECTION_DELIMITER); } // just a single staging file else { stagingFilenames = new String[] { caseListMetadata.getStagingFilenames() }; } if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), stagingFilenames: " + java.util.Arrays.toString(stagingFilenames)); } if (intersectionCaseList && !allStagingFilesExist(cancerStudyMetadata, stagingDirectory, stagingFilenames)) { continue; } // this is the set we will pass to writeCaseListFile LinkedHashSet<String> caseSet = new LinkedHashSet<String>(); // this indicates the number of staging files processed - // used to verify that an intersection should be written int numStagingFilesProcessed = 0; for (String stagingFilename : stagingFilenames) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), processing stagingFile: " + stagingFilename); } // compute the case set List<String> caseList = getCaseListFromStagingFile(strict, caseIDs, cancerStudyMetadata, stagingDirectory, stagingFilename); // we may not have this datatype in study if (caseList.size() == 0) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), stagingFileHeader is empty: " + stagingFilename + ", skipping..."); } continue; } // intersection if (intersectionCaseList) { if (caseSet.isEmpty()) { caseSet.addAll(caseList); } else { caseSet.retainAll(caseList); } } // otherwise union or single staging (treat the same) else { caseSet.addAll(caseList); } ++numStagingFilesProcessed; } // write the case list file (don't make empty case lists) if (caseSet.size() > 0) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), calling writeCaseListFile()..."); } // do not write out complete cases file unless we've processed all the files required if (intersectionCaseList && (numStagingFilesProcessed != stagingFilenames.length)) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), number of staging files processed != number staging files required for cases_complete.txt, skipping call to writeCaseListFile()..."); } continue; } writeCaseListFile(stagingDirectory, cancerStudyMetadata, caseListMetadata, caseSet.toArray(new String[0])); } else if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), caseSet.size() <= 0, skipping call to writeCaseListFile()..."); } // if union, write out the cancer study metadata file & patient list if (overwrite && caseSet.size() > 0 && caseListMetadata.getCaseListFilename().equals(CaseListMetadata.ALL_CASES_FILENAME)) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), processed all cases list, we can now update cancerStudyMetadata file()..."); } writeCancerStudyMetadataFile(stagingDirectory, cancerStudyMetadata, caseSet.size()); } } } private boolean allStagingFilesExist(CancerStudyMetadata cancerStudyMetadata, String stagingDirectory, String[] stagingFilenames) { for (String stagingFilename : stagingFilenames) { File stagingFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), stagingFilename); // sanity check if (!stagingFile.exists()) { return false; } } return true; } @Override public List<String> getCaseListFromStagingFile(boolean strict, CaseIDs caseIDs, CancerStudyMetadata cancerStudyMetadata, String stagingDirectory, String stagingFilename) throws Exception { if (LOG.isInfoEnabled()) { LOG.info("getCaseListFromStagingFile(): " + stagingFilename); } // we use set here HashSet<String> caseSet = new HashSet<String>(); CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByStableId(cancerStudyMetadata.getStableId()); // if we are processing mutations data and a sequencedSamplesFile exists, use it if (stagingFilename.equals(DatatypeMetadata.MUTATIONS_STAGING_FILENAME)) { File sequencedSamplesFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), DatatypeMetadata.SEQUENCED_SAMPLES_FILENAME); if (sequencedSamplesFile.exists()) { if (LOG.isInfoEnabled()) LOG.info("getCaseListFromStagingFile(), sequenceSamplesFile exists, calling getCaseListFromSequencedSamplesFile()"); return getCaseListFromSequencedSamplesFile(sequencedSamplesFile); } } // staging file File stagingFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), stagingFilename); // sanity check if (!stagingFile.exists()) { return new ArrayList<String>(); } // iterate over all rows in file org.apache.commons.io.LineIterator it = org.apache.commons.io.FileUtils.lineIterator(stagingFile); try { int mafCaseIDColumnIndex = 0; boolean processHeader = true; while (it.hasNext()) { String line = it.next(); if (line.startsWith(" if (line.startsWith("#"+Converter.MUTATION_CASE_LIST_META_HEADER+":")) { return Arrays.asList(line.substring(Converter.MUTATION_CASE_LIST_META_HEADER.length()+2).trim().split("[ \t]+")); } continue; } // create a string list from row in file List<String> thisRow = Arrays.asList(line.split(Converter.VALUE_DELIMITER)); // is this the header file? if (processHeader) { // look for MAF file case id column header mafCaseIDColumnIndex = thisRow.indexOf(Converter.MUTATION_CASE_ID_COLUMN_HEADER); // this is not a MAF file, header contains the case ids, return here if (mafCaseIDColumnIndex == -1) { if (LOG.isInfoEnabled()) LOG.info("getCaseListFromStagingFile(), this is not a MAF header contains sample ids..."); for (String potentialCaseID : thisRow) { if (!strict || caseIDs.isSampleId(cancerStudy.getInternalId(), potentialCaseID) || caseIDs.isTruncatedTCGAPatientId(potentialCaseID)) { // check to filter out column headers other than sample ids if (Converter.NON_CASE_IDS.contains(potentialCaseID.toUpperCase())) { continue; } caseSet.add(caseIDs.getSampleId(cancerStudy.getInternalId(), potentialCaseID)); } } break; } else { if (LOG.isInfoEnabled()) LOG.info("getCaseListFromStagingFile(), this is a MAF, samples ids in col: " + mafCaseIDColumnIndex); } processHeader = false; continue; } // we want to add the value at mafCaseIDColumnIndex into return set - this is a case ID String potentialCaseID = thisRow.get(mafCaseIDColumnIndex); if (!strict || caseIDs.isSampleId(cancerStudy.getInternalId(), potentialCaseID)) { caseSet.add(caseIDs.getSampleId(cancerStudy.getInternalId(), potentialCaseID)); } } } finally { it.close(); } // outta here return new ArrayList<String>(caseSet); } @Override public File createTmpFileWithContents(String filename, String fileContent) throws Exception { File tmpFile = org.apache.commons.io.FileUtils.getFile(org.apache.commons.io.FileUtils.getTempDirectoryPath(), filename); org.apache.commons.io.FileUtils.writeStringToFile(tmpFile, fileContent, false); return tmpFile; } @Override public File createFileWithContents(String filename, String fileContent) throws Exception { File file = org.apache.commons.io.FileUtils.getFile(filename); org.apache.commons.io.FileUtils.writeStringToFile(file, fileContent, false); // outta here return file; } @Override public File createFileFromStream(String filename, InputStream is) throws Exception { File file = org.apache.commons.io.FileUtils.getFile(filename); org.apache.commons.io.FileUtils.copyInputStreamToFile(is, file); // outta here return file; } @Override public void downloadFile(String urlSource, String urlDestination) throws Exception { // sanity check if (urlSource == null || urlSource.length() == 0 || urlDestination == null || urlDestination.length() == 0) { throw new IllegalArgumentException("downloadFile(): urlSource or urlDestination argument is null..."); } // URLs for given parameters URL source = new URL(urlSource); URL destination = new URL(urlDestination); // we have a compressed file if (GzipUtils.isCompressedFilename(urlSource)) { // downlod to temp destination File tempDestinationFile = org.apache.commons.io.FileUtils.getFile(org.apache.commons.io.FileUtils.getTempDirectory(), ""+System.currentTimeMillis()+"."+new File(source.getFile()).getName()); if (LOG.isInfoEnabled()) { LOG.info("downloadFile(), " + urlSource + ", this may take a while..."); } org.apache.commons.io.FileUtils.copyURLToFile(source, tempDestinationFile); if (LOG.isInfoEnabled()) { LOG.info("downloadFile(), gunzip: we have compressed file, decompressing..."); } // decompress the file gunzip(tempDestinationFile.getCanonicalPath()); if (LOG.isInfoEnabled()) { LOG.info("downloadFile(), gunzip complete..."); } // move temp/decompressed file to final destination File destinationFile = new File(destination.getFile()); if (destinationFile.exists()) { org.apache.commons.io.FileUtils.forceDelete(destinationFile); } org.apache.commons.io.FileUtils.moveFile(org.apache.commons.io.FileUtils.getFile(GzipUtils.getUncompressedFilename(tempDestinationFile.getCanonicalPath())), destinationFile); // lets cleanup after ourselves - remove compressed file tempDestinationFile.delete(); } // uncompressed file, download directry to urlDestination else { if (LOG.isInfoEnabled()) { LOG.info("downloadFile(), " + urlSource + ", this may take a while..."); } org.apache.commons.io.FileUtils.copyURLToFile(source, org.apache.commons.io.FileUtils.getFile(destination.getFile())); } } @Override public LineIterator getFileContents(String urlFile) throws Exception { return org.apache.commons.io.FileUtils.lineIterator(new File(new URL(urlFile).getFile())); } @Override public void writeCancerStudyMetadataFile(String stagingDirectory, CancerStudyMetadata cancerStudyMetadata, int numCases) throws Exception { File metaFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), cancerStudyMetadata.getCancerStudyMetadataFilename()); if (LOG.isInfoEnabled()) { LOG.info("writeCancerStudyMetadataFile(), meta file: " + metaFile); } PrintWriter writer = new PrintWriter(org.apache.commons.io.FileUtils.openOutputStream(metaFile, false)); writer.print("type_of_cancer: " + cancerStudyMetadata.getTumorType() + "\n"); writer.print("cancer_study_identifier: " + cancerStudyMetadata.getStableId() + "\n"); // String name = (cancerStudyMetadata.getName().length() > 0) ? // cancerStudyMetadata.getName() : cancerStudyMetadata.getTumorTypeMetadata().getName(); // name = name.replaceAll(CancerStudyMetadata.TUMOR_TYPE_NAME_TAG, // cancerStudyMetadata.getTumorTypeMetadata().getName()); writer.print("name: " + name + "\n"); writer.print("short_name: " + cancerStudyMetadata.getShortName() + "\n"); String description = cancerStudyMetadata.getDescription(); description = description.replaceAll(CancerStudyMetadata.NUM_CASES_TAG, Integer.toString(numCases)); // description = description.replaceAll(CancerStudyMetadata.TUMOR_TYPE_TAG, // cancerStudyMetadata.getTumorTypeMetadata().getType().toUpperCase()); // description = description.replaceAll(CancerStudyMetadata.TUMOR_TYPE_NAME_TAG, // cancerStudyMetadata.getTumorTypeMetadata().getName()); writer.print("description: " + description + "\n"); if (cancerStudyMetadata.getCitation().length() > 0) { writer.print("citation: " + cancerStudyMetadata.getCitation() + "\n"); } if (cancerStudyMetadata.getPMID().length() > 0) { writer.print("pmid: " + cancerStudyMetadata.getPMID() + "\n"); } if (cancerStudyMetadata.getGroups().length() > 0) { writer.print("groups: " + cancerStudyMetadata.getGroups() + "\n"); } writer.flush(); writer.close(); } public void updateCancerStudyMetadataFile(String stagingDirectory, CancerStudyMetadata cancerStudyMetadata, Map<String,String> properties) throws Exception { File metaFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), cancerStudyMetadata.getCancerStudyMetadataFilename()); if (LOG.isInfoEnabled()) { LOG.info("updateCancerStudyMetadataFile(), meta file: " + metaFile); } StringBuilder builder = new StringBuilder(); Pattern propertyPattern = Pattern.compile("^(\\w+)\\: .*$"); org.apache.commons.io.LineIterator it = org.apache.commons.io.FileUtils.lineIterator(metaFile); try { while (it.hasNext()) { String line = it.nextLine(); Matcher matcher = propertyPattern.matcher(line); if (matcher.find()) { if (properties.containsKey(matcher.group(1))) { builder.append(matcher.group(1) + ": " + properties.get(matcher.group(1)) + "\n"); } else { builder.append(line + "\n"); } } else { builder.append(line + "\n"); } } } finally { it.close(); } org.apache.commons.io.FileUtils.writeStringToFile(metaFile, builder.toString(), false); } public void writeMetadataFile(String stagingDirectory, CancerStudyMetadata cancerStudyMetadata, DatatypeMetadata datatypeMetadata, int numCases) throws Exception { String filename = stagingDirectory + File.separator + datatypeMetadata.getMetaFilename(); File metaFile = new File(filename); if (LOG.isInfoEnabled()) { LOG.info("writeMetadataFile(), meta file: " + metaFile); } PrintWriter writer = new PrintWriter(org.apache.commons.io.FileUtils.openOutputStream(metaFile, false)); writer.print("cancer_study_identifier: " + cancerStudyMetadata.getStableId() + "\n"); writer.print("genetic_alteration_type: " + datatypeMetadata.getMetaGeneticAlterationType() + "\n"); String stableID = datatypeMetadata.getMetaStableID(); stableID = stableID.replaceAll(DatatypeMetadata.CANCER_STUDY_TAG, cancerStudyMetadata.toString()); writer.print("stable_id: " + stableID + "\n"); writer.print("show_profile_in_analysis_tab: " + datatypeMetadata.getMetaShowProfileInAnalysisTab() + "\n"); String profileDescription = datatypeMetadata.getMetaProfileDescription(); if (numCases < 0) { numCases = 0; } //profileDescription = profileDescription.replaceAll(DatatypeMetadata.NUM_GENES_TAG, Integer.toString(dataMatrix.getGeneIDs().size())); profileDescription = profileDescription.replaceAll(DatatypeMetadata.NUM_CASES_TAG, Integer.toString(numCases)); profileDescription = profileDescription.replaceAll(DatatypeMetadata.TUMOR_TYPE_TAG, cancerStudyMetadata.getTumorType()); writer.print("profile_description: " + profileDescription + "\n"); writer.print("profile_name: " + datatypeMetadata.getMetaProfileName() + "\n"); writer.flush(); writer.close(); } @Override public void writeMetadataFile(String stagingDirectory, CancerStudyMetadata cancerStudyMetadata, DatatypeMetadata datatypeMetadata, DataMatrix dataMatrix) throws Exception { File metaFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), datatypeMetadata.getMetaFilename()); if (LOG.isInfoEnabled()) { LOG.info("writeMetadataFile(), meta file: " + metaFile); } PrintWriter writer = new PrintWriter(org.apache.commons.io.FileUtils.openOutputStream(metaFile, false)); writer.print("cancer_study_identifier: " + cancerStudyMetadata.getStableId() + "\n"); writer.print("genetic_alteration_type: " + datatypeMetadata.getMetaGeneticAlterationType() + "\n"); writer.print("datatype: " + datatypeMetadata.getMetaDatatypeType() + "\n"); String stableID = datatypeMetadata.getMetaStableID(); stableID = stableID.replaceAll(DatatypeMetadata.CANCER_STUDY_TAG, cancerStudyMetadata.toString()); writer.print("stable_id: " + stableID + "\n"); writer.print("show_profile_in_analysis_tab: " + datatypeMetadata.getMetaShowProfileInAnalysisTab() + "\n"); String profileDescription = datatypeMetadata.getMetaProfileDescription(); if (dataMatrix != null) { profileDescription = profileDescription.replaceAll(DatatypeMetadata.NUM_GENES_TAG, Integer.toString(dataMatrix.getGeneIDs().size())); profileDescription = profileDescription.replaceAll(DatatypeMetadata.NUM_CASES_TAG, Integer.toString(dataMatrix.getCaseIDs().size())); } profileDescription = profileDescription.replaceAll(DatatypeMetadata.TUMOR_TYPE_TAG, cancerStudyMetadata.getTumorType()); writer.print("profile_description: " + profileDescription + "\n"); writer.print("profile_name: " + datatypeMetadata.getMetaProfileName() + "\n"); writer.flush(); writer.close(); } @Override public void writeCopyNumberSegmentMetadataFile(String stagingDirectory, CancerStudyMetadata cancerStudyMetadata, DatatypeMetadata datatypeMetadata, DataMatrix dataMatrix) throws Exception { String metaFilename = datatypeMetadata.getMetaFilename().replaceAll(DatatypeMetadata.CANCER_STUDY_TAG, cancerStudyMetadata.toString()); File metaFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), metaFilename); if (LOG.isInfoEnabled()) { LOG.info("writeCopyNumberSegmentMetadataFile(), meta file: " + metaFile); } PrintWriter writer = new PrintWriter(org.apache.commons.io.FileUtils.openOutputStream(metaFile, false)); writer.print("cancer_study_identifier: " + cancerStudyMetadata.getStableId() + "\n"); if (datatypeMetadata.getDatatype().contains(CopyNumberSegmentFile.ReferenceGenomeId.hg18.toString())){ writer.print("reference_genome_id: " + CopyNumberSegmentFile.ReferenceGenomeId.hg18.toString() + "\n"); } else { writer.print("reference_genome_id: " + CopyNumberSegmentFile.ReferenceGenomeId.hg19.toString() + "\n"); } String profileDescription = datatypeMetadata.getMetaProfileDescription(); if (dataMatrix != null) { profileDescription = profileDescription.replaceAll(DatatypeMetadata.NUM_GENES_TAG, Integer.toString(dataMatrix.getGeneIDs().size())); profileDescription = profileDescription.replaceAll(DatatypeMetadata.NUM_CASES_TAG, Integer.toString(dataMatrix.getCaseIDs().size())); } profileDescription = profileDescription.replaceAll(DatatypeMetadata.TUMOR_TYPE_TAG, cancerStudyMetadata.getTumorType()); writer.print("description: " + profileDescription + "\n"); String cnaSegFilename = datatypeMetadata.getStagingFilename().replaceAll(DatatypeMetadata.CANCER_STUDY_TAG, cancerStudyMetadata.toString()); writer.print("data_filename: " + cnaSegFilename + "\n"); writer.flush(); writer.close(); } @Override public void writeStagingFile(String stagingDirectory, CancerStudyMetadata cancerStudyMetadata, DatatypeMetadata datatypeMetadata, DataMatrix dataMatrix) throws Exception { // staging file String stagingFilename = datatypeMetadata.getStagingFilename(); stagingFilename = stagingFilename.replaceAll(DatatypeMetadata.CANCER_STUDY_TAG, cancerStudyMetadata.toString()); stagingFilename = stagingFilename.replaceAll("_\\*", ""); File stagingFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), stagingFilename); if (LOG.isInfoEnabled()) { LOG.info("writingStagingFile(), staging file: " + stagingFile); } FileOutputStream out = org.apache.commons.io.FileUtils.openOutputStream(stagingFile, false); dataMatrix.write(out); IOUtils.closeQuietly(out); } @Override public void writeMutationStagingFile(String stagingDirectory, CancerStudyMetadata cancerStudyMetadata, DatatypeMetadata datatypeMetadata, DataMatrix dataMatrix) throws Exception { // we only have data matrix at this point, we need to create a temp with its contents File oncotatorInputFile = org.apache.commons.io.FileUtils.getFile(org.apache.commons.io.FileUtils.getTempDirectory(), ""+System.currentTimeMillis()+".oncotatorInputFile"); FileOutputStream out = org.apache.commons.io.FileUtils.openOutputStream(oncotatorInputFile); dataMatrix.write(out); IOUtils.closeQuietly(out); // output should be the path/name of staging file String stagingFilename = datatypeMetadata.getStagingFilename(); stagingFilename = stagingFilename.replaceAll(DatatypeMetadata.CANCER_STUDY_TAG, cancerStudyMetadata.toString()); File stagingFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), stagingFilename); // call oncotateAF oncotateMAF(org.mskcc.cbio.importer.FileUtils.FILE_URL_PREFIX + oncotatorInputFile.getCanonicalPath(), org.mskcc.cbio.importer.FileUtils.FILE_URL_PREFIX + stagingFile.getCanonicalPath()); // clean up if (oncotatorInputFile.exists()) { org.apache.commons.io.FileUtils.forceDelete(oncotatorInputFile); } } @Override public boolean writeZScoresStagingFile(String stagingDirectory, CancerStudyMetadata cancerStudyMetadata, DatatypeMetadata datatypeMetadata, DatatypeMetadata[] dependencies) throws Exception { // sanity check if (dependencies.length != 2) { throw new IllegalArgumentException("writeZScoresStagingFile(), datatypeMetadatas.length != 2, aborting..."); } // check for existence of dependencies if (LOG.isInfoEnabled()) { LOG.info("writeZScoresStagingFile(), checking for existence of dependencies: " + Arrays.asList(dependencies)); } File cnaFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), dependencies[0].getStagingFilename()); if (!cnaFile.exists()) { if (LOG.isInfoEnabled()) { LOG.info("writeZScoresStagingFile(), cannot find cna file dependency: " + cnaFile.getCanonicalPath()); } return false; } File expressionFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), dependencies[1].getStagingFilename()); if (!expressionFile.exists()) { if (LOG.isInfoEnabled()) { LOG.info("writeZScoresStagingFile(), cannot find expression file dependency: " + expressionFile.getCanonicalPath()); } return false; } // we need a zscore file File zScoresFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), datatypeMetadata.getStagingFilename()); // call NormalizeExpressionLevels String[] args = { cnaFile.getCanonicalPath(), expressionFile.getCanonicalPath(), zScoresFile.getCanonicalPath(), NormalizeExpressionLevels.TCGA_NORMAL_SUFFIX }; if (LOG.isInfoEnabled()) { LOG.info("writingZScoresStagingFlie(), calling NormalizeExpressionLevels: " + Arrays.toString(args)); } try { NormalizeExpressionLevels.driver(args); } catch (RuntimeException e) { // houston we have a problem... if (LOG.isInfoEnabled()) { LOG.info("writingZScoresStagingFlie(), exception thrown by NormalizeExpressionLevels: " + e.getMessage() + ", aborting..."); } if (zScoresFile.exists()) { org.apache.commons.io.FileUtils.forceDelete(zScoresFile); } return false; } return true; } @Override public File getOverrideFile(PortalMetadata portalMetadata, CancerStudyMetadata cancerStudyMetadata, String filename) throws Exception { File overrideFile = org.apache.commons.io.FileUtils.getFile(portalMetadata.getOverrideDirectory(), cancerStudyMetadata.getStudyPath(), filename); return (overrideFile.exists()) ? overrideFile : null; } @Override public void applyOverride(String overrideDirectory, String stagingDirectory, CancerStudyMetadata cancerStudyMetadata, String overrideFilename, String stagingFilename) throws Exception { // check for override file File overrideFile = org.apache.commons.io.FileUtils.getFile(overrideDirectory, cancerStudyMetadata.getStudyPath(), overrideFilename); if (overrideFile.exists()) { File stagingFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), stagingFilename); if (LOG.isInfoEnabled()) { LOG.info("applyOverride(), override file exists for " + stagingFile.getCanonicalPath() + ": " + overrideFile.getCanonicalPath()); } // copy override file to staging area if (overrideFile.isFile()) { org.apache.commons.io.FileUtils.copyFile(overrideFile, stagingFile); } else { org.apache.commons.io.FileUtils.copyDirectory(overrideFile, stagingFile); } } } @Override public void writeCaseListFile(String stagingDirectory, CancerStudyMetadata cancerStudyMetadata, CaseListMetadata caseListMetadata, String[] caseList) throws Exception { File caseListFile = org.apache.commons.io.FileUtils.getFile(stagingDirectory, cancerStudyMetadata.getStudyPath(), "case_lists", caseListMetadata.getCaseListFilename()); if (LOG.isInfoEnabled()) { LOG.info("writeCaseListFile(), case list file: " + caseListFile.getCanonicalPath()); } PrintWriter writer = new PrintWriter(org.apache.commons.io.FileUtils.openOutputStream(caseListFile, false)); writer.print("cancer_study_identifier: " + cancerStudyMetadata.getStableId() + "\n"); String stableID = caseListMetadata.getMetaStableID(); stableID = stableID.replaceAll(DatatypeMetadata.CANCER_STUDY_TAG, cancerStudyMetadata.toString()); writer.print("stable_id: " + stableID + "\n"); writer.print("case_list_name: " + caseListMetadata.getMetaCaseListName() + "\n"); String caseListDescription = caseListMetadata.getMetaCaseListDescription(); caseListDescription = caseListDescription.replaceAll(DatatypeMetadata.NUM_CASES_TAG, Integer.toString(caseList.length)); writer.print("case_list_description: " + caseListDescription + "\n"); writer.print("case_list_category: " + caseListMetadata.getMetaCaseListCategory() + "\n"); writer.print("case_list_ids: "); for (String caseID : caseList) { writer.print(caseID + Converter.VALUE_DELIMITER); } writer.println(); writer.flush(); writer.close(); } /** * Runs all MAFs for the given dataaSourcesMetadata through * the Oncotator and OMA tools. * * @param dataSourcesMetadata DataSourcesMetadata * @throws Exception */ @Override public void oncotateAllMAFs(DataSourcesMetadata dataSourcesMetadata) throws Exception { // iterate over datasource download directory and process all MAFs String[] extensions = new String[] { DatatypeMetadata.MAF_FILE_EXT }; for (File maf : listFiles(new File(dataSourcesMetadata.getDownloadDirectory()), extensions, true)) { // create temp for given maf File oncotatorInputFile = org.apache.commons.io.FileUtils.getFile(org.apache.commons.io.FileUtils.getTempDirectory(), ""+System.currentTimeMillis()+".oncotatorInputFile"); org.apache.commons.io.FileUtils.copyFile(maf, oncotatorInputFile); // input is tmp file we just created, we want output to go into the original maf oncotateMAF(org.mskcc.cbio.importer.FileUtils.FILE_URL_PREFIX + oncotatorInputFile.getCanonicalPath(), org.mskcc.cbio.importer.FileUtils.FILE_URL_PREFIX + maf.getCanonicalPath()); // clean up org.apache.commons.io.FileUtils.forceDelete(oncotatorInputFile); } } @Override public void oncotateMAF(String inputMAFURL, String outputMAFURL) throws Exception { // sanity check if (inputMAFURL == null || inputMAFURL.length() == 0 || outputMAFURL == null || outputMAFURL.length() == 0) { throw new IllegalArgumentException("oncotateMAFdownloadFile(): url or urlDestination argument is null..."); } URL inputMAF = new URL(inputMAFURL); URL outputMAF = new URL(outputMAFURL); // determine if we have to call liftover boolean cleanOncotatorInputFile = false; File oncotatorInputFile = new File(inputMAF.getFile()); org.apache.commons.io.LineIterator it = org.apache.commons.io.FileUtils.lineIterator(oncotatorInputFile); String[] parts = it.nextLine().split("\t"); int ixNcbiBuild = -1; for (int ix = 0; ix < parts.length; ix++) { if (parts[ix].equalsIgnoreCase("NCBI_Build")) { ixNcbiBuild = ix; break; } } if (ixNcbiBuild!=-1&&it.hasNext()) { parts = it.nextLine().split("\t"); if (parts[ixNcbiBuild].contains("36") || parts[ixNcbiBuild].equals("hg18")) { it.close(); File liftoverInputFile = org.apache.commons.io.FileUtils.getFile(org.apache.commons.io.FileUtils.getTempDirectory(), ""+System.currentTimeMillis()+".liftoverInputFile"); org.apache.commons.io.FileUtils.copyFile(oncotatorInputFile, liftoverInputFile); oncotatorInputFile = new File(inputMAF.getFile()); // call lift over if (LOG.isInfoEnabled()) { LOG.info("oncotateMAF(), calling Hg18ToHg19..."); } Hg18ToHg19.driver(liftoverInputFile.getCanonicalPath(), oncotatorInputFile.getCanonicalPath(), getLiftOverBinary(), getLiftOverChain()); org.apache.commons.io.FileUtils.forceDelete(liftoverInputFile); cleanOncotatorInputFile = true; } } // create a temp output file from the oncotator File oncotatorOutputFile = org.apache.commons.io.FileUtils.getFile(org.apache.commons.io.FileUtils.getTempDirectory(), ""+System.currentTimeMillis()+".oncotatorOutputFile"); // call oncotator if (LOG.isInfoEnabled()) { LOG.info("oncotateMAF(), calling OncotateTool..."); } OncotateTool.driver(oncotatorInputFile.getCanonicalPath(), oncotatorOutputFile.getCanonicalPath(), true, true, true); // we call OMA here - // we use output from oncotator as input file if (LOG.isInfoEnabled()) { LOG.info("oncotateMAF(), calling MutationAssessorTool..."); } File outputMAFFile = new File(outputMAF.getFile()); outputMAFFile.createNewFile(); MutationAssessorTool.driver(oncotatorOutputFile.getCanonicalPath(), outputMAFFile.getCanonicalPath(), false, true, true); // clean up org.apache.commons.io.FileUtils.forceDelete(oncotatorOutputFile); if (cleanOncotatorInputFile) org.apache.commons.io.FileUtils.forceDelete(oncotatorInputFile); } /** * Copy's the given portal's seg files to location used for linking to IGV from cBio Portal web site. * * @param portalMetadata PortalMetadata * @param datatypeMetadata DatataypeMetadata * @param remoteUserName String * @throws Exception */ @Override public void copySegFiles(PortalMetadata portalMetadata, DatatypeMetadata datatypeMetadata, String remoteUserName) throws Exception { if (LOG.isInfoEnabled()) { LOG.info("copySegFiles()"); } // check args if (portalMetadata == null || remoteUserName == null) { throw new IllegalArgumentException("portal or remoteUserName must not be null"); } // seg file location URL segFileLocation = portalMetadata.getIGVSegFileLinkingLocation(); // we need this to determine location Collection<DataSourcesMetadata> dataSourcesMetadata = config.getDataSourcesMetadata(Config.ALL); // iterate over all cancer studies for (CancerStudyMetadata cancerStudyMetadata : config.getCancerStudyMetadata(portalMetadata.getName())) { // lets determine if cancer study is in staging directory or studies directory String rootDirectory = MetadataUtils.getCancerStudyRootDirectory(portalMetadata, dataSourcesMetadata, cancerStudyMetadata); if (rootDirectory == null) { if (LOG.isInfoEnabled()) { LOG.info("loadStagingFiles(), cannot find root directory for study: " + cancerStudyMetadata + " skipping..."); } continue; } // construct staging filename for seg String sourceFilename = (rootDirectory + File.separator + cancerStudyMetadata.getStudyPath() + File.separator + datatypeMetadata.getStagingFilename()); sourceFilename = sourceFilename.replaceAll(DatatypeMetadata.CANCER_STUDY_TAG, cancerStudyMetadata.toString()); String destinationFilename = datatypeMetadata.getStagingFilename().replaceAll(DatatypeMetadata.CANCER_STUDY_TAG, cancerStudyMetadata.toString()); String[] command = new String[] { "scp", sourceFilename, remoteUserName + "@" + segFileLocation.getHost() + ":" + segFileLocation.getFile() + destinationFilename }; if (LOG.isInfoEnabled()) { LOG.info("executing: " + Arrays.asList(command)); } if (Shell.exec(Arrays.asList(command), ".")) { if (LOG.isInfoEnabled()) { LOG.info("copy successful."); } } else if (LOG.isInfoEnabled()) { LOG.info("copy unsucessful."); } } } /* * Given a zip stream, unzips it and returns an input stream to the desired data file. * * @param importDataRecord ImportDataRecord * @param is InputStream * @return InputStream */ private List<DataMatrix> getDataMatricesFromArchive(ImportDataRecord importDataRecord, DataMatrix methylationCorrelation) throws Exception { List<DataMatrix> toReturn = new ArrayList<DataMatrix>(); if (importDataRecord.getCanonicalPathToData().contains(DatatypeMetadata.MUT_PACK_CALLS_FILE)) { return processMutPackCalls(importDataRecord, methylationCorrelation); } try { File dataFile = new File(importDataRecord.getCanonicalPathToData()); InputStream is = org.apache.commons.io.FileUtils.openInputStream(dataFile); // decompress .gz file if (LOG.isInfoEnabled()) { LOG.info("getDataMatricesFromArchive(), decompressing: " + importDataRecord.getCanonicalPathToData()); } InputStream unzippedContent = new GzipCompressorInputStream(is); // if tarball, untar if (GzipUtils.isCompressedFilename(importDataRecord.getCanonicalPathToData().toLowerCase())) { if (LOG.isInfoEnabled()) { LOG.info("getDataMatricesFromArchive(), gzip file is a tarball, untarring"); } TarArchiveInputStream tis = new TarArchiveInputStream(unzippedContent); TarArchiveEntry entry = null; while ((entry = tis.getNextTarEntry()) != null) { String entryName = entry.getName(); String dataFilename = importDataRecord.getDataFilename(); if (dataFilename.contains(DatatypeMetadata.TUMOR_TYPE_TAG)) { dataFilename = dataFilename.replaceAll(DatatypeMetadata.TUMOR_TYPE_TAG, importDataRecord.getTumorTypeLabel()); } if (dataFilename.contains(DatatypeMetadata.CLINICAL_FOLLOWUP_VERSION)) { Matcher clinicalPatientFollowupMatcher = DatatypeMetadata.CLINICAL_FOLLOWUP_FILE_REGEX.matcher(entryName); if (clinicalPatientFollowupMatcher.find()) { dataFilename = dataFilename.replace(DatatypeMetadata.CLINICAL_FOLLOWUP_VERSION, clinicalPatientFollowupMatcher.group(1)); } } if (entryName.contains(dataFilename)) { if (LOG.isInfoEnabled()) { LOG.info("Processing tar-archive: " + importDataRecord.getDataFilename()); } DataMatrix m = getDataMatrix(entryName, tis, methylationCorrelation); if (m != null) { toReturn.add(m); } } } IOUtils.closeQuietly(tis); } else { DataMatrix m = getDataMatrix(dataFile.getName(), unzippedContent, methylationCorrelation); if (m != null) { toReturn.add(m); } IOUtils.closeQuietly(unzippedContent); } } catch (Exception e) { throw e; } // outta here return toReturn; } private List<DataMatrix> processMutPackCalls(ImportDataRecord importDataRecord, DataMatrix methylationCorrelation) throws Exception { List<DataMatrix> toReturn = new ArrayList<DataMatrix>(); File tmpFile = org.apache.commons.io.FileUtils.getFile(org.apache.commons.io.FileUtils.getTempDirectoryPath(), DatatypeMetadata.MUT_PACK_CALLS_FILE + ".txt"); logMessage(LOG, "processMutPackCalls, tmp file: " + tmpFile.getCanonicalPath()); File dataFile = new File(importDataRecord.getCanonicalPathToData()); InputStream unzippedContent = new GzipCompressorInputStream(org.apache.commons.io.FileUtils.openInputStream(dataFile)); TarArchiveInputStream tis = new TarArchiveInputStream(unzippedContent); TarArchiveEntry entry = null; boolean first = true; while ((entry = tis.getNextTarEntry()) != null) { logMessage(LOG, "processMutPackCalls, entry: " + entry.getName()); if (!entry.getName().endsWith(".maf.txt")) { logMessage(LOG, "skipping: " + entry.getName()); continue; } List<String> contents = IOUtils.readLines(tis, "UTF-8"); if (first) { first = false; org.apache.commons.io.FileUtils.writeLines(tmpFile, contents, false); } else { contents.remove(0); org.apache.commons.io.FileUtils.writeLines(tmpFile, contents, true); } } IOUtils.closeQuietly(tis); FileInputStream fis = org.apache.commons.io.FileUtils.openInputStream(tmpFile); DataMatrix m = getDataMatrix(tmpFile.getCanonicalPath(), fis, methylationCorrelation); IOUtils.closeQuietly(fis); if (m != null) { toReturn.add(m); } return toReturn; } /** * Helper function to create DataMatrix. * * @param data InputStream * @param methylationCorrelation DataMatrix * @return DataMatrix */ private DataMatrix getDataMatrix(String dataFilename, InputStream data, DataMatrix methylationCorrelation) throws Exception { // iterate over all lines in byte[] List<String> columnNames = null; List<LinkedList<String>> rowData = null; LineIterator it = IOUtils.lineIterator(data, null); Map<String,String> probeIdMap = initProbMap(methylationCorrelation); int count = -1; while (it.hasNext()) { // first row is our column heading, create column vector if (++count == 0) { columnNames = new LinkedList(Arrays.asList(it.nextLine().split(Converter.VALUE_DELIMITER, -1))); } // all other rows are rows in the table else { rowData = (rowData == null) ? new LinkedList<LinkedList<String>>() : rowData; LinkedList<String> thisRow = new LinkedList(Arrays.asList(it.nextLine().split(Converter.VALUE_DELIMITER, -1))); if (processingBCRClinicalFile(dataFilename) && skipClinicalDataRow(thisRow)) { continue; } if (methylationCorrelation == null) { rowData.add(thisRow); } // first line in methylation file is probeID else if (probeIdMap.containsKey(thisRow.getFirst())) { rowData.add(thisRow); } } } // problem reading from data? if (columnNames == null || rowData == null) { if (LOG.isInfoEnabled()) { LOG.info("getDataMatrix(), problem creating DataMatrix from file, data file probably missing data, returning null"); } return null; } // made it here, we can create DataMatrix if (LOG.isInfoEnabled()) { LOG.info("creating new DataMatrix(), from file data, num rows: " + rowData.size()); } // outta here return new DataMatrix(dataFilename, rowData, columnNames); } /** * Helper function to gunzip file. gzipFile param is canonical path. * * @param gzipFile String */ private static void gunzip(String gzipFile) throws Exception { // setup our gzip inputs tream FileOutputStream fos = null; String outFilePath = GzipUtils.getUncompressedFilename(gzipFile); GZIPInputStream gis = new GZIPInputStream(new FileInputStream(gzipFile)); try { // unzip into file less the .gz fos = new FileOutputStream(outFilePath); IOUtils.copy(gis, fos); } finally { // close up our streams IOUtils.closeQuietly(gis); if (fos != null) IOUtils.closeQuietly(fos); } } private static Map initProbMap(DataMatrix methylationCorrelation) { Map<String,String> toReturn = new HashMap<String,String>(); if (methylationCorrelation == null) return toReturn; for (String probeId : methylationCorrelation. getColumnData(MethylationConverterImpl.CORRELATE_METH_PROBE_COLUMN_HEADER_NAME).get(0)) { toReturn.put(probeId, probeId); } return toReturn; } private List<String> getCaseListFromSequencedSamplesFile(File sequencedSamplesFile) throws Exception { if (LOG.isInfoEnabled()) { LOG.info("getCaseListFromSequencedSamplesFile(): " + sequencedSamplesFile); } LinkedHashSet<String> caseSet = new LinkedHashSet<String>(); org.apache.commons.io.LineIterator it = org.apache.commons.io.FileUtils.lineIterator(sequencedSamplesFile); try { while (it.hasNext()) { caseSet.add(it.nextLine()); } } finally { it.close(); } if (LOG.isInfoEnabled()) { LOG.info("caseSet size: " + caseSet.size()); } return new ArrayList<String>(caseSet); } private boolean processingBCRClinicalFile(String dataFilename) { return (dataFilename.startsWith(DatatypeMetadata.BCR_CLINICAL_FILENAME_PREFIX)); } private boolean skipClinicalDataRow(LinkedList<String> row) { return (!row.getFirst().startsWith("TCGA") && !row.getFirst().startsWith(ClinicalAttributesNamespace.CDE_TAG)); } private void logMessage(Log log, String message) { if (log.isInfoEnabled()) { log.info(message); } } }
package com.intellij.codeInspection; import com.intellij.analysis.AnalysisScope; import com.intellij.codeInsight.daemon.GroupNames; import com.intellij.codeInsight.daemon.impl.RemoveSuppressWarningAction; import com.intellij.codeInspection.ex.*; import com.intellij.codeInspection.reference.RefClass; import com.intellij.codeInspection.reference.RefManagerImpl; import com.intellij.codeInspection.reference.RefVisitor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.BidirectionalMap; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author cdr */ public class RedundantSuppressInspection extends GlobalInspectionTool{ private BidirectionalMap<String, QuickFix> myQuickFixes = null; private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.RedundantSuppressInspection"); @NotNull public String getGroupDisplayName() { return GroupNames.GENERAL_GROUP_NAME; } @NotNull public String getDisplayName() { return InspectionsBundle.message("inspection.redundant.suppression.name"); } @NotNull @NonNls public String getShortName() { return "RedundantSuppression"; } public void runInspection(final AnalysisScope scope, final InspectionManager manager, final GlobalInspectionContext globalContext, final ProblemDescriptionsProcessor problemDescriptionsProcessor) { globalContext.getRefManager().iterate(new RefVisitor() { public void visitClass(RefClass refClass) { if (!globalContext.shouldCheck(refClass, RedundantSuppressInspection.this)) return; CommonProblemDescriptor[] descriptors = checkElement(refClass, manager, globalContext.getProject()); if (descriptors != null) { problemDescriptionsProcessor.addProblemElement(refClass, descriptors); } } }); } @Nullable private CommonProblemDescriptor[] checkElement(RefClass refEntity, InspectionManager manager, final Project project) { final PsiElement psiElement = refEntity.getElement(); final Map<PsiElement, Collection<String>> suppressedScopes = new THashMap<PsiElement, Collection<String>>(); psiElement.accept(new PsiRecursiveElementVisitor() { public void visitModifierList(PsiModifierList list) { super.visitModifierList(list); final PsiElement parent = list.getParent(); if (parent instanceof PsiModifierListOwner && !(parent instanceof PsiClass)) { checkElement(parent); } } public void visitComment(PsiComment comment) { checkElement(comment); } public void visitClass(PsiClass aClass) { if (aClass == psiElement) { super.visitClass(aClass); checkElement(aClass); } } private void checkElement(final PsiElement owner) { String idsString = InspectionManagerEx.getSuppressedInspectionIdsIn(owner); if (idsString != null && idsString.length() != 0) { List<String> ids = StringUtil.split(idsString, ","); Collection<String> suppressed = suppressedScopes.get(owner); if (suppressed == null) { suppressed = ids; } else { for (String id : ids) { if (!suppressed.contains(id)) { suppressed.add(id); } } } suppressedScopes.put(owner, suppressed); } } }); if (suppressedScopes.values().isEmpty()) return null; // have to visit all file from scratch since inspections can be written in any perversive way including checkFile() overriding final ModifiableModel model = InspectionProjectProfileManager.getInstance(manager.getProject()).getInspectionProfile(psiElement).getModifiableModel(); InspectionProfileWrapper profile = new InspectionProfileWrapper((InspectionProfile)model); profile.init(manager.getProject()); Collection<InspectionTool> suppressedTools = new THashSet<InspectionTool>(); InspectionTool[] tools = profile.getInspectionTools(); for (Collection<String> ids : suppressedScopes.values()) { for (String id : ids) { String shortName = id.trim(); for (InspectionTool tool : tools) { if (tool.getShortName().equals(shortName)) { suppressedTools.add(tool); } } } } GlobalInspectionContextImpl globalContext = ((InspectionManagerEx)InspectionManager.getInstance(project)).createNewGlobalContext(false); final RefManagerImpl refManager = ((RefManagerImpl)globalContext.getRefManager()); refManager.inspectionReadActionStarted(); final List<ProblemDescriptor> result; try { result = new ArrayList<ProblemDescriptor>(); for (InspectionTool tool : suppressedTools) { String toolId = tool.getShortName(); tool.initialize(globalContext); Collection<CommonProblemDescriptor> descriptors; if (tool instanceof LocalInspectionToolWrapper) { LocalInspectionToolWrapper local = (LocalInspectionToolWrapper)tool; if (local.getTool() instanceof UnfairLocalInspectionTool) continue; //cant't work with passes other than LocalInspectionPass local.processFile(psiElement.getContainingFile(), false, manager); descriptors = local.getProblemDescriptors(); } else if (tool instanceof GlobalInspectionToolWrapper) { GlobalInspectionToolWrapper global = (GlobalInspectionToolWrapper)tool; global.processFile(new AnalysisScope(psiElement.getContainingFile()), manager, globalContext); descriptors = global.getProblemDescriptors(); } else { continue; } for (PsiElement suppressedScope : suppressedScopes.keySet()) { Collection<String> suppressedIds = suppressedScopes.get(suppressedScope); if (!suppressedIds.contains(toolId)) continue; boolean hasErrorInsideSuppressedScope = false; for (CommonProblemDescriptor descriptor : descriptors) { if (!(descriptor instanceof ProblemDescriptor)) continue; PsiElement element = ((ProblemDescriptor)descriptor).getPsiElement(); if (element == null) continue; PsiElement annotation = InspectionManagerEx.getElementToolSuppressedIn(element, toolId); if (annotation != null && PsiTreeUtil.isAncestor(suppressedScope, annotation, false)) { hasErrorInsideSuppressedScope = true; break; } } if (!hasErrorInsideSuppressedScope) { PsiMember psiMember; if (suppressedScope instanceof PsiMember) { psiMember = (PsiMember)suppressedScope; } else { psiMember = PsiTreeUtil.getParentOfType(suppressedScope, PsiDocCommentOwner.class); } if (psiMember != null && psiMember.isValid()) { String description = InspectionsBundle.message("inspection.redundant.suppression.description"); if (myQuickFixes == null) myQuickFixes = new BidirectionalMap<String, QuickFix>(); QuickFix fix = myQuickFixes.get(toolId); if (fix == null) { fix = new RemoveSuppressWarningAction(toolId); myQuickFixes.put(toolId, fix); } PsiElement identifier = null; if (psiMember instanceof PsiMethod) { identifier = ((PsiMethod)psiMember).getNameIdentifier(); } else if (psiMember instanceof PsiField) { identifier = ((PsiField)psiMember).getNameIdentifier(); } else if (psiMember instanceof PsiClass) { identifier = ((PsiClass)psiMember).getNameIdentifier(); } if (identifier == null) { identifier = psiMember; } result.add(manager.createProblemDescriptor(identifier, description, (LocalQuickFix)fix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING)); } } } } } finally { refManager.inspectionReadActionFinished(); } return result.toArray(new ProblemDescriptor[result.size()]); } @Nullable public QuickFix getQuickFix(final String hint) { return myQuickFixes != null ? myQuickFixes.get(hint) : null; } @Nullable public String getHint(final QuickFix fix) { if (myQuickFixes != null) { final List<String> list = myQuickFixes.getKeysByValue(fix); if (list != null) { LOG.assertTrue(list.size() == 1); return list.get(0); } } return null; } public boolean isGraphNeeded() { return true; } }
package VASSAL.tools.image; import java.awt.Dimension; import java.awt.color.CMMException; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.Iterator; import java.util.Set; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream; import VASSAL.tools.io.IOUtils; import VASSAL.tools.io.RereadableInputStream; import VASSAL.tools.lang.Reference; /** * An image loader which wraps {@link ImageIO}. * * This class handles the assorted problems with various versions of * {@link ImageIO}, ensuring that we can reliably load image files to * {@link BufferedImages} with a predictable type. * * @since 3.1.0 * @author Joel Uckelman */ public class ImageIOImageLoader implements ImageLoader { protected final ImageTypeConverter tconv; /** * Create an image loader. * * @param tconv the <code>ImageTypeConverter</code> to use for type * conversions */ public ImageIOImageLoader(ImageTypeConverter tconv) { this.tconv = tconv; } // Used to indicate whether this version of Java has the PNG iTXt bug. // This can be removed once we no longer support Java 1.5. protected static final boolean iTXtBug; static { final String jvmver = System.getProperty("java.version"); iTXtBug = jvmver == null || jvmver.startsWith("1.5"); } protected static final Set<Integer> skip_iTXt = Collections.singleton(PNGDecoder.iTXt); // Used to indicate whether this version of Java has the JPEG color // correction bug. protected static final boolean YCbCrBug; static { BufferedImage img = null; InputStream in = null; try { // We intentionally bypass the normal image loading system // in order to see how ImageIO loads the test image. in = ImageIOImageLoader.class.getResourceAsStream("/images/black.jpg"); img = ImageIO.read(new MemoryCacheImageInputStream(in)); in.close(); } catch (IOException e) { // this should not happen throw new IllegalStateException(); } finally { IOUtils.closeQuietly(in); } if (img == null) { // this should not happen throw new IllegalStateException(); } // The pixel in the image is supposed to be black. If the pixel is // green, then ImageIO is misinterpreting the YCbCr data as RGB. If // the pixel is turquoise, then ImageIO is misinterpreting the color // in yet another way, which will also lead to same YCbCr mangling. // (So far the turquoise pixel happens only with 1.7.0_21 and 1.7.0_25 // JVMs on Linux...) final int pixel = img.getRGB(0,0); switch (pixel) { case 0xFF000000: YCbCrBug = false; break; case 0xFF008080: case 0xFF008700: YCbCrBug = true; break; default: // This JVM is broken in an unexpected way! throw new IllegalStateException( "Unexpected pixel value 0x" + String.format("%08x", pixel) ); } } // Workaround for Sun Bug 6986863: // java.awt.color.ICC_Profile.getInstance() isn't thread safe (!), but // is called from com.sun.imageio.plugins.jpeg.JPEGImageReader.getWidth(). // This means that not only is JPEGImageReader.getWidth() not thread-safe, // but it's not even thread-safe across different instances of // JPEGImageReader. Nobody will ever be trying to load more than one JPEG // at a time, right? WTF?! // To mitigate this, we attempt to turn off ProfileDeferralMgr, which will // stop calls to ProfileDeferralMgr.activateProfiles(), which is where the // race happens. static { // Try to find the ProfileDeferralMgr. It's is not a public part of the // JDK and it changed packages at some point, so we look both places, // newer location first. Class <?> c = null; try { c = Class.forName("sun.java2d.cmm.ProfileDeferralMgr"); } catch (ClassNotFoundException e) { try { c = Class.forName("sun.awt.color.ProfileDeferralMgr"); } catch (ClassNotFoundException ignore) { // No ProfileDeferralMgr, so probably no bug either. } } if (c != null) { Field df = null; try { df = c.getField("deferring"); } catch (NoSuchFieldException ignore) { // Nothing we can do } if (df != null) { try { if (df.getBoolean(null)) { Method am = null; try { am = c.getMethod("activateProfiles"); } catch (NoSuchMethodException ignore) { // Nothing we can do } if (am != null) { try { am.invoke(null); df.setBoolean(null, false); } catch (InvocationTargetException ignore) { // Nothing we can do } } } } catch (IllegalAccessException ignore) { // Nothing we can do } } } } /** * Loads an image. * * @param name the image name * @param in the input stream * @param typeIfOpaque the requested image type for opaque images * @param typeIfTransparent the requested image type for transparent images * @param managed <code>true</code> if a managed image should be returned * @return the image * * @throws BrokenImageException if the image is faulty * @throws UnrecognizedImageTypeException if the image type is not recognized * @throws ImageIOException if reading the image goes wrong */ public BufferedImage load( String name, InputStream in, int typeIfOpaque, int typeIfTransparent, boolean managed ) throws ImageIOException { // ImageIO fails on the following types of images: // Sun Bug 6788458: 8-bit/channel color type 2 (RGB) PNGs with tRNS chunks // Sun Bug 6541476: PNGs with iTXt chunks on Java 1.5 // Sun Bug 6444360: JPEGs with corrupt color profiles // Sun Bug 6404011: JPEGs with corrupt color profiles on Java 1.5 // Sun Bug 4712797: YCbCr JPEGs with no JFIF marker // Sun Bug 4776576: YCbCr JPEFs with no JFIF marker // Someday, when both ImageIO is fixed and everyone's JRE contains // that fix, we can do this the simple way. boolean fix_tRNS = false; int tRNS = 0x00000000; boolean fix_YCbCr = false; BufferedImage img = null; RereadableInputStream rin = null; try { rin = new RereadableInputStream(in); rin.mark(512); DataInputStream din = new DataInputStream(rin); // Is this a PNG? if (PNGDecoder.decodeSignature(din)) { // The PNG chunks refered to here are defined in the PNG PNGDecoder.Chunk ch = PNGDecoder.decodeChunk(din); // Sanity check: This is not a PNG if IHDR is not the first chunk. if (ch.type == PNGDecoder.IHDR) { // At present, ImageIO does not honor the tRNS chunk in 8-bit color // type 2 (RGB) PNGs. This is not a bug per se, as the PNG standard // the does not require compliant decoders to use ancillary chunks. // However, every other PNG decoder we can find *does* honor the // tRNS chunk for this type of image, and so the appearance for // users is that VASSAL is broken when their 8-bit RGB PNGs don't // show the correct transparency. // We check for type-2 8-bit PNGs with tRNS chunks. if (ch.data[8] == 8 && ch.data[9] == 2) { // This is an 8-bit-per-channel Truecolor image; we must check // whether there is a tRNS chunk, and if so, record the color // so that we can manually set transparency later. // IHDR is required to be first, and tRNS is required to appear // before the first IDAT chunk; therefore, if we find an IDAT // we're done. DONE_PNG: for (;;) { ch = PNGDecoder.decodeChunk(din); switch (ch.type) { case PNGDecoder.tRNS: fix_tRNS = true; break DONE_PNG; case PNGDecoder.IDAT: fix_tRNS = false; break DONE_PNG; default: } } if (fix_tRNS) { if (ch.data.length != 6) { // There is at least one piece of software (SplitImage) which // writes tRNS chunks for type 2 images which are only 3 bytes // long, and because this kind of thing is used by module // designers for slicing up scans of countersheets, we can // expect to see such crap from time to time. throw new BrokenImageException(name, "bad tRNS chunk length"); } // tRNS chunk: PNG Standard, 11.3.2.1 // tRNS data is stored as three 2-byte samples, but the high // byte of each sample is empty because we are dealing with // 8-bit-per-channel images. tRNS = 0xff000000 | ((ch.data[1] & 0xff) << 16) | ((ch.data[3] & 0xff) << 8) | (ch.data[5] & 0xff); } } if (iTXtBug) { // Filter out iTXt chunks on JVMs with the iTXt bug. rin.reset(); rin = new RereadableInputStream( new PNGChunkSkipInputStream(skip_iTXt, rin)); rin.mark(1); } } } else if (YCbCrBug) { rin.reset(); rin.mark(512); din = new DataInputStream(rin); // Is this a JPEG? if (JPEGDecoder.decodeSignature(din)) { // The case where ImageIO fails is when there is no JFIF marker, // no color profile, and three color components with the same // subsampling. In this case, ImageIO incorrectly assumes that // this image is RGB instead of YCbCr. JPEGDecoder.Chunk ch; fix_YCbCr = true; DONE_JPEG: for (;;) { ch = JPEGDecoder.decodeChunk(din); switch (ch.type) { case JPEGDecoder.SOF0: case JPEGDecoder.SOF1: case JPEGDecoder.SOF2: case JPEGDecoder.SOF3: case JPEGDecoder.SOF4: case JPEGDecoder.SOF5: case JPEGDecoder.SOF6: case JPEGDecoder.SOF7: case JPEGDecoder.SOF9: case JPEGDecoder.SOF10: case JPEGDecoder.SOF11: case JPEGDecoder.SOF12: case JPEGDecoder.SOF13: case JPEGDecoder.SOF14: case JPEGDecoder.SOF15: // The JPEG standard requires any APPn markers to appear before // the first SOF marker, so if we see an SOF marker, we know // there are no APPn markers to find. Hence, we can decide now // whether this JPEG triggers the bug. fix_YCbCr = ch.data.length == 15 && ch.data[5] == 3 && // color components ch.data[7] == ch.data[10] && ch.data[7] == ch.data[13]; break DONE_JPEG; case JPEGDecoder.APP0: if (ch.data.length >= 4 && ch.data[0] == 'J' && ch.data[1] == 'F' && ch.data[2] == 'I' && ch.data[3] == 'F') { // We've seen a JFIF, this image is ok. fix_YCbCr = false; break DONE_JPEG; } break; case JPEGDecoder.APP2: // Check whether we have a color profile. If so, then ImageIO // can handle decoding the image. if (ch.data.length >= 12 && ch.data[0] == 'I' && ch.data[1] == 'C' && ch.data[2] == 'C' && ch.data[3] == '_' && ch.data[4] == 'P' && ch.data[5] == 'R' && ch.data[6] == 'O' && ch.data[7] == 'F' && ch.data[8] == 'I' && ch.data[9] == 'L' && ch.data[10] == 'E' && ch.data[11] == 0x00) { // We have a color profile, this image is ok. fix_YCbCr = false; break DONE_JPEG; } break; case JPEGDecoder.APP13: case JPEGDecoder.APP14: fix_YCbCr = false; break DONE_JPEG; case JPEGDecoder.SOS: // We've reached a Start of Scan marker. Following this // is not a normal segment, but instead a lot of raw data. // This probably shouldn't happen with a valid JPEG. case JPEGDecoder.EOI: // We've reached the end. This probably shouldn't happen. break DONE_JPEG; default: } } } } // Load the image rin.reset(); img = wrapImageIO(name, rin, readImage); rin.close(); } catch (ImageIOException e) { // Don't wrap ImageIOExceptions. throw e; } catch (IOException e) { throw new ImageIOException(name, e); } finally { IOUtils.closeQuietly(rin); } final int type = img.getTransparency() == BufferedImage.OPAQUE && !fix_tRNS ? typeIfOpaque : typeIfTransparent; final Reference<BufferedImage> ref = new Reference<BufferedImage>(img); if (fix_tRNS) { // Fix up transparency in type 2 Truecolor images. img = null; img = fix_tRNS(ref, tRNS, type); ref.obj = img; } else if (fix_YCbCr) { // Fix up color space in misinterpreted JPEGs. img = null; img = fix_YCbCr(ref, type); ref.obj = img; } // We convert the image in two cases: // 1) the image is not yet the requested type, or // 2) a managed image was requested, but the image // was unmanaged by the transparency fix. if (img.getType() != type || (fix_tRNS && managed)) { img = null; img = tconv.convert(ref, type); } return img; } protected static interface Wrapper<T> { T run(String name, InputStream in) throws IOException; } protected <T> T wrapImageIO(String name, InputStream in, Wrapper<T> w) throws ImageIOException { try { return w.run(name, in); } catch (ArrayIndexOutOfBoundsException e) { // Note: ImageIO can throw an ArrayIndexOutOfBoundsException for // some corrupt JPEGs. This problem is noted in Sun Bug 6351707, throw new BrokenImageException(name, e); } catch (CMMException e) { // Note: ImageIO can throw a CMMException for JPEGs which have // broken color profiles. This problem is noted in Sun Bugs 6444360 // and 6839133. throw new BrokenImageException(name, e); } catch (IllegalArgumentException e) { // kinds of broken images, e.g., JPEGs which are in the RGB color // space but have non-RGB color profiles (see Bug 2673589 for an // example of this). This problem is noted in Sun Bug 6404011, throw new BrokenImageException(name, e); } catch (ImageIOException e) { // Don't wrap ImageIOExceptions. throw e; } catch (IOException e) { throw new ImageIOException(name, e); } } /** A functor for reading images. */ protected static Wrapper<BufferedImage> readImage = new Wrapper<BufferedImage>() { /** * Loads an image. * * @param name the image name * @param in the input stream * @return the image * * @throws UnrecognizedImageTypeException if the image type is unknown * @throws IOException if reading the image goes wrong */ public BufferedImage run(String name, InputStream in) throws IOException { final BufferedImage img = ImageIO.read(new MemoryCacheImageInputStream(in)); if (img == null) throw new UnrecognizedImageTypeException(name); return img; } }; /** A functor for reading image dimensions. */ protected static Wrapper<Dimension> readSize = new Wrapper<Dimension>() { /** * Gets the size of an image. * * @param name the image name * @param in the input stream * @return the size of the image * * @throws BrokenImageException if the image is faulty * @throws UnrecognizedImageTypeException if the image type is unknown * @throws IOException if reading the image goes wrong */ public Dimension run(String name, InputStream in) throws IOException { final ImageInputStream stream = new MemoryCacheImageInputStream(in); final Iterator<ImageReader> i = ImageIO.getImageReaders(stream); if (!i.hasNext()) throw new UnrecognizedImageTypeException(name); final ImageReader reader = i.next(); try { reader.setInput(stream); return new Dimension(reader.getWidth(0), reader.getHeight(0)); } finally { reader.dispose(); } } }; protected BufferedImage fix_tRNS(Reference<BufferedImage> ref, int tRNS, int type) throws ImageIOException { BufferedImage img = ref.obj; // Ensure that we are working with integer ARGB data. Whether it's // premultiplied doesn't matter, since fully transparent black pixels // are the same in both. if (img.getType() != BufferedImage.TYPE_INT_ARGB && img.getType() != BufferedImage.TYPE_INT_ARGB_PRE) { // If the requested type is not an ARGB one, then we convert to ARGB // for applying this fix. if (type != BufferedImage.TYPE_INT_ARGB && type != BufferedImage.TYPE_INT_ARGB_PRE) { type = BufferedImage.TYPE_INT_ARGB; } img = null; img = tconv.convert(ref, type); } // NB: This unmanages the image. final DataBufferInt db = (DataBufferInt) img.getRaster().getDataBuffer(); final int[] data = db.getData(); // Set all pixels of the transparent color to have alpha 0. for (int i = 0; i < data.length; ++i) { if (data[i] == tRNS) data[i] = 0x00000000; } return img; } protected BufferedImage fix_YCbCr(Reference<BufferedImage> ref, int type) throws ImageIOException { BufferedImage img = ref.obj; // Ensure that we are working with RGB or ARGB data. if (img.getType() != BufferedImage.TYPE_INT_RGB && img.getType() != BufferedImage.TYPE_INT_ARGB) { if (type != BufferedImage.TYPE_INT_RGB && type != BufferedImage.TYPE_INT_ARGB) { type = BufferedImage.TYPE_INT_ARGB; } img = null; img = tconv.convert(ref, type); } // NB: This unmanages the image. final DataBufferInt db = (DataBufferInt) img.getRaster().getDataBuffer(); final int[] data = db.getData(); for (int i = 0; i < data.length; ++i) { final int y = (data[i] >> 16) & 0xFF; final int pb = ((data[i] >> 8) & 0xFF) - 128; final int pr = ( data[i] & 0xFF) - 128; final int a = (data[i] >> 24) & 0xFF; final int r = (int) Math.round(y + 1.402*pr); final int g = (int) Math.round(y - 0.34414*pb - 0.71414*pr); final int b = (int) Math.round(y + 1.772*pb); data[i] = (a << 24) | ((r < 0 ? 0 : (r > 0xFF ? 0xFF : r)) << 16) | ((g < 0 ? 0 : (g > 0xFF ? 0xFF : g)) << 8) | (b < 0 ? 0 : (b > 0xFF ? 0xFF : b)); } return img; } /** * Gets the size of an image. * * @param name the image name * @param in the input stream * @return the size of the image * * @throws BrokenImageException if the image is faulty * @throws UnrecognizedImageTypeException if the image type is not recognized * @throws ImageIOException if reading the image goes wrong */ public Dimension size(String name, InputStream in) throws ImageIOException { return wrapImageIO(name, in, readSize); } }
package psidev.psi.mi.jami.utils.clone; import psidev.psi.mi.jami.model.*; import psidev.psi.mi.jami.model.impl.*; /** * Utility class for cloning a participant * * @author Marine Dumousseau (marine@ebi.ac.uk) * @version $Id$ * @since <pre>13/02/13</pre> */ public class ParticipantCloner { /*** * This method will copy properties of participant source in participant target and will override all the other properties of Target participant. * This method will ignore interaction * @param source * @param target * @param createNewFeature If true, this method will clone each feature from source instead of reusing the feature instances from source. * It will then set the participantEvidence of the cloned features to target */ public static void copyAndOverrideParticipantEvidenceProperties(ParticipantEvidence source, ParticipantEvidence target, boolean createNewFeature){ if (source != null && target != null){ target.setExperimentalRole(source.getExperimentalRole()); target.setExpressedInOrganism(source.getExpressedInOrganism()); target.setBiologicalRole(source.getBiologicalRole()); target.setStoichiometry(source.getStoichiometry()); // copy collections target.getCausalRelationships().clear(); target.getCausalRelationships().addAll(source.getCausalRelationships()); target.getAnnotations().clear(); target.getAnnotations().addAll(source.getAnnotations()); target.getConfidences().clear(); target.getConfidences().addAll(source.getConfidences()); target.getXrefs().clear(); target.getXrefs().addAll(source.getXrefs()); target.getAliases().clear(); target.getAliases().addAll(source.getAliases()); target.getExperimentalPreparations().clear(); target.getExperimentalPreparations().addAll(source.getExperimentalPreparations()); target.getParameters().clear(); target.getParameters().addAll(source.getParameters()); target.getIdentificationMethods().clear(); target.getIdentificationMethods().addAll(source.getIdentificationMethods()); // special case for participant candidates if (source instanceof ExperimentalParticipantPool && target instanceof ExperimentalParticipantPool){ ExperimentalParticipantPool poolTarget = (ExperimentalParticipantPool)target; ExperimentalParticipantPool poolSource = (ExperimentalParticipantPool)source; poolTarget.clear(); for (ExperimentalParticipantCandidate candidate : poolSource){ ExperimentalParticipantCandidate candidateClone = new DefaultExperimentalParticipantCandidate(candidate.getInteractor()); ParticipantCandidateCloner.copyAndOverrideExperimentalCandidateProperties(candidate, candidateClone, createNewFeature); poolTarget.add(candidateClone); } } else{ target.setInteractor(source.getInteractor()); } // copy features or create new ones if (!createNewFeature){ target.getFeatures().clear(); target.getFeatures().addAll(source.getFeatures()); } else { target.getFeatures().clear(); for (FeatureEvidence f : source.getFeatures()){ FeatureEvidence clone = new DefaultFeatureEvidence(); FeatureCloner.copyAndOverrideFeatureEvidenceProperties(f, clone); target.addFeature(clone); } } } } /*** * This method will copy properties of modelled participant source in modelled participant target and will override all the other properties of Target modelled participant. * This method will ignore interaction * @param source * @param target * @param createNewFeature If true, this method will clone each feature from source instead of reusing the feature instances from source. * It will then set the modelledParticipant of the cloned features to target */ public static void copyAndOverrideModelledParticipantProperties(ModelledParticipant source, ModelledParticipant target, boolean createNewFeature){ if (source != null && target != null){ target.setBiologicalRole(source.getBiologicalRole()); target.setStoichiometry(source.getStoichiometry()); // copy collections target.getCausalRelationships().clear(); target.getCausalRelationships().addAll(source.getCausalRelationships()); target.getAnnotations().clear(); target.getAnnotations().addAll(source.getAnnotations()); target.getXrefs().clear(); target.getXrefs().addAll(source.getXrefs()); target.getAliases().clear(); target.getAliases().addAll(source.getAliases()); // special case for participant candidates if (source instanceof ModelledParticipantPool && target instanceof ModelledParticipantPool){ ModelledParticipantPool poolTarget = (ModelledParticipantPool)target; ModelledParticipantPool poolSource = (ModelledParticipantPool)source; poolTarget.clear(); for (ModelledParticipantCandidate candidate : poolSource){ ModelledParticipantCandidate candidateClone = new DefaultModelledParticipantCandidate(candidate.getInteractor()); ParticipantCandidateCloner.copyAndOverrideModelledPCandidateProperties(candidate, candidateClone, createNewFeature); poolTarget.add(candidateClone); } } else{ target.setInteractor(source.getInteractor()); } // copy features or create new ones if (!createNewFeature){ target.getFeatures().clear(); target.getFeatures().addAll(source.getFeatures()); } else { target.getFeatures().clear(); for (ModelledFeature f : source.getFeatures()){ ModelledFeature clone = new DefaultModelledFeature(); FeatureCloner.copyAndOverrideModelledFeaturesProperties(f, clone); target.addFeature(clone); } } } } /** * This method will copy properties of participant source in participant target and will override all the other properties of Target participant. * @param source * @param target * @param createNewFeature If true, this method will clone each feature from source instead of reusing the feature instances from source. */ public static void copyAndOverrideBasicParticipantProperties(Participant source, Participant target, boolean createNewFeature){ if (source != null && target != null){ target.setBiologicalRole(source.getBiologicalRole()); target.setStoichiometry(source.getStoichiometry()); // copy collections target.getCausalRelationships().clear(); target.getCausalRelationships().addAll(source.getCausalRelationships()); target.getAnnotations().clear(); target.getAnnotations().addAll(source.getAnnotations()); target.getXrefs().clear(); target.getXrefs().addAll(source.getXrefs()); target.getAliases().clear(); target.getAliases().addAll(source.getAliases()); // special case for participant candidates if (source instanceof ParticipantPool && target instanceof ParticipantPool){ ParticipantPool poolTarget = (ParticipantPool)target; ParticipantPool poolSource = (ParticipantPool)source; poolTarget.clear(); for (Object candidate : poolSource){ ParticipantCandidate candidateClone = new DefaultParticipantCandidate(((ParticipantCandidate)candidate).getInteractor()); ParticipantCandidateCloner.copyAndOverrideBasicCandidateProperties((ParticipantCandidate)candidate, candidateClone, createNewFeature); poolTarget.add(candidateClone); } } else{ target.setInteractor(source.getInteractor()); } // copy features or create new ones if (!createNewFeature){ target.getFeatures().clear(); target.addAllFeatures(source.getFeatures()); } else { target.getFeatures().clear(); for (Object f : source.getFeatures()){ Feature clone = new DefaultFeature(); FeatureCloner.copyAndOverrideBasicFeaturesProperties((Feature)f, clone); target.addFeature(clone); } } } } public static void copyAndOverrideBasicEntityProperties(Entity source, Entity target, boolean createNewFeature){ if (source != null && target != null){ target.setStoichiometry(source.getStoichiometry()); // copy collections target.getCausalRelationships().clear(); target.getCausalRelationships().addAll(source.getCausalRelationships()); // special case for participant candidates if (source instanceof ParticipantPool && target instanceof ParticipantPool){ ParticipantPool poolTarget = (ParticipantPool)target; ParticipantPool poolSource = (ParticipantPool)source; poolTarget.clear(); for (Object candidate : poolSource){ ParticipantCandidate candidateClone = new DefaultParticipantCandidate(((ParticipantCandidate)candidate).getInteractor()); ParticipantCandidateCloner.copyAndOverrideBasicCandidateProperties((ParticipantCandidate)candidate, candidateClone, createNewFeature); poolTarget.add(candidateClone); } } else{ target.setInteractor(source.getInteractor()); } // copy features or create new ones if (!createNewFeature){ target.getFeatures().clear(); target.addAllFeatures(source.getFeatures()); } else { target.getFeatures().clear(); for (Object f : source.getFeatures()){ Feature clone = new DefaultFeature(); FeatureCloner.copyAndOverrideBasicFeaturesProperties((Feature)f, clone); target.addFeature(clone); } } } } }
package psidev.psi.mi.jami.xml.cache; import org.apache.commons.io.input.CountingInputStream; import org.codehaus.stax2.XMLInputFactory2; import psidev.psi.mi.jami.model.*; import psidev.psi.mi.jami.xml.PsiXmlVersion; import psidev.psi.mi.jami.xml.XmlEntryContext; import psidev.psi.mi.jami.xml.io.parser.JaxbUnmarshallerFactory; import psidev.psi.mi.jami.xml.io.parser.NonCloseableInputStreamWrapper; import psidev.psi.mi.jami.xml.io.parser.XmlReaderWithDefaultNamespace; import psidev.psi.mi.jami.xml.model.extension.*; import psidev.psi.mi.jami.xml.model.extension.xml300.XmlVariableParameterValue; import psidev.psi.mi.jami.xml.utils.PsiXmlUtils; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.*; import java.nio.channels.Channels; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Cache using a file and a weak map to cache the objects * * @author Marine Dumousseau (marine@ebi.ac.uk) * @version $Id$ * @since <pre>25/06/14</pre> */ public class PsiXmlFileIndexCache implements PsiXmlIdCache { private static final Logger logger = Logger.getLogger("PsiXmlFileIndexCache"); /** * Captures the identifier from a String looking like: id="1" */ private static final Pattern ID_PATTERN = Pattern.compile( "id(?:\\s*)=(?:\\s*)\"(\\d*)\"", Pattern.CANON_EQ ); private File file; private Unmarshaller unmarshaller; private RandomAccessFile randomAccessFile; private String namespaceUri; private Map<Integer, AbstractAvailability> mapOfReferencedAvailabilities; private Map<Integer, Long> experimentPositions; private Map<Integer, Long> interactorPositions; private Map<Integer, Long> interactionPositions; private Map<Integer, Long> participantPositions; private Map<Integer, Long> featurePositions; private Map<Integer, Long> variableParameterValuePositions; private Map<Integer, Long> complexPositions; private Map<Integer, Experiment> experimentWeakMap; private Map<Integer, Interactor> interactorWeakMap; private Map<Integer, Interaction> interactionWeakMap; private Map<Integer, Participant> participantWeakMap; private Map<Integer, Feature> featureWeakMap; private Map<Integer, VariableParameterValue> variableParameterValueWeakMap; private Map<Integer, Complex> complexWeakMap; private Interaction currentInteraction=null; private Experiment currentExperiment=null; public PsiXmlFileIndexCache(File file, Unmarshaller unmarshaller, PsiXmlVersion version) throws IOException { if (file == null){ throw new IllegalArgumentException("The file index cache needs the original file containing data."); } this.file = file; if (unmarshaller == null){ throw new IllegalArgumentException("The file index cache needs the unmarshaller to unmarshall partial object from file cache."); } this.unmarshaller = unmarshaller; this.randomAccessFile = new RandomAccessFile(this.file, "r"); this.mapOfReferencedAvailabilities = new HashMap<Integer, AbstractAvailability>(); this.experimentPositions = new HashMap<Integer, Long>(); this.interactorPositions = new HashMap<Integer, Long>(); this.interactionPositions = new HashMap<Integer, Long>(); this.participantPositions = new HashMap<Integer, Long>(); this.featurePositions = new HashMap<Integer, Long>(); this.variableParameterValuePositions = new HashMap<Integer, Long>(); this.complexPositions = new HashMap<Integer, Long>(); this.experimentWeakMap = new WeakHashMap<Integer, Experiment>(); this.interactorWeakMap = new WeakHashMap<Integer, Interactor>(); this.interactionWeakMap = new WeakHashMap<Integer, Interaction>(); this.participantWeakMap = new WeakHashMap<Integer, Participant>(); this.featureWeakMap = new WeakHashMap<Integer, Feature>(); this.variableParameterValueWeakMap = new WeakHashMap<Integer, VariableParameterValue>(); this.complexWeakMap = new WeakHashMap<Integer, Complex>(); switch (version){ case v2_5_4: this.namespaceUri = PsiXmlUtils.Xml254_NAMESPACE_URI; break; case v2_5_3: this.namespaceUri = PsiXmlUtils.Xml253_NAMESPACE_URI; break; case v3_0_0: this.namespaceUri = PsiXmlUtils.Xml300_NAMESPACE_URI; break; default: this.namespaceUri = PsiXmlUtils.Xml254_NAMESPACE_URI; break; } buildPositionIndex(this.file); } public PsiXmlFileIndexCache(File file, PsiXmlVersion version, InteractionCategory category) throws IOException, JAXBException { this(file, JaxbUnmarshallerFactory.getInstance().createUnmarshaller(version != null ? version : PsiXmlVersion.v2_5_4, category != null ? category : InteractionCategory.evidence), version); } @Override public void registerAvailability(int id, AbstractAvailability object) { this.mapOfReferencedAvailabilities.put(id, object); } @Override public AbstractAvailability getAvailability(int id) { return this.mapOfReferencedAvailabilities.get(id); } @Override public void registerExperiment(int id, Experiment object) { this.currentExperiment = object; this.experimentWeakMap.put(id, object); } @Override public Experiment getExperiment(int id) { if (this.experimentWeakMap.containsKey(id)){ return this.experimentWeakMap.get(id); } else if (!this.experimentPositions.containsKey(id)){ return null; } else { try { return loadFromFile(this.experimentPositions.get(id)); } catch (IOException e) { logger.log(Level.SEVERE, "cannot reload experiment "+id, e); } catch (JAXBException e) { logger.log(Level.SEVERE, "cannot reload experiment "+id, e); } catch (XMLStreamException e) { logger.log(Level.SEVERE, "cannot reload experiment "+id, e); } return null; } } @Override public void registerInteraction(int id, Interaction object) { this.currentExperiment = null; this.currentInteraction = object; this.interactionWeakMap.put(id, object); } @Override public Interaction getInteraction(int id) { if (this.interactionWeakMap.containsKey(id)){ return this.interactionWeakMap.get(id); } else if (!this.interactionPositions.containsKey(id)){ return null; } else { try { return loadFromFile(this.interactionPositions.get(id)); } catch (IOException e) { logger.log(Level.SEVERE, "cannot reload interaction "+id, e); } catch (JAXBException e) { logger.log(Level.SEVERE, "cannot reload interaction "+id, e); } catch (XMLStreamException e) { logger.log(Level.SEVERE, "cannot reload interaction "+id, e); } return null; } } @Override public void registerInteractor(int id, Interactor object) { this.interactorWeakMap.put(id, object); } @Override public Interactor getInteractor(int id) { if (this.interactorWeakMap.containsKey(id)){ return this.interactorWeakMap.get(id); } else if (!this.interactorPositions.containsKey(id)){ return null; } else { try { AbstractXmlInteractor interactor = loadFromFile(this.interactorPositions.get(id)); return XmlEntryContext.getInstance().getInteractorFactory().createInteractorFromXmlInteractorInstance(interactor); } catch (IOException e) { logger.log(Level.SEVERE, "cannot reload interactor "+id, e); } catch (JAXBException e) { logger.log(Level.SEVERE, "cannot reload interactor "+id, e); } catch (XMLStreamException e) { logger.log(Level.SEVERE, "cannot reload interactor "+id, e); } return null; } } @Override public void registerParticipant(int id, Participant object) { this.participantWeakMap.put(id, object); } @Override public Participant getParticipant(int id) { if (this.participantWeakMap.containsKey(id)){ return this.participantWeakMap.get(id); } else if (!this.participantPositions.containsKey(id)){ return null; } else { try { Interaction originalInteraction = loadFromFile(this.participantPositions.get(id)); if (originalInteraction == null){ logger.log(Level.SEVERE, "cannot reload participant "+id); } else{ for (Object p : originalInteraction.getParticipants()){ ExtendedPsiXmlParticipant participant = (ExtendedPsiXmlParticipant)p; if (participant.getId() == id){ return participant; } } logger.log(Level.SEVERE, "cannot reload participant "+id); return null; } } catch (IOException e) { logger.log(Level.SEVERE, "cannot reload participant "+id, e); } catch (JAXBException e) { logger.log(Level.SEVERE, "cannot reload participant "+id, e); } catch (XMLStreamException e) { logger.log(Level.SEVERE, "cannot reload participant "+id, e); } return null; } } @Override public void registerFeature(int id, Feature object) { this.featureWeakMap.put(id, object); } @Override public Feature getFeature(int id) { if (this.featureWeakMap.containsKey(id)){ return this.featureWeakMap.get(id); } else if (!this.featurePositions.containsKey(id)){ return null; } else { try { Interaction originalInteraction = loadFromFile(this.featurePositions.get(id)); if (originalInteraction == null){ logger.log(Level.SEVERE, "cannot reload feature "+id); } else{ for (Object p : originalInteraction.getParticipants()){ ExtendedPsiXmlParticipant participant = (ExtendedPsiXmlParticipant)p; for (Object f : participant.getFeatures()){ ExtendedPsiXmlFeature feature = (ExtendedPsiXmlFeature)f; if (feature.getId() == id){ return feature; } } } logger.log(Level.SEVERE, "cannot reload feature "+id); return null; } } catch (IOException e) { logger.log(Level.SEVERE, "cannot reload feature "+id, e); } catch (JAXBException e) { logger.log(Level.SEVERE, "cannot reload feature "+id, e); } catch (XMLStreamException e) { logger.log(Level.SEVERE, "cannot reload feature "+id, e); } return null; } } @Override public void registerComplex(int id, Complex object) { this.complexWeakMap.put(id, object); } @Override public Complex getComplex(int id) { if (this.complexWeakMap.containsKey(id)){ return this.complexWeakMap.get(id); } else if (!this.complexPositions.containsKey(id)){ return null; } else { try { Interaction originalInteraction = loadFromFile(this.complexPositions.get(id)); if (originalInteraction == null){ logger.log(Level.SEVERE, "cannot reload complex "+id); } else if (originalInteraction instanceof Complex){ return (Complex)originalInteraction; } // convert interaction evidence in a complex else if (originalInteraction instanceof ExtendedPsiXmlInteractionEvidence){ return new XmlInteractionEvidenceComplexWrapper((ExtendedPsiXmlInteractionEvidence)originalInteraction); } // wrap modelled interaction else if (originalInteraction instanceof ExtendedPsiXmlModelledInteraction){ return new XmlModelledInteractionComplexWrapper((ExtendedPsiXmlModelledInteraction)originalInteraction); } // wrap basic interaction else if (originalInteraction instanceof ExtendedPsiXmlInteraction){ return new XmlBasicInteractionComplexWrapper((ExtendedPsiXmlInteraction)originalInteraction); } else{ logger.log(Level.SEVERE, "cannot reload complex "+id); return null; } } catch (IOException e) { logger.log(Level.SEVERE, "cannot reload complex "+id, e); } catch (JAXBException e) { logger.log(Level.SEVERE, "cannot reload complex "+id, e); } catch (XMLStreamException e) { logger.log(Level.SEVERE, "cannot reload complex "+id, e); } return null; } } @Override public void registerVariableParameterValue(int id, VariableParameterValue object) { this.variableParameterValueWeakMap.put(id, object); } @Override public VariableParameterValue getVariableParameterValue(int id) { if (this.variableParameterValueWeakMap.containsKey(id)){ return this.variableParameterValueWeakMap.get(id); } else if (!this.variableParameterValuePositions.containsKey(id)){ return null; } else { try { Experiment originalExperiment = loadFromFile(this.variableParameterValuePositions.get(id)); if (originalExperiment == null){ logger.log(Level.SEVERE, "cannot reload variable parameter value "+id); } else{ for (VariableParameter p : originalExperiment.getVariableParameters()){ for (VariableParameterValue value : p.getVariableValues()){ XmlVariableParameterValue xmlValue = (XmlVariableParameterValue)value; if (xmlValue.getId() == id){ return xmlValue; } } } logger.log(Level.SEVERE, "cannot reload variable parameter value "+id); return null; } } catch (IOException e) { logger.log(Level.SEVERE, "cannot reload variable parameter value "+id, e); } catch (JAXBException e) { logger.log(Level.SEVERE, "cannot reload variable parameter value "+id, e); } catch (XMLStreamException e) { logger.log(Level.SEVERE, "cannot reload variable parameter value "+id, e); } return null; } } @Override public void clear() { this.currentExperiment = null; this.currentInteraction = null; this.mapOfReferencedAvailabilities.clear(); this.experimentWeakMap.clear(); this.interactorWeakMap.clear(); this.interactionWeakMap.clear(); this.complexWeakMap.clear(); this.participantWeakMap.clear(); this.featureWeakMap.clear(); this.variableParameterValueWeakMap.clear(); } @Override public void close() { clear(); this.experimentPositions.clear(); this.interactorPositions.clear(); this.interactionPositions.clear(); this.complexPositions.clear(); this.participantPositions.clear(); this.featurePositions.clear(); this.variableParameterValuePositions.clear(); try { this.randomAccessFile.close(); } catch (IOException e) { logger.log(Level.SEVERE, "cannot close random access file", e); } } @Override public boolean containsExperiment(int id) { return this.experimentWeakMap.containsKey(id) || this.experimentPositions.containsKey(id); } @Override public boolean containsAvailability(int id) { return this.mapOfReferencedAvailabilities.containsKey(id); } @Override public boolean containsInteraction(int id) { return this.interactionWeakMap.containsKey(id) || this.interactionPositions.containsKey(id); } @Override public boolean containsInteractor(int id) { return this.interactorWeakMap.containsKey(id) || this.interactorPositions.containsKey(id); } @Override public boolean containsParticipant(int id) { return this.participantWeakMap.containsKey(id) || this.participantPositions.containsKey(id); } @Override public boolean containsFeature(int id) { return this.featureWeakMap.containsKey(id) || this.featurePositions.containsKey(id); } @Override public boolean containsVariableParameter(int id) { return this.variableParameterValueWeakMap.containsKey(id) || this.variableParameterValuePositions.containsKey(id); } @Override public boolean containsComplex(int id) { return this.complexWeakMap.containsKey(id) || this.complexPositions.containsKey(id); } private <T extends Object> T loadFromFile(long id) throws IOException, JAXBException, XMLStreamException { InputStream in = new NonCloseableInputStreamWrapper(Channels.newInputStream(this.randomAccessFile.getChannel().position(id))); T obj = null; XMLStreamReader reader = null; try{ XMLInputFactory xmlif = XMLInputFactory2.newInstance(); reader = xmlif.createXMLStreamReader(in); //Create the filter (to add namespace) and set the xmlReader as its parent. XmlReaderWithDefaultNamespace filteredReader = new XmlReaderWithDefaultNamespace(reader, this.namespaceUri); obj = (T)this.unmarshaller.unmarshal(filteredReader); } finally { if (reader != null){ reader.close(); } } return obj; } /** * Indexes references component of the given file. that is experiments, interaction, interactor, feature and * participant so that we know where they are in the file and we can jump in the right position should we want to * extract one of them. * * @param f the file to index. * @return a PsimiXmlFileIndex that stores the mapping between object ids and their position. * @throws IOException */ public void buildPositionIndex( File f ) throws IOException { long start = System.currentTimeMillis(); long length = f.length(); logger.info( "length = " + length ); CountingInputStream fis = null; StringBuilder sb = new StringBuilder( 100 ); try{ fis = new CountingInputStream(new BufferedInputStream(new FileInputStream( f ))); long startPos = 0; char read = ' '; boolean recording = false; byte[] buf = new byte[1]; int currentId = -1; long currentExperimentPost = 0; long currentInteractionPos = 0; boolean readElements = false; while ( -1 != nextByte(fis, buf)) { read = (char)(buf[0] & 0xFF); if ( recording ) { if ( !isAlphabeticalChar( read ) ) { if ( read == '/' ) { // search for '>' and that's our position while ( -1 != nextByte(fis, buf) ) { read = (char)(buf[0] & 0xFF); if ( read == '>' ) { break; } } // it was a closing tag (<abc/> or </abc> ... problem will occur with <abc />) recording = false; } else if ( read == '!' ) { // This is the beginning of a comments. // Now fast forward until the end of the comment: '-->' recording = false; byte c1 = ' ', c2 = ' ', c3 = ' '; logger.fine("Skiping comment"); while ( -1 != nextByte(fis, buf) ) { c1 = c2; c2 = c3; c3 = buf[0]; if ( c1 == '-' && c2 == '-' && c3 == '>' ) { // found it logger.fine("End of comment"); break; } } } else { // check what start tag it is if ( "experimentDescription".equalsIgnoreCase( sb.toString() ) ) { int result = getId( fis, buf ); currentId = result; currentExperimentPost = startPos; this.experimentPositions.put(currentId, startPos); } else if ( "interactor".equalsIgnoreCase( sb.toString() ) ) { int result = getId( fis, buf ); currentId = result; this.interactorPositions.put(currentId, startPos); } else if ( "interaction".equalsIgnoreCase( sb.toString() ) ) { int result = getId( fis, buf ); currentId = result; currentInteractionPos = startPos; this.interactionPositions.put(currentId, startPos); } else if ( "abstractInteraction".equalsIgnoreCase( sb.toString() ) ) { int result = getId( fis,buf ); currentId = result; currentInteractionPos = startPos; this.interactionPositions.put(currentId, startPos); }else if ( "participant".equalsIgnoreCase( sb.toString() ) ) { int result = getId( fis, buf ); currentId = result; this.participantPositions.put(currentId, currentInteractionPos); } else if ( "feature".equalsIgnoreCase( sb.toString() ) ) { int result = getId( fis, buf ); currentId = result; currentInteractionPos = startPos; this.featurePositions.put(currentId, currentInteractionPos); } else if ( "variableValue".equalsIgnoreCase( sb.toString() ) ) { int result = getId( fis, buf ); currentId = result; currentInteractionPos = startPos; this.variableParameterValuePositions.put(currentId, currentExperimentPost); } recording = false; } } else { // add alphabetical char sb.append( new String(buf) ); } } if ( read == '<' ) { // start recording startPos = fis.getByteCount() -1; // we want the '<' included recording = true; sb.setLength(0); } } // while can read long stop = System.currentTimeMillis(); logger.info( "Time elapsed: " + ( stop - start ) + "ms" ); } finally { if (fis != null){ fis.close(); } } } private int getId( CountingInputStream r, byte[] buf) throws IOException { int id = -1; StringBuilder sb = new StringBuilder( 20 ); while ( -1 != nextByte(r, buf) ) { char read = (char)(buf[0] & 0xFF); if ( read == '>' ) { // completed the tag, extract the id Matcher matcher = ID_PATTERN.matcher( sb.toString() ); if ( matcher.matches() ) { String strId = matcher.group( 1 ); id = Integer.parseInt( strId ); } break; // stop here } else { sb.append( new String(buf) ); } } return id; } private boolean isAlphabeticalChar( char c ) { return ( ( c >= 'a' && c <= 'z' ) || ( ( c >= 'A' && c <= 'Z' ) ) ); } private static int nextByte(CountingInputStream cis, byte[] buf) throws IOException { int result = cis.read(buf); while (result != -1 && buf[0] == 0 ){ result = cis.read(buf); } return result; } }
package com.intellij.compiler.progress; import com.intellij.build.*; import com.intellij.build.events.MessageEvent; import com.intellij.build.progress.BuildProgress; import com.intellij.build.progress.BuildProgressDescriptor; import com.intellij.compiler.impl.CompilerPropertiesAction; import com.intellij.compiler.impl.ExcludeFromCompileAction; import com.intellij.compiler.impl.ExitStatus; import com.intellij.execution.ExecutionBundle; import com.intellij.execution.filters.RegexpFilter; import com.intellij.icons.AllIcons; import com.intellij.ide.IdeBundle; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.compiler.CompilerMessage; import com.intellij.openapi.compiler.CompilerMessageCategory; import com.intellij.openapi.compiler.JavaCompilerBundle; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.ex.ProgressIndicatorEx; import com.intellij.pom.Navigatable; import com.intellij.util.SmartList; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.Collections; import java.util.List; import static com.intellij.compiler.impl.CompileDriver.CLASSES_UP_TO_DATE_CHECK; import static com.intellij.execution.filters.RegexpFilter.*; import static com.intellij.openapi.util.text.StringUtil.*; import static com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile; @ApiStatus.Internal public class BuildOutputService implements BuildViewService { private static final String ANSI_RESET = "\u001B[0m"; //NON-NLS private static final String ANSI_RED = "\u001B[31m"; //NON-NLS private static final String ANSI_YELLOW = "\u001B[33m"; //NON-NLS private static final String ANSI_BOLD = "\u001b[1m"; //NON-NLS private final @NotNull Project myProject; private final @NotNull BuildProgress<BuildProgressDescriptor> myBuildProgress; private final @NotNull String myContentName; public BuildOutputService(@NotNull Project project, @NotNull String contentName) { myProject = project; myContentName = contentName; myBuildProgress = BuildViewManager.createBuildProgress(project); } @Override public void registerCloseAction(Runnable onClose) { } @Override public void onProgressChange(Object sessionId, ProgressIndicator indicator) { } @Override public void onStart(Object sessionId, long startCompilationStamp, Runnable restartWork, ProgressIndicator indicator) { List<AnAction> restartActions = getRestartActions(restartWork, indicator); List<AnAction> contextActions = getContextActions(); String title; if (myContentName.equals(JavaCompilerBundle.message("compiler.content.name.rebuild")) || myContentName.equals(JavaCompilerBundle.message("compiler.content.name.recompile")) || myContentName.equals(JavaCompilerBundle.message("compiler.content.name.make"))) { title = myProject.getName(); } else { title = capitalize(wordsToBeginFromLowerCase(myContentName)); } DefaultBuildDescriptor buildDescriptor = new DefaultBuildDescriptor(sessionId, title, notNullize(myProject.getBasePath()), startCompilationStamp) .withRestartActions(restartActions.toArray(AnAction.EMPTY_ARRAY)) .withAction(new CompilerPropertiesAction()) .withExecutionFilter(new ModuleLinkFilter(myProject)) .withExecutionFilter(new RegexpFilter(myProject, FILE_PATH_MACROS + ":" + LINE_MACROS + ":" + COLUMN_MACROS)) .withContextAction(node -> { return new ExcludeFromCompileAction(myProject) { @Override protected @Nullable VirtualFile getFile() { List<Navigatable> navigatables = node.getNavigatables(); if (navigatables.size() != 1) return null; Navigatable navigatable = navigatables.get(0); if (navigatable instanceof OpenFileDescriptor) { return ((OpenFileDescriptor)navigatable).getFile(); } else if (navigatable instanceof FileNavigatable) { OpenFileDescriptor fileDescriptor = ((FileNavigatable)navigatable).getFileDescriptor(); return fileDescriptor != null ? fileDescriptor.getFile() : null; } return null; } }; }) .withContextActions(contextActions.toArray(AnAction.EMPTY_ARRAY)); myBuildProgress.start(new BuildProgressDescriptor() { @NotNull @Override public String getTitle() { return buildDescriptor.getTitle(); } @Override public @NotNull BuildDescriptor getBuildDescriptor() { return buildDescriptor; } }); addIndicatorDelegate(indicator); } @Override public void onEnd(Object sessionId, ExitStatus exitStatus, long endBuildStamp) { String message; if (exitStatus == ExitStatus.ERRORS) { message = BuildBundle.message("build.messages.failed", wordsToBeginFromLowerCase(myContentName)); myBuildProgress.fail(endBuildStamp, message); } else if (exitStatus == ExitStatus.CANCELLED) { message = BuildBundle.message("build.messages.cancelled", wordsToBeginFromLowerCase(myContentName)); myBuildProgress.cancel(endBuildStamp, message); } else { boolean isUpToDate = exitStatus == ExitStatus.UP_TO_DATE; if (CLASSES_UP_TO_DATE_CHECK.equals(myContentName)) { if (isUpToDate) { myBuildProgress.output(JavaCompilerBundle.message("compiler.build.messages.classes.check.uptodate"), true); } else { myBuildProgress.output(JavaCompilerBundle.message("compiler.build.messages.classes.check.outdated"), true); } } message = BuildBundle.message("build.messages.finished", wordsToBeginFromLowerCase(myContentName)); myBuildProgress.finish(endBuildStamp, isUpToDate, message); } } @Override public void addMessage(Object sessionId, CompilerMessage compilerMessage) { MessageEvent.Kind kind = convertCategory(compilerMessage.getCategory()); VirtualFile virtualFile = compilerMessage.getVirtualFile(); Navigatable navigatable = compilerMessage.getNavigatable(); if (virtualFile != null) { File file = virtualToIoFile(virtualFile); FilePosition filePosition; if (navigatable instanceof OpenFileDescriptor) { OpenFileDescriptor fileDescriptor = (OpenFileDescriptor)navigatable; int column = fileDescriptor.getColumn(); int line = fileDescriptor.getLine(); filePosition = new FilePosition(file, line, column); } else { filePosition = new FilePosition(file, 0, 0); } String title = getMessageTitle(compilerMessage); myBuildProgress.fileMessage(title, compilerMessage.getMessage(), kind, filePosition); } else { if (kind == MessageEvent.Kind.ERROR || kind == MessageEvent.Kind.WARNING) { String title = getMessageTitle(compilerMessage); myBuildProgress.message(title, compilerMessage.getMessage(), kind, navigatable); } String color; if (kind == MessageEvent.Kind.ERROR) { color = ANSI_RED; } else if (kind == MessageEvent.Kind.WARNING) { color = ANSI_YELLOW; } else { color = ANSI_BOLD; } myBuildProgress.output(color + compilerMessage.getMessage() + ANSI_RESET + '\n', kind != MessageEvent.Kind.ERROR); } } @NotNull private List<AnAction> getRestartActions(Runnable restartWork, ProgressIndicator indicator) { List<AnAction> restartActions = new SmartList<>(); if (restartWork != null) { AnAction restartAction = new DumbAwareAction( ExecutionBundle.messagePointer("rerun.configuration.action.name", escapeMnemonics(myContentName)), Presentation.NULL_STRING, AllIcons.Actions.Compile) { @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabled(!indicator.isRunning()); } @Override public void actionPerformed(@NotNull AnActionEvent e) { restartWork.run(); } }; restartActions.add(restartAction); } AnAction stopAction = new DumbAwareAction(IdeBundle.messagePointer("action.stop"), AllIcons.Actions.Suspend) { @Override public void actionPerformed(@NotNull AnActionEvent e) { indicator.cancel(); } @Override public void update(@NotNull AnActionEvent event) { event.getPresentation().setEnabled(indicator.isRunning()); } }; restartActions.add(stopAction); return restartActions; } private void addIndicatorDelegate(ProgressIndicator indicator) { if (!(indicator instanceof ProgressIndicatorEx)) { return; } ((ProgressIndicatorEx)indicator).addStateDelegate(new CompilerMessagesService.DummyProgressIndicator() { private String lastMessage = null; @Override public void setText(@Nls(capitalization = Nls.Capitalization.Sentence) String text) { if (isEmptyOrSpaces(text) || text.equals(lastMessage)) return; lastMessage = text; myBuildProgress.output(text + '\n', true); } @Override public void setFraction(double fraction) { myBuildProgress.progress(lastMessage, 100, (long)(fraction * 100), "%"); } }); } @NotNull private static List<AnAction> getContextActions() { List<AnAction> contextActions = new SmartList<>(); ActionGroup compilerErrorsViewPopupGroup = (ActionGroup)ActionManager.getInstance().getAction(IdeActions.GROUP_COMPILER_ERROR_VIEW_POPUP); if (compilerErrorsViewPopupGroup != null) { Collections.addAll(contextActions, compilerErrorsViewPopupGroup.getChildren(null)); } return contextActions; } private static String getMessageTitle(@NotNull CompilerMessage compilerMessage) { String message = null; String[] messages = splitByLines(compilerMessage.getMessage()); if (messages.length > 1) { final String line0 = messages[0]; final String line1 = messages[1]; final int colonIndex = line1.indexOf(':'); if (colonIndex > 0) { String part1 = line1.substring(0, colonIndex).trim(); // extract symbol information from the compiler message of the following template: // java: cannot find symbol // symbol: class AClass // location: class AnotherClass if ("symbol".equals(part1)) { String symbol = line1.substring(colonIndex + 1).trim(); message = line0 + " " + symbol; } } } if (message == null) { message = messages[0]; } return trimEnd(trimStart(message, "java: "), '.'); //NON-NLS } @NotNull private static MessageEvent.Kind convertCategory(@NotNull CompilerMessageCategory category) { switch (category) { case ERROR: return MessageEvent.Kind.ERROR; case WARNING: return MessageEvent.Kind.WARNING; case INFORMATION: return MessageEvent.Kind.INFO; case STATISTICS: return MessageEvent.Kind.STATISTICS; default: return MessageEvent.Kind.SIMPLE; } } }
package net.bull.javamelody; // NOPMD import static net.bull.javamelody.HttpParameters.CONNECTIONS_PART; import static net.bull.javamelody.HttpParameters.CONTENT_DISPOSITION; import static net.bull.javamelody.HttpParameters.COUNTER_PARAMETER; import static net.bull.javamelody.HttpParameters.COUNTER_SUMMARY_PER_CLASS_PART; import static net.bull.javamelody.HttpParameters.CURRENT_REQUESTS_PART; import static net.bull.javamelody.HttpParameters.DATABASE_PART; import static net.bull.javamelody.HttpParameters.DEFAULT_WITH_CURRENT_REQUESTS_PART; import static net.bull.javamelody.HttpParameters.EXPLAIN_PLAN_PART; import static net.bull.javamelody.HttpParameters.FORMAT_PARAMETER; import static net.bull.javamelody.HttpParameters.GRAPH_PARAMETER; import static net.bull.javamelody.HttpParameters.GRAPH_PART; import static net.bull.javamelody.HttpParameters.HEAP_HISTO_PART; import static net.bull.javamelody.HttpParameters.HEIGHT_PARAMETER; import static net.bull.javamelody.HttpParameters.JNDI_PART; import static net.bull.javamelody.HttpParameters.JROBINS_PART; import static net.bull.javamelody.HttpParameters.MBEANS_PART; import static net.bull.javamelody.HttpParameters.OTHER_JROBINS_PART; import static net.bull.javamelody.HttpParameters.PART_PARAMETER; import static net.bull.javamelody.HttpParameters.PATH_PARAMETER; import static net.bull.javamelody.HttpParameters.PERIOD_PARAMETER; import static net.bull.javamelody.HttpParameters.PROCESSES_PART; import static net.bull.javamelody.HttpParameters.REQUEST_PARAMETER; import static net.bull.javamelody.HttpParameters.SESSIONS_PART; import static net.bull.javamelody.HttpParameters.SESSION_ID_PARAMETER; import static net.bull.javamelody.HttpParameters.THREADS_PART; import static net.bull.javamelody.HttpParameters.WIDTH_PARAMETER; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; class SerializableController { private final Collector collector; SerializableController(Collector collector) { super(); assert collector != null; this.collector = collector; } void doSerializable(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Serializable serializable) throws IOException { final String format = httpRequest.getParameter(FORMAT_PARAMETER); final TransportFormat transportFormat = TransportFormat.valueOfIgnoreCase(format); httpResponse.setContentType(transportFormat.getMimeType()); final String fileName = "JavaMelody_" + getApplication().replace(' ', '_').replace("/", "") + '_' + I18N.getCurrentDate().replace('/', '_') + '.' + transportFormat.getCode(); final String contentDisposition = "inline;filename=" + fileName; httpResponse.addHeader(CONTENT_DISPOSITION, contentDisposition.replace('\n', '_').replace('\r', '_')); transportFormat.writeSerializableTo(serializable, httpResponse.getOutputStream()); } Serializable createSerializable(HttpServletRequest httpRequest, List<JavaInformations> javaInformationsList, String messageForReport) throws Exception { // NOPMD final Serializable resultForSystemActions = createSerializableForSystemActions(httpRequest); if (resultForSystemActions != null) { return resultForSystemActions; } return createOtherSerializable(httpRequest, javaInformationsList, messageForReport); } @SuppressWarnings("unchecked") private Serializable createOtherSerializable(HttpServletRequest httpRequest, List<JavaInformations> javaInformationsList, String messageForReport) throws IOException { final Range range = getRangeForSerializable(httpRequest); final String part = httpRequest.getParameter(PART_PARAMETER); if (JROBINS_PART.equalsIgnoreCase(part)) { // pour UI Swing final int width = Integer.parseInt(httpRequest.getParameter(WIDTH_PARAMETER)); final int height = Integer.parseInt(httpRequest.getParameter(HEIGHT_PARAMETER)); final String graphName = httpRequest.getParameter(GRAPH_PARAMETER); return getJRobinsImages(range, width, height, graphName); } else if (OTHER_JROBINS_PART.equalsIgnoreCase(part)) { // pour UI Swing final int width = Integer.parseInt(httpRequest.getParameter(WIDTH_PARAMETER)); final int height = Integer.parseInt(httpRequest.getParameter(HEIGHT_PARAMETER)); final Collection<JRobin> jrobins = collector.getOtherJRobins(); return (Serializable) convertJRobinsToImages(jrobins, range, width, height); } else if (THREADS_PART.equalsIgnoreCase(part)) { return new ArrayList<ThreadInformations>(javaInformationsList.get(0) .getThreadInformationsList()); } else if (COUNTER_SUMMARY_PER_CLASS_PART.equalsIgnoreCase(part)) { final String counterName = httpRequest.getParameter(COUNTER_PARAMETER); final String requestId = httpRequest.getParameter(GRAPH_PARAMETER); final Counter counter = collector.getRangeCounter(range, counterName).clone(); final List<CounterRequest> requestList = new CounterRequestAggregation(counter) .getRequestsAggregatedOrFilteredByClassName(requestId); return new ArrayList<CounterRequest>(requestList); } else if (GRAPH_PART.equalsIgnoreCase(part)) { final String requestId = httpRequest.getParameter(GRAPH_PARAMETER); return getCounterRequestById(requestId, range); } else if (CURRENT_REQUESTS_PART.equalsIgnoreCase(part)) { final Map<JavaInformations, List<CounterRequestContext>> result = new HashMap<JavaInformations, List<CounterRequestContext>>(); result.put(javaInformationsList.get(0), getCurrentRequests()); return (Serializable) result; } else if (DEFAULT_WITH_CURRENT_REQUESTS_PART.equalsIgnoreCase(part)) { final List<Serializable> result = new ArrayList<Serializable>(); result.addAll((List<Serializable>) createDefaultSerializable(javaInformationsList, range, messageForReport)); result.addAll(getCurrentRequests()); return (Serializable) result; } else if (EXPLAIN_PLAN_PART.equalsIgnoreCase(part)) { // pour UI Swing, final String sqlRequest = httpRequest.getHeader(REQUEST_PARAMETER); return explainPlanFor(sqlRequest); } return createDefaultSerializable(javaInformationsList, range, messageForReport); } private Serializable getCounterRequestById(String requestId, Range range) throws IOException { for (final Counter counter : collector.getCounters()) { if (counter.isRequestIdFromThisCounter(requestId)) { final Counter rangeCounter = collector.getRangeCounter(range, counter.getName()) .clone(); for (final CounterRequest request : rangeCounter.getRequests()) { if (requestId.equals(request.getId())) { return request; } } } } return null; } private Serializable getJRobinsImages(Range range, int width, int height, String graphName) throws IOException { if (graphName != null) { final JRobin jrobin = collector.getJRobin(graphName); if (jrobin != null) { return jrobin.graph(range, width, height); } return null; } final Collection<JRobin> jrobins = collector.getCounterJRobins(); return (Serializable) convertJRobinsToImages(jrobins, range, width, height); } private Serializable explainPlanFor(String sqlRequest) { assert sqlRequest != null; try { return DatabaseInformations.explainPlanFor(sqlRequest); } catch (final Exception ex) { return ex.toString(); } } private List<CounterRequestContext> getCurrentRequests() { final List<Counter> counters = collector.getCounters(); final List<Counter> newCounters = new ArrayList<Counter>(); for (final Counter counter : counters) { final Counter cloneLight = new Counter(counter.getName(), counter.getStorageName(), counter.getIconName(), counter.getChildCounterName()); newCounters.add(cloneLight); } return collector.getRootCurrentContexts(newCounters); } private Map<String, byte[]> convertJRobinsToImages(Collection<JRobin> jrobins, Range range, int width, int height) throws IOException { final Map<String, byte[]> images = new LinkedHashMap<String, byte[]>(jrobins.size()); for (final JRobin jrobin : jrobins) { if (collector.isJRobinDisplayed(jrobin)) { final byte[] image = jrobin.graph(range, width, height); images.put(jrobin.getName(), image); } } return images; } private Serializable createSerializableForSystemActions(HttpServletRequest httpRequest) throws Exception { // NOPMD final String part = httpRequest.getParameter(PART_PARAMETER); if (HEAP_HISTO_PART.equalsIgnoreCase(part)) { Action.checkSystemActionsEnabled(); return VirtualMachine.createHeapHistogram(); } else if (SESSIONS_PART.equalsIgnoreCase(part)) { Action.checkSystemActionsEnabled(); final String sessionId = httpRequest.getParameter(SESSION_ID_PARAMETER); if (sessionId == null) { return new ArrayList<SessionInformations>( SessionListener.getAllSessionsInformations()); } return SessionListener.getSessionInformationsBySessionId(sessionId); } else if (PROCESSES_PART.equalsIgnoreCase(part)) { Action.checkSystemActionsEnabled(); return new ArrayList<ProcessInformations>( ProcessInformations.buildProcessInformations()); } else if (JNDI_PART.equalsIgnoreCase(part)) { Action.checkSystemActionsEnabled(); final String path = httpRequest.getParameter(PATH_PARAMETER); return new ArrayList<JndiBinding>(JndiBinding.listBindings(path)); } else if (MBEANS_PART.equalsIgnoreCase(part)) { Action.checkSystemActionsEnabled(); return new ArrayList<MBeanNode>(MBeans.getAllMBeanNodes()); } else if (DATABASE_PART.equalsIgnoreCase(part)) { Action.checkSystemActionsEnabled(); final int requestIndex = DatabaseInformations.parseRequestIndex(httpRequest .getParameter(REQUEST_PARAMETER)); return new DatabaseInformations(requestIndex); } else if (CONNECTIONS_PART.equalsIgnoreCase(part)) { Action.checkSystemActionsEnabled(); return new ArrayList<ConnectionInformations>( JdbcWrapper.getConnectionInformationsList()); } return null; } Serializable createDefaultSerializable(List<JavaInformations> javaInformationsList, Range range, String messageForReport) throws IOException { final List<Counter> counters = collector.getRangeCounters(range); final List<Serializable> serialized = new ArrayList<Serializable>(counters.size() + javaInformationsList.size()); for (final Counter counter : counters) { serialized.add(counter.clone()); } serialized.addAll(javaInformationsList); if (messageForReport != null) { serialized.add(messageForReport); } return (Serializable) serialized; } Range getRangeForSerializable(HttpServletRequest httpRequest) { final Range range; if (httpRequest.getParameter(PERIOD_PARAMETER) == null) { range = Period.TOUT.getRange(); } else { range = Range.parse(httpRequest.getParameter(PERIOD_PARAMETER)); } return range; } private String getApplication() { return collector.getApplication(); } }
package org.jbehave.mojo; import static java.util.Arrays.asList; import java.io.File; import java.util.List; import java.util.Properties; import org.apache.maven.plugin.AbstractMojo; import org.jbehave.core.InjectableEmbedder; import org.jbehave.core.embedder.Embedder; import org.jbehave.core.embedder.EmbedderClassLoader; import org.jbehave.core.embedder.EmbedderControls; import org.jbehave.core.embedder.EmbedderMonitor; import org.jbehave.core.embedder.MetaFilter; import org.jbehave.core.embedder.UnmodifiableEmbedderControls; import org.jbehave.core.failures.BatchFailures; import org.jbehave.core.io.StoryFinder; import org.jbehave.core.junit.AnnotatedEmbedderRunner; import org.jbehave.core.model.Meta; import org.jbehave.core.model.StoryMaps; import org.jbehave.core.reporters.ReportsCount; /** * Abstract mojo that holds all the configuration parameters to specify and load * stories. * * @requiresDependencyResolution */ public abstract class AbstractEmbedderMojo extends AbstractMojo { static final String TEST_SCOPE = "test"; /** * @parameter expression="${project.build.sourceDirectory}" * @required */ String sourceDirectory; /** * @parameter expression="${project.build.testSourceDirectory}" * @required */ String testSourceDirectory; /** * The scope of the mojo classpath, either "compile" or "test" * * @parameter default-value="compile" */ String scope; /** * Include filters, relative to the root source directory determined by the * scope * * @parameter */ List<String> includes; /** * Exclude filters, relative to the root source directory determined by the * scope * * @parameter */ List<String> excludes; /** * Compile classpath. * * @parameter expression="${project.compileClasspathElements}" * @required * @readonly */ List<String> compileClasspathElements; /** * Test classpath. * * @parameter expression="${project.testClasspathElements}" * @required * @readonly */ List<String> testClasspathElements; /** * The boolean flag to skip stories * * @parameter default-value="false" */ boolean skip = false; /** * The boolean flag to run in batch mode * * @parameter default-value="false" */ boolean batch = false; /** * The boolean flag to ignore failure in stories * * @parameter default-value="false" */ boolean ignoreFailureInStories = false; /** * The boolean flag to ignore failure in view * * @parameter default-value="false" */ boolean ignoreFailureInView = false; /** * The boolean flag to generate view after stories are run * * @parameter default-value="true" */ boolean generateViewAfterStories = true; /** * The embedder class * * @parameter default-value="org.jbehave.core.embedder.Embedder" */ String embedderClass = Embedder.class.getName(); /** * The class that is injected with the embedder * * @parameter */ String injectableEmbedderClass; /** * The annotated embedder runner class * * @parameter default-value="org.jbehave.core.junit.AnnotatedEmbedderRunner" */ protected String annotatedEmbedderRunnerClass = AnnotatedEmbedderRunner.class.getName(); /** * Used to find story paths and class names * * @parameter */ String storyFinderClass = StoryFinder.class.getName(); /** * The meta filter * * @parameter */ List<String> metaFilters = asList(); /** * The system properties * * @parameter */ Properties systemProperties = new Properties(); /** * The class loader */ private EmbedderClassLoader classLoader; /** * Determines if the scope of the mojo classpath is "test" * * @return A boolean <code>true</code> if test scoped */ boolean isTestScope() { return TEST_SCOPE.equals(scope); } String searchDirectory() { if (isTestScope()) { return testSourceDirectory; } return sourceDirectory; } /** * Returns the EmbedderClassLoader with the classpath element of the * selected scope. * * @return An EmbedderClassLoader */ protected EmbedderClassLoader classLoader() { if ( classLoader == null ){ classLoader = new EmbedderClassLoader(classpathElements()); } return classLoader; } List<String> classpathElements() { List<String> classpathElements = compileClasspathElements; if (isTestScope()) { classpathElements = testClasspathElements; } return classpathElements; } /** * Finds story paths, using the {@link #newStoryFinder()}, in the * {@link #searchDirectory()} given specified {@link #includes} and * {@link #excludes}. * * @return A List of story paths found */ protected List<String> storyPaths() { getLog().debug("Searching for story paths including " + includes + " and excluding " + excludes); List<String> storyPaths = newStoryFinder().findPaths(searchDirectory(), includes, excludes); getLog().info("Found story paths: " + storyPaths); return storyPaths; } /** * Finds class names, using the {@link #newStoryFinder()}, in the * {@link #searchDirectory()} given specified {@link #includes} and * {@link #excludes}. * * @return A List of class names found */ protected List<String> classNames() { getLog().debug("Searching for class names including " + includes + " and excluding " + excludes); List<String> classNames = newStoryFinder().findClassNames(searchDirectory(), includes, excludes); getLog().info("Found class names: " + classNames); return classNames; } /** * Creates an instance of StoryFinder, using the {@link #storyFinderClass} * * @return A StoryFinder */ protected StoryFinder newStoryFinder() { return classLoader().newInstance(StoryFinder.class, storyFinderClass); } /** * Creates an instance of Embedder, either using * {@link #injectableEmbedderClass} (if set) or defaulting to * {@link #embedderClass}. * * @return An Embedder */ protected Embedder newEmbedder() { Embedder embedder = null; EmbedderClassLoader classLoader = classLoader(); if (injectableEmbedderClass != null) { embedder = classLoader.newInstance(InjectableEmbedder.class, injectableEmbedderClass).injectedEmbedder(); } else { embedder = classLoader.newInstance(Embedder.class, embedderClass); } embedder.useClassLoader(classLoader); embedder.useSystemProperties(systemProperties); EmbedderMonitor embedderMonitor = embedderMonitor(); embedder.useEmbedderMonitor(embedderMonitor); if ( !metaFilters.isEmpty() ) { embedder.useMetaFilters(metaFilters); } embedder.useEmbedderControls(embedderControls()); return embedder; } protected EmbedderMonitor embedderMonitor() { return new MavenEmbedderMonitor(); } protected EmbedderControls embedderControls() { return new UnmodifiableEmbedderControls(new EmbedderControls().doBatch(batch).doSkip(skip) .doGenerateViewAfterStories(generateViewAfterStories).doIgnoreFailureInStories(ignoreFailureInStories) .doIgnoreFailureInView(ignoreFailureInView)); } protected class MavenEmbedderMonitor implements EmbedderMonitor { public void batchFailed(BatchFailures failures) { getLog().warn("Failed to run batch " + failures); } public void embeddableFailed(String name, Throwable cause) { getLog().warn("Failed to run embeddable " + name, cause); } public void embeddablesSkipped(List<String> classNames) { getLog().info("Skipped embeddables " + classNames); } public void metaNotAllowed(Meta meta, MetaFilter filter) { getLog().info(meta + " not allowed by filter '" + filter.asString() + "'"); } public void runningEmbeddable(String name) { getLog().info("Running embeddable " + name); } public void runningStory(String path) { getLog().info("Running story " + path); } public void storiesSkipped(List<String> storyPaths) { getLog().info("Skipped stories " + storyPaths); } public void storyFailed(String path, Throwable cause) { getLog().warn("Failed to run story " + path, cause); } public void annotatedInstanceNotOfType(Object annotatedInstance, Class<?> type) { getLog().warn("Annotated instance " + annotatedInstance + " not of type " + type); } public void generatingReportsView(File outputDirectory, List<String> formats, Properties viewProperties) { getLog().info( "Generating reports view to '" + outputDirectory + "' using formats '" + formats + "'" + " and view properties '" + viewProperties + "'"); } public void reportsViewGenerationFailed(File outputDirectory, List<String> formats, Properties viewProperties, Throwable cause) { String message = "Failed to generate reports view to '" + outputDirectory + "' using formats '" + formats + "'" + " and view properties '" + viewProperties + "'"; getLog().warn(message, cause); } public void reportsViewGenerated(ReportsCount count) { getLog().info("Reports view generated with " + count.getStories() + " stories containing " + count.getScenarios() + " scenarios (of which " + count.getScenariosFailed() + " failed)"); if (count.getStoriesNotAllowed() > 0 || count.getScenariosNotAllowed() > 0) { getLog().info("Meta filters did not allow " + count.getStoriesNotAllowed() + " stories and " + count.getScenariosNotAllowed() + " scenarios"); } } public void reportsViewNotGenerated() { getLog().info("Reports view not generated"); } public void mappingStory(String storyPath, List<String> metaFilters) { getLog().info("Mapping story "+storyPath+" with meta filters "+metaFilters); } public void generatingMapsView(File outputDirectory, StoryMaps storyMaps, Properties viewProperties) { getLog().info("Generating maps view to '" + outputDirectory + "' using story maps '" + storyMaps + "'" + " and view properties '" + viewProperties + "'"); } public void mapsViewGenerationFailed(File outputDirectory, StoryMaps storyMaps, Properties viewProperties, Throwable cause) { getLog().info("Generating maps view to '" + outputDirectory + "' using story maps '" + storyMaps + "'" + " and view properties '" + viewProperties + "'"); } public void processingSystemProperties(Properties properties) { getLog().info("Processing system properties " + properties); } public void systemPropertySet(String name, String value) { getLog().info("System property '" + name + "' set to '"+value+"'"); } @Override public String toString() { return this.getClass().getSimpleName(); } } }
package org.jlib.core.traverser; import org.jlib.core.observer.ItemObserver; import org.jlib.core.observer.ItemObserverException; /** * {@link RemoveTraverser} allowing its remove operation to be attended by * {@link ItemObserver} instances. * * @param <Item> * type of the traversed items * * @author Igor Akkerman */ public interface ObservedReplaceTraverser<Item> extends ReplaceTraverser<Item> { public void replace(Item newItem, @SuppressWarnings({ "unchecked", /* "varargs" */}) ItemObserver<Item>... removeObservers) throws NoItemToRemoveException, IllegalTraversibleStateException, ItemObserverException; }
package com.Acrobot.ChestShop; import org.bukkit.Bukkit; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.UUID; import java.util.logging.Level; public class Metrics { /** * The current revision number */ private final static int REVISION = 5; /** * The base url of the metrics domain */ private static final String BASE_URL = "http://mcstats.org"; /** * The url used to report a server's status */ private static final String REPORT_URL = "/report/%s"; /** * The file where guid and opt out is stored in */ private static final String CONFIG_FILE = "plugins/PluginMetrics/config.yml"; /** * Interval of time to ping (in minutes) */ private final static int PING_INTERVAL = 10; /** * The plugin this metrics submits for */ private final Plugin plugin; /** * The plugin configuration file */ private final YamlConfiguration configuration; /** * The plugin configuration file */ private final File configurationFile; /** * Unique server id */ private final String guid; /** * Lock for synchronization */ private final Object optOutLock = new Object(); /** * Id of the scheduled task */ private volatile int taskId = -1; public Metrics(Plugin plugin) throws IOException { if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null"); } this.plugin = plugin; // load the config configurationFile = new File(CONFIG_FILE); configuration = YamlConfiguration.loadConfiguration(configurationFile); // add some defaults configuration.addDefault("opt-out", false); configuration.addDefault("guid", UUID.randomUUID().toString()); // Do we need to create the file? if (configuration.get("guid", null) == null) { configuration.options().header("http://mcstats.org").copyDefaults(true); configuration.save(configurationFile); } // Load the guid then guid = configuration.getString("guid"); } /** * Start measuring statistics. This will immediately create an async repeating task as the plugin and send * the initial data to the metrics backend, and then after that it will post in increments of * PING_INTERVAL * 1200 ticks. * * @return True if statistics measuring is running, otherwise false. */ public boolean start() { synchronized (optOutLock) { // Did we opt out? if (isOptOut()) { return false; } // Is metrics already running? if (taskId >= 0) { return true; } // Begin hitting the server with glorious data taskId = plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() { private boolean firstPost = true; public void run() { try { // This has to be synchronized or it can collide with the disable method. synchronized (optOutLock) { // Disable Task, if it is running and the server owner decided to opt-out if (isOptOut() && taskId > 0) { plugin.getServer().getScheduler().cancelTask(taskId); taskId = -1; } } // We use the inverse of firstPost because if it is the first time we are posting, // it is not a interval ping, so it evaluates to FALSE // Each time thereafter it will evaluate to TRUE, i.e PING! postPlugin(!firstPost); // After the first post we set firstPost to false // Each post thereafter will be a ping firstPost = false; } catch (IOException e) { Bukkit.getLogger().log(Level.INFO, "[Metrics] {0}", e.getMessage()); } } }, 0, PING_INTERVAL * 1200); return true; } } /** * Has the server owner denied plugin metrics? * * @return */ public boolean isOptOut() { synchronized(optOutLock) { try { // Reload the metrics file configuration.load(CONFIG_FILE); } catch (IOException ex) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); return true; } catch (InvalidConfigurationException ex) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); return true; } return configuration.getBoolean("opt-out", false); } } /** * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. * * @throws IOException */ public void enable() throws IOException { // This has to be synchronized or it can collide with the check in the task. synchronized (optOutLock) { // Check if the server owner has already set opt-out, if not, set it. if (isOptOut()) { configuration.set("opt-out", false); configuration.save(configurationFile); } // Enable Task, if it is not running if (taskId < 0) { start(); } } } /** * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. * * @throws IOException */ public void disable() throws IOException { // This has to be synchronized or it can collide with the check in the task. synchronized (optOutLock) { // Check if the server owner has already set opt-out, if not, set it. if (!isOptOut()) { configuration.set("opt-out", true); configuration.save(configurationFile); } // Disable Task, if it is running if (taskId > 0) { this.plugin.getServer().getScheduler().cancelTask(taskId); taskId = -1; } } } /** * Generic method that posts a plugin to the metrics website */ private void postPlugin(boolean isPing) throws IOException { // The plugin's description file containg all of the plugin data such as name, version, author, etc final PluginDescriptionFile description = plugin.getDescription(); // Construct the post data final StringBuilder data = new StringBuilder(100); data.append(encode("guid")).append('=').append(encode(guid)); encodeDataPair(data, "version", description.getVersion()); encodeDataPair(data, "server", Bukkit.getVersion()); encodeDataPair(data, "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length)); encodeDataPair(data, "revision", String.valueOf(REVISION)); // If we're pinging, append it if (isPing) { encodeDataPair(data, "ping", "true"); } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(plugin.getDescription().getName()))); // Connect to the website URLConnection connection; // Mineshafter creates a socks proxy, so we can safely bypass it // It does not reroute POST requests so we need to go around it if (isMineshafterPresent()) { connection = url.openConnection(Proxy.NO_PROXY); } else { connection = url.openConnection(); } connection.setDoOutput(true); // Write the data final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data.toString()); writer.flush(); // Now read the response final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); final String response = reader.readLine(); // close resources writer.close(); reader.close(); if (response == null || response.startsWith("ERR")) { throw new IOException(response); //Throw the exception } //if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right } /** * Check if mineshafter is present. If it is, we need to bypass it to send POST requests * * @return */ private static boolean isMineshafterPresent() { try { Class.forName("mineshafter.MineServer"); return true; } catch (Exception e) { return false; } } /** * <p>Encode a key/value data pair to be used in a HTTP post request. This INCLUDES a & so the first * key/value pair MUST be included manually, e.g:</p> * <code> * StringBuffer data = new StringBuffer(); * data.append(encode("guid")).append('=').append(encode(guid)); * encodeDataPair(data, "version", description.getVersion()); * </code> * * @param buffer * @param key * @param value * @return */ private static void encodeDataPair(final StringBuilder buffer, final String key, final String value) throws UnsupportedEncodingException { buffer.append('&').append(encode(key)).append('=').append(encode(value)); } /** * Encode text as UTF-8 * * @param text * @return */ private static String encode(String text) throws UnsupportedEncodingException { return URLEncoder.encode(text, "UTF-8"); } }
package com.cinnamon.gfx; import com.cinnamon.object.GObject; import com.cinnamon.system.ComponentFactory; import com.cinnamon.system.Game; import com.cinnamon.system.OnOrphanChangedListener; import com.cinnamon.utils.Comparison; import com.cinnamon.utils.Sort; /** * <p> * ImageFactory is responsible for not only producing {@link ImageComponent}s to provide a visual representation for * {@link GObject}s, but also supplying the {@link Canvas} with drawing information. * </p> */ public abstract class ImageFactory extends ComponentFactory<ImageComponent, ShaderFactory> { // Listener for ImageComponent visibility changes private final OnDrawVisibilityChangedListener mVisibilityListener = new VisibilitySentry(); // Listener for drawing order needing sort private final OnDrawOrderChangeListener mDrawOrderListener = new DrawOrderSentry(); // Listener for orphan status - implies visibility change private final OnOrphanChangedListener mOrphanVisibilityListener = new OrphanChangedVisibilitySentry(); // Listener for pending drawing private final OnFrameEndListener mFrameEndListener; // Sorting alg for sorting draw order before drawing private final Sort<ImageComponent> mDrawSorter; // Order of drawing ImageComponents private ImageComponent[] mDrawOrder; // Number of visible ImageComponents private int mVisibleCount; // Growth rate of draw order array private float mDrawGrowth; // Whether or not the draw order array needs to be sorted private boolean mDrawChanged = false; /** * <p>Constructor for an ImageFactory.</p> * * @param factory {@link ShaderFactory}. * @param sort {@link Sort} used for arranging the draw order. * @param load initial capacity. * @param growth normalized capacity growth. */ protected ImageFactory(ShaderFactory factory, Sort<ImageComponent> sort, int load, float growth) { super(factory, load, growth); mDrawSorter = sort; mDrawOrder = new ImageComponent[load]; mDrawGrowth = growth; mFrameEndListener = new OnFrameEndListener(); // Wrap user provided compare with outer layer pushing null and orphaned components to the arr's right final Comparison<ImageComponent> cmp = new OrphanFilter(mDrawSorter.getComparison()); mDrawSorter.setComparison(cmp); } @Override protected final ImageComponent createIdentifiable() { return new ImageComponent(); } /** * {@inheritDoc} * * <p>Overriding classes must call super for {@link ImageComponent}s to be properly setup.</p> * * @param object ImageComponent. */ @Override protected void onRequisition(ImageComponent object) { // Expand drawing arr if constrained if (mVisibleCount >= mDrawOrder.length) { final int newCap = (int) (mDrawOrder.length * (1f + mDrawGrowth)); increaseDrawCapacity(newCap); } // Attach listener for orphan status changes object.setOnOrphanChangedListener(mOrphanVisibilityListener); // Attach listener for changes to visibility such as transparency or toggles object.setOnVisibilityChangeListener(mVisibilityListener); // Attach listener for changes to the z position object.setOnDrawOrderChangeListener(mDrawOrderListener); // Add new component to be sorted for drawing mDrawOrder[mVisibleCount] = object; notifyDrawOrderChanged(); } /** * <p>Expands the draw order array to a new capacity.</p> * * @param capacity new capacity. */ private void increaseDrawCapacity(int capacity) { final ImageComponent[] larger = new ImageComponent[capacity]; System.arraycopy(mDrawOrder, 0, larger, 0, mVisibleCount); mDrawOrder = larger; } /** * <p>Gets an {@link ImageComponent} of a certain distance away from the front-most ImageComponent on the screen. * The given index is the n-th ImageComponent from the front.</p> * * @param index n-th from the front. * @return ImageComponent. */ public final ImageComponent getAtDistance(int index) { return mDrawOrder[index]; } /** * <p>Notifies the ImageFactory that an {@link ImageComponent} has changed such that the drawing order is * affected.</p> */ public final void notifyDrawOrderChanged() { mDrawChanged = true; } /** * {@inheritDoc} * * <p>Overriding classes must call super for {@link ImageComponent}s to be properly drawn.</p> * * @param object ImageComponent. */ @Override protected void onRemove(ImageComponent object) { notifyDrawOrderChanged(); } /** * <p>Gets the number of visible {@link ImageComponent}s. This is the number of ImageComponents to be drawn.</p> * * @return number of visible ImageComponents. */ public final int getVisibleCount() { return mVisibleCount; } /** * <p>Gets an {@link OnFrameEndListener} to be be called whenever drawing data is about to be sent to the * {@link Canvas}.</p> * * @return OnFrameEndListener. */ public final OnFrameEndListener newOnFrameEndListener() { return mFrameEndListener; } /** * <p> * Listener to be called by {@link Game} at the end of a frame but before the drawing data is requested to be * sent for rendering. This is where the drawing order may be resorted, should * {@link #notifyDrawOrderChanged()} have been called at any time during the frame. * </p> */ public final class OnFrameEndListener { public void onFrameEnd() { final ImageFactory factory = ImageFactory.this; if (factory.mDrawChanged) { factory.mDrawSorter.sort(factory.mDrawOrder); factory.mDrawChanged = false; } } } /** * <p> * This class is to be set on each {@link ImageComponent} produced by the {@link ImageFactory} in order to * notify the factory of transparency or toggle changes and the need to sort the drawing order. * </p> */ private class VisibilitySentry implements OnDrawVisibilityChangedListener { @Override public void onChange(boolean visible) { // Update visible count based off of current visibility mVisibleCount = (visible) ? (mVisibleCount + 1) : (mVisibleCount - 1); // Notify ImageFactory drawing order needs resort ImageFactory.this.notifyDrawOrderChanged(); } } /** * <p> * This class is to be set on each {@link ImageComponent} produced by the {@link ImageFactory} in order to * notify the factory of changes to the z position and the need to sort the drawing order. * </p> */ private class DrawOrderSentry implements OnDrawOrderChangeListener { @Override public void onChange() { ImageFactory.this.notifyDrawOrderChanged(); } } /** * <p> * Orphan status listener for {@link ImageComponent}s. Disables ImageComponent's drawing and notifies the * factory of a change in drawing order. * </p> */ private class OrphanChangedVisibilitySentry implements OnOrphanChangedListener { @Override public void onOrphanChanged(int id, boolean isOrphan) { // Update visible count based off of current visibility mVisibleCount = (isOrphan) ? (mVisibleCount - 1) : (mVisibleCount + 1); // Notify ImageFactory drawing order needs resort notifyDrawOrderChanged(); } } /** * <p> * Wraps the {@link Comparison} used to order drawing data and adds the {@link Component}'s orphan status as * a factor in the sorting. * </p> */ private class OrphanFilter implements Comparison<ImageComponent> { // Original drawing order decider private final Comparison<ImageComponent> mUserCmp; /** * <p>Constructs an OrphanFilter.</p> * * @param comparison {@link Comparison} submitted to order drawing data. */ OrphanFilter(Comparison<ImageComponent> comparison) { mUserCmp = comparison; } @Override public int compare(ImageComponent obj0, ImageComponent obj1) { // Null ImageComponents should be on the arr's right side final boolean null0 = obj0 == null; final boolean null1 = obj1 == null; if (null0 && !null1) { return 1; } else if (!null0 && null1) { return -1; } else if (null0) { return 0; } // Orphan ImageComponents should be on the arr's right side final boolean orphan0 = obj0.getGObjectId() == Component.NULL; final boolean orphan1 = obj1.getGObjectId() == Component.NULL; if (orphan0 && !orphan1) { return 1; } else if (!orphan0 && orphan1) { return -1; } else if (orphan0) { return 0; } // Defer compare to user's comparison when objs aren't null or orphans return mUserCmp.compare(obj0, obj1); } } }
package mod._forms; import java.io.PrintWriter; import lib.StatusException; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import util.FormTools; import util.SOfficeFactory; import util.WriterTools; import com.sun.star.awt.XControlModel; import com.sun.star.awt.XDevice; import com.sun.star.awt.XGraphics; import com.sun.star.awt.XListBox; import com.sun.star.awt.XToolkit; import com.sun.star.awt.XWindow; import com.sun.star.awt.XWindowPeer; import com.sun.star.drawing.XControlShape; import com.sun.star.drawing.XShape; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.text.XTextDocument; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import com.sun.star.util.XCloseable; import com.sun.star.view.XControlAccess; public class OListBoxControl extends TestCase { XTextDocument xTextDoc; protected void initialize ( TestParameters Param, PrintWriter log) { SOfficeFactory SOF = SOfficeFactory.getFactory( ((XMultiServiceFactory) Param.getMSF()) ); try { log.println( "creating a textdocument" ); xTextDoc = SOF.createTextDoc( null ); } catch ( com.sun.star.uno.Exception e ) { // Some exception occures.FAILED e.printStackTrace( log ); throw new StatusException( "Couldn't create document", e ); } } protected void cleanup(TestParameters tParam, PrintWriter log) { log.println(" disposing xTextDoc "); try { XCloseable closer = (XCloseable) UnoRuntime.queryInterface( XCloseable.class, xTextDoc); closer.close(true); } catch (com.sun.star.util.CloseVetoException e) { log.println("couldn't close document"); } catch (com.sun.star.lang.DisposedException e) { log.println("couldn't close document"); } } protected TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) { XInterface oObj = null; Object anotherCtrl = null ; XWindowPeer the_win = null; XToolkit the_kit = null; XDevice aDevice = null; XGraphics aGraphic = null; //Insert a ControlShape and get the ControlModel XControlShape aShape = FormTools.createControlShape( xTextDoc,3000,4500,15000,10000,"ListBox"); WriterTools.getDrawPage(xTextDoc).add((XShape) aShape); XControlModel the_Model = aShape.getControl(); XControlShape aShape2 = FormTools.createControlShape( xTextDoc,3000,4500,5000,10000,"TextField"); WriterTools.getDrawPage(xTextDoc).add((XShape) aShape2); XControlModel the_Model2 = aShape2.getControl(); //Try to query XControlAccess XControlAccess the_access = (XControlAccess) UnoRuntime.queryInterface( XControlAccess.class,xTextDoc.getCurrentController()); //now get the OListBoxControl try { oObj = the_access.getControl(the_Model); anotherCtrl = the_access.getControl(the_Model2); the_win = the_access.getControl(the_Model).getPeer(); the_kit = the_win.getToolkit(); aDevice = the_kit.createScreenCompatibleDevice(200,200); aGraphic = aDevice.createGraphics(); } catch (Exception e) { log.println("Couldn't get OListBoxControl"); e.printStackTrace(log); throw new StatusException("Couldn't get OListBoxControl", e ); } log.println( "creating a new environment for OListBoxControl object" ); TestEnvironment tEnv = new TestEnvironment( oObj ); //Adding ObjRelation for XView tEnv.addObjRelation("GRAPHICS",aGraphic); //Adding ObjRelation for XControl tEnv.addObjRelation("CONTEXT",xTextDoc); tEnv.addObjRelation("WINPEER",the_win); tEnv.addObjRelation("TOOLKIT",the_kit); tEnv.addObjRelation("MODEL",the_Model); // Adding relation for XItemListener ifc.awt._XItemListener.TestItemListener listener = new ifc.awt._XItemListener.TestItemListener() ; final XListBox box = (XListBox) UnoRuntime.queryInterface(XListBox.class, oObj) ; box.addItemListener(listener) ; tEnv.addObjRelation("TestItemListener", listener) ; // Adding relation for XWindow XWindow forObjRel = (XWindow) UnoRuntime.queryInterface(XWindow.class, anotherCtrl); XWindow objWin = (XWindow) UnoRuntime.queryInterface(XWindow.class, oObj); tEnv.addObjRelation("XWindow.AnotherWindow",forObjRel); tEnv.addObjRelation("XWindow.ControlShape",aShape); tEnv.addObjRelation("Win1",objWin); tEnv.addObjRelation("Win2",forObjRel); tEnv.addObjRelation("CONTROL",anotherCtrl); // adding relation for XChangeBroadcaster box.addItem("Item1", (short) 0); box.addItem("Item2", (short) 1); tEnv.addObjRelation("XChangeBroadcaster.Changer", new ifc.form._XChangeBroadcaster.Changer() { public void change(){ box.addItem("Item1", (short) 0); box.addItem("Item2", (short) 1); box.selectItemPos((short) 0, true); box.selectItemPos((short) 1, true); } } ); return tEnv; } // finish method getTestEnvironment } // finish class OListBoxControl
package com.qiscus.sdk; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Handler; import com.google.gson.Gson; import com.qiscus.sdk.data.local.QiscusCacheManager; import com.qiscus.sdk.data.local.QiscusDataBaseHelper; import com.qiscus.sdk.data.model.QiscusAccount; import com.qiscus.sdk.data.model.QiscusChatConfig; import com.qiscus.sdk.data.model.QiscusChatRoom; import com.qiscus.sdk.data.remote.QiscusApi; import com.qiscus.sdk.event.QiscusUserEvent; import com.qiscus.sdk.service.QiscusPusherService; import com.qiscus.sdk.ui.QiscusChatActivity; import com.qiscus.sdk.ui.fragment.QiscusChatFragment; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class Qiscus { private static Application APP_INSTANCE; private static volatile Handler APP_HANDLER; private static LocalDataManager LOCAL_DATA_MANAGER; private static QiscusChatConfig CHAT_CONFIG; private static String APP_ID; private static long HEART_BEAT; public static void init(Application application, String qiscusAppId) { APP_INSTANCE = application; APP_ID = qiscusAppId; APP_HANDLER = new Handler(APP_INSTANCE.getMainLooper()); LOCAL_DATA_MANAGER = new LocalDataManager(); CHAT_CONFIG = new QiscusChatConfig(); HEART_BEAT = 5000; APP_INSTANCE.startService(new Intent(APP_INSTANCE, QiscusPusherService.class)); } public static SetUserBuilder setUser(String userEmail, String userKey) { return new SetUserBuilder(userEmail, userKey); } public static Application getApps() { checkAppIdSetup(); return APP_INSTANCE; } public static String getAppsName() { checkAppIdSetup(); return APP_INSTANCE.getApplicationInfo().loadLabel(APP_INSTANCE.getPackageManager()).toString(); } public static Handler getAppsHandler() { checkAppIdSetup(); return APP_HANDLER; } public static String getAppId() { checkAppIdSetup(); return APP_ID; } public static boolean hasSetupUser() { return LOCAL_DATA_MANAGER.isLogged(); } public static QiscusAccount getQiscusAccount() { checkUserSetup(); return LOCAL_DATA_MANAGER.getAccountInfo(); } public static String getToken() { checkUserSetup(); return LOCAL_DATA_MANAGER.getToken(); } public static QiscusChatConfig getChatConfig() { checkAppIdSetup(); return CHAT_CONFIG; } public static ChatBuilder buildChatRoomWith(String email) { checkUserSetup(); return new ChatBuilder(email); } public static ChatActivityBuilder buildChatWith(String email) { checkUserSetup(); return new ChatActivityBuilder(email); } public static ChatFragmentBuilder buildChatFragmentWith(String email) { checkUserSetup(); return new ChatFragmentBuilder(email); } public static void setHeartBeat(long heartBeat) { checkAppIdSetup(); HEART_BEAT = heartBeat; } public static long getHeartBeat() { return HEART_BEAT; } private static void checkAppIdSetup() throws RuntimeException { if (APP_ID == null) { throw new RuntimeException("Please init Qiscus with your app id before!"); } } private static void checkUserSetup() throws RuntimeException { checkAppIdSetup(); if (!hasSetupUser()) { throw new RuntimeException("Please set Qiscus user before start the chatting!"); } } public static void clearUser() { LOCAL_DATA_MANAGER.clearData(); QiscusDataBaseHelper.getInstance().clear(); QiscusCacheManager.getInstance().clearData(); EventBus.getDefault().post(QiscusUserEvent.LOGOUT); } private static class LocalDataManager { private final SharedPreferences sharedPreferences; private final Gson gson; private String token; LocalDataManager() { sharedPreferences = Qiscus.getApps().getSharedPreferences("qiscus.cfg", Context.MODE_PRIVATE); gson = new Gson(); token = isLogged() ? getAccountInfo().getToken() : null; } private boolean isLogged() { return sharedPreferences.contains("cached_account"); } private void saveAccountInfo(QiscusAccount qiscusAccount) { sharedPreferences.edit().putString("cached_account", gson.toJson(qiscusAccount)).apply(); setToken(qiscusAccount.getToken()); } private QiscusAccount getAccountInfo() { return gson.fromJson(sharedPreferences.getString("cached_account", ""), QiscusAccount.class); } private String getToken() { return token; } private void setToken(String token) { this.token = token; } private void clearData() { sharedPreferences.edit().clear().apply(); setToken(null); } } public static class SetUserBuilder { private String email; private String password; private String username; private String avatarUrl; private SetUserBuilder(String email, String password) { this.email = email; this.password = password; } public SetUserBuilder withUsername(String username) { this.username = username; return this; } public SetUserBuilder withAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; return this; } public void save(SetUserListener listener) { save().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(listener::onSuccess, listener::onError); } public Observable<QiscusAccount> save() { return QiscusApi.getInstance() .loginOrRegister(email, password, username, avatarUrl) .doOnNext(qiscusAccount -> { Qiscus.LOCAL_DATA_MANAGER.saveAccountInfo(qiscusAccount); EventBus.getDefault().post(QiscusUserEvent.LOGIN); }); } } public interface SetUserListener { void onSuccess(QiscusAccount qiscusAccount); void onError(Throwable throwable); } public static class ChatBuilder { private Set<String> emails; private ChatBuilder(String email) { emails = new HashSet<>(); emails.add(email); } public ChatBuilder addEmail(String email) { emails.add(email); return this; } public void build(ChatBuilderListener listener) { build().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(listener::onSuccess, listener::onError); } public Observable<QiscusChatRoom> build() { return QiscusApi.getInstance() .getChatRoom(new ArrayList<>(emails)); } } public interface ChatBuilderListener { void onSuccess(QiscusChatRoom qiscusChatRoom); void onError(Throwable throwable); } public static class ChatActivityBuilder { private Set<String> emails; private String title; private String subtitle; private QiscusChatConfig chatConfig; private ChatActivityBuilder(String email) { emails = new HashSet<>(); title = "Chat"; subtitle = ""; emails.add(email); } public ChatActivityBuilder addEmail(String email) { emails.add(email); return this; } public ChatActivityBuilder withTitle(String title) { this.title = title; return this; } public ChatActivityBuilder withSubtitle(String subtitle) { this.subtitle = subtitle; return this; } public ChatActivityBuilder withChatConfig(QiscusChatConfig qiscusChatConfig) { this.chatConfig = qiscusChatConfig; return this; } public void build(Context context, ChatActivityBuilderListener listener) { build(context).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(listener::onSuccess, listener::onError); } public Observable<Intent> build(Context context) { return QiscusApi.getInstance() .getChatRoom(new ArrayList<>(emails)) .doOnNext(qiscusChatRoom -> { qiscusChatRoom.setName(title); qiscusChatRoom.setSubtitle(subtitle); }) .map(qiscusChatRoom -> QiscusChatActivity.generateIntent(context, qiscusChatRoom)); } } public interface ChatActivityBuilderListener { void onSuccess(Intent intent); void onError(Throwable throwable); } public static class ChatFragmentBuilder { private Set<String> emails; private QiscusChatConfig chatConfig; private ChatFragmentBuilder(String email) { emails = new HashSet<>(); emails.add(email); } public ChatFragmentBuilder addEmail(String email) { emails.add(email); return this; } public ChatFragmentBuilder withChatConfig(QiscusChatConfig qiscusChatConfig) { this.chatConfig = qiscusChatConfig; return this; } public void build(ChatFragmentBuilderListener listener) { build().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(listener::onSuccess, listener::onError); } public Observable<QiscusChatFragment> build() { return QiscusApi.getInstance() .getChatRoom(new ArrayList<>(emails)) .map(QiscusChatFragment::newInstance); } } public interface ChatFragmentBuilderListener { void onSuccess(QiscusChatFragment qiscusChatFragment); void onError(Throwable throwable); } }
import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.Interval; import org.antlr.v4.runtime.tree.TerminalNode; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Very basic Java to Swift syntax converter. * See test/Test.java and test/Test.swift for an idea of what this produces. * This is a work in progress... * * TODO: * Class (static) method invocations should be qualified. * Method and fields with the same name should be disambiguated. * Final vars should become "let" vars. * * @author Pat Niemeyer (pat@pat.net) */ public class J2SwiftListener extends Java8BaseListener { CommonTokenStream tokens; TokenStreamRewriter rewriter; boolean inConstructor; int formalParameterPosition; // Some basic type mappings static Map<String,String> typeMap = new HashMap<>(); static { typeMap.put("float", "Float"); typeMap.put("Float", "Float"); typeMap.put("int", "Int"); typeMap.put("Integer", "Int"); typeMap.put("long", "Int"); typeMap.put("Long", "Int"); typeMap.put("boolean", "Bool"); typeMap.put("Boolean", "Bool"); typeMap.put("Map", "Dictionary"); typeMap.put("HashSet", "Set"); typeMap.put("List", "Array"); } // Some basic modifier mappings (others in context) static Map<String,String> modifierMap = new HashMap<>(); static { modifierMap.put("protected", "internal"); } public J2SwiftListener( CommonTokenStream tokens ) { this.tokens = tokens; this.rewriter = new TokenStreamRewriter( tokens ); } Java8Parser.UnannTypeContext unannType; @Override public void enterFieldDeclaration( Java8Parser.FieldDeclarationContext ctx ) { //: fieldModifier* unannType variableDeclaratorList ';' // Store the unannType for the variableDeclarator (convenience) unannType = ctx.unannType(); } @Override public void exitFieldDeclaration( Java8Parser.FieldDeclarationContext ctx ) { // replace on exit because the unannType rules will rewrite it replace( ctx.unannType(), "var" ); unannType = null; } @Override public void enterLocalVariableDeclaration( Java8Parser.LocalVariableDeclarationContext ctx ) { //: variableModifier* unannType variableDeclaratorList unannType = ctx.unannType(); } @Override public void exitLocalVariableDeclaration( Java8Parser.LocalVariableDeclarationContext ctx ) { replace( ctx.unannType(), "var" ); unannType = null; } @Override public void enterConstantDeclaration( Java8Parser.ConstantDeclarationContext ctx ) { //: constantModifier* unannType variableDeclaratorList ';' unannType = ctx.unannType(); } @Override public void exitConstantDeclaration( Java8Parser.ConstantDeclarationContext ctx ) { replace( ctx.unannType(), "var" ); unannType = null; } @Override public void exitVariableDeclarator( Java8Parser.VariableDeclaratorContext ctx ) { //: variableDeclaratorId ('=' variableInitializer)? // We could search the parent contexts for unannType but since we have to remove it anyway we store it. // Use the rewritten text, not the original. // todo: not sure what's up here, crashing on lambdas try { rewriter.insertAfter( ctx.variableDeclaratorId().stop, " : " + getText( unannType ) ); } catch ( Exception e ) { // do nothing } } @Override public void enterConstructorDeclaration( Java8Parser.ConstructorDeclarationContext ctx ) { //: constructorModifier* constructorDeclarator throws_? constructorBody // Search children of constructorBody for any explicit constructor invocations List<Java8Parser.ExplicitConstructorInvocationContext> eci = ctx.constructorBody().getRuleContexts( Java8Parser.ExplicitConstructorInvocationContext.class ); if ( !eci.isEmpty() ) { rewriter.insertBefore( ctx.constructorDeclarator().start, "convenience " ); } } @Override public void enterConstructorDeclarator( Java8Parser.ConstructorDeclaratorContext ctx ) { //: typeParameters? simpleTypeName '(' formalParameterList? ')' replace( ctx.simpleTypeName(), "init"); inConstructor = true; } @Override public void exitConstructorDeclaration( Java8Parser.ConstructorDeclarationContext ctx ) { inConstructor = false; } @Override public void enterFormalParameterList( Java8Parser.FormalParameterListContext ctx ) { // called from methodDeclarator //: formalParameters ',' lastFormalParameter // | lastFormalParameter formalParameterPosition = 0; } @Override public void enterFormalParameters( Java8Parser.FormalParametersContext ctx ) { // called from formalParameterList //: formalParameter (',' formalParameter)* // | receiverParameter (',' formalParameter)* formalParameterPosition = 0; } @Override public void exitFormalParameter( Java8Parser.FormalParameterContext ctx ) { rewriter.insertAfter( ctx.variableDeclaratorId().stop, " : " + getText( ctx.unannType() ) ); //: variableModifier* unannType variableDeclaratorId if ( formalParameterPosition++ > 0 || inConstructor ) { replace( ctx.unannType(), "_" ); } else { removeRight( ctx.unannType() ); } } @Override public void exitMethodHeader( Java8Parser.MethodHeaderContext ctx ) { //: result methodDeclarator throws_? //| typeParameters annotation* result methodDeclarator throws_? if ( !ctx.result().getText().equals( "void" )) { rewriter.insertAfter( ctx.methodDeclarator().stop, " -> " + getText( ctx.result() ) ); } replace( ctx.result(), "func" ); } @Override public void enterPackageDeclaration( Java8Parser.PackageDeclarationContext ctx ) { rewriter.insertBefore( ctx.start, " } @Override public void enterPrimaryNoNewArray_lfno_primary( Java8Parser.PrimaryNoNewArray_lfno_primaryContext ctx ) { if ( ctx.getText().equals( "this" )) { replace( ctx, "self" ); } } @Override public void enterFieldModifier( Java8Parser.FieldModifierContext ctx ) { // changed in 1.2 //if ( ctx.getText().equals( "static" )) { replace( ctx, "class" ); } } @Override public void enterMethodModifier( Java8Parser.MethodModifierContext ctx ) { if ( ctx.getText().equals( "static" )) { replace( ctx, "class" ); } } @Override public void enterLiteral( Java8Parser.LiteralContext ctx ) { //IntegerLiteral // | FloatingPointLiteral // | BooleanLiteral // | CharacterLiteral // | StringLiteral // | NullLiteral if ( ctx.getText().equals( "null" ) ) { replace(ctx, "nil"); } else if ( ctx.FloatingPointLiteral() != null ) { String text = ctx.getText(); if ( text.toLowerCase().endsWith( "f" ) ) { text = text.substring( 0, text.length()-1 ); replace(ctx, text); } } } @Override public void enterClassInstanceCreationExpression( Java8Parser.ClassInstanceCreationExpressionContext ctx ) { //: 'new' typeArguments? annotation* Identifier ('.' annotation* Identifier)* typeArgumentsOrDiamond? '(' argumentList? ')' classBody? //| expressionName '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? //| primary '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? if ( ctx.start.getText().equals( "new" ) ) { rewriter.delete( ctx.start ); rewriter.delete( ctx.start.getTokenIndex() + 1 ); // space } } @Override public void enterClassInstanceCreationExpression_lfno_primary( Java8Parser.ClassInstanceCreationExpression_lfno_primaryContext ctx ) { //: 'new' typeArguments? annotation* Identifier ('.' annotation* Identifier)* typeArgumentsOrDiamond? '(' argumentList? ')' classBody? //| expressionName '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? if ( ctx.start.getText().equals( "new" ) ) { rewriter.delete( ctx.start ); rewriter.delete( ctx.start.getTokenIndex() + 1 ); // space } } @Override public void enterThrowStatement( Java8Parser.ThrowStatementContext ctx ) { //: 'throw' expression ';' rewriter.insertBefore( ctx.start, "throwException() /* " ); rewriter.insertAfter( ctx.stop, " */" ); } @Override public void enterCastExpression( Java8Parser.CastExpressionContext ctx ) { //: '(' primitiveType ')' unaryExpression // | '(' referenceType additionalBound* ')' unaryExpressionNotPlusMinus // | '(' referenceType additionalBound* ')' lambdaExpression if ( ctx.primitiveType() != null ) { replace( ctx.primitiveType(), mapType( ctx.primitiveType() ) ); } } @Override public void exitUnannType( Java8Parser.UnannTypeContext ctx ) { // mapping may already have been done by more specific rule but this shouldn't hurt it // todo: this needs to be more specific, preventing rewrites on generic type args //if ( !ctx.getText().contains( "<" ) && !ctx.getText().contains( "[" )) { replace( ctx, mapType( getText( ctx ) ) ); } @Override public void exitArrayType( Java8Parser.ArrayTypeContext ctx ) { //: primitiveType dims //| classOrInterfaceType dims //| typeVariable dims ParserRuleContext rule; if ( ctx.primitiveType() != null ) { rule = ctx.primitiveType(); } else if ( ctx.classOrInterfaceType() != null ) { rule = ctx.classOrInterfaceType(); } else { rule = ctx.typeVariable(); } replace( ctx, "["+mapType(rule)+"]" ); } @Override public void exitUnannArrayType( Java8Parser.UnannArrayTypeContext ctx ) { //: unannPrimitiveType dims //| unannClassOrInterfaceType dims //| unannTypeVariable dims ParserRuleContext rule; if ( ctx.unannPrimitiveType() != null ) { rule = ctx.unannPrimitiveType(); } else if ( ctx.unannClassOrInterfaceType() != null ) { rule = ctx.unannClassOrInterfaceType(); } else { rule = ctx.unannTypeVariable(); } replace( ctx, "["+mapType(rule)+"]" ); } @Override public void enterExplicitConstructorInvocation( Java8Parser.ExplicitConstructorInvocationContext ctx ) { //: typeArguments? 'this' '(' argumentList? ')' ';' // | typeArguments? 'super' '(' argumentList? ')' ';' // | expressionName '.' typeArguments? 'super' '(' argumentList? ')' ';' // | primary '.' typeArguments? 'super' '(' argumentList? ')' ';' List<TerminalNode> thisTokens = ctx.getTokens( Java8Lexer.THIS ); if ( thisTokens != null && !thisTokens.isEmpty() ) { rewriter.replace( thisTokens.get( 0 ).getSymbol().getTokenIndex(), "self.init" ); } } @Override public void enterImportDeclaration( Java8Parser.ImportDeclarationContext ctx ) { rewriter.insertBefore( ctx.start, " } @Override public void enterSuperclass( Java8Parser.SuperclassContext ctx ) { //: 'extends' classType replaceFirst( ctx, Java8Lexer.EXTENDS, " : " ); } @Override public void enterSuperinterfaces( Java8Parser.SuperinterfacesContext ctx ) { //: 'implements' interfaceTypeList replaceFirst( ctx, Java8Lexer.IMPLEMENTS, " : " ); } @Override public void exitFieldModifier( Java8Parser.FieldModifierContext ctx ) { replace( ctx, mapModifier( ctx ) ); } @Override public void exitMethodModifier( Java8Parser.MethodModifierContext ctx ) { replace( ctx, mapModifier( ctx ) ); } @Override public void exitClassModifier( Java8Parser.ClassModifierContext ctx ) { replace( ctx, mapModifier( ctx ) ); } @Override public void enterNormalInterfaceDeclaration( Java8Parser.NormalInterfaceDeclarationContext ctx ) { //: interfaceModifier* 'interface' Identifier typeParameters? extendsInterfaces? interfaceBody List<TerminalNode> intfTokens = ctx.getTokens( Java8Lexer.INTERFACE ); rewriter.replace( intfTokens.get( 0 ).getSymbol().getTokenIndex(), "protocol" ); } @Override public void exitBasicForStatement( Java8Parser.BasicForStatementContext ctx ) { //: 'for' '(' forInit? ';' expression? ';' forUpdate? ')' statement deleteFirst( ctx, Java8Lexer.RPAREN ); deleteFirst( ctx, Java8Lexer.LPAREN ); if ( !ctx.statement().start.getText().equals( "{" ) ) { rewriter.insertBefore( ctx.statement().start, "{ " ); rewriter.insertAfter( ctx.statement().stop, " }" ); } } @Override public void exitWhileStatement( Java8Parser.WhileStatementContext ctx ) { //: 'while' '(' expression ')' statement deleteFirst( ctx, Java8Lexer.RPAREN ); deleteFirst( ctx, Java8Lexer.LPAREN ); if ( !ctx.statement().start.getText().equals( "{" ) ) { rewriter.insertBefore( ctx.statement().start, "{ " ); rewriter.insertAfter( ctx.statement().stop, " }" ); } } @Override public void exitMethodInvocation( Java8Parser.MethodInvocationContext ctx ) { // todo: make a map for these if ( ctx.getText().startsWith( "System.out.println" ) ) { replace( ctx, "println(" + getText( ctx.argumentList() ) + ")" ); } } @Override public void exitEnhancedForStatement( Java8Parser.EnhancedForStatementContext ctx ) { //: 'for' '(' variableModifier* unannType variableDeclaratorId ':' expression ')' statement if ( !ctx.statement().start.getText().equals( "{" ) ) { rewriter.insertBefore( ctx.statement().start, "{ " ); rewriter.insertAfter( ctx.statement().stop, " }" ); } String st = getText( ctx.statement() ); String out = "for "+getText(ctx.variableDeclaratorId())+" : "+getText( ctx.unannType() ) +" in "+getText( ctx.expression() ) + " " +st; replace( ctx, out ); } @Override public void exitUnannClassType_lfno_unannClassOrInterfaceType( Java8Parser.UnannClassType_lfno_unannClassOrInterfaceTypeContext ctx ) { //unannClassType_lfno_unannClassOrInterfaceType //: Identifier typeArguments? replaceFirst( ctx, ctx.Identifier().getSymbol().getType(), mapType( ctx.Identifier().getText() ) ); } // util private void deleteFirst( ParserRuleContext ctx, int token ) { List<TerminalNode> tokens = ctx.getTokens( token ); rewriter.delete( tokens.get(0).getSymbol().getTokenIndex() ); } private void replaceFirst( ParserRuleContext ctx, int token, String str ) { List<TerminalNode> tokens = ctx.getTokens( token ); rewriter.replace( tokens.get( 0 ).getSymbol().getTokenIndex(), str ); } // Get possibly rewritten text private String getText( ParserRuleContext ctx ) { if ( ctx == null ) { return ""; } return rewriter.getText( new Interval( ctx.start.getTokenIndex(), ctx.stop.getTokenIndex() ) ); } private void replace( ParserRuleContext ctx, String s ) { rewriter.replace( ctx.start, ctx.stop, s ); } // remove context and hidden tokens to right private void removeRight( ParserRuleContext ctx ) { rewriter.delete( ctx.start, ctx.stop ); List<Token> htr = tokens.getHiddenTokensToRight( ctx.stop.getTokenIndex() ); for (Token token : htr) { rewriter.delete( token ); } } public String mapType( ParserRuleContext ctx ) { //if ( ctx instanceof Java8Parser.UnannArrayTypeContext ) { } //String text = ctx.getText(); String text = getText(ctx); return mapType( text ); } public String mapType( String text ) { String mapText = typeMap.get( text ); return mapText == null ? text : mapText; } public String mapModifier( ParserRuleContext ctx ) { //if ( ctx instanceof Java8Parser.UnannArrayTypeContext ) { } //String text = ctx.getText(); String text = getText( ctx ); return mapModifier( text ); } public String mapModifier( String text ) { String mapText = modifierMap.get( text ); return mapText == null ? text : mapText; } }
package edu.umd.cs.findbugs; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; 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.jar.Attributes; import java.util.jar.Manifest; import org.dom4j.DocumentException; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.URLClassPath; import edu.umd.cs.findbugs.filter.Filter; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.xml.OutputStreamXMLOutput; import edu.umd.cs.findbugs.xml.XMLAttributeList; import edu.umd.cs.findbugs.xml.XMLOutput; import edu.umd.cs.findbugs.xml.XMLOutputUtil; import edu.umd.cs.findbugs.xml.XMLWriteable; /** * A project in the GUI. * This consists of some number of Jar files to analyze for bugs, and optionally * <p/> * <ul> * <li> some number of source directories, for locating the program's * source code * <li> some number of auxiliary classpath entries, for locating classes * referenced by the program which the user doesn't want to analyze * <li> some number of boolean options * </ul> * * @author David Hovemeyer */ public class Project implements XMLWriteable { private static final boolean DEBUG = SystemProperties.getBoolean("findbugs.project.debug"); private File currentWorkingDirectory; /** * Project filename. */ @Deprecated private String projectFileName; private String projectName; /** * Options. */ private Map<String, Boolean> optionsMap; /** * The list of project files. */ private List<String> fileList; /** * The list of source directories. */ private List<String> srcDirList; /** * The list of auxiliary classpath entries. */ private List<String> auxClasspathEntryList; /** * Flag to indicate that this Project has been modified. */ private boolean isModified; /** * Constant used to name anonymous projects. */ public static final String UNNAMED_PROJECT = "<<unnamed project>>"; private long timestamp = 0L; @NonNull private Filter suppressionFilter = new Filter(); /** * Create an anonymous project. */ public Project() { this.projectFileName = UNNAMED_PROJECT; optionsMap = new HashMap<String, Boolean>(); optionsMap.put(RELATIVE_PATHS, Boolean.FALSE); fileList = new LinkedList<String>(); srcDirList = new LinkedList<String>(); auxClasspathEntryList = new LinkedList<String>(); isModified = false; } /** * Return an exact copy of this Project. */ public Project duplicate() { Project dup = new Project(); dup.projectFileName = this.projectFileName; dup.currentWorkingDirectory = this.currentWorkingDirectory; dup.optionsMap.clear(); dup.optionsMap.putAll(this.optionsMap); dup.fileList.addAll(this.fileList); dup.srcDirList.addAll(this.srcDirList); dup.auxClasspathEntryList.addAll(this.auxClasspathEntryList); dup.timestamp = timestamp; return dup; } /** * add information from project2 to this project */ public void add(Project project2) { optionsMap.putAll(project2.optionsMap); fileList = appendWithoutDuplicates(fileList, project2.fileList); srcDirList = appendWithoutDuplicates(srcDirList, project2.srcDirList); auxClasspathEntryList = appendWithoutDuplicates(auxClasspathEntryList, project2.auxClasspathEntryList); } public static <T> List<T> appendWithoutDuplicates(List<T> lst1, List<T> lst2) { LinkedHashSet<T> joined = new LinkedHashSet<T>(lst1); joined.addAll(lst2); return new ArrayList<T>(joined); } public void setCurrentWorkingDirectory(File f) { this.currentWorkingDirectory = f; } /** * Return whether or not this Project has unsaved modifications. */ public boolean isModified() { return isModified; } /** * Set whether or not this Project has unsaved modifications. */ public void setModified(boolean isModified) { this.isModified = isModified; } /** * Get the project filename. */ @Deprecated public String getProjectFileName() { return projectFileName; } /** * Set the project filename. * * @param projectFileName the new filename */ @Deprecated public void setProjectFileName(String projectFileName) { this.projectFileName = projectFileName; } /** * Add a file to the project. * * @param fileName the file to add * @return true if the file was added, or false if the * file was already present */ public boolean addFile(String fileName) { return addToListInternal(fileList, makeAbsoluteCWD(fileName)); } /** * Add a source directory to the project. * @param dirName the directory to add * @return true if the source directory was added, or false if the * source directory was already present */ public boolean addSourceDir(String dirName) { return addToListInternal(srcDirList, makeAbsoluteCWD(dirName)); } /** * Retrieve the Options value. * * @param option the name of option to get * @return the value of the option */ public boolean getOption(String option) { Boolean value = optionsMap.get(option); return value != null && value.booleanValue(); } /** * Get the number of files in the project. * * @return the number of files in the project */ public int getFileCount() { return fileList.size(); } /** * Get the given file in the list of project files. * * @param num the number of the file in the list of project files * @return the name of the file */ public String getFile(int num) { return fileList.get(num); } /** * Remove file at the given index in the list of project files * * @param num index of the file to remove in the list of project files */ public void removeFile(int num) { fileList.remove(num); isModified = true; } /** * Get the list of files, directories, and zip files in the project. */ public List<String> getFileList() { return fileList; } /** * Get the number of source directories in the project. * * @return the number of source directories in the project */ public int getNumSourceDirs() { return srcDirList.size(); } /** * Get the given source directory. * * @param num the number of the source directory * @return the source directory */ public String getSourceDir(int num) { return srcDirList.get(num); } /** * Remove source directory at given index. * * @param num index of the source directory to remove */ public void removeSourceDir(int num) { srcDirList.remove(num); isModified = true; } /** * Get project files as an array of Strings. */ public String[] getFileArray() { return fileList.toArray(new String[fileList.size()]); } /** * Get source dirs as an array of Strings. */ public String[] getSourceDirArray() { return srcDirList.toArray(new String[srcDirList.size()]); } /** * Get the source dir list. */ public List<String> getSourceDirList() { return srcDirList; } /** * Add an auxiliary classpath entry * * @param auxClasspathEntry the entry * @return true if the entry was added successfully, or false * if the given entry is already in the list */ public boolean addAuxClasspathEntry(String auxClasspathEntry) { return addToListInternal(auxClasspathEntryList, makeAbsoluteCWD(auxClasspathEntry)); } /** * Get the number of auxiliary classpath entries. */ public int getNumAuxClasspathEntries() { return auxClasspathEntryList.size(); } /** * Get the n'th auxiliary classpath entry. */ public String getAuxClasspathEntry(int n) { return auxClasspathEntryList.get(n); } /** * Remove the n'th auxiliary classpath entry. */ public void removeAuxClasspathEntry(int n) { auxClasspathEntryList.remove(n); isModified = true; } /** * Return the list of aux classpath entries. */ public List<String> getAuxClasspathEntryList() { return auxClasspathEntryList; } /** * Worklist item for finding implicit classpath entries. */ private static class WorkListItem { private URL url; /** * Constructor. * * @param url the URL of the Jar or Zip file */ public WorkListItem(URL url) { this.url = url; } /** * Get URL of Jar/Zip file. */ public URL getURL() { return this.url; } } /** * Worklist for finding implicit classpath entries. */ private static class WorkList { private LinkedList<WorkListItem> itemList; private HashSet<String> addedSet; /** * Constructor. * Creates an empty worklist. */ public WorkList() { this.itemList = new LinkedList<WorkListItem>(); this.addedSet = new HashSet<String>(); } /** * Create a URL from a filename specified in the project file. */ public URL createURL(String fileName) throws MalformedURLException { String protocol = URLClassPath.getURLProtocol(fileName); if (protocol == null) { fileName = "file:" + fileName; } return new URL(fileName); } /** * Create a URL of a file relative to another URL. */ public URL createRelativeURL(URL base, String fileName) throws MalformedURLException { return new URL(base, fileName); } /** * Add a worklist item. * * @param item the WorkListItem representing a zip/jar file to be examined * @return true if the item was added, false if not (because it was * examined already) */ public boolean add(WorkListItem item) { if (DEBUG) System.out.println("Adding " + item.getURL().toString()); if (!addedSet.add(item.getURL().toString())) { if (DEBUG) System.out.println("\t==> Already processed"); return false; } itemList.add(item); return true; } /** * Return whether or not the worklist is empty. */ public boolean isEmpty() { return itemList.isEmpty(); } /** * Get the next item in the worklist. */ public WorkListItem getNextItem() { return itemList.removeFirst(); } } /** * Return the list of implicit classpath entries. The implicit * classpath is computed from the closure of the set of jar files * that are referenced by the <code>"Class-Path"</code> attribute * of the manifest of the any jar file that is part of this project * or by the <code>"Class-Path"</code> attribute of any directly or * indirectly referenced jar. The referenced jar files that exist * are the list of implicit classpath entries. * * @deprecated FindBugs2 and ClassPathBuilder take care of this automatically */ public List<String> getImplicitClasspathEntryList() { final LinkedList<String> implicitClasspath = new LinkedList<String>(); WorkList workList = new WorkList(); // Prime the worklist by adding the zip/jar files // in the project. for (String fileName : fileList) { try { URL url = workList.createURL(fileName); WorkListItem item = new WorkListItem(url); workList.add(item); } catch (MalformedURLException ignore) { // Ignore } } // Scan recursively. while (!workList.isEmpty()) { WorkListItem item = workList.getNextItem(); processComponentJar(item.getURL(), workList, implicitClasspath); } return implicitClasspath; } /** * Examine the manifest of a single zip/jar file for implicit * classapth entries. * * @param jarFileURL URL of the zip/jar file * @param workList worklist of zip/jar files to examine * @param implicitClasspath list of implicit classpath entries found */ private void processComponentJar(URL jarFileURL, WorkList workList, List<String> implicitClasspath) { if (DEBUG) System.out.println("Processing " + jarFileURL.toString()); if (!jarFileURL.toString().endsWith(".zip") && !jarFileURL.toString().endsWith(".jar")) return; try { URL manifestURL = new URL("jar:" + jarFileURL.toString() + "!/META-INF/MANIFEST.MF"); InputStream in = null; try { in = manifestURL.openStream(); Manifest manifest = new Manifest(in); Attributes mainAttrs = manifest.getMainAttributes(); String classPath = mainAttrs.getValue("Class-Path"); if (classPath != null) { String[] fileList = classPath.split("\\s+"); for (String jarFile : fileList) { URL referencedURL = workList.createRelativeURL(jarFileURL, jarFile); if (workList.add(new WorkListItem(referencedURL))) { implicitClasspath.add(referencedURL.toString()); if (DEBUG) System.out.println("Implicit jar: " + referencedURL.toString()); } } } } finally { if (in != null) { in.close(); } } } catch (IOException ignore) { // Ignore } } private static final String OPTIONS_KEY = "[Options]"; private static final String JAR_FILES_KEY = "[Jar files]"; private static final String SRC_DIRS_KEY = "[Source dirs]"; private static final String AUX_CLASSPATH_ENTRIES_KEY = "[Aux classpath entries]"; // Option keys public static final String RELATIVE_PATHS = "relative_paths"; /** * Save the project to an output file. * * @param outputFile name of output file * @param useRelativePaths true if the project should be written * using only relative paths * @param relativeBase if useRelativePaths is true, * this file is taken as the base directory in terms of which * all files should be made relative * @throws IOException if an error occurs while writing */ @Deprecated public void write(String outputFile, boolean useRelativePaths, String relativeBase) throws IOException { PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile))); try { writer.println(JAR_FILES_KEY); for (String jarFile : fileList) { if (useRelativePaths) jarFile = convertToRelative(jarFile, relativeBase); writer.println(jarFile); } writer.println(SRC_DIRS_KEY); for (String srcDir : srcDirList) { if (useRelativePaths) srcDir = convertToRelative(srcDir, relativeBase); writer.println(srcDir); } writer.println(AUX_CLASSPATH_ENTRIES_KEY); for (String auxClasspathEntry : auxClasspathEntryList) { if (useRelativePaths) auxClasspathEntry = convertToRelative(auxClasspathEntry, relativeBase); writer.println(auxClasspathEntry); } if (useRelativePaths) { writer.println(OPTIONS_KEY); writer.println(RELATIVE_PATHS + "=true"); } } finally { writer.close(); } // Project successfully saved isModified = false; } public static Project readXML(File f) throws IOException, DocumentException, SAXException { Project project = new Project(); InputStream in = new BufferedInputStream(new FileInputStream(f)); String tag = Util.getXMLType(in); SAXBugCollectionHandler handler; if (tag.equals("Project")) { handler = new SAXBugCollectionHandler(project, f); } else if (tag.equals("BugCollection")) { SortedBugCollection bugs = new SortedBugCollection(); handler = new SAXBugCollectionHandler(bugs, project, f); } else throw new IOException("Can't load a project from a " + tag + " file"); try { XMLReader xr = null; if (true) try { xr = XMLReaderFactory.createXMLReader(); } catch (SAXException e) { AnalysisContext.logError("Couldn't create XMLReaderFactory", e); } if (xr == null) { xr = new org.dom4j.io.aelfred.SAXDriver(); } xr.setContentHandler(handler); xr.setErrorHandler(handler); Reader reader = Util.getReader(in); xr.parse(new InputSource(reader)); } finally { in.close(); } // Presumably, project is now up-to-date project.setModified(false); return project; } public void writeXML(File f) throws IOException { OutputStream out = new FileOutputStream(f); XMLOutput xmlOutput = new OutputStreamXMLOutput(out); try { writeXML(xmlOutput); } finally { xmlOutput.finish(); } } /** * Read the project from an input file. * This method should only be used on an empty Project * (created with the default constructor). * * @param inputFile name of the input file to read the project from * @throws IOException if an error occurs while reading */ public void read(String inputFile) throws IOException { if (isModified) throw new IllegalStateException("Reading into a modified Project!"); // Make the input file absolute, if necessary File file = new File(inputFile); if (!file.isAbsolute()) inputFile = file.getAbsolutePath(); // Store the project filename setProjectFileName(inputFile); BufferedReader reader = null; try { reader = new BufferedReader(Util.getFileReader(inputFile)); String line; line = getLine(reader); if (line == null || !line.equals(JAR_FILES_KEY)) throw new IOException("Bad format: missing jar files key"); while ((line = getLine(reader)) != null && !line.equals(SRC_DIRS_KEY)) { addToListInternal(fileList, line); } if (line == null) throw new IOException("Bad format: missing source dirs key"); while ((line = getLine(reader)) != null && !line.equals(AUX_CLASSPATH_ENTRIES_KEY)) { addToListInternal(srcDirList, line); } // The list of aux classpath entries is optional if (line != null) { while ((line = getLine(reader)) != null) { if (line.equals(OPTIONS_KEY)) break; addToListInternal(auxClasspathEntryList, line); } } // The Options section is also optional if (line != null && line.equals(OPTIONS_KEY)) { while ((line = getLine(reader)) != null && !line.equals(JAR_FILES_KEY)) parseOption(line); } // If this project has the relative paths option set, // resolve all internal relative paths into absolute // paths, using the absolute path of the project // file as a base directory. if (getOption(RELATIVE_PATHS)) { makeListAbsoluteProject(fileList); makeListAbsoluteProject(srcDirList); makeListAbsoluteProject(auxClasspathEntryList); } // Clear the modification flag set by the various "add" methods. isModified = false; } finally { if (reader != null) reader.close(); } } /** * Read a line from a BufferedReader, ignoring blank lines * and comments. */ private static String getLine(BufferedReader reader) throws IOException { String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.equals("") && !line.startsWith(" break; } return line; } public String projectNameFromProjectFileName() { String name = projectFileName; int lastSep = name.lastIndexOf(File.separatorChar); if (lastSep >= 0) name = name.substring(lastSep + 1); int dot = name.lastIndexOf('.'); if (dot >= 0) name = name.substring(0, dot); return name; } /** * Convert to a string in a nice (displayable) format. */ @Override public String toString() { String name = projectFileName; int lastSep = name.lastIndexOf(File.separatorChar); if (lastSep >= 0) name = name.substring(lastSep + 1); //int dot = name.lastIndexOf('.'); //Don't hide every suffix--some are informative and/or disambiguative. int dot = (name.endsWith(".fb") ? name.length()-3 : -1); if (dot >= 0) name = name.substring(0, dot); return name; } /** * Transform a user-entered filename into a proper filename, * by adding the ".fb" file extension if it isn't already present. */ public static String transformFilename(String fileName) { if (!fileName.endsWith(".fb")) fileName = fileName + ".fb"; return fileName; } static final String JAR_ELEMENT_NAME = "Jar"; static final String AUX_CLASSPATH_ENTRY_ELEMENT_NAME = "AuxClasspathEntry"; static final String SRC_DIR_ELEMENT_NAME = "SrcDir"; static final String FILENAME_ATTRIBUTE_NAME = "filename"; static final String PROJECTNAME_ATTRIBUTE_NAME = "projectName"; public void writeXML(XMLOutput xmlOutput) throws IOException { XMLAttributeList attributeList = new XMLAttributeList().addAttribute(FILENAME_ATTRIBUTE_NAME, getProjectFileName()); if (getProjectName() != null) attributeList = attributeList.addAttribute(PROJECTNAME_ATTRIBUTE_NAME, getProjectName()); xmlOutput.openTag( BugCollection.PROJECT_ELEMENT_NAME, attributeList ); XMLOutputUtil.writeElementList(xmlOutput, JAR_ELEMENT_NAME, fileList); XMLOutputUtil.writeElementList(xmlOutput, AUX_CLASSPATH_ENTRY_ELEMENT_NAME, auxClasspathEntryList); XMLOutputUtil.writeElementList(xmlOutput, SRC_DIR_ELEMENT_NAME, srcDirList); if (suppressionFilter != null && !suppressionFilter.isEmpty()) { xmlOutput.openTag("SuppressionFilter"); suppressionFilter.writeBodyAsXML(xmlOutput); xmlOutput.closeTag("SuppressionFilter"); } xmlOutput.closeTag(BugCollection.PROJECT_ELEMENT_NAME); } /** * Parse one line in the [Options] section. * * @param option one line in the [Options] section */ private void parseOption(String option) throws IOException { int equalPos = option.indexOf("="); if (equalPos < 0) throw new IOException("Bad format: invalid option format"); String name = option.substring(0, equalPos); String value = option.substring(equalPos + 1); optionsMap.put(name, Boolean.valueOf(value)); } /** * Hack for whether files are case insensitive. * For now, we'll assume that Windows is the only * case insensitive OS. (OpenVMS users, * feel free to submit a patch :-) */ private static final boolean FILE_IGNORE_CASE = SystemProperties.getProperty("os.name", "unknown").startsWith("Windows"); /** * Converts a full path to a relative path if possible * * @param srcFile path to convert * @return the converted filename */ private String convertToRelative(String srcFile, String base) { String slash = SystemProperties.getProperty("file.separator"); if (FILE_IGNORE_CASE) { srcFile = srcFile.toLowerCase(); base = base.toLowerCase(); } if (base.equals(srcFile)) return "."; if (!base.endsWith(slash)) base = base + slash; if (base.length() <= srcFile.length()) { String root = srcFile.substring(0, base.length()); if (root.equals(base)) { // Strip off the base directory, make relative return "." + SystemProperties.getProperty("file.separator") + srcFile.substring(base.length()); } } //See if we can build a relative path above the base using .. notation int slashPos = srcFile.indexOf(slash); int branchPoint; if (slashPos >= 0) { String subPath = srcFile.substring(0, slashPos); if ((subPath.length() == 0) || base.startsWith(subPath)) { branchPoint = slashPos + 1; slashPos = srcFile.indexOf(slash, branchPoint); while (slashPos >= 0) { subPath = srcFile.substring(0, slashPos); if (base.startsWith(subPath)) branchPoint = slashPos + 1; else break; slashPos = srcFile.indexOf(slash, branchPoint); } int slashCount = 0; slashPos = base.indexOf(slash, branchPoint); while (slashPos >= 0) { slashCount++; slashPos = base.indexOf(slash, slashPos + 1); } StringBuffer path = new StringBuffer(); String upDir = ".." + slash; for (int i = 0; i < slashCount; i++) path.append(upDir); path.append(srcFile.substring(branchPoint)); return path.toString(); } } return srcFile; } /** * Converts a relative path to an absolute path if possible. * * @param fileName path to convert * @return the converted filename */ private String convertToAbsolute(String fileName) throws IOException { // At present relative paths are only calculated if the fileName is // below the project file. This need not be the case, and we could use .. // syntax to move up the tree. (To Be Added) File file = new File(fileName); if (!file.isAbsolute()) { // Only try to make the relative path absolute // if the project file is absolute. File projectFile = new File(projectFileName); if (projectFile.isAbsolute()) { // Get base directory (parent of the project file) String base = new File(projectFileName).getParent(); // Make the file absolute in terms of the parent directory fileName = new File(base, fileName).getCanonicalPath(); } } return fileName; } /** * Make the given filename absolute relative to the * current working directory. */ private String makeAbsoluteCWD(String fileName) { boolean hasProtocol = (URLClassPath.getURLProtocol(fileName) != null); if (hasProtocol) return fileName; if (new File(fileName).isAbsolute()) return fileName; return new File(currentWorkingDirectory, fileName).getAbsolutePath(); } /** * Add a value to given list, making the Project modified * if the value is not already present in the list. * * @param list the list * @param value the value to be added * @return true if the value was not already present in the list, * false otherwise */ private boolean addToListInternal(Collection<String> list, String value) { if (!list.contains(value)) { list.add(value); isModified = true; return true; } else return false; } /** * Make the given list of pathnames absolute relative * to the absolute path of the project file. */ private void makeListAbsoluteProject(List<String> list) throws IOException { List<String> replace = new LinkedList<String>(); for (String fileName : list) { fileName = convertToAbsolute(fileName); replace.add(fileName); } list.clear(); list.addAll(replace); } /** * @param timestamp The timestamp to set. */ public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public void addTimestamp(long timestamp) { if (this.timestamp < timestamp) this.timestamp = timestamp; } /** * @return Returns the timestamp. */ public long getTimestamp() { return timestamp; } /** * @param projectName The projectName to set. */ public void setProjectName(String projectName) { this.projectName = projectName; } /** * @return Returns the projectName. */ public String getProjectName() { return projectName; } /** * @param suppressionFilter The suppressionFilter to set. */ public void setSuppressionFilter(Filter suppressionFilter) { this.suppressionFilter = suppressionFilter; } /** * @return Returns the suppressionFilter. */ public Filter getSuppressionFilter() { if (suppressionFilter == null) suppressionFilter = new Filter(); return suppressionFilter; } } // vim:ts=4
package edu.umd.cs.findbugs.ba; import edu.umd.cs.findbugs.graph.AbstractEdge; import org.apache.bcel.generic.InstructionHandle; /** * An edge of a control flow graph. * * @author David Hovemeyer * @see BasicBlock * @see CFG */ public class Edge extends AbstractEdge<Edge, BasicBlock> implements EdgeTypes, Debug { private int type; private int flags; /** * Constructor. * * @param source source basic block * @param dest destination basic block */ public Edge(BasicBlock source, BasicBlock dest) { super(source, dest); } public int getId() { return getLabel(); } /** * Get the type of edge. */ public int getType() { return type; } /** * Set the type of edge. */ public void setType(int type) { this.type = type; } /** * Get the edge flags. */ public int getFlags() { return flags; } /** * Set the edge flags. */ public void setFlags(int flags) { this.flags = flags; } /** * Return if given edge flag is set. * * @param flag the edge flag * @return true if the flag is set, false otherwise */ public boolean isFlagSet(int flag) { return (this.flags & flag) != 0; } /** * Is the edge an exception edge? */ public boolean isExceptionEdge() { return type == HANDLED_EXCEPTION_EDGE || type == UNHANDLED_EXCEPTION_EDGE; } public boolean equals(Object o) { if (this.getClass() != o.getClass()) return false; Edge other = (Edge) o; return this.getSource() == other.getSource() && this.getTarget() == other.getTarget() && this.getType() == other.getType(); } public int hashCode() { return 2003 * getSource().getLabel() + getTarget().getLabel(); } /** * Compare with other edge. */ public int compareTo(Edge other) { int cmp = super.compareTo(other); if (cmp != 0) return cmp; return type - other.type; } public String toString() { return formatAsString(false); } /** * Return a string representation of the edge. */ public String formatAsString(boolean reverse) { BasicBlock source = getSource(); BasicBlock target = getTarget(); StringBuffer buf = new StringBuffer(); buf.append(reverse ? "REVERSE_EDGE(" : "EDGE("); buf.append(getLabel()); buf.append(") type "); buf.append(edgeTypeToString(type)); buf.append(" from block "); buf.append(reverse ? target.getId() : source.getId()); buf.append(" to block "); buf.append(reverse ? source.getId() : target.getId()); InstructionHandle sourceInstruction = source.getLastInstruction(); InstructionHandle targetInstruction = target.getFirstInstruction(); String exInfo = " -> "; if (targetInstruction == null && target.isExceptionThrower()) { targetInstruction = target.getExceptionThrower(); exInfo = " => "; } if (sourceInstruction != null && targetInstruction != null) { buf.append(" [bytecode "); buf.append(sourceInstruction.getPosition()); buf.append(exInfo); buf.append(targetInstruction.getPosition()); buf.append(']'); } else if (source.isExceptionThrower()) { if (type == FALL_THROUGH_EDGE) buf.append(" [successful check]"); else { buf.append(" [failed check for "); buf.append(source.getExceptionThrower().getPosition()); if (targetInstruction != null) { buf.append(" to "); buf.append(targetInstruction.getPosition()); } buf.append(']'); } } return buf.toString(); } /** * Get string representing given edge type. */ public static String edgeTypeToString(int edgeType) { switch (edgeType) { case FALL_THROUGH_EDGE: return "FALL_THROUGH"; case IFCMP_EDGE: return "IFCMP"; case SWITCH_EDGE: return "SWITCH"; case SWITCH_DEFAULT_EDGE: return "SWITCH_DEFAULT"; case JSR_EDGE: return "JSR"; case RET_EDGE: return "RET"; case GOTO_EDGE: return "GOTO"; case RETURN_EDGE: return "RETURN"; case UNHANDLED_EXCEPTION_EDGE: return "UNHANDLED_EXCEPTION"; case HANDLED_EXCEPTION_EDGE: return "HANDLED_EXCEPTION"; case START_EDGE: return "START"; case BACKEDGE_TARGET_EDGE: return "BACKEDGE_TARGET_EDGE"; case BACKEDGE_SOURCE_EDGE: return "BACKEDGE_SOURCE_EDGE"; case EXIT_EDGE: return "EXIT_EDGE"; } throw new IllegalStateException("unknown edge type: " + edgeType); } /** * Get numeric edge type from string representation. */ public static int stringToEdgeType(String s) { s = s.toUpperCase(); if (s.equals("FALL_THROUGH")) return FALL_THROUGH_EDGE; else if (s.equals("IFCMP")) return IFCMP_EDGE; else if (s.equals("SWITCH")) return SWITCH_EDGE; else if (s.equals("SWITCH_DEFAULT")) return SWITCH_DEFAULT_EDGE; else if (s.equals("JSR")) return JSR_EDGE; else if (s.equals("RET")) return RET_EDGE; else if (s.equals("GOTO")) return GOTO_EDGE; else if (s.equals("RETURN")) return RETURN_EDGE; else if (s.equals("UNHANDLED_EXCEPTION")) return UNHANDLED_EXCEPTION_EDGE; else if (s.equals("HANDLED_EXCEPTION")) return HANDLED_EXCEPTION_EDGE; else if (s.equals("START")) return START_EDGE; else if (s.equals("BACKEDGE_TARGET_EDGE")) return BACKEDGE_TARGET_EDGE; else if (s.equals("BACKEDGE_SOURCE_EDGE")) return BACKEDGE_SOURCE_EDGE; else if (s.equals("EXIT_EDGE")) return EXIT_EDGE; else throw new IllegalArgumentException("Unknown edge type: " + s); } } // vim:ts=4
package com.qiniu.android.http.connectCheck; import com.qiniu.android.http.ResponseInfo; import com.qiniu.android.http.metrics.UploadSingleRequestMetrics; import com.qiniu.android.http.request.IRequestClient; import com.qiniu.android.http.request.Request; import com.qiniu.android.http.request.httpclient.SystemHttpClient; import com.qiniu.android.storage.GlobalConfiguration; import com.qiniu.android.utils.SingleFlight; import com.qiniu.android.utils.Wait; import org.json.JSONObject; public class ConnectChecker { private static SingleFlight<Boolean> singleFlight = new SingleFlight<>(); public static boolean check() { final CheckResult result = new CheckResult(); final Wait wait = new Wait(); check(new CheckCompleteHandler() { @Override public void complete(boolean isConnected) { result.isConnected = isConnected; wait.stopWait(); } }); wait.startWait(); return result.isConnected; } private static void check(final CheckCompleteHandler completeHandler) { try { singleFlight.perform("connect_check", new SingleFlight.ActionHandler<Boolean>() { @Override public void action(final SingleFlight.CompleteHandler<Boolean> singleFlightComplete) throws Exception { checkAllHosts(new CheckCompleteHandler() { @Override public void complete(boolean isConnected) { singleFlightComplete.complete(isConnected); } }); } }, new SingleFlight.CompleteHandler<Boolean>() { @Override public void complete(Boolean value) { completeHandler.complete(value); } }); } catch (Exception e) { completeHandler.complete(true); } } private static void checkAllHosts(final CheckCompleteHandler completeHandler) { String[] allHosts = GlobalConfiguration.getInstance().connectCheckURLStrings; if (allHosts == null) { completeHandler.complete(true); return; } allHosts = allHosts.clone(); final CheckStatus checkStatus = new CheckStatus(); checkStatus.totalCount = allHosts.length; for (String host : allHosts) { checkHost(host, new CheckCompleteHandler() { @Override public void complete(boolean isHostConnected) { synchronized (this) { checkStatus.completeCount += 1; } if (isHostConnected) { checkStatus.isConnected = true; } if (checkStatus.completeCount == checkStatus.totalCount) { completeHandler.complete(checkStatus.isConnected); } } }); } } private static void checkHost(String host, final CheckCompleteHandler completeHandler) { Request request = new Request(host, "HEAD", null, null, 3); SystemHttpClient client = new SystemHttpClient(); client.request(request, true, null, null, new IRequestClient.RequestClientCompleteHandler() { @Override public void complete(ResponseInfo responseInfo, UploadSingleRequestMetrics metrics, JSONObject response) { if (responseInfo.statusCode > 99) { completeHandler.complete(true); } else { completeHandler.complete(false); } } }); } private interface CheckCompleteHandler { void complete(boolean isConnected); } private static class CheckStatus { private int totalCount = 0; private int completeCount = 0; private boolean isConnected = false; } private static class CheckResult { private boolean isConnected = false; } }
package uk.org.ownage.dmdirc.ui; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.beans.PropertyVetoException; import javax.swing.ImageIcon; import uk.org.ownage.dmdirc.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JInternalFrame; import uk.org.ownage.dmdirc.logger.Logger; import uk.org.ownage.dmdirc.logger.ErrorLevel; import uk.org.ownage.dmdirc.ui.framemanager.FrameManager; import uk.org.ownage.dmdirc.ui.framemanager.tree.TreeFrameManager; /** * The main application frame * @author chris */ public class MainFrame extends javax.swing.JFrame implements WindowListener { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** * Singleton instance of MainFrame */ private static MainFrame me; /** * Whether the internal frames are maximised or not */ private boolean maximised = false; /** * The current number of pixels to displace new frames in the X direction */ private int xOffset = 0; /** * The current number of pixels to displace new frames in the Y direction */ private int yOffset = 0; /** * The main application icon */ private ImageIcon imageIcon; /** * The frame manager that's being used */ private FrameManager frameManager; /** * Returns the singleton instance of MainFrame * @return MainFrame instance */ public static MainFrame getMainFrame() { if (me == null) { me = new MainFrame(); } return me; } /** Creates new form MainFrame */ public MainFrame() { initComponents(); // Load an icon ClassLoader cldr = this.getClass().getClassLoader(); java.net.URL imageURL = cldr.getResource("uk/org/ownage/dmdirc/res/icon.png"); imageIcon = new ImageIcon(imageURL); setIconImage(imageIcon.getImage()); frameManager = new TreeFrameManager(); frameManager.setParent(jPanel1); setVisible(true); miAddServer.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { NewServerDialog.showNewServerDialog(); } }); toggleStateMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { try { getActiveFrame().setMaximum(!getActiveFrame().isMaximum()); } catch (PropertyVetoException ex) { Logger.error(ErrorLevel.WARNING, ex); } } }); addWindowListener(this); checkWindowState(); } /** * Adds the specified InternalFrame as a child of the main frame * @param frame the frame to be added */ public void addChild(JInternalFrame frame) { // Add the frame desktopPane.add(frame); // Make sure it'll fit with our offsets if (frame.getWidth()+xOffset > desktopPane.getWidth()) { xOffset = 0; } if (frame.getHeight()+yOffset > desktopPane.getHeight()) { yOffset = 0; } // Position the frame frame.setLocation(xOffset, yOffset); frame.moveToFront(); // Increase the offsets xOffset += 30; yOffset += 30; } /** * Removes the specified InternalFrame from our desktop pane * @param frame The frame to be removed */ public void delChild(JInternalFrame frame) { desktopPane.remove(frame); } /** * Retrieves the frame manager that's currently in use * @return The current frame manager */ public FrameManager getFrameManager() { return frameManager; } /** * Retrieves the application icon * @return The application icon */ public ImageIcon getIcon() { return imageIcon; } /** * Returns the JInternalFrame that is currently active * @return The active JInternalFrame */ public JInternalFrame getActiveFrame() { return desktopPane.getSelectedFrame(); } /** * Sets whether or not the internal frame state is currently maximised * @param max whether the frame is maxomised */ public void setMaximised(boolean max) { maximised = max; if (max) { if (getActiveFrame() != null) { setTitle("DMDirc - "+getActiveFrame().getTitle()); } } else { setTitle("DMDirc"); } checkWindowState(); } /** * Gets whether or not the internal frame state is currently maximised * @return True iff frames should be maximised, false otherwise */ public boolean getMaximised() { return maximised; } /** * Checks the current state of the internal frames, and configures the * window menu to behave appropriately */ private void checkWindowState() { if (getActiveFrame() == null) { toggleStateMenuItem.setEnabled(false); return; } toggleStateMenuItem.setEnabled(true); if (maximised) { toggleStateMenuItem.setText("Restore"); toggleStateMenuItem.setMnemonic('r'); toggleStateMenuItem.invalidate(); } else { toggleStateMenuItem.setText("Maximise"); toggleStateMenuItem.setMnemonic('m'); toggleStateMenuItem.invalidate(); } } /** * Called when the window is opened. Not implemented. * @param windowEvent The event associated with this callback */ public void windowOpened(WindowEvent windowEvent) { } /** * Called when the window is closing. Saves the config and has all servers * disconnect with the default close method * @param windowEvent The event associated with this callback */ public void windowClosing(WindowEvent windowEvent) { ServerManager.getServerManager().closeAll(Config.getOption("general","closemessage")); Config.save(); } /** * Called when the window is closed. Not implemented. * @param windowEvent The event associated with this callback */ public void windowClosed(WindowEvent windowEvent) { } /** * Called when the window is iconified. Not implemented. * @param windowEvent The event associated with this callback */ public void windowIconified(WindowEvent windowEvent) { } /** * Called when the window is deiconified. Not implemented. * @param windowEvent The event associated with this callback */ public void windowDeiconified(WindowEvent windowEvent) { } /** * Called when the window is activated. Not implemented. * @param windowEvent The event associated with this callback */ public void windowActivated(WindowEvent windowEvent) { } /** * Called when the window is deactivated. Not implemented. * @param windowEvent The event associated with this callback */ public void windowDeactivated(WindowEvent windowEvent) { } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { desktopPane = new javax.swing.JDesktopPane(); jPanel1 = new javax.swing.JPanel(); jMenuBar1 = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); miAddServer = new javax.swing.JMenuItem(); windowMenu = new javax.swing.JMenu(); toggleStateMenuItem = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("DMDirc"); desktopPane.setBackground(new java.awt.Color(238, 238, 238)); org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 135, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 493, Short.MAX_VALUE) ); fileMenu.setMnemonic('f'); fileMenu.setText("File"); miAddServer.setText("New Server..."); fileMenu.add(miAddServer); jMenuBar1.add(fileMenu); windowMenu.setMnemonic('w'); windowMenu.setText("Window"); toggleStateMenuItem.setMnemonic('m'); toggleStateMenuItem.setText("Maximise"); windowMenu.add(toggleStateMenuItem); jMenuBar1.add(windowMenu); setJMenuBar(jMenuBar1); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(desktopPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 611, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, desktopPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 493, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JDesktopPane desktopPane; private javax.swing.JMenu fileMenu; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JPanel jPanel1; private javax.swing.JMenuItem miAddServer; private javax.swing.JMenuItem toggleStateMenuItem; private javax.swing.JMenu windowMenu; // End of variables declaration//GEN-END:variables }
package com.qiniu.android.http.connectCheck; import com.qiniu.android.http.ResponseInfo; import com.qiniu.android.http.metrics.UploadSingleRequestMetrics; import com.qiniu.android.http.request.IRequestClient; import com.qiniu.android.http.request.Request; import com.qiniu.android.http.request.httpclient.SystemHttpClient; import com.qiniu.android.storage.GlobalConfiguration; import com.qiniu.android.utils.LogUtil; import com.qiniu.android.utils.SingleFlight; import com.qiniu.android.utils.Wait; import org.json.JSONObject; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ConnectChecker { private static ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); private static SingleFlight<UploadSingleRequestMetrics> singleFlight = new SingleFlight<>(); public static boolean isConnected(UploadSingleRequestMetrics metrics) { return metrics != null && metrics.response != null && metrics.response.statusCode > 99; } public static UploadSingleRequestMetrics check() { final CheckResult result = new CheckResult(); final Wait wait = new Wait(); check(new CheckCompleteHandler() { @Override public void complete(UploadSingleRequestMetrics metrics) { result.metrics = metrics; wait.stopWait(); } }); wait.startWait(); return result.metrics; } private static void check(final CheckCompleteHandler completeHandler) { try { singleFlight.perform("connect_check", new SingleFlight.ActionHandler<UploadSingleRequestMetrics>() { @Override public void action(final SingleFlight.CompleteHandler<UploadSingleRequestMetrics> singleFlightComplete) throws Exception { checkAllHosts(new CheckCompleteHandler() { @Override public void complete(UploadSingleRequestMetrics metrics) { singleFlightComplete.complete(metrics); } }); } }, new SingleFlight.CompleteHandler<UploadSingleRequestMetrics>() { @Override public void complete(UploadSingleRequestMetrics metrics) { completeHandler.complete(metrics); } }); } catch (Exception e) { completeHandler.complete(null); } } private static void checkAllHosts(final CheckCompleteHandler completeHandler) { String[] allHosts = GlobalConfiguration.getInstance().connectCheckURLStrings; if (allHosts == null) { completeHandler.complete(null); return; } allHosts = allHosts.clone(); final CheckStatus checkStatus = new CheckStatus(); checkStatus.totalCount = allHosts.length; checkStatus.completeCount = 0; checkStatus.isCompleted = false; for (String host : allHosts) { checkHost(host, new CheckCompleteHandler() { @Override public void complete(UploadSingleRequestMetrics metrics) { boolean isHostConnected = isConnected(metrics); synchronized (checkStatus) { checkStatus.completeCount += 1; } if (isHostConnected || checkStatus.completeCount == checkStatus.totalCount) { synchronized (checkStatus) { if (checkStatus.isCompleted) { LogUtil.i("== check all hosts has completed totalCount:" + checkStatus.totalCount + " completeCount:" + checkStatus.completeCount); return; } else { LogUtil.i("== check all hosts completed totalCount:" + checkStatus.totalCount + " completeCount:" + checkStatus.completeCount); checkStatus.isCompleted = true; } } completeHandler.complete(metrics); } else { LogUtil.i("== check all hosts not completed totalCount:" + checkStatus.totalCount + " completeCount:" + checkStatus.completeCount); } } }); } } private static void checkHost(final String host, final CheckCompleteHandler completeHandler) { final boolean[] hasCallback = {false}; int timeout = GlobalConfiguration.getInstance().connectCheckTimeout; final UploadSingleRequestMetrics timeoutMetrics = new UploadSingleRequestMetrics(); timeoutMetrics.start(); executorService.schedule(new Callable<Object>() { @Override public Object call() throws Exception { synchronized (this) { if (hasCallback[0]) { return null; } hasCallback[0] = true; } timeoutMetrics.end(); completeHandler.complete(timeoutMetrics); return null; } }, timeout, TimeUnit.SECONDS); Request request = new Request(host, Request.HttpMethodHEAD, null, null, timeout); SystemHttpClient client = new SystemHttpClient(); LogUtil.i("== checkHost:" + host); client.request(request, true, null, null, new IRequestClient.RequestClientCompleteHandler() { @Override public void complete(ResponseInfo responseInfo, UploadSingleRequestMetrics metrics, JSONObject response) { synchronized (this) { if (hasCallback[0]) { return; } hasCallback[0] = true; } LogUtil.i("== checkHost:" + host + " responseInfo:" + responseInfo); completeHandler.complete(metrics); } }); } private interface CheckCompleteHandler { void complete(UploadSingleRequestMetrics metrics); } private static class CheckStatus { private int totalCount = 0; private int completeCount = 0; private boolean isCompleted = false; } private static class CheckResult { private UploadSingleRequestMetrics metrics; } }
package com.xunsoft.location; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.amap.api.location.AMapLocation; import com.amap.api.location.AMapLocationClient; import com.amap.api.location.AMapLocationClientOption; import com.amap.api.location.AMapLocationListener; import com.amap.api.location.AMapLocationClientOption.AMapLocationMode; public class Location extends CordovaPlugin { private static String TAG="location"; public boolean stopListen = true; public AMapLocationClient mLocationClient = null; public CallbackContext context=null; public AMapLocationListener mLocationListener = new AMapLocationListener(){ @Override public void onLocationChanged(AMapLocation arg0) { // TODO Auto-generated method stub Log.d(TAG, "location finished"); if(arg0.getErrorCode()==0){ JSONObject r = new JSONObject(); try { r.put("locationType", arg0.getLocationType()); r.put("latitude", arg0.getLatitude()); r.put("longitude", arg0.getLongitude()); r.put("accuracy", arg0.getAccuracy()); r.put("altitude", arg0.getAltitude()); r.put("address", arg0.getAddress()); r.put("country", arg0.getCountry()); r.put("province", arg0.getProvince()); r.put("city", arg0.getCity()); r.put("district", arg0.getDistrict()); r.put("street", arg0.getStreet()); r.put("locationDetail", arg0.getLocationDetail()); Log.d(TAG,r.toString()); //context.success(r); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, r); pluginResult.setKeepCallback(true); context.sendPluginResult(pluginResult); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else{ JSONObject r = new JSONObject(); try{ r.put("code", arg0.getErrorCode()); r.put("message", arg0.getErrorInfo()); Log.d(TAG,r.toString()); context.error(r); }catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(stopListen) { mLocationClient.stopLocation(); mLocationClient.onDestroy(); } } }; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { context=callbackContext; Log.d(TAG, "We are entering execute"); if(action.equals("getCurrentPosition")){ stopListen = true; if(mLocationClient!=null) { mLocationClient.stopLocation(); mLocationClient.onDestroy(); } mLocationClient=new AMapLocationClient(this.cordova.getActivity().getApplicationContext()); AMapLocationClientOption mLocationOption=new AMapLocationClientOption(); mLocationOption.setOnceLocation(true); mLocationOption.setInterval(1000); mLocationOption.setNeedAddress(true); mLocationOption.setHttpTimeOut(100000); mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy); mLocationClient.setLocationListener(mLocationListener); mLocationClient.setLocationOption(mLocationOption); mLocationClient.startLocation(); } else if(action.equals("watchPosition")){ stopListen = false; if(mLocationClient!=null) { mLocationClient.stopLocation(); mLocationClient.onDestroy(); } mLocationClient=new AMapLocationClient(this.cordova.getActivity().getApplicationContext()); AMapLocationClientOption mLocationOption=new AMapLocationClientOption(); mLocationOption.setOnceLocation(false); mLocationOption.setInterval(1000); mLocationOption.setNeedAddress(true); mLocationOption.setHttpTimeOut(100000); mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy); mLocationClient.setLocationListener(mLocationListener); mLocationClient.setLocationOption(mLocationOption); mLocationClient.startLocation(); } else if(action.equals("clearWatch")) { if (mLocationClient != null && mLocationClient.isStarted()) { mLocationClient.stopLocation(); mLocationClient.onDestroy(); } } return true; } }
package com.codespair.mockstocks; import com.codespair.mockstocks.service.kafka.spring.producer.StockQuoteGenerator; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import javax.annotation.PostConstruct; @Slf4j @SpringBootApplication @EnableAsync public class MockStocksApplication { private StockQuoteGenerator stockQuoteGenerator; protected MockStocksApplication(StockQuoteGenerator stockQuoteGenerator) { this.stockQuoteGenerator = stockQuoteGenerator; } @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(25); return executor; } @SuppressWarnings("squid:S2095") public static void main(String[] args) { SpringApplication.run(MockStocksApplication.class, args); } @SuppressWarnings("squid:S2189") // avoid being marked by check for infinite loop from sonarqube @PostConstruct public void startQuoteGeneration() { try { stockQuoteGenerator.startGenerator(); } catch (InterruptedException e) { log.error("Error starting stock quotes generation", e.getMessage(), e); } } }
package com.haulmont.cuba.web.gui.components.filter; import com.haulmont.bali.util.Dom4j; import com.haulmont.chile.core.model.MetaClass; import com.haulmont.chile.core.model.MetaProperty; import com.haulmont.cuba.core.global.MessageProvider; import com.haulmont.cuba.gui.AppConfig; import com.haulmont.cuba.gui.UserSessionClient; import com.haulmont.cuba.gui.components.IFrame; import com.haulmont.cuba.gui.components.ValuePathHelper; import com.haulmont.cuba.gui.data.CollectionDatasource; import com.haulmont.cuba.security.entity.FilterEntity; import com.haulmont.cuba.web.App; import com.haulmont.cuba.web.gui.components.WebComponentsHelper; import com.haulmont.cuba.web.gui.components.WebFilter; import com.vaadin.data.Property; import com.vaadin.event.Action; import com.vaadin.ui.*; import com.vaadin.ui.themes.BaseTheme; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.dom4j.Element; import java.util.*; import java.util.regex.Pattern; import static org.apache.commons.lang.BooleanUtils.isTrue; public class FilterEditor { private WebFilter webFilter; private FilterEntity filterEntity; private Element filterDescriptor; private MetaClass metaClass; private CollectionDatasource datasource; private List<ConditionDescriptor> descriptors = new ArrayList<ConditionDescriptor>(); private List<String> existingNames; private List<Condition> conditions = new ArrayList<Condition>(); private AbstractOrderedLayout layout; private TextField nameField; private Table table; private String messagesPack; private String filterComponentName; private AbstractSelect addSelect; private static final String EDITOR_WIDTH = "640px"; private static final String TABLE_WIDTH = "600px"; private static List<String> defaultExcludedProps = Arrays.asList("version"); private CheckBox globalCb; private Button saveBtn; private Button upBtn; private Button downBtn; public FilterEditor(final WebFilter webFilter, FilterEntity filterEntity, Element filterDescriptor, List<String> existingNames) { this.webFilter = webFilter; this.filterEntity = filterEntity; this.filterDescriptor = filterDescriptor; this.datasource = webFilter.getDatasource(); this.messagesPack = webFilter.getFrame().getMessagesPack(); this.metaClass = datasource.getMetaClass(); this.existingNames = existingNames; String[] strings = ValuePathHelper.parse(filterEntity.getComponentId()); this.filterComponentName = ValuePathHelper.format(Arrays.copyOfRange(strings, 1, strings.length)); parseDescriptorXml(); FilterParser parser = new FilterParser(this.filterEntity.getXml(), messagesPack, filterComponentName, datasource); this.conditions = parser.fromXml().getConditions(); } public void init() { layout = new VerticalLayout(); layout.setSpacing(true); layout.setMargin(true, false, false, false); layout.setWidth(EDITOR_WIDTH); GridLayout topGrid = new GridLayout(2, 1); topGrid.setWidth("100%"); topGrid.setSpacing(true); GridLayout bottomGrid = new GridLayout(2, 1); bottomGrid.setWidth("100%"); bottomGrid.setSpacing(true); HorizontalLayout controlLayout = new HorizontalLayout(); controlLayout.setSpacing(true); // Move up button upBtn = WebComponentsHelper.createButton("icons/up.png"); upBtn.addListener(new Button.ClickListener() { public void buttonClick(Button.ClickEvent event) { Object item = table.getValue(); if (item != table.getNullSelectionItemId()) { Condition condition = (Condition) item; int index = conditions.indexOf(condition); if (index > 0) { Condition next = conditions.get(index - 1); conditions.set(index - 1, condition); conditions.set(index, next); updateTable(); } } } }); upBtn.setEnabled(true); // Move down button downBtn = WebComponentsHelper.createButton("icons/down.png"); downBtn.addListener(new Button.ClickListener() { public void buttonClick(Button.ClickEvent event) { Object item = table.getValue(); if (item != table.getNullSelectionItemId()) { Condition condition = (Condition) item; int index = conditions.indexOf(condition); int count = conditions.size(); if (index < count - 1) { Condition next = conditions.get(index + 1); conditions.set(index + 1, condition); conditions.set(index, next); updateTable(); } } } }); downBtn.setEnabled(true); // Save button saveBtn = WebComponentsHelper.createButton("icons/ok.png"); saveBtn.setCaption(MessageProvider.getMessage(AppConfig.getInstance().getMessagesPack(), "actions.Ok")); saveBtn.addListener(new Button.ClickListener() { public void buttonClick(Button.ClickEvent event) { if (commit()) webFilter.editorCommitted(); } }); if (filterEntity.getCode() != null) saveBtn.setEnabled(false); controlLayout.addComponent(saveBtn); // Cancel button Button cancelBtn = WebComponentsHelper.createButton("icons/cancel.png"); cancelBtn.setCaption(MessageProvider.getMessage(AppConfig.getInstance().getMessagesPack(), "actions.Cancel")); cancelBtn.addListener(new Button.ClickListener() { public void buttonClick(Button.ClickEvent event) { webFilter.editorCancelled(); } }); controlLayout.addComponent(cancelBtn); bottomGrid.addComponent(controlLayout, 0, 0); globalCb = new CheckBox(); globalCb.setCaption(getMessage("FilterEditor.global")); globalCb.setValue(filterEntity.getUser() == null); globalCb.setEnabled(UserSessionClient.getUserSession().isSpecificPermitted("cuba.gui.filter.global")); controlLayout.addComponent(globalCb); bottomGrid.addComponent(globalCb, 1, 0); bottomGrid.setComponentAlignment(globalCb, Alignment.MIDDLE_RIGHT); HorizontalLayout nameLayout = new HorizontalLayout(); nameLayout.setSpacing(true); Label label = new Label(getMessage("FilterEditor.nameLab")); nameLayout.addComponent(label); nameField = new TextField(); nameField.setValue(filterEntity.getName()); nameField.setWidth("200px"); nameLayout.addComponent(nameField); topGrid.addComponent(nameLayout, 0, 0); topGrid.setWidth(TABLE_WIDTH); HorizontalLayout addLayout = new HorizontalLayout(); addLayout.setSpacing(true); initAddSelect(addLayout); topGrid.addComponent(addLayout, 1, 0); topGrid.setComponentAlignment(addLayout, Alignment.MIDDLE_RIGHT); HorizontalLayout hlayLayout = new HorizontalLayout(); hlayLayout.setSpacing(true); VerticalLayout controlsAndtable = new VerticalLayout(); controlsAndtable.addComponent(topGrid); controlsAndtable.setSpacing(true); initTable(controlsAndtable); hlayLayout.addComponent(controlsAndtable); VerticalLayout upDownLayout = new VerticalLayout(); upDownLayout.setSpacing(true); upDownLayout.addComponent(upBtn); upDownLayout.addComponent(downBtn); hlayLayout.addComponent(upDownLayout); hlayLayout.setComponentAlignment(upDownLayout,Alignment.MIDDLE_CENTER); layout.addComponent(hlayLayout); layout.addComponent(bottomGrid); updateControls(); } private void initAddSelect(AbstractLayout layout) { Label label = new Label(getMessage("FilterEditor.addCondition")); layout.addComponent(label); addSelect = new Select(); addSelect.setImmediate(true); addSelect.setNullSelectionAllowed(true); addSelect.setWidth("100px"); for (ConditionDescriptor descriptor : descriptors) { addSelect.addItem(descriptor); addSelect.setItemCaption(descriptor, descriptor.getLocCaption()); } if (UserSessionClient.getUserSession().isSpecificPermitted("cuba.gui.filter.customConditions")) { ConditionCreator conditionCreator = new ConditionCreator(filterComponentName, datasource); addSelect.addItem(conditionCreator); addSelect.setItemCaption(conditionCreator, conditionCreator.getLocCaption()); } addSelect.addListener(new Property.ValueChangeListener() { public void valueChange(Property.ValueChangeEvent event) { if (addSelect.getValue() != null) { addCondition((ConditionDescriptor) addSelect.getValue()); addSelect.select(null); } } }); layout.addComponent(addSelect); } private void initTable(AbstractLayout layout) { table = new com.haulmont.cuba.web.toolkit.ui.Table(); table.setImmediate(true); table.setSelectable(true); table.setPageLength(0); table.setWidth(TABLE_WIDTH); table.setHeight("200px"); table.setStyleName("filter-conditions"); String nameCol = getMessage("FilterEditor.column.name"); String opCol = getMessage("FilterEditor.column.op"); String paramCol = getMessage("FilterEditor.column.param"); String hiddenCol = getMessage("FilterEditor.column.hidden"); String cntrCol = getMessage("FilterEditor.column.control"); table.addContainerProperty(nameCol, NameEditor.class, null); table.setColumnWidth(nameCol, 160); table.addContainerProperty(opCol, OperationEditor.class, null); table.setColumnWidth(opCol, 100); table.addContainerProperty(paramCol, ParamEditor.class, null); table.setColumnWidth(paramCol, 160); table.addContainerProperty(hiddenCol, CheckBox.class, null); table.setColumnWidth(cntrCol, 50); table.addContainerProperty(cntrCol, Button.class, null); table.setColumnWidth(cntrCol, 30); for (final Condition condition : this.conditions) { NameEditor nameEditor = new NameEditor(condition); OperationEditor operationEditor = condition.createOperationEditor(); ParamEditor paramEditor = new ParamEditor(condition, false); table.addItem(new Object[]{ nameEditor, operationEditor, paramEditor, createHiddenCheckbox(condition), createDeleteConditionBtn(condition) }, condition ); } final Action showNameAction = new Action(MessageProvider.getMessage(getClass(), "FilterEditor.showNameAction")); table.addActionHandler( new Action.Handler() { public Action[] getActions(Object target, Object sender) { return new Action[]{showNameAction}; } public void handleAction(Action action, Object sender, Object target) { if (action.equals(showNameAction)) { App.getInstance().getWindowManager().showMessageDialog( MessageProvider.getMessage(getClass(), "FilterEditor.showNameTitle"), ((Condition) target).getParam().getName(), IFrame.MessageType.CONFIRMATION ); } } } ); layout.addComponent(table); } private String getMessage(String key) { return MessageProvider.getMessage(getClass(), key); } private void addCondition(ConditionDescriptor descriptor) { Condition condition = descriptor.createCondition(); conditions.add(condition); NameEditor nameEditor = new NameEditor(condition); OperationEditor operationEditor = condition.createOperationEditor(); ParamEditor paramEditor = new ParamEditor(condition, false); table.addItem(new Object[]{ nameEditor, operationEditor, paramEditor, createHiddenCheckbox(condition), createDeleteConditionBtn(condition) }, condition ); updateControls(); } private void deleteCondition(Condition condition) { conditions.remove(condition); table.removeItem(condition); updateControls(); } private void updateControls() { if (filterEntity.getCode() == null) saveBtn.setEnabled(!conditions.isEmpty()); else saveBtn.setEnabled(false); } private void updateTable() { table.removeAllItems(); for (final Condition condition : this.conditions) { NameEditor nameEditor = new NameEditor(condition); OperationEditor operationEditor = condition.createOperationEditor(); ParamEditor paramEditor = new ParamEditor(condition, false); table.addItem(new Object[]{ nameEditor, operationEditor, paramEditor, createHiddenCheckbox(condition), createDeleteConditionBtn(condition) }, condition ); } updateControls(); } private Button createDeleteConditionBtn(final Condition condition) { Button delBtn = WebComponentsHelper.createButton("icons/tab-remove.png"); delBtn.setStyleName(BaseTheme.BUTTON_LINK); delBtn.addListener(new Button.ClickListener() { public void buttonClick(Button.ClickEvent event) { deleteCondition(condition); } }); return delBtn; } private CheckBox createHiddenCheckbox(final Condition condition) { final CheckBox checkBox = new CheckBox(); checkBox.setValue(condition.isHidden()); checkBox.addListener(new Button.ClickListener() { public void buttonClick(Button.ClickEvent event) { boolean hidden = BooleanUtils.isTrue((Boolean) checkBox.getValue()); condition.setHidden(hidden); } }); return checkBox; } private void parseDescriptorXml() { for (Element element : Dom4j.elements(filterDescriptor)) { ConditionDescriptor conditionDescriptor; if ("properties".equals(element.getName())) { addMultiplePropertyDescriptors(element, filterComponentName); } else if ("property".equals(element.getName())) { conditionDescriptor = new PropertyConditionDescriptor(element, messagesPack, filterComponentName, datasource); descriptors.add(conditionDescriptor); } else if ("custom".equals(element.getName())) { conditionDescriptor = new CustomConditionDescriptor(element, messagesPack, filterComponentName, datasource); descriptors.add(conditionDescriptor); } else throw new UnsupportedOperationException("Element not supported: " + element.getName()); } Collections.sort(descriptors, new Comparator<ConditionDescriptor>() { public int compare(ConditionDescriptor cd1, ConditionDescriptor cd2) { return cd1.getLocCaption().compareTo(cd2.getLocCaption()); } }); } private void addMultiplePropertyDescriptors(Element element, String filterComponentName) { List<String> includedProps = new ArrayList<String>(); String inclRe = element.attributeValue("include"); Pattern inclPattern = Pattern.compile(inclRe); for (MetaProperty property : metaClass.getProperties()) { if (property.getRange().getCardinality().isMany()) continue; if (defaultExcludedProps.contains(property.getName())) continue; if (inclPattern.matcher(property.getName()).matches()) { includedProps.add(property.getName()); } } String exclRe = element.attributeValue("exclude"); Pattern exclPattern = null; if (!StringUtils.isBlank(exclRe)) exclPattern = Pattern.compile(exclRe); for (String prop : includedProps) { if (exclPattern == null || !exclPattern.matcher(prop).matches()) { ConditionDescriptor conditionDescriptor = new PropertyConditionDescriptor(prop, null, messagesPack, filterComponentName, datasource); descriptors.add(conditionDescriptor); } } } public AbstractOrderedLayout getLayout() { return layout; } public FilterEntity getFilterEntity() { return filterEntity; } public boolean commit() { if (existingNames.contains(nameField.getValue())) { App.getInstance().getAppWindow().showNotification( getMessage("FilterEditor.commitError"), getMessage("FilterEditor.nameAlreadyExists"), Window.Notification.TYPE_HUMANIZED_MESSAGE); return false; } StringBuilder sb = new StringBuilder(); for (Condition condition : conditions) { String error = condition.getError(); if (error != null) sb.append(error).append("\n"); } if (sb.length() > 0) { App.getInstance().getAppWindow().showNotification( getMessage("FilterEditor.commitError"), sb.toString(), Window.Notification.TYPE_HUMANIZED_MESSAGE); return false; } FilterParser parser = new FilterParser(conditions, messagesPack, filterComponentName, datasource); String xml = parser.toXml().getXml(); filterEntity.setName((String) nameField.getValue()); filterEntity.setXml(xml); if (isTrue((Boolean) globalCb.getValue())) filterEntity.setUser(null); else filterEntity.setUser(UserSessionClient.getUserSession().getCurrentOrSubstitutedUser()); return true; } public List<Condition> getConditions() { return conditions; } }
package com.nepxion.thunder.common.util; public class StringUtil { public static String firstLetterToUpper(String value) { Character character = Character.toUpperCase(value.charAt(0)); return character.toString().concat(value.substring(1)); } public static String firstLetterToLower(String value) { Character character = Character.toLowerCase(value.charAt(0)); return character.toString().concat(value.substring(1)); } /*public static String firstLetterToUpper(String value){ char[] array = value.toCharArray(); array[0] -= 32; return String.valueOf(array); } public static String firstLetterToLower(String value){ char[] array = value.toCharArray(); array[0] += 32; return String.valueOf(array); }*/ }
package org.nuxeo.ecm.platform.ws; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.jws.soap.SOAPBinding.Style; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.annotation.ejb.SerializedConcurrentAccess; import org.nuxeo.common.utils.Base64; import org.nuxeo.ecm.core.api.Blob; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DataModel; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentModelList; import org.nuxeo.ecm.core.api.DocumentRef; import org.nuxeo.ecm.core.api.IdRef; import org.nuxeo.ecm.core.api.NuxeoGroup; import org.nuxeo.ecm.core.api.NuxeoPrincipal; import org.nuxeo.ecm.core.api.impl.DocumentModelImpl; import org.nuxeo.ecm.core.api.impl.blob.StreamingBlob; import org.nuxeo.ecm.core.api.security.ACE; import org.nuxeo.ecm.core.api.security.ACL; import org.nuxeo.ecm.core.api.security.ACP; import org.nuxeo.ecm.core.api.security.impl.ACLImpl; import org.nuxeo.ecm.platform.api.ws.DocumentBlob; import org.nuxeo.ecm.platform.api.ws.DocumentDescriptor; import org.nuxeo.ecm.platform.api.ws.DocumentProperty; import org.nuxeo.ecm.platform.api.ws.DocumentSnapshot; import org.nuxeo.ecm.platform.api.ws.NuxeoRemoting; import org.nuxeo.ecm.platform.api.ws.session.WSRemotingSession; import org.nuxeo.ecm.platform.mimetype.MimetypeDetectionException; import org.nuxeo.ecm.platform.mimetype.interfaces.MimetypeRegistry; import org.nuxeo.runtime.api.Framework; /** * Nuxeo remoting stateful session bean. * * @author <a href="mailto:ja@nuxeo.com">Julien Anguenot</a> */ @Stateless @SerializedConcurrentAccess @Local(NuxeoRemoting.class) @Remote(NuxeoRemoting.class) @WebService(name = "NuxeoRemotingInterface", serviceName = "NuxeoRemotingService") @SOAPBinding(style = Style.DOCUMENT) // @SecurityDomain("nuxeo-ecm") // @PortComponent(authMethod="BASIC", transportGuarantee="NONE", // configName="Standard WSSecurity Endpoint") public class NuxeoRemotingBean extends AbstractNuxeoWebService implements NuxeoRemoting { private static final long serialVersionUID = 359922583442116202L; @SuppressWarnings("unused") private static final Log log = LogFactory.getLog(NuxeoRemotingBean.class); @WebMethod public String getRepositoryName(String sid) throws ClientException { WSRemotingSession rs = initSession(sid); return rs.getRepository(); } @WebMethod public ACE[] getDocumentACL(String sid, String uuid) throws ClientException { WSRemotingSession rs = initSession(sid); ACP acp = rs.getDocumentManager().getACP(new IdRef(uuid)); if (acp != null) { ACL acl = acp.getMergedACLs("MergedACL"); return acl.toArray(new ACE[acl.size()]); } else { return null; } } @WebMethod public DocumentSnapshot getDocumentSnapshot(String sid, String uuid) throws ClientException { WSRemotingSession rs = initSession(sid); DocumentModel doc = rs.getDocumentManager().getDocument(new IdRef(uuid)); DocumentProperty[] props = getDocumentNoBlobProperties(doc, rs); DocumentBlob[] blobs = getDocumentBlobs(doc, rs); ACE[] resACP=null; ACP acp = doc.getACP(); if (acp != null) { ACL acl = acp.getMergedACLs("MergedACL"); resACP= acl.toArray(new ACE[acl.size()]); } DocumentSnapshot ds = new DocumentSnapshot(props,blobs,doc.getPathAsString(),resACP); return ds; } @WebMethod public ACE[] getDocumentLocalACL(String sid, String uuid) throws ClientException { WSRemotingSession rs = initSession(sid); ACP acp = rs.getDocumentManager().getACP(new IdRef(uuid)); if (acp != null) { ACL mergedAcl = new ACLImpl("MergedACL", true); for (ACL acl : acp.getACLs()) { if (!ACL.INHERITED_ACL.equals(acl.getName())) { mergedAcl.addAll(acl); } } return mergedAcl.toArray(new ACE[mergedAcl.size()]); } else { return null; } } public boolean hasPermission(String sid, String uuid, String permission) throws ClientException { WSRemotingSession rs = initSession(sid); CoreSession docMgr = rs.getDocumentManager(); DocumentModel doc = docMgr.getDocument(new IdRef(uuid)); if (doc == null) { throw new ClientException("No such document: " + uuid); } return docMgr.hasPermission(doc.getRef(), permission); } @WebMethod public DocumentBlob[] getDocumentBlobs(String sid, String uuid) throws ClientException { WSRemotingSession rs = initSession(sid); DocumentModel doc = rs.getDocumentManager().getDocument(new IdRef(uuid)); if (doc == null) { return null; } return getDocumentBlobs(doc, rs); } protected DocumentBlob[] getDocumentBlobs(DocumentModel doc, WSRemotingSession rs) throws ClientException { List<DocumentBlob> blobs = new ArrayList<DocumentBlob>(); String[] schemas = doc.getDeclaredSchemas(); for (String schema : schemas) { DataModel dm = doc.getDataModel(schema); Map<String, Object> map = dm.getMap(); for (Map.Entry<String, Object> entry : map.entrySet()) { collectBlobs(rs, "", map, entry.getKey(), entry.getValue(), blobs); } } return blobs.toArray(new DocumentBlob[blobs.size()]); } @WebMethod public String[] listUsers(String sid, int from, int to) throws ClientException { WSRemotingSession rs = initSession(sid); List<NuxeoPrincipal> principals = rs.getUserManager().getAvailablePrincipals(); String[] users = new String[principals.size()]; int i = 0; for (NuxeoPrincipal user : principals) { users[i++] = user.getName(); } return users; } @WebMethod public String[] listGroups(String sid, int from, int to) throws ClientException { WSRemotingSession rs = initSession(sid); List<NuxeoGroup> ngroups = rs.getUserManager().getAvailableGroups(); String[] groups = new String[ngroups.size()]; int i = 0; for (NuxeoGroup group : ngroups) { groups[i++] = group.getName(); } return groups; } @WebMethod public DocumentProperty[] getDocumentProperties(String sid, String uuid) throws ClientException { WSRemotingSession rs = initSession(sid); DocumentModel doc = rs.getDocumentManager().getDocument(new IdRef(uuid)); List<DocumentProperty> props = new ArrayList<DocumentProperty>(); if (doc != null) { String[] schemas = doc.getDeclaredSchemas(); for (String schema : schemas) { DataModel dm = doc.getDataModel(schema); Map<String, Object> map = dm.getMap(); for (Map.Entry<String, Object> entry : map.entrySet()) { collectProperty("", entry.getKey(), entry.getValue(), props); } } } return props.toArray(new DocumentProperty[props.size()]); } @WebMethod public DocumentProperty[] getDocumentNoBlobProperties(String sid, String uuid) throws ClientException { WSRemotingSession rs = initSession(sid); DocumentModel doc = rs.getDocumentManager().getDocument(new IdRef(uuid)); return getDocumentNoBlobProperties(doc, rs); } protected DocumentProperty[] getDocumentNoBlobProperties(DocumentModel doc, WSRemotingSession rs) throws ClientException { List<DocumentProperty> props = new ArrayList<DocumentProperty>(); if (doc != null) { String[] schemas = doc.getDeclaredSchemas(); for (String schema : schemas) { DataModel dm = doc.getDataModel(schema); Map<String, Object> map = dm.getMap(); for (Map.Entry<String, Object> entry : map.entrySet()) { collectNoBlobProperty("", entry.getKey(), entry.getValue(), props); } } } return props.toArray(new DocumentProperty[props.size()]); } public DocumentDescriptor getCurrentVersion(String sid, String uuid) throws ClientException { WSRemotingSession rs = initSession(sid); DocumentModel doc = rs.getDocumentManager().getLastDocumentVersion( new IdRef(uuid)); if (doc != null) { return new DocumentDescriptor(doc, (String) doc.getContextData("version.label")); // TODO } return null; } public DocumentDescriptor getSourceDocument(String sid, String uid) throws ClientException { WSRemotingSession rs = initSession(sid); DocumentModel doc = rs.getDocumentManager().getDocument(new IdRef(uid)); String srcid = doc.getSourceId(); if (srcid != null) { if (srcid != uid) { doc = rs.getDocumentManager().getSourceDocument(doc.getRef()); } } if (doc != null) { return new DocumentDescriptor(doc); } return null; } public DocumentDescriptor[] getVersions(String sid, String uid) throws ClientException { WSRemotingSession rs = initSession(sid); List<DocumentModel> versions = rs.getDocumentManager().getVersions( new IdRef(uid)); if (versions == null) { return null; } DocumentDescriptor[] docs = new DocumentDescriptor[versions.size()]; int i = 0; for (DocumentModel version : versions) { docs[i++] = new DocumentDescriptor(version, (String) version.getContextData("version.label")); } return null; } @WebMethod public DocumentDescriptor getRootDocument(String sessionId) throws ClientException { WSRemotingSession rs = initSession(sessionId); DocumentModel doc = rs.getDocumentManager().getRootDocument(); return doc != null ? new DocumentDescriptor(doc) : null; } @WebMethod public DocumentDescriptor getDocument(String sessionId, String uuid) throws ClientException { WSRemotingSession rs = initSession(sessionId); DocumentModel doc = rs.getDocumentManager().getDocument(new IdRef(uuid)); return doc != null ? new DocumentDescriptor(doc) : null; } @WebMethod public DocumentDescriptor[] getChildren(String sessionId, String uuid) throws ClientException { WSRemotingSession rs = initSession(sessionId); DocumentModelList docList = rs.getDocumentManager().getChildren( new IdRef(uuid)); DocumentDescriptor[] docs = new DocumentDescriptor[docList.size()]; int i = 0; for (DocumentModel doc : docList) { docs[i++] = new DocumentDescriptor(doc); } return docs; } @SuppressWarnings("unchecked") protected void collectProperty(String prefix, String name, Object value, List<DocumentProperty> props) throws ClientException { final String STRINGS_LIST_SEP = ";"; if (value instanceof Map) { Map<String, Object> map = (Map<String, Object>) value; prefix = prefix + name + '/'; for (Map.Entry<String, Object> entry : map.entrySet()) { collectProperty(prefix, entry.getKey(), entry.getValue(), props); } } else if (value instanceof List) { prefix = prefix + name + '/'; List<Object> list = (List<Object>) value; for (int i = 0, len = list.size(); i < len; i++) { collectProperty(prefix, String.valueOf(i), list.get(i), props); } } else { String strValue = null; if (value != null) { if (value instanceof Blob) { try { //strValue = ((Blob) value).getString(); byte[] bytes = ((Blob) value).getByteArray(); strValue = Base64.encodeBytes(bytes); } catch (IOException e) { throw new ClientException( "Failed to get blob property value", e); } } else if (value instanceof Calendar) { strValue = ((Calendar) value).getTime().toString(); } else if (value instanceof String[]) { for (String each : (String[]) value) { if (strValue == null) { strValue = each; } else { strValue = strValue + STRINGS_LIST_SEP + each; } } // FIXME: this condition is always false here. } else if (value instanceof List) { for (String each : (List<String>) value) { if (strValue == null) { strValue = each; } else { strValue = strValue + STRINGS_LIST_SEP + each; } } } else { strValue = value.toString(); } // TODO: use decode method from field type? } props.add(new DocumentProperty(prefix + name, strValue)); } } @SuppressWarnings("unchecked") protected void collectNoBlobProperty(String prefix, String name, Object value, List<DocumentProperty> props) throws ClientException { if (value instanceof Map) { Map<String, Object> map = (Map<String, Object>) value; prefix = prefix + name + '/'; for (Map.Entry<String, Object> entry : map.entrySet()) { collectNoBlobProperty(prefix, entry.getKey(), entry.getValue(), props); } } else if (value instanceof List) { prefix = prefix + name + '/'; List<Object> list = (List<Object>) value; for (int i = 0, len = list.size(); i < len; i++) { collectNoBlobProperty(prefix, String.valueOf(i), list.get(i), props); } } else if (!(value instanceof Blob)) { if (value == null) { props.add(new DocumentProperty(prefix + name, null)); } else { collectProperty(prefix, name, value, props); } } } @SuppressWarnings("unchecked") protected void collectBlobs(WSRemotingSession rs, String prefix, Map<String, Object> container, String name, Object value, List<DocumentBlob> blobs) throws ClientException { if (value instanceof Map) { Map<String, Object> map = (Map<String, Object>) value; prefix = prefix + name + '/'; for (Map.Entry<String, Object> entry : map.entrySet()) { collectBlobs(rs, prefix, map, entry.getKey(), entry.getValue(), blobs); } } else if (value instanceof List) { prefix = prefix + name + '/'; List<Object> list = (List<Object>) value; for (int i = 0, len = list.size(); i < len; i++) { collectBlobs(rs, prefix, container, String.valueOf(i), list.get(i), blobs); } } else if (value instanceof Blob) { try { Blob blob = (Blob) value; String filename = (String) container.get("filename"); if (filename == null) { filename = prefix + name; } DocumentBlob db = new DocumentBlob(filename, blob); // List<String> extensions = // rs.mimeTypeReg.getExtensionsFromMimetypeName(blob.getMimeType()); // if (extensions != null) { // db.setExtensions(extensions.toArray(new // String[extensions.size()])); blobs.add(db); } catch (IOException e) { throw new ClientException("Failed to get document blob", e); } } } @WebMethod public String[] getUsers(String sid, String parentGroup) throws ClientException { if (parentGroup == null) { return listUsers(sid, 0, Integer.MAX_VALUE); } WSRemotingSession rs = initSession(sid); List<String> users; // FIXME: parentGroup is always non-null here if (parentGroup == null) { List<NuxeoPrincipal> principals = rs.getUserManager().getAvailablePrincipals(); users = new ArrayList<String>(principals.size()); for (NuxeoPrincipal principal : principals) { users.add(principal.getName()); } } else { NuxeoGroup group = rs.getUserManager().getGroup(parentGroup); if (group == null) { return null; } users = group.getMemberUsers(); } return users.toArray(new String[users.size()]); } @WebMethod public String[] getGroups(String sid, String parentGroup) throws ClientException { WSRemotingSession rs = initSession(sid); List<String> groups; if (parentGroup == null) { groups = rs.getUserManager().getTopLevelGroups(); } else { groups = rs.getUserManager().getGroupsInGroup(parentGroup); } return groups.toArray(new String[groups.size()]); } @SuppressWarnings("unchecked") @WebMethod public String getRelativePathAsString(String sessionId, String uuid) throws ClientException { WSRemotingSession rs = initSession(sessionId); DocumentModel doc = rs.getDocumentManager().getDocument(new IdRef(uuid)); if (doc == null) { log.debug("Document not found for uuid=" + uuid); return ""; } else { return doc.getPathAsString(); } } public Map<String, Object> createDataMap(String[] propertiesArray) { Map<String, Object> map = new HashMap<String, Object>(); for (int i = 0; i < propertiesArray.length; i += 2) { String key = propertiesArray[i]; String value = propertiesArray[i + 1]; String[] path = key.split("\\."); createSubMaps(map, path, value, 0); } return map; } @SuppressWarnings("unchecked") private void createSubMaps(Map<String, Object> map, String[] path, String value, int depth) { String key = path[depth]; if (depth == path.length - 1) { map.put(key, value); } else { Map<String, Object> subMap = (Map<String, Object>) map.get(key); if (subMap == null) { subMap = new HashMap<String, Object>(); map.put(path[depth], subMap); } createSubMaps(subMap, path, value, depth + 1); } } @SuppressWarnings("unchecked") @WebMethod public String uploadDocument(String sid, String parentUUID, String type, String[] properties) throws ClientException { // TODO Note: This method is intented to be a general method, but now it // can only be used by NuxeoCompanionForOffice // In the future, a new method (which will set the properties of a // document from a given map) will be probably // available in org.nuxeo.ecm.core.api.impl.DocumentHelper and then this // method will be made "general". WSRemotingSession rs = initSession(sid); String name = "file_" + System.currentTimeMillis(); CoreSession documentManager = rs.getDocumentManager(); DocumentRef parentRef = new IdRef(parentUUID); DocumentModel document = new DocumentModelImpl( documentManager.getDocument(parentRef), name, type); document = documentManager.createDocument(document); Map<String, Object> propertiesMap = createDataMap(properties); Map<String, Object> fileMap = (Map<String, Object>) propertiesMap.get("file"); Map<String, Object> contentMap = (Map<String, Object>) fileMap.get("content"); Map<String, Object> dublincoreMap = (Map<String, Object>) propertiesMap.get("dublincore"); document.setProperty("dublincore", "description", dublincoreMap.get("description")); document.setProperty("dublincore", "title", dublincoreMap.get("title")); String filname = (String) fileMap.get("filename"); document.setProperty("file", "filename", filname); final byte[] contentData = Base64.decode((String) contentMap.get("data")); // String contentType = (String) contentMap.get("mime-type") ; Blob blob = StreamingBlob.createFromByteArray(contentData); MimetypeRegistry mimeService=null; try { mimeService = Framework.getService(MimetypeRegistry.class); } catch (Exception e1) { log.error("Unable to access Mimetype service: " + e1.getMessage()); } String mimetype = ""; if (mimeService != null) { try { mimetype = mimeService.getMimetypeFromFilenameAndBlobWithDefault( filname, blob, mimetype); } catch (MimetypeDetectionException e) { log.error(String.format( "error during mimetype detection for %s: %s", filname, e.getMessage())); } } String encoding = (String) contentMap.get("encoding"); blob.setEncoding(encoding); blob.setMimeType(mimetype); document.setProperty("file", "content", blob); documentManager.saveDocument(document); documentManager.save(); return ""; } }
package jade.imtp.leap.JICP; //#MIDP_EXCLUDE_FILE import jade.mtp.TransportAddress; import jade.imtp.leap.*; import jade.util.leap.Properties; import java.io.*; import java.net.*; import java.util.Hashtable; import java.util.Enumeration; import java.util.StringTokenizer; /** * Class declaration * @author Giovanni Caire - TILAB * @author Ronnie Taib - Motorola * @author Nicolas Lhuillier - Motorola * @author Steffen Rusitschka - Siemens */ public class JICPServer extends Thread { protected ServerSocket server; protected ICP.Listener cmdListener; protected boolean listen = true; private int mediatorCnt = 1; private Hashtable mediators = new Hashtable(); private int handlersCnt = 0; private int maxHandlers; private ConnectionFactory connFactory; private static int verbosity = 1; /** * Constructor declaration * @param port * @param cmdHandler */ public JICPServer(int port, boolean changePortIfBusy, ICP.Listener l, ConnectionFactory f, int max) throws ICPException { cmdListener = l; connFactory = f; maxHandlers = max; try { server = new ServerSocket(port); } catch (IOException ioe) { if (changePortIfBusy) { // The specified port is busy. Let the system find a free one try { server = new ServerSocket(0); } catch (IOException ioe2) { throw new ICPException("Problems initializing server socket. No free port found"); } } else { throw new ICPException("I/O error opening server socket on port "+port); } } setDaemon(true); setName("Main"); } public int getLocalPort() { return server.getLocalPort(); } /** * Method declaration * @see */ public void shutdown() { listen = false; try { // Force the listening thread (this) to exit from the accept() // Calling this.interrupt(); should be the right way, but it seems // not to work...so do that by closing the server socket. server.close(); // Wait for the listening thread to complete this.join(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (InterruptedException ie) { ie.printStackTrace(); } } private boolean paused = false; private synchronized void pause() { log("Pausing JICPServer...", 2); try { paused = true; server.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } private synchronized void restart(int port) { log("Restarting JICPServer...", 2); while (true) { try { server = new ServerSocket(port); paused = false; return; } catch (BindException be) { // The port is still busy. Wait a bit log("Local port "+port+" still busy. Wait a bit before retrying...", 2); waitABit(10000); } catch (Exception e) { log("PANIC: Cannot restart JICPServer", 1); break; } } } public synchronized void dummyReply(InetAddress addr, int port) { if (addr != null) { int oldPort = getLocalPort(); // Send the dummy reply Socket s = null; while (true) { try { pause(); log("Sending dummy reply to "+addr+":"+port, 2); s = new Socket(addr, port, InetAddress.getLocalHost(), oldPort); } catch (BindException be) { // The port is still busy. Wait a bit log("Local port "+oldPort+" still busy. Wait a bit before retrying...", 2); waitABit(30000); } catch (Exception e) { log("Dummy reply sent", 2); break; } finally { try { s.close(); } catch (Exception e) {} restart(oldPort); } } } } private void waitABit(long time) { try { Thread.sleep(time); } catch (InterruptedException ie) { log("InterruptedException in Thread.sleep()", 1); } } /** * Method declaration * @see */ public void run() { while (listen) { try { // Accept connection Socket s = server.accept(); InetAddress addr = s.getInetAddress(); int port = s.getPort(); log("Incoming connection from "+s.getInetAddress()+":"+s.getPort(), 3); new ConnectionHandler(connFactory.createConnection(s), addr, port).start(); // start a handler and go back to listening } catch (InterruptedIOException e) { // These can be generated by socket timeout (just ignore // the exception) or by a call to the shutdown() // method (the listen flag has been set to false and the // server will exit). } catch (Exception e) { if (paused) { log("JICPServer paused", 2); synchronized (this) { log("JICPServer resumed ", 2); } } else { // If the listen flag is false then this exception has // been forced by the shutdown() method --> do nothing. // Otherwise some error occurred if (listen) { log("Problems accepting a new connection", 1); e.printStackTrace(); // Stop listening listen = false; } } } } // release socket try { server.close(); } catch (IOException io) { log("I/O error closing the server socket", 1); io.printStackTrace(); } server = null; // Close all mediators Enumeration e = mediators.elements(); while (e.hasMoreElements()) { Mediator m = (Mediator) e.nextElement(); m.kill(); } mediators.clear(); } /** * Called by a Mediator to notify that it is no longer active */ public void deregisterMediator(String id) { mediators.remove(id); } /** * Class declaration * @author LEAP */ class ConnectionHandler extends Thread { private Connection c; private InetAddress addr; private int port; /** * Constructor declaration * @param s */ public ConnectionHandler(Connection c, InetAddress addr, int port) { this.c = c; this.addr = addr; this.port = port; } /** * Thread entry point */ public void run() { handlersCnt++; OutputStream out = null; InputStream inp = null; boolean closeConnection = true; int status = 0; byte type = (byte) 0; try { // Get input and output stream from the connection inp = c.getInputStream(); out = c.getOutputStream(); boolean loop = true; while (loop) { // Read the input JICPPacket pkt = JICPPacket.readFrom(inp); status = 1; loop = false; // Reply packet JICPPacket reply = null; type = pkt.getType(); switch (type) { case JICPProtocol.COMMAND_TYPE: case JICPProtocol.RESPONSE_TYPE: // Get the right recipient and let it process the command. String recipientID = pkt.getRecipientID(); if (recipientID != null) { // The recipient is one of the mediators JICPMediator m = (JICPMediator) mediators.get(recipientID); if (m != null) { reply = m.handleJICPPacket(pkt, addr, port); } else { if (type == JICPProtocol.COMMAND_TYPE) { reply = new JICPPacket("Unknown recipient "+recipientID, null); } } } else { loop = true; // The recipient is my ICP.Listener (the local CommandDispatcher) // If the packet is not a command, just ignore it if (type == JICPProtocol.COMMAND_TYPE) { byte[] rsp = cmdListener.handleCommand(pkt.getData()); byte dataInfo = JICPProtocol.COMPRESSED_INFO; if (handlersCnt >= maxHandlers) { dataInfo |= JICPProtocol.TERMINATED_INFO; loop = false; } reply = new JICPPacket(JICPProtocol.RESPONSE_TYPE, dataInfo, rsp); } if ((pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) { loop = false; } } break; case JICPProtocol.GET_ADDRESS_TYPE: // Respond sending back the caller address log("Received a GET_ADDRESS request from "+addr+":"+port, 2); reply = new JICPPacket(JICPProtocol.GET_ADDRESS_TYPE, JICPProtocol.DEFAULT_INFO, addr.getHostAddress().getBytes()); break; case JICPProtocol.CREATE_MEDIATOR_TYPE: // Starts a new Mediator and sends back its ID String id = String.valueOf(mediatorCnt++); log("Received a CREATE_MEDIATOR request from "+addr+":"+port+". New Mediator ID is "+id+".", 2); String s = new String(pkt.getData()); Properties p = parseProperties(s); JICPMediator m = startMediator(id, p); m.handleIncomingConnection(c, addr, port, JICPProtocol.CREATE_MEDIATOR_TYPE); mediators.put(id, m); reply = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, id.getBytes()); closeConnection = false; break; case JICPProtocol.CONNECT_MEDIATOR_TYPE: // A mediated container is (re)connecting to its mediator recipientID = pkt.getRecipientID(); log("Received a CONNECT_MEDIATOR request from "+addr+":"+port+". Mediator ID is "+recipientID, 2); m = (JICPMediator) mediators.get(recipientID); if (m != null) { // Don't close the connection, but pass it to the proper // mediator. Use the response (if any) prepared by the // Mediator itself reply = m.handleIncomingConnection(c, addr, port, JICPProtocol.CONNECT_MEDIATOR_TYPE); closeConnection = false; } else { reply = new JICPPacket("Mediator "+recipientID+" not found", null); } break; default: // Send back an error response log("Uncorrect JICP data type: "+pkt.getType(), 1); reply = new JICPPacket("Uncorrect JICP data type: "+pkt.getType(), null); } status = 2; // Send the actual response data if (reply != null) { reply.writeTo(out); } status = 3; } } catch (Exception e) { switch (status) { case 0: log("Communication error reading incoming packet from "+addr+":"+port, 1); e.printStackTrace(); break; case 1: log("Error handling incoming packet", 1); e.printStackTrace(); // If the incoming packet was a command, try // to send back a generic error response if (type == JICPProtocol.COMMAND_TYPE && out != null) { try { new JICPPacket("Unexpected error", e).writeTo(out); } catch (IOException ioe) { // Just print a warning log("Can't send back error indication "+ioe, 1); } } break; case 2: log("Communication error writing return packet to "+addr+":"+port, 1); e.printStackTrace(); break; case 3: // This is a re-used connection waiting for the next incoming packet if (e instanceof EOFException) { log("Client "+addr+":"+port+" has closed the connection.", 2); } else { log("Unexpected client "+addr+":"+port+" termination. "+e.toString(), 1); } } } finally { try { if (closeConnection) { // Close connection c.close(); } } catch (IOException io) { log("I/O error while closing the connection", 1); io.printStackTrace(); } handlersCnt } } } private Properties parseProperties(String s) throws ICPException { StringTokenizer st = new StringTokenizer(s, "=;"); Properties p = new Properties(); while (st.hasMoreTokens()) { String key = st.nextToken(); if (!st.hasMoreTokens()) { throw new ICPException("Wrong initialization properties format."); } p.setProperty(key, st.nextToken()); } return p; } private JICPMediator startMediator(String id, Properties p) throws Exception { String className = p.getProperty(JICPProtocol.MEDIATOR_CLASS_KEY); if (className != null) { JICPMediator m = (JICPMediator) Class.forName(className).newInstance(); m.init(this, id, p); return m; } else { throw new ICPException("No JICPMediator class specified."); } } static void log(String s, int level) { if (verbosity >= level) { String name = Thread.currentThread().getName(); System.out.println("JICPServer("+name+")[LVL-"+level+"]["+System.currentTimeMillis()+"]: "+s); } } }
// This file is part of the OpenNMS(R) Application. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // and included code are below. // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // For more information contact: package org.opennms.netmgt.dao.jdbc; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import org.opennms.netmgt.dao.AssetRecordDao; import org.opennms.netmgt.dao.jdbc.asset.AssetRecordSaveOrUpdate; import org.opennms.netmgt.dao.jdbc.asset.FindAll; import org.opennms.netmgt.dao.jdbc.asset.FindByAssetId; import org.opennms.netmgt.dao.jdbc.asset.LazyAssetRecord; import org.opennms.netmgt.model.OnmsAssetRecord; import org.springframework.jdbc.core.RowCallbackHandler; public class AssetRecordDaoJdbc extends AbstractDaoJdbc implements AssetRecordDao { public static class Save extends AssetRecordSaveOrUpdate { // DO NOT CHANGE THIS STATEMENT UNLESS YOU CHANGE THE UPDATE STATEMENT AND THE // PARAMETERS IN AssetRecordSaveOrUpdate private static final String insertStmt = "insert into assets (" + "category, " + "manufacturer, " + "vendor, " + "modelNumber, " + "serialNumber, " + "description, " + "circuitId, " + "assetNumber, " + "operatingSystem, " + "rack, " + "slot, " + "port, " + "region, " + "division, " + "department, " + "address1, " + "address2, " + "city, " + "state, " + "zip, " + "building, " + "floor, " + "room, " + "vendorPhone, " + "vendorFax, " + "vendorAssetNumber, " + "userLastModified, " + "lastModifiedDate, " + "dateInstalled, " + "lease, " + "leaseExpires, " + "supportPhone, " + "maintContract, " + "maintContractExpires, " + "displayCategory, " + "notifyCategory, " + "pollerCategory, " + "thresholdCategory, " + "comment, " + "managedObjectInstance, " + "managedObjectType , " + "nodeID" + ") values " + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + " ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + " ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + " ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + " ?, ?)"; public Save(DataSource ds) { super(ds, insertStmt); } public int doInsert(OnmsAssetRecord asset) { return persist(asset); } } public static class Update extends AssetRecordSaveOrUpdate { // DO NOT CHANGE THIS STATEMENT UNLESS YOU CHANGE THE INSERT STATEMENT AND THE // PARAMETERS IN AssetRecordSaveOrUpdate private static final String updateStmt = "update assets set " + "category = ?, " + "manufacturer = ?, " + "vendor = ?, " + "modelNumber = ?, " + "serialNumber = ?, " + "description = ?, " + "circuitId = ?, " + "assetNumber = ?, " + "operatingSystem = ?, " + "rack = ?, " + "slot = ?, " + "port = ?, " + "region = ?, " + "division = ?, " + "department = ?, " + "address1 = ?, " + "address2 = ?, " + "city = ?, " + "state = ?, " + "zip = ?, " + "building = ?, " + "floor = ?, " + "room = ?, " + "vendorPhone = ?, " + "vendorFax = ?, " + "vendorAssetNumber = ?, " + "userLastModified = ?, " + "lastModifiedDate = ?, " + "dateInstalled = ?, " + "lease = ?, " + "leaseExpires = ?, " + "supportPhone = ?," + " maintContract = ?, " + "maintContractExpires = ?, " + "displayCategory = ?, " + "notifyCategory = ?, " + "pollerCategory = ?, " + "thresholdCategory = ?, " + "comment = ?, " + "managedObjectInstance = ?, " + "managedObjectType = ? " + "where nodeID = ?"; public Update(DataSource ds) { super(ds, updateStmt); } public int doUpdate(OnmsAssetRecord asset) { return persist(asset); } } public AssetRecordDaoJdbc() { super(); } public AssetRecordDaoJdbc(DataSource ds) { super(ds); } public int countAll() { return getJdbcTemplate().queryForInt("select count(*) from assets"); } public Collection findAll() { return new FindAll(getDataSource()).execute(); } public Map findImportedAssetNumbersToNodeIds(String foreignSource) { final Map assetNumbersToNodeIds = new HashMap(); getJdbcTemplate().query("select assetNumber, nodeId from assets where assetNumber like '"+foreignSource+"%'", new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { assetNumbersToNodeIds.put(rs.getString("assetNumber"), rs.getObject("nodeId")); } }); return assetNumbersToNodeIds; } public OnmsAssetRecord findByNodeId(Integer id) { return get(id); } public void flush() { } public OnmsAssetRecord get(Integer id) { return new FindByAssetId(getDataSource()).findUnique(id); } public OnmsAssetRecord load(Integer id) { OnmsAssetRecord asset = get(id); if (asset == null) throw new IllegalArgumentException("unable to load asset with id: "+id); return asset; } public void save(OnmsAssetRecord asset) { new Save(getDataSource()).doInsert(asset); } public void update(OnmsAssetRecord asset) { if (!isDirty(asset)) return; new Update(getDataSource()).doUpdate(asset); } private boolean isDirty(OnmsAssetRecord asset) { if (asset instanceof LazyAssetRecord) { LazyAssetRecord lazyAsset = (LazyAssetRecord) asset; return lazyAsset.isDirty(); } return true; } }
package org.osmdroid.tileprovider; import java.util.LinkedHashMap; import java.util.NoSuchElementException; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.Log; import org.osmdroid.api.IMapView; import org.osmdroid.config.Configuration; import org.osmdroid.tileprovider.constants.OpenStreetMapTileProviderConstants; public class LRUMapTileCache extends LinkedHashMap<MapTile, Drawable> { public interface TileRemovedListener { void onTileRemoved(MapTile mapTile); } private static final long serialVersionUID = -541142277575493335L; private int mCapacity; private TileRemovedListener mTileRemovedListener; public LRUMapTileCache(final int aCapacity) { super(aCapacity + 2, 0.1f, true); mCapacity = aCapacity; } public void ensureCapacity(final int aCapacity) { if (aCapacity > mCapacity) { Log.i(IMapView.LOGTAG, "Tile cache increased from " + mCapacity + " to " + aCapacity); mCapacity = aCapacity; } } @Override public Drawable remove(final Object aKey) { final Drawable drawable = super.remove(aKey); // Only recycle if we are running on a project less than 2.3.3 Gingerbread. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { if (drawable instanceof BitmapDrawable) { final Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); if (bitmap != null) { bitmap.recycle(); } } } if (getTileRemovedListener() != null && aKey instanceof MapTile) getTileRemovedListener().onTileRemoved((MapTile) aKey); if (drawable instanceof ReusableBitmapDrawable) BitmapPool.getInstance().returnDrawableToPool((ReusableBitmapDrawable) drawable); return drawable; } @Override public void clear() { // remove them all individually so that they get recycled while (!isEmpty()) { try { remove(keySet().iterator().next()); } catch (NoSuchElementException nse) { // as a protection } } // and then clear super.clear(); } @Override protected boolean removeEldestEntry(final java.util.Map.Entry<MapTile, Drawable> aEldest) { if (size() > mCapacity) { final MapTile eldest = aEldest.getKey(); if (Configuration.getInstance().isDebugMode()) { Log.d(IMapView.LOGTAG,"LRU Remove old tile: " + eldest); } remove(eldest); // don't return true because we've already removed it } return false; } public TileRemovedListener getTileRemovedListener() { return mTileRemovedListener; } public void setTileRemovedListener(TileRemovedListener tileRemovedListener) { mTileRemovedListener = tileRemovedListener; } }
package com.intellij.codeInsight.hint; import com.intellij.icons.AllIcons; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.roots.*; import com.intellij.openapi.util.NlsSafe; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import javax.swing.*; import java.util.List; public final class ElementLocationUtil { private ElementLocationUtil() { } /** * @deprecated use {@link #renderElementLocation(PsiElement, Ref)} */ @Deprecated public static void customizeElementLabel(final PsiElement element, final JLabel label) { Ref<Icon> ref = new Ref<>(); label.setText(renderElementLocation(element, ref)); label.setIcon(ref.get()); } public static @NlsSafe String renderElementLocation(final PsiElement element, final Ref<? super Icon> icon) { if (element != null) { PsiFile file = element.getContainingFile(); VirtualFile vfile = file == null ? null : file.getVirtualFile(); if (vfile == null) { icon.set(null); return ""; } final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(element.getProject()).getFileIndex(); final Module module = fileIndex.getModuleForFile(vfile); if (module != null) { if (ModuleType.isInternal(module)) { icon.set(null); return ""; } icon.set(ModuleType.get(module).getIcon()); return module.getName(); } else { final List<OrderEntry> entries = fileIndex.getOrderEntriesForFile(vfile); OrderEntry entry = null; for (OrderEntry order : entries) { if (order instanceof LibraryOrderEntry || order instanceof JdkOrderEntry) { entry = order; break; } } if (entry != null) { icon.set(AllIcons.Nodes.PpLibFolder); return entry.getPresentableName(); } } } icon.set(null); return ""; } }
package com.intellij.ide.projectView.impl; import com.intellij.application.options.OptionsApplicabilityFilter; import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryAction; import com.intellij.icons.AllIcons; import com.intellij.ide.*; import com.intellij.ide.impl.ProjectViewSelectInGroupTarget; import com.intellij.ide.impl.ProjectViewSelectInTarget; import com.intellij.ide.projectView.HelpID; import com.intellij.ide.projectView.ProjectView; import com.intellij.ide.projectView.ProjectViewNode; import com.intellij.ide.projectView.impl.nodes.*; import com.intellij.ide.ui.SplitterProportionsDataImpl; import com.intellij.ide.util.DeleteHandler; import com.intellij.ide.util.treeView.AbstractTreeBuilder; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.TransactionGuard; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.module.UnloadedModuleDescription; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.ui.configuration.actions.ModuleDeleteProvider; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.SimpleToolWindowPanel; import com.intellij.openapi.ui.SplitterProportionsData; import com.intellij.openapi.ui.popup.IPopupChooserBuilder; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.*; import com.intellij.openapi.wm.ex.ToolWindowEx; import com.intellij.openapi.wm.ex.ToolWindowManagerListener; import com.intellij.openapi.wm.impl.content.ToolWindowContentUi; import com.intellij.psi.*; import com.intellij.psi.impl.file.PsiDirectoryFactory; import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.AutoScrollFromSourceHandler; import com.intellij.ui.AutoScrollToSourceHandler; import com.intellij.ui.GuiUtils; import com.intellij.ui.IdeUICustomization; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; import com.intellij.ui.content.ContentManagerAdapter; import com.intellij.ui.content.ContentManagerEvent; import com.intellij.ui.switcher.QuickActionProvider; import com.intellij.ui.tree.TreeVisitor; import com.intellij.util.*; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.JBIterable; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.util.List; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import static com.intellij.application.options.OptionId.PROJECT_VIEW_SHOW_VISIBILITY_ICONS; import static com.intellij.ui.tree.TreePathUtil.toTreePathArray; @State(name = "ProjectView", storages = { @Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE), @Storage(value = StoragePathMacros.WORKSPACE_FILE, deprecated = true) }) public class ProjectViewImpl extends ProjectView implements PersistentStateComponent<Element>, Disposable, QuickActionProvider, BusyObject { private static final Logger LOG = Logger.getInstance("#com.intellij.ide.projectView.impl.ProjectViewImpl"); private static final Key<String> ID_KEY = Key.create("pane-id"); private static final Key<String> SUB_ID_KEY = Key.create("pane-sub-id"); private static final ExecutorService ourParsingExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("Project View Autoscroll", 1); private final CopyPasteDelegator myCopyPasteDelegator; private boolean isInitialized; private final AtomicBoolean myExtensionsLoaded = new AtomicBoolean(false); @NotNull private final Project myProject; private final ProjectViewState myCurrentState; // + options private final Option myAbbreviatePackageNames = new Option() { @NotNull @Override public String getName() { return IdeBundle.message("action.abbreviate.qualified.package.names"); } @Override public String getDescription() { return getName(); } @Override public boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return myFlattenPackages.isSelected() && myFlattenPackages.isEnabled(pane) && pane.supportsAbbreviatePackageNames(); } @Override public boolean isSelected() { return myCurrentState.getAbbreviatePackageNames(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; boolean updated = selected != isSelected(); myCurrentState.setAbbreviatePackageNames(selected); getDefaultState().setAbbreviatePackageNames(selected); getGlobalOptions().setAbbreviatePackages(selected); if (updated) updatePanes(false); } }; private final Option myAutoscrollFromSource = new Option() { @NotNull @Override public String getName() { return "Always Select Opened File"; } @Override public String getDescription() { return "When an editor tab is selected, select the corresponding file in Project view"; } @Override public boolean isSelected() { return myCurrentState.getAutoscrollFromSource(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; myCurrentState.setAutoscrollFromSource(selected); getDefaultState().setAutoscrollFromSource(selected); getGlobalOptions().setAutoscrollFromSource(selected); if (selected && !myAutoScrollFromSourceHandler.isCurrentProjectViewPaneFocused()) { myAutoScrollFromSourceHandler.scrollFromSource(); } } }; private final Option myAutoscrollToSource = new Option() { @NotNull @Override public String getName() { return "Open Files with Single Click"; } @Override public String getDescription() { return "When a file is selected, open it for editing"; } @Override public boolean isSelected() { return myCurrentState.getAutoscrollToSource(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; myCurrentState.setAutoscrollToSource(selected); getDefaultState().setAutoscrollToSource(selected); getGlobalOptions().setAutoscrollToSource(selected); } }; private final Option myCompactDirectories = new Option() { @NotNull @Override public String getName() { return IdeBundle.message("action.compact.directories.text"); } @Override public String getDescription() { return IdeBundle.message("action.compact.directories.description"); } @Override public boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return pane.supportsCompactDirectories(); } @Override public boolean isSelected() { return myCurrentState.getCompactDirectories(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; boolean updated = selected != isSelected(); myCurrentState.setCompactDirectories(selected); getDefaultState().setCompactDirectories(selected); getGlobalOptions().setCompactDirectories(selected); if (updated) updatePanes(false); } }; private final Option myFlattenModules = new Option() { @NotNull @Override public String getName() { return ProjectBundle.message("project.roots.flatten.modules.action.text"); } @Override public String getDescription() { return ProjectBundle.message("project.roots.flatten.modules.action.description"); } @Override public boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return pane.supportsFlattenModules(); } @Override public boolean isSelected() { return myCurrentState.getFlattenModules(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; boolean updated = selected != isSelected(); myCurrentState.setFlattenModules(selected); getDefaultState().setFlattenModules(selected); getGlobalOptions().setFlattenModules(selected); if (updated) updatePanes(false); } }; private final Option myFlattenPackages = new Option() { @NotNull @Override public String getName() { return IdeBundle.message("action.flatten.packages"); } @Override public String getDescription() { return getName(); } @Override public boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return ProjectViewDirectoryHelper.getInstance(myProject).supportsFlattenPackages(); } @Override public boolean isSelected() { return myCurrentState.getFlattenPackages(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; boolean updated = selected != isSelected(); myCurrentState.setFlattenPackages(selected); getDefaultState().setFlattenPackages(selected); getGlobalOptions().setFlattenPackages(selected); if (updated) updatePanes(false); } }; private final Option myFoldersAlwaysOnTop = new Option() { @NotNull @Override public String getName() { return "Folders Always on Top"; } @Override public boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return pane.supportsFoldersAlwaysOnTop(); } @Override public boolean isSelected() { return myCurrentState.getFoldersAlwaysOnTop(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; boolean updated = selected != isSelected(); myCurrentState.setFoldersAlwaysOnTop(selected); getDefaultState().setFoldersAlwaysOnTop(selected); getGlobalOptions().setFoldersAlwaysOnTop(selected); if (updated) updatePanes(true); } }; private final Option myHideEmptyMiddlePackages = new Option() { @NotNull @Override public String getName() { return myFlattenPackages.isSelected() ? IdeBundle.message("action.hide.empty.middle.packages") : IdeBundle.message("action.compact.empty.middle.packages"); } @Override public String getDescription() { return myFlattenPackages.isSelected() ? IdeBundle.message("action.show.hide.empty.middle.packages") : IdeBundle.message("action.show.compact.empty.middle.packages"); } @Override public boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return pane.supportsHideEmptyMiddlePackages() && ProjectViewDirectoryHelper.getInstance(myProject).supportsHideEmptyMiddlePackages(); } @Override public boolean isSelected() { return myCurrentState.getHideEmptyMiddlePackages(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; boolean updated = selected != isSelected(); myCurrentState.setHideEmptyMiddlePackages(selected); getDefaultState().setHideEmptyMiddlePackages(selected); getGlobalOptions().setHideEmptyPackages(selected); if (updated) updatePanes(false); } }; private final Option myManualOrder = new Option() { @NotNull @Override public String getName() { AbstractProjectViewPane pane = getCurrentProjectViewPane(); return pane != null ? pane.getManualOrderOptionText() : IdeBundle.message("action.manual.order"); } @Override public boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return pane.supportsManualOrder(); } @Override public boolean isSelected() { return myCurrentState.getManualOrder(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; boolean updated = selected != isSelected(); myCurrentState.setManualOrder(selected); getDefaultState().setManualOrder(selected); getGlobalOptions().setManualOrder(selected); if (updated) updatePanes(true); } }; private final Option myShowExcludedFiles = new Option() { @NotNull @Override public String getName() { return IdeBundle.message("action.show.excluded.files"); } @Override public String getDescription() { return IdeBundle.message("action.show.hide.excluded.files"); } @Override public boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return pane.supportsShowExcludedFiles(); } @Override public boolean isSelected() { return myCurrentState.getShowExcludedFiles(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; boolean updated = selected != isSelected(); myCurrentState.setShowExcludedFiles(selected); getDefaultState().setShowExcludedFiles(selected); getGlobalOptions().setShowExcludedFiles(selected); if (updated) updatePanes(false); } }; private final Option myShowLibraryContents = new Option() { @NotNull @Override public String getName() { return IdeBundle.message("action.show.libraries.contents"); } @Override public String getDescription() { return IdeBundle.message("action.show.hide.library.contents"); } @Override public boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return pane.supportsShowLibraryContents(); } @Override public boolean isSelected() { return myCurrentState.getShowLibraryContents(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; boolean updated = selected != isSelected(); myCurrentState.setShowLibraryContents(selected); getDefaultState().setShowLibraryContents(selected); getGlobalOptions().setShowLibraryContents(selected); if (updated) updatePanes(false); } }; private final Option myShowMembers = new Option() { @NotNull @Override public String getName() { return IdeBundle.message("action.show.members"); } @Override public String getDescription() { return IdeBundle.message("action.show.hide.members"); } @Override public boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return isShowMembersOptionSupported(); } @Override public boolean isSelected() { return myCurrentState.getShowMembers(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; boolean updated = selected != isSelected(); myCurrentState.setShowMembers(selected); getDefaultState().setShowMembers(selected); getGlobalOptions().setShowMembers(selected); if (updated) updatePanes(false); } }; private final Option myShowModules = new Option() { @NotNull @Override public String getName() { return IdeBundle.message("action.show.modules"); } @Override public String getDescription() { return IdeBundle.message("action.description.show.modules"); } @Override public boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return pane.supportsShowModules(); } @Override public boolean isSelected() { return myCurrentState.getShowModules(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; boolean updated = selected != isSelected(); myCurrentState.setShowModules(selected); getDefaultState().setShowModules(selected); getGlobalOptions().setShowModules(selected); if (updated) updatePanes(false); } }; private final Option myShowVisibilityIcons = new Option() { @NotNull @Override public String getName() { return IdeBundle.message("action.show.visibility.icons.text"); } @Override public String getDescription() { return IdeBundle.message("action.show.visibility.icons.description"); } @Override public boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return OptionsApplicabilityFilter.isApplicable(PROJECT_VIEW_SHOW_VISIBILITY_ICONS); } @Override public boolean isSelected() { return myCurrentState.getShowVisibilityIcons(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; boolean updated = selected != isSelected(); myCurrentState.setShowVisibilityIcons(selected); getDefaultState().setShowVisibilityIcons(selected); getGlobalOptions().setShowVisibilityIcons(selected); if (updated) updatePanes(false); } }; private final Option mySortByType = new Option() { @NotNull @Override public String getName() { return IdeBundle.message("action.sort.by.type"); } @Override public String getDescription() { return getName(); } @Override public boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return pane.supportsSortByType(); } @Override public boolean isSelected() { return myCurrentState.getSortByType(); } @Override public void setSelected(boolean selected) { if (myProject.isDisposed()) return; boolean updated = selected != isSelected(); myCurrentState.setSortByType(selected); getDefaultState().setSortByType(selected); getGlobalOptions().setSortByType(selected); if (updated) updatePanes(true); } }; private String myCurrentViewId; private String myCurrentViewSubId; // - options private final AutoScrollToSourceHandler myAutoScrollToSourceHandler; private final MyAutoScrollFromSourceHandler myAutoScrollFromSourceHandler; private volatile ThreeState myCurrentSelectionObsolete = ThreeState.NO; private final IdeView myIdeView = new IdeViewForProjectViewPane(this::getCurrentProjectViewPane); private final MyDeletePSIElementProvider myDeletePSIElementProvider = new MyDeletePSIElementProvider(); private final ModuleDeleteProvider myDeleteModuleProvider = new ModuleDeleteProvider(); private SimpleToolWindowPanel myPanel; private final Map<String, AbstractProjectViewPane> myId2Pane = new LinkedHashMap<>(); private final Collection<AbstractProjectViewPane> myUninitializedPanes = new THashSet<>(); private static final DataKey<ProjectViewImpl> DATA_KEY = DataKey.create("com.intellij.ide.projectView.impl.ProjectViewImpl"); private DefaultActionGroup myActionGroup; private String mySavedPaneId = getDefaultViewId(); private String mySavedPaneSubId; @NonNls private static final String ELEMENT_NAVIGATOR = "navigator"; @NonNls private static final String ELEMENT_PANES = "panes"; @NonNls private static final String ELEMENT_PANE = "pane"; @NonNls private static final String ATTRIBUTE_CURRENT_VIEW = "currentView"; @NonNls private static final String ATTRIBUTE_CURRENT_SUBVIEW = "currentSubView"; private static final String ATTRIBUTE_ID = "id"; private JPanel myViewContentPanel; private static final Comparator<AbstractProjectViewPane> PANE_WEIGHT_COMPARATOR = Comparator.comparingInt(AbstractProjectViewPane::getWeight); private final MyPanel myDataProvider; private final SplitterProportionsData splitterProportions = new SplitterProportionsDataImpl(); private final MessageBusConnection myConnection; private final Map<String, Element> myUninitializedPaneState = new THashMap<>(); private final Map<String, SelectInTarget> mySelectInTargets = new LinkedHashMap<>(); private ContentManager myContentManager; public ProjectViewImpl(@NotNull Project project) { myProject = project; myCurrentState = ProjectViewState.getInstance(project); constructUi(); myConnection = project.getMessageBus().connect(); myAutoScrollFromSourceHandler = new MyAutoScrollFromSourceHandler(); myDataProvider = new MyPanel(); myDataProvider.add(myPanel, BorderLayout.CENTER); myCopyPasteDelegator = new CopyPasteDelegator(myProject, myPanel); myAutoScrollToSourceHandler = new AutoScrollToSourceHandler() { @Override protected boolean isAutoScrollMode() { return myAutoscrollToSource.isSelected(); } @Override protected void setAutoScrollMode(boolean state) { myAutoscrollToSource.setSelected(state); } @Override protected boolean isAutoScrollEnabledFor(@NotNull VirtualFile file) { if (!super.isAutoScrollEnabledFor(file)) return false; AbstractProjectViewPane pane = getCurrentProjectViewPane(); return pane == null || pane.isAutoScrollEnabledFor(file); } @Override protected String getActionName() { return myAutoscrollToSource.getName(); } @Override protected String getActionDescription() { return myAutoscrollToSource.getDescription(); } }; myConnection.subscribe(ToolWindowManagerListener.TOPIC, new ToolWindowManagerListener() { private boolean toolWindowVisible; @Override public void stateChanged() { ToolWindow window = ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.PROJECT_VIEW); if (window == null || toolWindowVisible == window.isVisible()) return; myCurrentSelectionObsolete = ThreeState.NO; if (window.isVisible() && !toolWindowVisible) { AbstractProjectViewPane currentProjectViewPane = getCurrentProjectViewPane(); if (currentProjectViewPane != null && isAutoscrollFromSource(currentProjectViewPane.getId())) { SimpleSelectInContext context = myAutoScrollFromSourceHandler.findSelectInContext(); if (context != null) { myCurrentSelectionObsolete = ThreeState.UNSURE; context.selectInCurrentTarget(); } } } toolWindowVisible = window.isVisible(); } }); } private void constructUi() { myViewContentPanel = new JPanel(); myPanel = new SimpleToolWindowPanel(true).setProvideQuickActions(false); myPanel.setContent(myViewContentPanel); } @NotNull @Override public String getName() { return IdeUICustomization.getInstance().getProjectViewTitle(); } @NotNull @Override public List<AnAction> getActions(boolean originalProvider) { DefaultActionGroup views = new DefaultActionGroup("Change View", true); ChangeViewAction lastHeader = null; for (int i = 0; i < myContentManager.getContentCount(); i++) { Content each = myContentManager.getContent(i); if (each == null) continue; String id = each.getUserData(ID_KEY); String subId = each.getUserData(SUB_ID_KEY); ChangeViewAction newHeader = new ChangeViewAction(id, subId); if (lastHeader != null) { boolean lastHasKids = lastHeader.mySubId != null; boolean newHasKids = newHeader.mySubId != null; if (lastHasKids != newHasKids || lastHasKids && lastHeader.myId != newHeader.myId) { views.add(Separator.getInstance()); } } views.add(newHeader); lastHeader = newHeader; } List<AnAction> result = new ArrayList<>(); result.add(views); result.add(Separator.getInstance()); if (myActionGroup != null) { List<AnAction> secondary = new ArrayList<>(); for (AnAction each : myActionGroup.getChildren(null)) { if (myActionGroup.isPrimary(each)) { result.add(each); } else { secondary.add(each); } } result.add(Separator.getInstance()); result.addAll(secondary); } return result; } private static ProjectViewState getDefaultState() { return ProjectViewState.getDefaultInstance(); } private class ChangeViewAction extends AnAction { @NotNull private final String myId; @Nullable private final String mySubId; private ChangeViewAction(@NotNull String id, @Nullable String subId) { myId = id; mySubId = subId; } @Override public void update(@NotNull AnActionEvent e) { AbstractProjectViewPane pane = getProjectViewPaneById(myId); e.getPresentation().setText(mySubId != null ? pane.getPresentableSubIdName(mySubId) : pane.getTitle()); e.getPresentation().setIcon(mySubId != null ? pane.getPresentableSubIdIcon(mySubId) : pane.getIcon()); } @Override public void actionPerformed(@NotNull AnActionEvent e) { changeView(myId, mySubId); } } @Override public synchronized void addProjectPane(@NotNull final AbstractProjectViewPane pane) { myUninitializedPanes.add(pane); SelectInTarget selectInTarget = pane.createSelectInTarget(); String id = selectInTarget.getMinorViewId(); if (pane.getId().equals(id)) { mySelectInTargets.put(id, selectInTarget); } else { try { LOG.error("Unexpected SelectInTarget: " + selectInTarget.getClass() + "\n created by project pane:" + pane.getClass()); } catch (AssertionError ignored) { } } if (isInitialized) { doAddUninitializedPanes(); } } @Override public synchronized void removeProjectPane(@NotNull AbstractProjectViewPane pane) { ApplicationManager.getApplication().assertIsDispatchThread(); myUninitializedPanes.remove(pane); //assume we are completely initialized here String idToRemove = pane.getId(); if (!myId2Pane.containsKey(idToRemove)) return; for (int i = getContentManager().getContentCount() - 1; i >= 0; i Content content = getContentManager().getContent(i); String id = content != null ? content.getUserData(ID_KEY) : null; if (idToRemove.equals(id)) { getContentManager().removeContent(content, true); } } myId2Pane.remove(idToRemove); mySelectInTargets.remove(idToRemove); viewSelectionChanged(); } private synchronized void doAddUninitializedPanes() { for (AbstractProjectViewPane pane : myUninitializedPanes) { doAddPane(pane); } final Content[] contents = getContentManager().getContents(); for (int i = 1; i < contents.length; i++) { Content content = contents[i]; Content prev = contents[i - 1]; if (!StringUtil.equals(content.getUserData(ID_KEY), prev.getUserData(ID_KEY)) && prev.getUserData(SUB_ID_KEY) != null && content.getSeparator() == null) { content.setSeparator(""); } } String selectID = null; String selectSubID = null; // try to find saved selected view... for (Content content : contents) { final String id = content.getUserData(ID_KEY); final String subId = content.getUserData(SUB_ID_KEY); if (id != null && id.equals(mySavedPaneId) && StringUtil.equals(subId, mySavedPaneSubId)) { selectID = id; selectSubID = subId; mySavedPaneId = null; mySavedPaneSubId = null; break; } } // saved view not found (plugin disabled, ID changed etc.) - select first available view... if (selectID == null && contents.length > 0 && myCurrentViewId == null) { Content content = contents[0]; selectID = content.getUserData(ID_KEY); selectSubID = content.getUserData(SUB_ID_KEY); } if (selectID != null) { changeView(selectID, selectSubID); } myUninitializedPanes.clear(); } private void doAddPane(@NotNull final AbstractProjectViewPane newPane) { ApplicationManager.getApplication().assertIsDispatchThread(); int index; final ContentManager manager = getContentManager(); for (index = 0; index < manager.getContentCount(); index++) { Content content = manager.getContent(index); String id = content.getUserData(ID_KEY); AbstractProjectViewPane pane = myId2Pane.get(id); int comp = PANE_WEIGHT_COMPARATOR.compare(pane, newPane); LOG.assertTrue(comp != 0, "Project view pane " + newPane + " has the same weight as " + pane + ". Please make sure that you overload getWeight() and return a distinct weight value."); if (comp > 0) { break; } } final String id = newPane.getId(); myId2Pane.put(id, newPane); String[] subIds = newPane.getSubIds(); subIds = subIds.length == 0 ? new String[]{null} : subIds; boolean first = true; for (String subId : subIds) { final String title = subId != null ? newPane.getPresentableSubIdName(subId) : newPane.getTitle(); final Content content = getContentManager().getFactory().createContent(getComponent(), title, false); content.setTabName(title); content.putUserData(ID_KEY, id); content.putUserData(SUB_ID_KEY, subId); content.putUserData(ToolWindow.SHOW_CONTENT_ICON, Boolean.TRUE); Icon icon = subId != null ? newPane.getPresentableSubIdIcon(subId) : newPane.getIcon(); content.setIcon(icon); content.setPopupIcon(icon); content.setPreferredFocusedComponent(() -> { final AbstractProjectViewPane current = getCurrentProjectViewPane(); return current != null ? current.getComponentToFocus() : null; }); content.setBusyObject(this); if (first && subId != null) { content.setSeparator(newPane.getTitle()); } manager.addContent(content, index++); first = false; } } private void showPane(@NotNull AbstractProjectViewPane newPane) { AbstractProjectViewPane currentPane = getCurrentProjectViewPane(); PsiElement selectedPsiElement = null; if (currentPane != null) { if (currentPane != newPane) { currentPane.saveExpandedPaths(); } final PsiElement[] elements = currentPane.getSelectedPSIElements(); if (elements.length > 0) { selectedPsiElement = elements[0]; } } myViewContentPanel.removeAll(); JComponent component = newPane.createComponent(); UIUtil.removeScrollBorder(component); myViewContentPanel.setLayout(new BorderLayout()); myViewContentPanel.add(component, BorderLayout.CENTER); myCurrentViewId = newPane.getId(); String newSubId = myCurrentViewSubId = newPane.getSubId(); myViewContentPanel.revalidate(); myViewContentPanel.repaint(); createToolbarActions(newPane); myAutoScrollToSourceHandler.install(newPane.myTree); IdeFocusManager.getInstance(myProject).requestFocusInProject(newPane.getComponentToFocus(), myProject); newPane.restoreExpandedPaths(); if (selectedPsiElement != null && newSubId != null) { final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(selectedPsiElement); ProjectViewSelectInTarget target = virtualFile == null ? null : getProjectViewSelectInTarget(newPane); if (target != null && target.isSubIdSelectable(newSubId, new FileSelectInContext(myProject, virtualFile, null))) { newPane.select(selectedPsiElement, virtualFile, true); } } myAutoScrollToSourceHandler.onMouseClicked(newPane.myTree); } // public for tests public synchronized void setupImpl(@NotNull ToolWindow toolWindow) { setupImpl(toolWindow, true); } // public for tests public synchronized void setupImpl(@NotNull ToolWindow toolWindow, final boolean loadPaneExtensions) { ApplicationManager.getApplication().assertIsDispatchThread(); myActionGroup = new DefaultActionGroup(); myAutoScrollFromSourceHandler.install(); myContentManager = toolWindow.getContentManager(); if (!ApplicationManager.getApplication().isUnitTestMode()) { toolWindow.setDefaultContentUiType(ToolWindowContentUiType.COMBO); ((ToolWindowEx)toolWindow).setAdditionalGearActions(myActionGroup); toolWindow.getComponent().putClientProperty(ToolWindowContentUi.HIDE_ID_LABEL, "true"); } GuiUtils.replaceJSplitPaneWithIDEASplitter(myPanel); SwingUtilities.invokeLater(() -> splitterProportions.restoreSplitterProportions(myPanel)); if (loadPaneExtensions) { ensurePanesLoaded(); } isInitialized = true; doAddUninitializedPanes(); getContentManager().addContentManagerListener(new ContentManagerAdapter() { @Override public void selectionChanged(@NotNull ContentManagerEvent event) { if (event.getOperation() == ContentManagerEvent.ContentOperation.add) { viewSelectionChanged(); } } }); viewSelectionChanged(); } private void ensurePanesLoaded() { if (myExtensionsLoaded.getAndSet(true)) return; // avoid recursive loading AbstractProjectViewPane[] extensions = AbstractProjectViewPane.EP_NAME.getExtensions(myProject); Arrays.sort(extensions, PANE_WEIGHT_COMPARATOR); for (AbstractProjectViewPane pane : extensions) { if (myUninitializedPaneState.containsKey(pane.getId())) { try { pane.readExternal(myUninitializedPaneState.get(pane.getId())); } catch (InvalidDataException e) { // ignore } myUninitializedPaneState.remove(pane.getId()); } if (pane.isInitiallyVisible() && !myId2Pane.containsKey(pane.getId())) { addProjectPane(pane); } } } private void viewSelectionChanged() { Content content = getContentManager().getSelectedContent(); if (content == null) return; String id = content.getUserData(ID_KEY); String subId = content.getUserData(SUB_ID_KEY); if (Objects.equals(id, myCurrentViewId) && Objects.equals(subId, myCurrentViewSubId)) return; final AbstractProjectViewPane newPane = getProjectViewPaneById(id); if (newPane == null) return; newPane.setSubId(subId); showPane(newPane); ProjectViewSelectInTarget target = getProjectViewSelectInTarget(newPane); if (target != null) target.setSubId(subId); if (isAutoscrollFromSource(id)) { myAutoScrollFromSourceHandler.scrollFromSource(); } } private void createToolbarActions(@NotNull AbstractProjectViewPane pane) { if (myActionGroup == null) return; myActionGroup.removeAll(); myActionGroup.addAction(Action.SHOW_MODULES).setAsSecondary(true); myActionGroup.addAction(Action.FLATTEN_MODULES).setAsSecondary(true); myActionGroup.addAction(Action.FLATTEN_PACKAGES).setAsSecondary(true); myActionGroup.addAction(Action.HIDE_EMPTY_MIDDLE_PACKAGES).setAsSecondary(true); myActionGroup.addAction(Action.ABBREVIATE_PACKAGE_NAMES).setAsSecondary(true); myActionGroup.addAction(Action.COMPACT_DIRECTORIES).setAsSecondary(true); myActionGroup.addAction(Action.SHOW_MEMBERS).setAsSecondary(true); myActionGroup.addAction(Separator.getInstance()).setAsSecondary(true); myActionGroup.addAction(Action.SHOW_LIBRARY_CONTENTS).setAsSecondary(true); myActionGroup.addAction(Action.SHOW_EXCLUDED_FILES).setAsSecondary(true); myActionGroup.addAction(Action.SHOW_VISIBILITY_ICONS).setAsSecondary(true); myActionGroup.addAction(Action.MANUAL_ORDER).setAsSecondary(true); myActionGroup.addAction(Action.SORT_BY_TYPE).setAsSecondary(true); myActionGroup.addAction(Action.FOLDERS_ALWAYS_ON_TOP).setAsSecondary(true); myActionGroup.addAction(Separator.getInstance()).setAsSecondary(true); myActionGroup.addAction(Action.AUTOSCROLL_TO_SOURCE).setAsSecondary(true); myActionGroup.addAction(Action.AUTOSCROLL_FROM_SOURCE).setAsSecondary(true); myActionGroup.addAction(Separator.getInstance()).setAsSecondary(true); AnAction editScopesAction = ActionManager.getInstance().getAction("ScopeView.EditScopes"); if (editScopesAction != null) myActionGroup.addAction(editScopesAction).setAsSecondary(true); pane.addToolbarActions(myActionGroup); List<AnAction> titleActions = ContainerUtil.newSmartList(); createTitleActions(titleActions); if (!titleActions.isEmpty()) { ToolWindowEx window = (ToolWindowEx)ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.PROJECT_VIEW); if (window != null) { window.setTitleActions(titleActions.toArray(AnAction.EMPTY_ARRAY)); } } } protected void createTitleActions(@NotNull List<? super AnAction> titleActions) { titleActions.add(new ScrollFromSourceAction()); AnAction collapseAllAction = CommonActionsManager.getInstance().createCollapseAllAction(new TreeExpander() { @Override public boolean canExpand() { return false; } @Override public void collapseAll() { AbstractProjectViewPane pane = getCurrentProjectViewPane(); JTree tree = pane.myTree; if (tree != null) { TreeUtil.collapseAll(tree, 0); } } @Override public boolean canCollapse() { return true; } }, getComponent()); collapseAllAction.getTemplatePresentation().setIcon(AllIcons.General.CollapseAll); collapseAllAction.getTemplatePresentation().setHoveredIcon(AllIcons.General.CollapseAllHover); titleActions.add(collapseAllAction); } protected boolean isShowMembersOptionSupported() { return true; } @Override public AbstractProjectViewPane getProjectViewPaneById(String id) { if (!ApplicationManager.getApplication().isUnitTestMode() && ApplicationManager.getApplication().isDispatchThread()) { // most tests don't need all panes to be loaded, but also we should not initialize panes on background threads ensurePanesLoaded(); } final AbstractProjectViewPane pane = myId2Pane.get(id); if (pane != null) { return pane; } for (AbstractProjectViewPane viewPane : myUninitializedPanes) { if (viewPane.getId().equals(id)) { return viewPane; } } return null; } @Override public AbstractProjectViewPane getCurrentProjectViewPane() { return getProjectViewPaneById(myCurrentViewId); } @Override public void refresh() { AbstractProjectViewPane currentProjectViewPane = getCurrentProjectViewPane(); if (currentProjectViewPane != null) { // may be null for e.g. default project currentProjectViewPane.updateFromRoot(false); } } private boolean isCurrentSelectionObsolete(boolean requestFocus) { if (myCurrentSelectionObsolete == ThreeState.YES) { myCurrentSelectionObsolete = ThreeState.NO; return true; } if (myCurrentSelectionObsolete == ThreeState.UNSURE) { myCurrentSelectionObsolete = requestFocus ? ThreeState.YES : ThreeState.NO; } return false; } @Override public void select(final Object element, VirtualFile file, boolean requestFocus) { if (isCurrentSelectionObsolete(requestFocus)) return; final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane != null) { viewPane.select(element, file, requestFocus); } } @NotNull @Override public ActionCallback selectCB(Object element, VirtualFile file, boolean requestFocus) { if (isCurrentSelectionObsolete(requestFocus)) return ActionCallback.REJECTED; final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane instanceof AbstractProjectViewPSIPane) { return ((AbstractProjectViewPSIPane)viewPane).selectCB(element, file, requestFocus); } select(element, file, requestFocus); return ActionCallback.DONE; } @Override public void dispose() { myConnection.disconnect(); } @Override public JComponent getComponent() { return myDataProvider; } @Override public String getCurrentViewId() { return myCurrentViewId; } private SelectInTarget getCurrentSelectInTarget() { return getSelectInTarget(getCurrentViewId()); } private SelectInTarget getSelectInTarget(String id) { return mySelectInTargets.get(id); } private ProjectViewSelectInTarget getProjectViewSelectInTarget(AbstractProjectViewPane pane) { SelectInTarget target = getSelectInTarget(pane.getId()); return target instanceof ProjectViewSelectInTarget ? (ProjectViewSelectInTarget)target : null; } @Override public PsiElement getParentOfCurrentSelection() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane == null) { return null; } TreePath path = viewPane.getSelectedPath(); if (path == null) { return null; } path = path.getParentPath(); if (path == null) { return null; } ProjectViewNode descriptor = TreeUtil.getLastUserObject(ProjectViewNode.class, path); if (descriptor != null) { Object element = descriptor.getValue(); if (element instanceof PsiElement) { PsiElement psiElement = (PsiElement)element; if (!psiElement.isValid()) return null; return psiElement; } else { return null; } } return null; } public ContentManager getContentManager() { if (myContentManager == null) { ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.PROJECT_VIEW).getContentManager(); } return myContentManager; } @Override public void changeView() { final List<AbstractProjectViewPane> views = new ArrayList<>(myId2Pane.values()); views.remove(getCurrentProjectViewPane()); Collections.sort(views, PANE_WEIGHT_COMPARATOR); IPopupChooserBuilder<AbstractProjectViewPane> builder = JBPopupFactory.getInstance() .createPopupChooserBuilder(views) .setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); AbstractProjectViewPane pane = (AbstractProjectViewPane)value; setText(pane.getTitle()); return this; } }) .setTitle(IdeBundle.message("title.popup.views")) .setItemChosenCallback(pane -> changeView(pane.getId())); if (!views.isEmpty()) { builder = builder.setSelectedValue(views.get(0), true); } builder .createPopup() .showInCenterOf(getComponent()); } @Override public void changeView(@NotNull String viewId) { changeView(viewId, null); } @Override public void changeView(@NotNull String viewId, @Nullable String subId) { changeViewCB(viewId, subId); } @NotNull @Override public ActionCallback changeViewCB(@NotNull String viewId, @Nullable String subId) { AbstractProjectViewPane pane = getProjectViewPaneById(viewId); LOG.assertTrue(pane != null, "Project view pane not found: " + viewId + "; subId:" + subId + "; project: " + myProject); boolean hasSubViews = pane.getSubIds().length > 0; if (hasSubViews) { if (subId == null) { // we try not to change subview // get currently selected subId from the pane subId = pane.getSubId(); } } else { if (subId != null) { LOG.error("View doesn't have subviews: " + viewId + "; subId:" + subId + "; project: " + myProject); } } if (viewId.equals(myCurrentViewId) && Objects.equals(subId, myCurrentViewSubId)) return ActionCallback.REJECTED; // at this point null subId means that view has no subviews OR subview was never selected // we then search first content with the right viewId ignoring subIds of contents for (Content content : getContentManager().getContents()) { if (viewId.equals(content.getUserData(ID_KEY)) && (subId == null || subId.equals(content.getUserData(SUB_ID_KEY)))) { return getContentManager().setSelectedContentCB(content); } } return ActionCallback.REJECTED; } private final class MyDeletePSIElementProvider implements DeleteProvider { @Override public boolean canDeleteElement(@NotNull DataContext dataContext) { final PsiElement[] elements = getElementsToDelete(); return DeleteHandler.shouldEnableDeleteAction(elements); } @Override public void deleteElement(@NotNull DataContext dataContext) { List<PsiElement> validElements = new ArrayList<>(); for (PsiElement psiElement : getElementsToDelete()) { if (psiElement != null && psiElement.isValid()) validElements.add(psiElement); } final PsiElement[] elements = PsiUtilCore.toPsiElementArray(validElements); LocalHistoryAction a = LocalHistory.getInstance().startAction(IdeBundle.message("progress.deleting")); try { TransactionGuard.getInstance().submitTransactionAndWait(() -> DeleteHandler.deletePsiElement(elements, myProject)); } finally { a.finish(); } } @NotNull private PsiElement[] getElementsToDelete() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); PsiElement[] elements = viewPane.getSelectedPSIElements(); for (int idx = 0; idx < elements.length; idx++) { final PsiElement element = elements[idx]; if (element instanceof PsiDirectory) { PsiDirectory directory = (PsiDirectory)element; final ProjectViewDirectoryHelper directoryHelper = ProjectViewDirectoryHelper.getInstance(myProject); if (isHideEmptyMiddlePackages(viewPane.getId()) && directory.getChildren().length == 0 && !directoryHelper.skipDirectory(directory)) { while (true) { PsiDirectory parent = directory.getParentDirectory(); if (parent == null) break; if (directoryHelper.skipDirectory(parent) || PsiDirectoryFactory.getInstance(myProject).getQualifiedName(parent, false).isEmpty()) break; PsiElement[] children = parent.getChildren(); if (children.length == 0 || children.length == 1 && children[0] == directory) { directory = parent; } else { break; } } elements[idx] = directory; } final VirtualFile virtualFile = directory.getVirtualFile(); final String path = virtualFile.getPath(); if (path.endsWith(JarFileSystem.JAR_SEPARATOR)) { // if is jar-file root final VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(path.substring(0, path.length() - JarFileSystem.JAR_SEPARATOR.length())); if (vFile != null) { final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(vFile); if (psiFile != null) { elements[idx] = psiFile; } } } } } return elements; } } private final class MyPanel extends JPanel implements DataProvider { MyPanel() { super(new BorderLayout()); Collection<AbstractProjectViewPane> snapshot = new ArrayList<>(myId2Pane.values()); UIUtil.putClientProperty( this, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, (Iterable<JComponent>)() -> JBIterable.from(snapshot) .map(pane -> { JComponent last = null; for (Component c : UIUtil.uiParents(pane.getComponentToFocus(), false)) { if (c == this || !(c instanceof JComponent)) return null; last = (JComponent)c; } return last; }) .filter(Conditions.notNull()) .iterator()); } @Nullable private Object getSelectedNodeElement() { final AbstractProjectViewPane currentProjectViewPane = getCurrentProjectViewPane(); if (currentProjectViewPane == null) { // can happen if not initialized yet return null; } NodeDescriptor descriptor = TreeUtil.getLastUserObject(NodeDescriptor.class, currentProjectViewPane.getSelectedPath()); if (descriptor == null) { return null; } return descriptor instanceof AbstractTreeNode ? ((AbstractTreeNode)descriptor).getValue() : descriptor.getElement(); } @Override public Object getData(@NotNull String dataId) { final AbstractProjectViewPane currentProjectViewPane = getCurrentProjectViewPane(); if (currentProjectViewPane != null) { final Object paneSpecificData = currentProjectViewPane.getData(dataId); if (paneSpecificData != null) return paneSpecificData; } if (CommonDataKeys.PSI_ELEMENT.is(dataId)) { if (currentProjectViewPane == null) return null; final PsiElement[] elements = currentProjectViewPane.getSelectedPSIElements(); return elements.length == 1 ? elements[0] : null; } if (LangDataKeys.PSI_ELEMENT_ARRAY.is(dataId)) { if (currentProjectViewPane == null) { return null; } PsiElement[] elements = currentProjectViewPane.getSelectedPSIElements(); return elements.length == 0 ? null : elements; } if (LangDataKeys.MODULE.is(dataId)) { VirtualFile[] virtualFiles = (VirtualFile[])getData(CommonDataKeys.VIRTUAL_FILE_ARRAY.getName()); if (virtualFiles == null || virtualFiles.length <= 1) return null; final Set<Module> modules = new HashSet<>(); for (VirtualFile virtualFile : virtualFiles) { modules.add(ModuleUtilCore.findModuleForFile(virtualFile, myProject)); } return modules.size() == 1 ? modules.iterator().next() : null; } if (LangDataKeys.TARGET_PSI_ELEMENT.is(dataId)) { return null; } if (PlatformDataKeys.CUT_PROVIDER.is(dataId)) { return myCopyPasteDelegator.getCutProvider(); } if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) { return myCopyPasteDelegator.getCopyProvider(); } if (PlatformDataKeys.PASTE_PROVIDER.is(dataId)) { return myCopyPasteDelegator.getPasteProvider(); } if (LangDataKeys.IDE_VIEW.is(dataId)) { return myIdeView; } if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER.is(dataId)) { final Module[] modules = getSelectedModules(); if (modules != null || !getSelectedUnloadedModules().isEmpty()) { return myDeleteModuleProvider; } final LibraryOrderEntry orderEntry = getSelectedLibrary(); if (orderEntry != null) { return new DeleteProvider() { @Override public void deleteElement(@NotNull DataContext dataContext) { detachLibrary(orderEntry, myProject); } @Override public boolean canDeleteElement(@NotNull DataContext dataContext) { return true; } }; } return myDeletePSIElementProvider; } if (PlatformDataKeys.HELP_ID.is(dataId)) { return HelpID.PROJECT_VIEWS; } if (DATA_KEY.is(dataId)) { return ProjectViewImpl.this; } if (PlatformDataKeys.PROJECT_CONTEXT.is(dataId)) { Object selected = getSelectedNodeElement(); return selected instanceof Project ? selected : null; } if (LangDataKeys.MODULE_CONTEXT.is(dataId)) { Object selected = getSelectedNodeElement(); if (selected instanceof Module) { return !((Module)selected).isDisposed() ? selected : null; } else if (selected instanceof PsiDirectory) { return moduleBySingleContentRoot(((PsiDirectory)selected).getVirtualFile()); } else if (selected instanceof VirtualFile) { return moduleBySingleContentRoot((VirtualFile)selected); } else { return null; } } if (LangDataKeys.MODULE_CONTEXT_ARRAY.is(dataId)) { return getSelectedModules(); } if (UNLOADED_MODULES_CONTEXT_KEY.is(dataId)) { return Collections.unmodifiableList(getSelectedUnloadedModules()); } if (ModuleGroup.ARRAY_DATA_KEY.is(dataId)) { final List<ModuleGroup> selectedElements = getSelectedElements(ModuleGroup.class); return selectedElements.isEmpty() ? null : selectedElements.toArray(new ModuleGroup[0]); } if (LibraryGroupElement.ARRAY_DATA_KEY.is(dataId)) { final List<LibraryGroupElement> selectedElements = getSelectedElements(LibraryGroupElement.class); return selectedElements.isEmpty() ? null : selectedElements.toArray(new LibraryGroupElement[0]); } if (NamedLibraryElement.ARRAY_DATA_KEY.is(dataId)) { final List<NamedLibraryElement> selectedElements = getSelectedElements(NamedLibraryElement.class); return selectedElements.isEmpty() ? null : selectedElements.toArray(new NamedLibraryElement[0]); } if (PlatformDataKeys.SELECTED_ITEMS.is(dataId)) { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); return viewPane == null ? null : viewPane.getSelectedElements(); } if (QuickActionProvider.KEY.is(dataId)) { return ProjectViewImpl.this; } return null; } @Nullable private LibraryOrderEntry getSelectedLibrary() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane == null) return null; TreePath path = viewPane.getSelectedPath(); if (path == null) return null; TreePath parent = path.getParentPath(); if (parent == null) return null; Object userObject = TreeUtil.getLastUserObject(parent); if (userObject instanceof LibraryGroupNode) { userObject = TreeUtil.getLastUserObject(path); if (userObject instanceof NamedLibraryElementNode) { NamedLibraryElement element = ((NamedLibraryElementNode)userObject).getValue(); OrderEntry orderEntry = element.getOrderEntry(); return orderEntry instanceof LibraryOrderEntry ? (LibraryOrderEntry)orderEntry : null; } PsiDirectory directory = ((PsiDirectoryNode)userObject).getValue(); VirtualFile virtualFile = directory.getVirtualFile(); Module module = (Module)TreeUtil.getLastUserObject(AbstractTreeNode.class, parent.getParentPath()).getValue(); if (module == null) return null; ModuleFileIndex index = ModuleRootManager.getInstance(module).getFileIndex(); OrderEntry entry = index.getOrderEntryForFile(virtualFile); if (entry instanceof LibraryOrderEntry) { return (LibraryOrderEntry)entry; } } return null; } private void detachLibrary(@NotNull final LibraryOrderEntry orderEntry, @NotNull Project project) { final Module module = orderEntry.getOwnerModule(); String message = IdeBundle.message("detach.library.from.module", orderEntry.getPresentableName(), module.getName()); String title = IdeBundle.message("detach.library"); int ret = Messages.showOkCancelDialog(project, message, title, Messages.getQuestionIcon()); if (ret != Messages.OK) return; CommandProcessor.getInstance().executeCommand(module.getProject(), () -> { final Runnable action = () -> { ModuleRootManager rootManager = ModuleRootManager.getInstance(module); OrderEntry[] orderEntries = rootManager.getOrderEntries(); ModifiableRootModel model = rootManager.getModifiableModel(); OrderEntry[] modifiableEntries = model.getOrderEntries(); for (int i = 0; i < orderEntries.length; i++) { OrderEntry entry = orderEntries[i]; if (entry instanceof LibraryOrderEntry && ((LibraryOrderEntry)entry).getLibrary() == orderEntry.getLibrary()) { model.removeOrderEntry(modifiableEntries[i]); } } model.commit(); }; ApplicationManager.getApplication().runWriteAction(action); }, title, null); } @Nullable private Module[] getSelectedModules() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane == null) return null; final Object[] elements = viewPane.getSelectedElements(); ArrayList<Module> result = new ArrayList<>(); for (Object element : elements) { if (element instanceof Module) { final Module module = (Module)element; if (!module.isDisposed()) { result.add(module); } } else if (element instanceof ModuleGroup) { Collection<Module> modules = ((ModuleGroup)element).modulesInGroup(myProject, true); result.addAll(modules); } else if (element instanceof PsiDirectory) { Module module = moduleBySingleContentRoot(((PsiDirectory)element).getVirtualFile()); if (module != null) result.add(module); } else if (element instanceof VirtualFile) { Module module = moduleBySingleContentRoot((VirtualFile)element); if (module != null) result.add(module); } } return result.isEmpty() ? null : result.toArray(Module.EMPTY_ARRAY); } private List<UnloadedModuleDescription> getSelectedUnloadedModules() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane == null) return Collections.emptyList(); List<UnloadedModuleDescription> result = new SmartList<>(); for (Object element : viewPane.getSelectedElements()) { if (element instanceof PsiDirectory) { ContainerUtil.addIfNotNull(result, getUnloadedModuleByContentRoot(((PsiDirectory)element).getVirtualFile())); } else if (element instanceof VirtualFile) { ContainerUtil.addIfNotNull(result, getUnloadedModuleByContentRoot((VirtualFile)element)); } } return result; } } /** Project view has the same node for module and its single content root * => MODULE_CONTEXT data key should return the module when its content root is selected * When there are multiple content roots, they have different nodes under the module node * => MODULE_CONTEXT should be only available for the module node * otherwise VirtualFileArrayRule will return all module's content roots when just one of them is selected */ @Nullable private Module moduleBySingleContentRoot(@NotNull VirtualFile file) { if (ProjectRootsUtil.isModuleContentRoot(file, myProject)) { Module module = ProjectRootManager.getInstance(myProject).getFileIndex().getModuleForFile(file); if (module != null && !module.isDisposed() && ModuleRootManager.getInstance(module).getContentRoots().length == 1) { return module; } } return null; } @Nullable private UnloadedModuleDescription getUnloadedModuleByContentRoot(@NotNull VirtualFile file) { String moduleName = ProjectRootsUtil.findUnloadedModuleByContentRoot(file, myProject); if (moduleName != null) { return ModuleManager.getInstance(myProject).getUnloadedModuleDescription(moduleName); } return null; } @NotNull private <T> List<T> getSelectedElements(@NotNull Class<T> klass) { List<T> result = new ArrayList<>(); final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane == null) return result; final Object[] elements = viewPane.getSelectedElements(); for (Object element : elements) { //element still valid if (element != null && klass.isAssignableFrom(element.getClass())) { result.add((T)element); } } return result; } @Override public void selectPsiElement(@NotNull PsiElement element, boolean requestFocus) { VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element); select(element, virtualFile, requestFocus); } @Override public void loadState(@NotNull Element parentNode) { Element navigatorElement = parentNode.getChild(ELEMENT_NAVIGATOR); if (navigatorElement != null) { mySavedPaneId = navigatorElement.getAttributeValue(ATTRIBUTE_CURRENT_VIEW); mySavedPaneSubId = navigatorElement.getAttributeValue(ATTRIBUTE_CURRENT_SUBVIEW); if (mySavedPaneId == null) { mySavedPaneId = getDefaultViewId(); mySavedPaneSubId = null; } try { splitterProportions.readExternal(navigatorElement); } catch (InvalidDataException ignored) { } } Element panesElement = parentNode.getChild(ELEMENT_PANES); if (panesElement != null) { readPaneState(panesElement); } } @NotNull public static String getDefaultViewId() { //noinspection SpellCheckingInspection if ("AndroidStudio".equals(PlatformUtils.getPlatformPrefix()) && !Boolean.getBoolean("studio.projectview")) { // the default in Android Studio unless studio.projectview is set: issuetracker.google.com/37091465 return "AndroidView"; } else { return ProjectViewPane.ID; } } private void readPaneState(@NotNull Element panesElement) { final List<Element> paneElements = panesElement.getChildren(ELEMENT_PANE); for (Element paneElement : paneElements) { String paneId = paneElement.getAttributeValue(ATTRIBUTE_ID); if (StringUtil.isEmptyOrSpaces(paneId)) { continue; } final AbstractProjectViewPane pane = myId2Pane.get(paneId); if (pane != null) { try { pane.readExternal(paneElement); } catch (InvalidDataException ignore) { } } else { myUninitializedPaneState.put(paneId, paneElement); } } } @Override public Element getState() { Element parentNode = new Element("projectView"); Element navigatorElement = new Element(ELEMENT_NAVIGATOR); AbstractProjectViewPane currentPane = getCurrentProjectViewPane(); if (currentPane != null) { String subId = currentPane.getSubId(); if (subId != null || !currentPane.getId().equals(getDefaultViewId())) { navigatorElement.setAttribute(ATTRIBUTE_CURRENT_VIEW, currentPane.getId()); if (subId != null) { navigatorElement.setAttribute(ATTRIBUTE_CURRENT_SUBVIEW, subId); } } } splitterProportions.saveSplitterProportions(myPanel); try { splitterProportions.writeExternal(navigatorElement); } catch (WriteExternalException ignored) { } if (!JDOMUtil.isEmpty(navigatorElement)) { parentNode.addContent(navigatorElement); } Element panesElement = new Element(ELEMENT_PANES); writePaneState(panesElement); parentNode.addContent(panesElement); return parentNode; } private void writePaneState(@NotNull Element panesElement) { for (AbstractProjectViewPane pane : myId2Pane.values()) { Element paneElement = new Element(ELEMENT_PANE); paneElement.setAttribute(ATTRIBUTE_ID, pane.getId()); try { pane.writeExternal(paneElement); } catch (WriteExternalException e) { continue; } panesElement.addContent(paneElement); } for (Element element : myUninitializedPaneState.values()) { panesElement.addContent(element.clone()); } } private static ProjectViewSharedSettings getGlobalOptions() { return ProjectViewSharedSettings.Companion.getInstance(); } @Override public boolean isAutoscrollToSource(String paneId) { return myAutoscrollToSource.isSelected() && myAutoscrollToSource.isEnabled(paneId); } public void setAutoscrollToSource(boolean autoscrollMode, String paneId) { if (myAutoscrollToSource.isEnabled(paneId)) myAutoscrollToSource.setSelected(autoscrollMode); } @Override public boolean isAutoscrollFromSource(String paneId) { return myAutoscrollFromSource.isSelected() && myAutoscrollFromSource.isEnabled(paneId); } public void setAutoscrollFromSource(boolean autoscrollMode, String paneId) { if (myAutoscrollFromSource.isEnabled(paneId)) myAutoscrollFromSource.setSelected(autoscrollMode); } @Override public boolean isFlattenPackages(String paneId) { return myFlattenPackages.isSelected() && myFlattenPackages.isEnabled(paneId); } public void setFlattenPackages(String paneId, boolean flattenPackages) { if (myFlattenPackages.isEnabled(paneId)) myFlattenPackages.setSelected(flattenPackages); } @Override public boolean isFoldersAlwaysOnTop(String paneId) { return myFoldersAlwaysOnTop.isSelected() && myFoldersAlwaysOnTop.isEnabled(paneId); } /** * @deprecated use {@link ProjectView#isFoldersAlwaysOnTop(String)} instead */ @Deprecated @SuppressWarnings("DeprecatedIsStillUsed") public boolean isFoldersAlwaysOnTop() { return myFoldersAlwaysOnTop.isSelected() && myFoldersAlwaysOnTop.isEnabled(); } public void setFoldersAlwaysOnTop(boolean foldersAlwaysOnTop) { if (myFoldersAlwaysOnTop.isEnabled()) myFoldersAlwaysOnTop.setSelected(foldersAlwaysOnTop); } @Override public boolean isShowMembers(String paneId) { return myShowMembers.isSelected() && myShowMembers.isEnabled(paneId); } @Override public boolean isHideEmptyMiddlePackages(String paneId) { return myHideEmptyMiddlePackages.isSelected() && myHideEmptyMiddlePackages.isEnabled(paneId); } @Override public boolean isAbbreviatePackageNames(String paneId) { return myAbbreviatePackageNames.isSelected() && myAbbreviatePackageNames.isEnabled(paneId); } @Override public boolean isShowExcludedFiles(String paneId) { return myShowExcludedFiles.isSelected() && myShowExcludedFiles.isEnabled(paneId); } @Override public boolean isShowVisibilityIcons(String paneId) { return myShowVisibilityIcons.isSelected() && myShowVisibilityIcons.isEnabled(paneId); } @Override public boolean isShowLibraryContents(String paneId) { return myShowLibraryContents.isSelected() && myShowLibraryContents.isEnabled(paneId); } @Override public void setShowLibraryContents(@NotNull String paneId, boolean showLibraryContents) { if (myShowLibraryContents.isEnabled(paneId)) myShowLibraryContents.setSelected(showLibraryContents); } @Override public boolean isShowModules(String paneId) { return myShowModules.isSelected() && myShowModules.isEnabled(paneId); } @Override public void setShowModules(@NotNull String paneId, boolean showModules) { if (myShowModules.isEnabled(paneId)) myShowModules.setSelected(showModules); } @Override public boolean isFlattenModules(String paneId) { return myFlattenModules.isSelected() && myFlattenModules.isEnabled(paneId); } @Override public void setFlattenModules(@NotNull String paneId, boolean flattenModules) { if (myFlattenModules.isEnabled(paneId)) myFlattenModules.setSelected(flattenModules); } @Override public boolean isShowURL(String paneId) { return Registry.is("project.tree.structure.show.url"); } @Override public void setHideEmptyPackages(@NotNull String paneId, boolean hideEmptyPackages) { if (myHideEmptyMiddlePackages.isEnabled(paneId)) myHideEmptyMiddlePackages.setSelected(hideEmptyPackages); } @Override public boolean isCompactDirectories(String paneId) { return myCompactDirectories.isSelected() && myCompactDirectories.isEnabled(paneId); } @Override public void setCompactDirectories(@NotNull String paneId, boolean compactDirectories) { if (myCompactDirectories.isEnabled(paneId)) myCompactDirectories.setSelected(compactDirectories); } @Override public void setAbbreviatePackageNames(@NotNull String paneId, boolean abbreviatePackageNames) { if (myAbbreviatePackageNames.isEnabled(paneId)) myAbbreviatePackageNames.setSelected(abbreviatePackageNames); } private static class SelectionInfo { @NotNull private final Object[] myElements; private SelectionInfo(@NotNull Object[] elements) { myElements = elements; } public void apply(final AbstractProjectViewPane viewPane) { if (viewPane == null) { return; } AbstractTreeBuilder treeBuilder = viewPane.getTreeBuilder(); JTree tree = viewPane.myTree; if (treeBuilder != null) { DefaultTreeModel treeModel = (DefaultTreeModel)tree.getModel(); List<TreePath> paths = new ArrayList<>(myElements.length); for (final Object element : myElements) { DefaultMutableTreeNode node = treeBuilder.getNodeForElement(element); if (node == null) { treeBuilder.buildNodeForElement(element); node = treeBuilder.getNodeForElement(element); } if (node != null) { paths.add(new TreePath(treeModel.getPathToRoot(node))); } } if (!paths.isEmpty()) { tree.setSelectionPaths(toTreePathArray(paths)); } } else { List<TreeVisitor> visitors = AbstractProjectViewPane.createVisitors(myElements); if (1 == visitors.size()) { TreeUtil.promiseSelect(tree, visitors.get(0)); } else if (!visitors.isEmpty()) { TreeUtil.promiseSelect(tree, visitors.stream()); } } } @NotNull public static SelectionInfo create(final AbstractProjectViewPane viewPane) { List<Object> selectedElements = Collections.emptyList(); if (viewPane != null) { final TreePath[] selectionPaths = viewPane.getSelectionPaths(); if (selectionPaths != null) { selectedElements = new ArrayList<>(); for (TreePath path : selectionPaths) { NodeDescriptor descriptor = TreeUtil.getLastUserObject(NodeDescriptor.class, path); if (descriptor != null) selectedElements.add(descriptor.getElement()); } } } return new SelectionInfo(selectedElements.toArray()); } } private class MyAutoScrollFromSourceHandler extends AutoScrollFromSourceHandler { private MyAutoScrollFromSourceHandler() { super(ProjectViewImpl.this.myProject, myViewContentPanel, ProjectViewImpl.this); } @Override protected void selectElementFromEditor(@NotNull FileEditor fileEditor) { if (myProject.isDisposed() || !myViewContentPanel.isShowing()) return; if (isAutoscrollFromSource(getCurrentViewId()) && !isCurrentProjectViewPaneFocused()) { SimpleSelectInContext context = getSelectInContext(fileEditor); if (context != null) context.selectInCurrentTarget(); } } void scrollFromSource() { SimpleSelectInContext context = findSelectInContext(); if (context != null) context.selectInCurrentTarget(); } @Nullable SimpleSelectInContext findSelectInContext() { FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject); SimpleSelectInContext context = getSelectInContext(fileEditorManager.getSelectedEditor()); if (context != null) return context; for (FileEditor fileEditor : fileEditorManager.getSelectedEditors()) { context = getSelectInContext(fileEditor); if (context != null) return context; } return null; } @Nullable private SimpleSelectInContext getSelectInContext(@Nullable FileEditor fileEditor) { if (fileEditor instanceof TextEditor) { TextEditor textEditor = (TextEditor)fileEditor; PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(textEditor.getEditor().getDocument()); return psiFile == null ? null : new EditorSelectInContext(psiFile, textEditor.getEditor()); } PsiFile psiFile = getPsiFile(getVirtualFile(fileEditor)); return psiFile == null ? null : new SimpleSelectInContext(psiFile); } private PsiFile getPsiFile(VirtualFile file) { return file == null || !file.isValid() ? null : PsiManager.getInstance(myProject).findFile(file); } private VirtualFile getVirtualFile(FileEditor fileEditor) { return fileEditor == null ? null : FileEditorManagerEx.getInstanceEx(myProject).getFile(fileEditor); } private boolean isCurrentProjectViewPaneFocused() { AbstractProjectViewPane pane = getCurrentProjectViewPane(); return pane != null && IJSwingUtilities.hasFocus(pane.getComponentToFocus()); } @Override protected boolean isAutoScrollEnabled() { return myAutoscrollFromSource.isSelected(); } @Override protected void setAutoScrollEnabled(boolean state) { myAutoscrollFromSource.setSelected(state); } @Override protected String getActionName() { return myAutoscrollFromSource.getName(); } @Override protected String getActionDescription() { return myAutoscrollFromSource.getDescription(); } } private class SimpleSelectInContext extends SmartSelectInContext { SimpleSelectInContext(@NotNull PsiFile psiFile) { super(psiFile, psiFile); } void selectInCurrentTarget() { SelectInTarget target = getCurrentSelectInTarget(); if (target != null && getPsiFile() != null) { selectIn(target, false); } } @Override @NotNull public FileEditorProvider getFileEditorProvider() { return () -> ArrayUtil.getFirstElement(FileEditorManager.getInstance(myProject).openFile(getVirtualFile(), false)); } } private class EditorSelectInContext extends SimpleSelectInContext { private final Editor editor; EditorSelectInContext(@NotNull PsiFile psiFile, @NotNull Editor editor) { super(psiFile); this.editor = editor; } @Override void selectInCurrentTarget() { if (PsiDocumentManager.getInstance(getProject()) == null) return; runWhenPsiAtCaretIsParsed(super::selectInCurrentTarget); } private void runWhenPsiAtCaretIsParsed(Runnable runnable) { int offset = editor.getCaretModel().getOffset(); ReadAction .nonBlocking(() -> { PsiFile file = getPsiFile(); return file == null ? null : file.findElementAt(offset); }) .withDocumentsCommitted(getProject()) .finishOnUiThread(ModalityState.defaultModalityState(), parsedLeaf -> { if (editor.getCaretModel().getOffset() != offset) { runWhenPsiAtCaretIsParsed(runnable); } else { runnable.run(); } }) .submit(ourParsingExecutor); } @Override public Object getSelectorInFile() { PsiFile file = getPsiFile(); if (file != null) { int offset = editor.getCaretModel().getOffset(); PsiDocumentManager manager = PsiDocumentManager.getInstance(getProject()); LOG.assertTrue(manager.isCommitted(editor.getDocument())); PsiElement element = file.findElementAt(offset); if (element != null) return element; } return file; } } @Override public boolean isManualOrder(String paneId) { return myManualOrder.isSelected() && myManualOrder.isEnabled(paneId); } @Override public void setManualOrder(@NotNull String paneId, final boolean enabled) { if (myManualOrder.isEnabled(paneId)) myManualOrder.setSelected(enabled); } @Override public boolean isSortByType(String paneId) { return mySortByType.isSelected() && mySortByType.isEnabled(paneId); } @Override public void setSortByType(@NotNull String paneId, final boolean sortByType) { if (mySortByType.isEnabled(paneId)) mySortByType.setSelected(sortByType); } private class ScrollFromSourceAction extends AnAction implements DumbAware { private ScrollFromSourceAction() { super("Select Opened File" + getScrollToSourceShortcut(), "Select the file open in the active editor", AllIcons.General.Locate); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myAutoScrollFromSourceHandler.scrollFromSource(); } @Override public void update(@NotNull AnActionEvent event) { event.getPresentation().setEnabledAndVisible(!isAutoscrollFromSource(myCurrentViewId)); } } private String getScrollToSourceShortcut() { String selectInProjectViewShortcut = KeymapUtil.getFirstKeyboardShortcutText("SelectInProjectView"); if (!selectInProjectViewShortcut.isEmpty()) { return " (" + selectInProjectViewShortcut + ")"; } String selectInShortcut = KeymapUtil.getFirstKeyboardShortcutText("SelectIn"); if (!selectInShortcut.isEmpty()) { SelectInTarget[] targets = SelectInManager.getInstance(myProject).getTargets(); int index = ContainerUtil.indexOf(Arrays.asList(targets), (target) -> target instanceof ProjectViewSelectInGroupTarget); if (index >= 0) { return " (" + selectInShortcut + ", " + (index + 1) + ")"; } } return ""; } @NotNull @Override public Collection<String> getPaneIds() { return Collections.unmodifiableCollection(myId2Pane.keySet()); } @NotNull @Override public Collection<SelectInTarget> getSelectInTargets() { ensurePanesLoaded(); return mySelectInTargets.values(); } @NotNull @Override public ActionCallback getReady(@NotNull Object requestor) { AbstractProjectViewPane pane = myId2Pane.get(myCurrentViewSubId); if (pane == null) { pane = myId2Pane.get(myCurrentViewId); } return pane != null ? pane.getReady(requestor) : ActionCallback.DONE; } @NotNull public ToggleAction getAutoScrollToSourceAction() { return Action.AUTOSCROLL_TO_SOURCE; } @NotNull public ToggleAction getAutoScrollFromSourceAction() { return Action.AUTOSCROLL_FROM_SOURCE; } private void updatePanes(boolean withComparator) { for (AbstractProjectViewPane pane : myId2Pane.values()) { JTree tree = pane.getTree(); if (tree != null) { SelectionInfo info = pane.getId().equals(myCurrentViewId) ? SelectionInfo.create(pane) : null; if (withComparator) pane.installComparator(); pane.updateFromRoot(false); if (info != null) info.apply(pane); } } } abstract class Option implements ToggleOptionAction.Option { @Override public boolean isEnabled() { return isEnabled(getCurrentViewId()); } boolean isEnabled(@Nullable String paneId) { AbstractProjectViewPane pane = myId2Pane.get(paneId); return pane != null ? isEnabled(pane) : ApplicationManager.getApplication().isUnitTestMode(); } boolean isEnabled(@NotNull AbstractProjectViewPane pane) { return true; } } static class Action extends ToggleOptionAction implements DumbAware { static final Action ABBREVIATE_PACKAGE_NAMES = new Action(view -> view.myAbbreviatePackageNames, AllIcons.ObjectBrowser.AbbreviatePackageNames); static final Action AUTOSCROLL_FROM_SOURCE = new Action(view -> view.myAutoscrollFromSource, AllIcons.General.AutoscrollFromSource); static final Action AUTOSCROLL_TO_SOURCE = new Action(view -> view.myAutoscrollToSource, AllIcons.General.AutoscrollToSource); static final Action COMPACT_DIRECTORIES = new Action(view -> view.myCompactDirectories, null); static final Action FLATTEN_MODULES = new Action(view -> view.myFlattenModules, AllIcons.ObjectBrowser.FlattenModules); static final Action FLATTEN_PACKAGES = new Action(view -> view.myFlattenPackages, AllIcons.ObjectBrowser.FlattenPackages); static final Action FOLDERS_ALWAYS_ON_TOP = new Action(view -> view.myFoldersAlwaysOnTop, null); static final Action HIDE_EMPTY_MIDDLE_PACKAGES = new Action(view -> view.myHideEmptyMiddlePackages, null); static final Action MANUAL_ORDER = new Action(view -> view.myManualOrder, AllIcons.ObjectBrowser.Sorted); static final Action SHOW_EXCLUDED_FILES = new Action(view -> view.myShowExcludedFiles, null); static final Action SHOW_LIBRARY_CONTENTS = new Action(view -> view.myShowLibraryContents, AllIcons.ObjectBrowser.ShowLibraryContents); static final Action SHOW_MEMBERS = new Action(view -> view.myShowMembers, AllIcons.ObjectBrowser.ShowMembers); static final Action SHOW_MODULES = new Action(view -> view.myShowModules, AllIcons.Actions.GroupByModule); static final Action SHOW_VISIBILITY_ICONS = new Action(view -> view.myShowVisibilityIcons, null); static final Action SORT_BY_TYPE = new Action(view -> view.mySortByType, AllIcons.ObjectBrowser.SortByType); private Action(@NotNull Function<ProjectViewImpl, Option> optionSupplier, @Nullable Icon icon) { super(event -> { Project project = event.getProject(); ProjectView view = project == null || project.isDisposed() ? null : getInstance(project); return view instanceof ProjectViewImpl ? optionSupplier.apply((ProjectViewImpl)view) : null; }, icon); } } }
package com.khorn.terraincontrol.forge; import com.khorn.terraincontrol.LocalWorld; import com.khorn.terraincontrol.TerrainControl; import com.khorn.terraincontrol.configuration.WorldConfig; import com.khorn.terraincontrol.configuration.WorldSettings; import com.khorn.terraincontrol.forge.generator.BiomeCacheWrapper; import com.khorn.terraincontrol.forge.generator.TCWorldChunkManager; import com.khorn.terraincontrol.forge.util.WorldHelper; import com.khorn.terraincontrol.generator.biome.BiomeGenerator; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.world.World; import net.minecraft.world.WorldType; import net.minecraft.world.biome.WorldChunkManager; import net.minecraft.world.chunk.IChunkProvider; import java.io.File; public class TCWorldType extends WorldType { public ForgeWorld worldTC; public TCWorldType(String paramString) { super(paramString); } @SideOnly(Side.CLIENT) public boolean showWorldInfoNotice() { return true; } // Actually: getBiomeManager @Override public WorldChunkManager getChunkManager(World world) { try { if (world instanceof WorldClient) { return super.getChunkManager(world); } } catch (NoClassDefFoundError e) { // There isn't a WorldClient class, so we are on a stand-alone // server. Continue normally. } // Restore old biomes ForgeWorld.restoreBiomes(); // Load everything File worldDirectory = new File(TerrainControl.getEngine().getTCDataFolder(), "worlds" + File.separator + world.getSaveHandler().getWorldDirectoryName()); if (!worldDirectory.exists()) { System.out.println("TerrainControl: settings does not exist, creating defaults"); if (!worldDirectory.mkdirs()) System.out.println("TerrainControl: cant create folder " + worldDirectory.getAbsolutePath()); } this.worldTC = new ForgeWorld(world.getSaveHandler().getWorldDirectoryName()); WorldSettings config = new WorldSettings(worldDirectory, worldTC, false); this.worldTC.Init(world, config); WorldChunkManager chunkManager = null; Class<? extends BiomeGenerator> biomeManagerClass = this.worldTC.getSettings().worldConfig.biomeMode; if (biomeManagerClass == TerrainControl.getBiomeModeManager().VANILLA) { chunkManager = super.getChunkManager(world); } else { chunkManager = new TCWorldChunkManager(this.worldTC); BiomeGenerator biomeManager = TerrainControl.getBiomeModeManager().create(biomeManagerClass, worldTC, new BiomeCacheWrapper(chunkManager)); ((TCWorldChunkManager) chunkManager).setBiomeManager(biomeManager); this.worldTC.setBiomeManager(biomeManager); } return chunkManager; } @Override public IChunkProvider getChunkGenerator(World world, String generatorOptions) { if (this.worldTC.getSettings().worldConfig.ModeTerrain != WorldConfig.TerrainMode.Default) { return this.worldTC.getChunkGenerator(); } else return super.getChunkGenerator(world, generatorOptions); } @Override public int getMinimumSpawnHeight(World mcWorld) { LocalWorld world = WorldHelper.toLocalWorld(mcWorld); if (world == null) { // MCPC+ has an interesting load order sometimes return 64; } return world.getSettings().worldConfig.waterLevelMax; } }
package org.jboss.reddeer.gef.editor; import java.util.List; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPartListener; import org.eclipse.gef.GraphicalViewer; import org.eclipse.swt.widgets.Control; import org.jboss.reddeer.gef.GEFLayerException; import org.jboss.reddeer.gef.api.Palette; import org.jboss.reddeer.gef.condition.EditorHasEditParts; import org.jboss.reddeer.gef.handler.ViewerHandler; import org.jboss.reddeer.gef.impl.editpart.internal.BasicEditPart; import org.jboss.reddeer.gef.lookup.ViewerLookup; import org.jboss.reddeer.gef.view.PaletteView; import org.jboss.reddeer.core.reference.ReferencedComposite; import org.jboss.reddeer.core.util.Display; import org.jboss.reddeer.common.wait.WaitUntil; import org.jboss.reddeer.workbench.impl.editor.DefaultEditor; /** * * GEF Editor * * @author apodhrad * */ public class GEFEditor extends DefaultEditor implements ReferencedComposite { protected GraphicalViewer viewer; /** * Constructs a GEF editor with currently active editor. It also initializes graphical viewer which can be * overridden by initGraphicalViewer(). */ public GEFEditor() { super(); initGraphicalViewer(); } /** * Constructs a GEF editor with a given title. It also initializes graphical viewer which can be overridden by * initGraphicalViewer(). * * @param title * Editor title */ public GEFEditor(String title) { super(title); initGraphicalViewer(); } /** * Initializes a graphical viewer which is needed for GEF operations. */ protected void initGraphicalViewer() { viewer = ViewerLookup.getInstance().findGraphicalViewer(getEditorPart()); } protected GraphicalViewer getGraphicalViewer() { if (viewer == null) { throw new GEFLayerException( "No graphical viewer has been initialized. Graphical viewer is needed for many GED operations."); } return viewer; } /** * Returns the number of all available edit parts. * * @return Number of edit parts */ public int getNumberOfEditParts() { return ViewerHandler.getInstance().getEditParts(viewer).size(); } /** * Clicks at the specified coordinates. * * @param x * X-axis * @param y * Y-axis */ public void click(int x, int y) { ViewerHandler.getInstance().click(viewer, x, y); } /** * Returns a palette. * * @return Palette */ public Palette getPalette() { new PaletteView().open(); return ViewerHandler.getInstance().getPalette(viewer); } /** * Adds a tool from a palette to the specified coordinates. * * @param tool * Tool label * @param x * X-axis * @param y * Y-axis */ public org.jboss.reddeer.gef.api.EditPart addToolFromPalette(String tool, final int x, final int y) { return addToolFromPalette(tool, null, x, y); } /** * Adds a tool in a given group from a palette to the specified coordinates. * * @param tool * Tool label * @param group * Group label * @param x * X-axis * @param y * Y-axis */ public org.jboss.reddeer.gef.api.EditPart addToolFromPalette(String tool, String group, final int x, final int y) { int oldCount = getNumberOfEditParts(); final ViewerListener viewerListener = new ViewerListener(); Display.asyncExec(new Runnable() { @Override public void run() { List<EditPart> editParts = ViewerHandler.getInstance().getEditParts(viewer); for (EditPart editPart : editParts) { editPart.addEditPartListener(viewerListener); } } }); getPalette().activateTool(tool, group); click(x, y); return getAddedEditPart(viewerListener, oldCount); } /** * Waits and detects the new component. Override this method if you need to change the default behavior, e.g. if * there is a wizard before adding the component. * * @param viewerListener * Viewer listener * @param oldCount * Number of components before adding the new one * @return The new component */ protected org.jboss.reddeer.gef.api.EditPart getAddedEditPart(ViewerListener viewerListener, int oldCount) { new WaitUntil(new EditorHasEditParts(this, oldCount)); if (viewerListener.getAddedEditPart() == null) { throw new GEFLayerException("No new edit part was detected"); } return new BasicEditPart(viewerListener.getAddedEditPart()); } @Override public Control getControl() { return viewer.getControl(); } /** * Helper class for detecting changes in the viewer. * * @author Andrej Podhradsky (andrej.podhradsky@gmail.com) * */ private class ViewerListener implements EditPartListener { private EditPart addedEditPart; public EditPart getAddedEditPart() { return addedEditPart; } @Override public void childAdded(EditPart child, int index) { log.info("New edit part " + child); addedEditPart = child; } @Override public void partActivated(EditPart editpart) { } @Override public void partDeactivated(EditPart editpart) { } @Override public void removingChild(EditPart child, int index) { } @Override public void selectedStateChanged(EditPart editpart) { } } }
package view.editor.gameeditor; import java.util.ArrayList; import java.util.Arrays; import java.util.ResourceBundle; import api.IDataReader; import api.IDataWriter; import api.ISerializable; import datamanagement.XMLReader; import datamanagement.XMLWriter; import enums.DefaultStrings; import enums.GUISize; import enums.Indexes; import enums.ViewInsets; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import view.Authoring; import view.Utilities; import view.editor.Editor; public class GameEditor extends Editor { private VBox pane; private ResourceBundle myResources; @SuppressWarnings("unused") private Authoring authEnv; private String myLanguage; private ObservableList<ISerializable> masterEntityList; private ObservableList<ISerializable> masterEnvironmentList; private ObservableList<ISerializable> masterEventList; private ObservableList<String> userActions; private GameDetails gameDetails; private ObjectDisplay entDisp, envDisp, eventDisplay; public GameEditor(Authoring authEnv, String language, String fileName){ this(authEnv, language); loadFile(fileName); } public GameEditor(Authoring authEnv, String language){ myLanguage = language; gameDetails = new GameDetails(language); myResources = ResourceBundle.getBundle(language); this.authEnv=authEnv; this.masterEntityList = FXCollections.observableArrayList(); this.masterEnvironmentList = FXCollections.observableArrayList(); this.masterEventList = FXCollections.observableArrayList(); this.userActions = FXCollections.observableArrayList(); entDisp = new EntityDisplay(myLanguage, masterEntityList, authEnv); envDisp = new EnvironmentDisplay(myLanguage, masterEnvironmentList, masterEntityList, authEnv); eventDisplay = new EventDisplay(myLanguage, masterEntityList, authEnv, userActions); setPane(); } private void setPane() { pane = new VBox(GUISize.GAME_EDITOR_PADDING.getSize()); pane.setPadding(ViewInsets.GAME_EDIT.getInset()); pane.setAlignment(Pos.TOP_LEFT); } private void loadFile(String fileName) { IDataReader<SaveGame> xReader = new XMLReader<>(); SaveGame s = xReader.readSingleFromFile(DefaultStrings.CREATE_LOC.getDefault() + fileName+ DefaultStrings.XML.getDefault()); gameDetails.setDetails(Arrays.asList(s.getName(), s.getDesc(), s.getIcon())); masterEntityList.addAll(s.getEntites()); masterEnvironmentList.addAll(s.getEnvironments()); } @Override public Pane getPane() { populateLayout(); return pane; } @Override public void populateLayout() { VBox right = rightPane(); VBox left = leftPane(); left.prefWidthProperty().bind(pane.widthProperty().divide(2)); right.prefWidthProperty().bind(pane.widthProperty().divide(2)); HBox container = new HBox(GUISize.GAME_EDITOR_PADDING.getSize()); container.getChildren().addAll(left, right); pane.getChildren().addAll(container); } private VBox rightPane() { VBox temp = new VBox(GUISize.GAME_EDITOR_PADDING.getSize()); temp.getChildren().add( new Label(myResources.getString("entities"))); temp.getChildren().add(entDisp.init()); temp.getChildren().add( new Label(myResources.getString("environments"))); temp.getChildren().add(envDisp.init()); return temp; } private VBox leftPane() { VBox temp = new VBox(GUISize.GAME_EDITOR_PADDING.getSize()); temp.getChildren().addAll(gameDetails.getElements()); temp.getChildren().addAll(Arrays.asList(entDisp.makeNewObject(), envDisp.makeNewObject(), eventDisplay.makeNewObject(), Utilities.makeButton(myResources.getString("saveGame"), e->saveGame()))); return temp; } private void saveGame() { SaveGame sGame = new SaveGame(gameDetails.getGameDetails(), new ArrayList<ISerializable>(masterEntityList), new ArrayList<ISerializable>(masterEnvironmentList)); IDataWriter<SaveGame> writer = new XMLWriter<>(); String name = gameDetails.getGameDetails().get(Indexes.GAME_NAME.getIndex()); writer.writeToFile(DefaultStrings.CREATE_LOC.getDefault() + name.trim()+ DefaultStrings.XML.getDefault(),sGame); System.out.println("Saved"); } @Override public void updateEditor() { populateLayout(); } @Override public void addSerializable(ISerializable serialize) {} @Override public void loadDefaults() {} }
package railo.intergral.fusiondebug.server.util; import java.util.Iterator; import railo.intergral.fusiondebug.server.type.FDVariable; import railo.runtime.exp.PageException; import railo.runtime.op.Constants; import railo.runtime.type.Array; import railo.runtime.type.ArrayImpl; import railo.runtime.type.Collection; import railo.runtime.type.Collection.Key; import railo.runtime.type.KeyImpl; import railo.runtime.type.Query; import railo.runtime.type.QueryImpl; import railo.runtime.type.Struct; import railo.runtime.type.StructImpl; import com.intergral.fusiondebug.server.IFDValue; import com.intergral.fusiondebug.server.IFDVariable; public class FDDump { //private static PrintStream out=System.out; public static void dump(IFDVariable var) { System.out.print(toString(var)); } public static String toString(Object value) { StringBuffer sb=new StringBuffer(); dump(sb,value, 0); return sb.toString(); } public static String toString(IFDVariable var) { StringBuffer sb=new StringBuffer(); dump(sb,var, 0); return sb.toString(); } private static void dump(StringBuffer sb,Object value,int level) { if(value instanceof IFDValue) dump(sb, (IFDValue)value, level); else dump(sb, (IFDVariable)value, level); } private static void dump(StringBuffer sb,IFDValue value,int level) { for(int i=0;i<level;i++){ sb.append(" - "); } sb.append(value.toString()); sb.append("\n"); if(value.hasChildren()){ Iterator it = value.getChildren().iterator(); while(it.hasNext()){ Object o=it.next(); dump(sb,(IFDVariable) o,level+1); } } } private static void dump(StringBuffer sb,IFDVariable var,int level) { for(int i=0;i<level;i++){ sb.append(" - "); } sb.append(var.getName()); sb.append(":"); IFDValue value = var.getValue(); sb.append(value.toString()); sb.append("\n"); //print.err(value.getClass().getName()); if(value.hasChildren()){ Iterator it = value.getChildren().iterator(); while(it.hasNext()){ Object o=it.next(); //print.err(o.getClass().getName()); dump(sb,(IFDVariable) o,level+1); //dump(sb,(IFDVariable) it.next(),level+1); } } } /*public static void main(String[] args) throws PageException { Array arr = new ArrayImpl(); arr.setEL(1, "aaa"); arr.setEL(2, Boolean.TRUE); arr.setEL(5, Constants.INTEGER_3); Array sub1 = new ArrayImpl(); sub1.setEL(1, "ddd"); arr.setEL(6, sub1); Struct sct=new StructImpl(); sct.set("susi1", "eee"); sct.set("susi2", "fff"); arr.setEL(7, sct); Key aaa = KeyImpl.intern("aaa"); Key bbb = KeyImpl.intern("bbb"); Query qry=new QueryImpl(new Collection.Key[]{aaa,bbb},2,"quererli"); qry.setAt(aaa, 1, "a1"); qry.setAt(bbb, 1, "b1"); qry.setAt(aaa, 2, "a2"); qry.setAt(bbb, 2, sct); arr.setEL(8, qry); //arr.setEL(9, new StringBuffer()); dump(new FDVariable(null,"susi",FDCaster.toFDValue(null,"susi",qry))); //dump(new FDVariable(null,"susi",FDCaster.toFDValue(null,"susi",arr))); //dump(FDCaster.toFDVariable("susi",arr)); }*/ }
package railo.runtime.functions.arrays; import railo.runtime.PageContext; import railo.runtime.exp.PageException; import railo.runtime.ext.function.Function; import railo.runtime.type.Array; public final class ArrayFindNoCase implements Function { public static double call(PageContext pc , Array array, Object value) { return ArrayFind.find(array,value,false); } }
package org.eclipse.persistence.sdo.helper; import commonj.sdo.Property; import commonj.sdo.Type; import commonj.sdo.helper.DataHelper; import commonj.sdo.helper.HelperContext; import commonj.sdo.impl.HelperProvider; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; import java.util.TimeZone; import java.util.regex.Pattern; import javax.xml.namespace.QName; import org.eclipse.persistence.sdo.SDOConstants; import org.eclipse.persistence.sdo.SDOProperty; import org.eclipse.persistence.exceptions.ConversionException; import org.eclipse.persistence.exceptions.SDOException; import org.eclipse.persistence.internal.helper.ClassConstants; import org.eclipse.persistence.internal.oxm.XMLConversionManager; import org.eclipse.persistence.mappings.DatabaseMapping; import org.eclipse.persistence.oxm.XMLConstants; /** * <p><b>Purpose</b>: A helper class for performing data conversions.</p> */ public class SDODataHelper implements DataHelper { // hold the context containing all helpers so that we can preserve inter-helper relationships private HelperContext aHelperContext; private XMLConversionManager xmlConversionManager; public SDODataHelper() { // TODO: JIRA129 - default to static global context - Do Not use this convenience constructor outside of JUnit testing //aHelperContext = HelperProvider.getDefaultContext(); xmlConversionManager = (XMLConversionManager)XMLConversionManager.getDefaultXMLManager().clone(); xmlConversionManager.setTimeZone(TimeZone.getTimeZone("GMT")); } public SDODataHelper(HelperContext aContext) { aHelperContext = aContext; xmlConversionManager = (XMLConversionManager)XMLConversionManager.getDefaultXMLManager().clone(); xmlConversionManager.setTimeZone(TimeZone.getTimeZone("GMT")); } /** * The specified TimeZone will be used for all String to date object * conversions. By default the TimeZone from the JVM is used. */ public void setTimeZone(TimeZone timeZone) { if (null == timeZone) { xmlConversionManager.setTimeZone(TimeZone.getTimeZone("GMT")); } else { xmlConversionManager.setTimeZone(timeZone); } } /** * By setting this flag to true the marshalled date objects marshalled to * the XML schema types time and dateTime will be qualified by a time zone. * By default time information is not time zone qualified. */ public void setTimeZoneQualified(boolean timeZoneQualified) { xmlConversionManager.setTimeZoneQualified(timeZoneQualified); } public Date toDate(String dateString) { Calendar c = toCalendar(dateString); return c.getTime(); } public Calendar toCalendar(String dateString) { if (dateString == null) { throw new IllegalArgumentException(SDOException.conversionError(null)); } else { Calendar c = Calendar.getInstance(); c.clear(); if (Pattern.matches("(^--0[1-9]-(([0-2][0-9])|(3[0-1])))|(^--1[0-2]-" + "(([0-2][0-9])|(3[0-1])))", dateString)) { //gMonthDay int _case = 1; iterDateString(dateString, _case, "-", c); } else if (Pattern.matches("(^----(([0-2][0-9])|(3[0-1])))", dateString)) { // gDay int _case = 2; iterDateString(dateString, _case, "-", c); } else if (Pattern.matches("--((0[1-9])|(1[0-2]))--", dateString)) { // gMonth int _case = 1; iterDateString(dateString, _case, "-", c); } else if (Pattern.matches("[0-9]{4}", dateString)) { // gYear int _case = 0; iterDateString(dateString, _case, "-", c); } else if (Pattern.matches("[0-9]{4}-((0[0-9])|(1[0-2]))", dateString)) { // gYearMonth int _case = 0; iterDateString(dateString, _case, "-", c); } else if (Pattern.matches("[0-9]{4}-((0[0-9])|(1[0-2]))-(([0-2][0-9])|(3[0-1]))", dateString)) { // Date int _case = 0; iterDateString(dateString, _case, "-", c); } else if (Pattern.matches("[0-9]{4}-((0[0-9])|(1[0-2]))-(([0-2][0-9])|(3[0-1]))T(([0-1]" + "[0-9])|(2[0-4]))(:[0-5][0-9]){2}((.[0-9]{3})|)", dateString)) { //DateTime int _case = 0; iterDateString(dateString, _case, "-T:.", c); } else if (Pattern.matches("(([0-1][0-9])|(2[0-4]))(:[0-5][0-9]){2}((.[0-9]{3})|)", dateString)) { // Time int _case = 3; iterDateString(dateString, _case, ":.", c); } else if (Pattern.matches("[Pp][0-9]+[Yy][0-9]+[Mm][0-9]+[Dd][Tt]" + "[0-9]+[Hh][0-9]+[Mm][0-9]+.[0-9]{1,3}[Ss]", dateString)) { //DateTime// Duration int _case = 0; iterDateStringDur(dateString, _case, "PYMDTHS", c); } else { throw new IllegalArgumentException(SDOException.conversionError(null)); } return c; } } public Calendar toCalendar(String dateString, Locale locale) { if (dateString == null) { throw new IllegalArgumentException(SDOException.conversionError(null)); } Calendar c = null; if (locale == null) { c = Calendar.getInstance(); } else { c = Calendar.getInstance(locale); } c.clear(); if (Pattern.matches("(^--0[1-9]-(([0-2][0-9])|(3[0-1])))|(^--1[0-2]-" +//gMonthDay "(([0-2][0-9])|(3[0-1])))", dateString)) { int _case = 1; iterDateString(dateString, _case, "-", c); } else if (Pattern.matches("(^----(([0-2][0-9])|(3[0-1])))", dateString))// gDay { int _case = 2; iterDateString(dateString, _case, "-", c); } else if (Pattern.matches("--((0[1-9])|(1[0-2]))--", dateString))// gMonth { int _case = 1; iterDateString(dateString, _case, "-", c); } else if (Pattern.matches("[0-9]{4}", dateString))// gYear { int _case = 0; iterDateString(dateString, _case, "-", c); } else if (Pattern.matches("[0-9]{4}-((0[0-9])|(1[0-2]))", dateString))// gYearMonth { int _case = 0; iterDateString(dateString, _case, "-", c); } else if (Pattern.matches("[0-9]{4}-((0[0-9])|(1[0-2]))-(([0-2][0-9])|(3[0-1]))", dateString)) {// Date int _case = 0; iterDateString(dateString, _case, "-", c); } else if (Pattern.matches("[0-9]{4}-((0[0-9])|(1[0-2]))-(([0-2][0-9])|(3[0-1]))T(([0-1]" + "[0-9])|(2[0-4]))(:[0-5][0-9]){2}((.[0-9]{3})|)", dateString)) {//DateTime int _case = 0; iterDateString(dateString, _case, "-T:.", c); } else if (Pattern.matches("(([0-1][0-9])|(2[0-4]))(:[0-5][0-9]){2}((.[0-9]{3})|)", dateString)) {// Time int _case = 3; iterDateString(dateString, _case, ":.", c); } else if (Pattern.matches("[Pp][0-9]+[Yy][0-9]+[Mm][0-9]+[Dd][Tt]" + "[0-9]+[Hh][0-9]+[Mm][0-9]+.[0-9]{1,3}[Ss]", dateString)) {// Duration int _case = 0; iterDateStringDur(dateString, _case, "PYMDTHS", c); } else { throw new IllegalArgumentException(SDOException.conversionError(null)); } return c; } /** * Convert from a Date to a String representation of the DateTime type. * @param date the date * @return a Date to a String representation of the DateTime type. */ public String toDateTime(Date date) { if (date == null) { return null; } return xmlConversionManager.stringFromDate(date, XMLConstants.DATE_TIME_QNAME); } /** * Convert from a Date to a String representation of the Duration type. * @param date the date * @return a Date to a String representation of the Duration type. */ public String toDuration(Date date) { if (date == null) { return null; } Calendar outPut = Calendar.getInstance(); outPut.setTime(date); return toDuration(outPut); } /** * Convert from a Date to a String representation of the Time type. * @param date the date * @return a Date to a String representation of the Time type. */ public String toTime(Date date) { if (date == null) { return null; } return xmlConversionManager.stringFromDate(date, XMLConstants.TIME_QNAME); } /** * Convert from a Date to a String representation of the Day type. * @param date the date * @return a Date to a String representation of the Day type. */ public String toDay(Date date) { if (date == null) { return null; } return xmlConversionManager.stringFromDate(date, XMLConstants.G_DAY_QNAME); } /** * Convert from a Date to a String representation of the Month type. * @param date the date * @return a Date to a String representation of the Month type. */ public String toMonth(Date date) { if (date == null) { return null; } return xmlConversionManager.stringFromDate(date, XMLConstants.G_MONTH_QNAME); } /** * Convert from a Date to a String representation of the MonthDay type. * @param date the date * @return a Date to a String representation of the MonthDay type. */ public String toMonthDay(Date date) { if (date == null) { return null; } return xmlConversionManager.stringFromDate(date, XMLConstants.G_MONTH_DAY_QNAME); } /** * Convert from a Date to a String representation of the Year type. * @param date the date * @return a Date to a String representation of the Year type. */ public String toYear(Date date) { if (date == null) { return null; } return xmlConversionManager.stringFromDate(date, XMLConstants.G_YEAR_QNAME); } /** * Convert from a Date to a String representation of the YearMonth type. * @param date the date * @return a Date to a String representation of the YearMonth type. */ public String toYearMonth(Date date) { if (date == null) { return null; } return xmlConversionManager.stringFromDate(date, XMLConstants.G_YEAR_MONTH_QNAME); } /** * Convert from a Date to a String representation of the YearMonthDay type. * @param date the date * @return a Date to a String representation of the YearMonthDay type. */ public String toYearMonthDay(Date date) { if (date == null) { return null; } return xmlConversionManager.stringFromDate(date, XMLConstants.DATE_QNAME); } /** * Convert from a Calendar to a String representation of the DateTime type. * @param calendar the calendar to convert * @return a Calendar to a String representation of the DateTime type. */ public String toDateTime(Calendar calendar) { if (calendar == null) { return null; } return xmlConversionManager.stringFromCalendar(calendar, XMLConstants.DATE_TIME_QNAME); } /** * Convert from a Calendar to a String representation of the Duration type. * @param calendar the calendar to convert * @return a Calendar to a String representation of the Duration type. */ public String toDuration(Calendar calendar) { if (calendar == null) { return null; } StringBuffer dur = new StringBuffer(); dur.append("P"); dur.append(calendar.get(Calendar.YEAR)); dur.append("Y"); dur.append(calendar.get(Calendar.MONTH) + 1); dur.append("M"); dur.append(calendar.get(Calendar.DATE)); dur.append("DT"); dur.append(calendar.get(Calendar.HOUR)); dur.append("H"); dur.append(calendar.get(Calendar.MINUTE)); dur.append("M"); float s = (calendar.get(Calendar.SECOND) * 1000) + calendar.get(Calendar.MILLISECOND); dur.append(s / 1000); dur.append("S"); return dur.toString(); } /** * Convert from a Calendar to a String representation of the Time type. * @param calendar the calendar to convert * @return a Calendar to a String representation of the Time type. */ public String toTime(Calendar calendar) { if (calendar == null) { return null; } return xmlConversionManager.stringFromCalendar(calendar, XMLConstants.TIME_QNAME); } /** * Convert from a Calendar to a String representation of the Day type. * @param calendar the calendar to convert * @return a Calendar to a String representation of the Day type. */ public String toDay(Calendar calendar) { if (calendar == null) { return null; } return xmlConversionManager.stringFromCalendar(calendar, XMLConstants.G_DAY_QNAME); } /** * Convert from a Calendar to a String representation of the Month type. * @param calendar the calendar to convert * @return a Calendar to a String representation of the Month type. */ public String toMonth(Calendar calendar) { if (calendar == null) { return null; } return xmlConversionManager.stringFromCalendar(calendar, XMLConstants.G_MONTH_QNAME); } /** * Convert from a Calendar to a String representation of the MonthDay type. * @param calendar the calendar to convert * @return a Calendar to a String representation of the MonthDay type. */ public String toMonthDay(Calendar calendar) { if (calendar == null) { return null; } return xmlConversionManager.stringFromCalendar(calendar, XMLConstants.G_MONTH_DAY_QNAME); } /** * Convert from a Calendar to a String representation of the Year type. * @param calendar the calendar to convert * @return a Calendar to a String representation of the Year type. */ public String toYear(Calendar calendar) { if (calendar == null) { return null; } return xmlConversionManager.stringFromCalendar(calendar, XMLConstants.G_YEAR_QNAME); } /** * Convert from a Calendar to a String representation of the YearMonth type. * @param calendar the calendar to convert * @return a Calendar to a String representation of the YearMonth type. */ public String toYearMonth(Calendar calendar) { if (calendar == null) { return null; } return xmlConversionManager.stringFromCalendar(calendar, XMLConstants.G_YEAR_MONTH_QNAME); } /** * Convert from a Calendar to a String representation of the YearMonthDay type. * @param calendar the calendar to convert * @return a Calendar to a String representation of the YearMonthDay type. */ public String toYearMonthDay(Calendar calendar) { if (calendar == null) { return null; } return xmlConversionManager.stringFromCalendar(calendar, XMLConstants.DATE_QNAME); } /** * Perform Calendar setting based on passed in parameters. * @param c the Calendar to be set * @param i an offset indicate what value to be set * @param data the value to set to the Calendar */ private void setCalendar(Calendar c, int i, int data) { switch (i) { case 0: c.set(Calendar.YEAR, data); break; case 1: c.set(Calendar.MONTH, data - 1); break; case 2: c.set(Calendar.DATE, data); break; case 3: c.set(Calendar.HOUR, data); break; case 4: c.set(Calendar.MINUTE, data); break; case 5: c.set(Calendar.SECOND, data); break; case 6: c.set(Calendar.MILLISECOND, data); break; } } /** * Set a Calendar's value according to a string, e.g. "2001-11-23T01:12:23.001". * @param dateString a string of duration * @param _case an int to indicate calendar's value setting offset, * e.g. year = 0, month = 1 etc. * @param pattern delimiter of StringTokenizer. * @param c the calendar to be set. */ private void iterDateString(String dateString, int _case, String pattern, Calendar c) { StringTokenizer tokn = new StringTokenizer(dateString, pattern); while (tokn.hasMoreTokens()) { int data = Integer.parseInt(tokn.nextToken()); setCalendar(c, _case, data); _case++; } } /** * Set a Calendar's value according to a Duration string, * e.g. "P12Y10M2DT0H40M27.87S". * @param dateString a string of duration * @param _case an int to indicate calendar's value setting offset, * e.g. year = 0, month = 1 etc. * @param pattern delimiter of StringTokenizer. * @param c the calendar to be set. */ private void iterDateStringDur(String dateString, int _case, String pattern, Calendar c) { StringTokenizer tokn = new StringTokenizer(dateString, pattern); while (tokn.hasMoreTokens()) { if (_case < 5) {// process Year, month, date, hour, and minute int data = Integer.parseInt(tokn.nextToken()); setCalendar(c, _case, data); } else {// process second with or without millisecond String secMec = tokn.nextToken(); int data = Integer.parseInt(secMec.substring(0, 2));//extract seconds setCalendar(c, _case, data); double da = Double.parseDouble(secMec); int mec = (int)((da * 1000) - (data * 1000));// extract possible milliseconds setCalendar(c, _case + 1, mec); } _case++; } } /** * Convert a value based to the appropriate type. * @param value The value to convert. * @param convertClass The class to convert the value to. * @param schemaType The schema type if available. * @return the original value converted based on the convertClass parameter. */ public Object convertValue(Object value, Class convertClass, QName schemaType) { return xmlConversionManager.convertObject(value, convertClass, schemaType); } /** * Convert a String value based to the appropriate type. * @param value The String value to convert. * @param convertClass The class to convert the value to. * @return the original value converted based on the convertClass parameter. */ public Object convertFromStringValue(String value, Class convertClass) { if (convertClass == ClassConstants.UTILDATE) { return toDate(value); } else if (convertClass == ClassConstants.CALENDAR) { return toCalendar(value); } else { return xmlConversionManager.convertObject(value, convertClass); } } /** * Convert a String value based to the appropriate type. * @param value The String value to convert. * @param sdoType The SDO type of the value to convert the value to. * @return the original value converted based on the SDO type. */ public Object convertFromStringValue(String value, Type sdoType) { return convertFromStringValue(value, sdoType, null); } /** * Convert a String value based to the appropriate type. * @param value The String value to convert. * @param sdoType The SDO type of the value to convert the value to. * @param schemaType The schema type if available. * @return the original value converted based on the convertClass parameter. */ public Object convertFromStringValue(String value, Type sdoType, QName schemaType) { Class convertClass = ((SDOTypeHelper)getHelperContext().getTypeHelper()).getJavaWrapperTypeForSDOType(sdoType); if (convertClass != null) { if (schemaType == null) { return ((SDODataHelper)getHelperContext().getDataHelper()).convertFromStringValue(value, convertClass); } else { return ((SDODataHelper)getHelperContext().getDataHelper()).convertFromStringValue(value, convertClass, schemaType); } } return value; } /** * Convert a String value based to the appropriate type. * @param value The String value to convert. * @param convertClass The class to convert the value to. * @param schemaType The schema type if available. * @return the original value converted based on the convertClass parameter. */ public Object convertFromStringValue(String value, Class convertClass, QName schemaType) { if (convertClass == ClassConstants.UTILDATE) { return toDate(value); } else if (convertClass == ClassConstants.CALENDAR) { return toCalendar(value); } else { return xmlConversionManager.convertObject(value, convertClass, schemaType); } } /** * Convert to a String value based to the SDO type. * @param value The value to convert. * @param sdoType the SDO type * @return the original value converted to a String based on the SDO type specified. */ public String convertToStringValue(Object value, Type sdoType) { if (value.getClass() == ClassConstants.CALENDAR) { if (sdoType.equals(SDOConstants.SDO_DATETIME)) { return toDateTime((Calendar)value); } else if (sdoType.equals(SDOConstants.SDO_TIME)) { return toTime((Calendar)value); } else if (sdoType.equals(SDOConstants.SDO_DAY)) { return toDay((Calendar)value); } else if (sdoType.equals(SDOConstants.SDO_DURATION)) { return toDuration((Calendar)value); } else if (sdoType.equals(SDOConstants.SDO_MONTH)) { return toMonth((Calendar)value); } else if (sdoType.equals(SDOConstants.SDO_MONTHDAY)) { return toMonthDay((Calendar)value); } else if (sdoType.equals(SDOConstants.SDO_YEAR)) { return toYear((Calendar)value); } else if (sdoType.equals(SDOConstants.SDO_YEARMONTH)) { return toYearMonth((Calendar)value); } else if (sdoType.equals(SDOConstants.SDO_YEARMONTHDAY)) { return toYearMonthDay((Calendar)value); } } else if (value.getClass() == ClassConstants.UTILDATE) { if (sdoType.equals(SDOConstants.SDO_DATETIME)) { return toDateTime((Date)value); } else if (sdoType.equals(SDOConstants.SDO_TIME)) { return toTime((Date)value); } else if (sdoType.equals(SDOConstants.SDO_DAY)) { return toDay((Date)value); } else if (sdoType.equals(SDOConstants.SDO_DURATION)) { return toDuration((Date)value); } else if (sdoType.equals(SDOConstants.SDO_MONTH)) { return toMonth((Date)value); } else if (sdoType.equals(SDOConstants.SDO_MONTHDAY)) { return toMonthDay((Date)value); } else if (sdoType.equals(SDOConstants.SDO_YEAR)) { return toYear((Date)value); } else if (sdoType.equals(SDOConstants.SDO_YEARMONTH)) { return toYearMonth((Date)value); } else if (sdoType.equals(SDOConstants.SDO_YEARMONTHDAY)) { return toYearMonthDay((Date)value); } } return (String)xmlConversionManager.convertObject(value, ClassConstants.STRING); } public Object convert(Type type, Object value) { Class convertClass; if (type.isDataType()) { convertClass = type.getInstanceClass(); } else { convertClass = ((org.eclipse.persistence.sdo.SDOType)type).getImplClass(); } if (value.getClass() == ClassConstants.STRING) { return convertFromStringValue((String)value, type); } else if (convertClass == ClassConstants.STRING) { return convertToStringValue(value, type); } else { try { return xmlConversionManager.convertObject(value, convertClass); } catch (ConversionException e) { throw new IllegalArgumentException(SDOException.conversionError(e)); } } } public Object convert(Property property, Object value) { if (null == property) { throw new IllegalArgumentException(SDOException.conversionError(null)); } Type convertType = property.getType(); if (property.isMany()) { if (value == null) { return null; } else if (!(value instanceof List)) { throw new IllegalArgumentException(SDOException.conversionError(null)); } else { List theList = (List)value; Object nextItem = null; for (int i = 0; i < theList.size(); i++) { nextItem = theList.get(i); theList.set(i, convert(convertType, nextItem)); } return theList; } } else { return convert(convertType, value); } } /** * INTERNAL: */ public Object convertValueToClass(Property prop, Object valueToConvert, Class convertToClass) { try { if (valueToConvert == null) { return null; } if (convertToClass == ClassConstants.STRING) { return convertToStringValue(valueToConvert, prop.getType()); } else { SDOProperty sdoProp = (SDOProperty) prop; DatabaseMapping xmlMapping = sdoProp.getXmlMapping(); if (xmlMapping != null && xmlMapping.isDirectToFieldMapping() && sdoProp.getXsdType() != null) { return xmlConversionManager.convertObject(valueToConvert, convertToClass, sdoProp.getXsdType()); } else { return xmlConversionManager.convertObject(valueToConvert, convertToClass); } } } catch (ConversionException e) { throw new IllegalArgumentException(SDOException.conversionError(e)); } } /** * INTERNAL: */ public HelperContext getHelperContext() { if (null == aHelperContext) { aHelperContext = HelperProvider.getDefaultContext(); } return aHelperContext; } /** * INTERNAL: */ public void setHelperContext(HelperContext helperContext) { aHelperContext = helperContext; } }
package org.axway.grapes.server.db.datamodel; import org.jongo.marshall.jackson.oid.Id; import java.util.ArrayList; import java.util.List; /** * Organization Model Class * * * <P> Model Objects are used in the communication with the Grapes server. * These objects are serialized/un-serialized in JSON objects to be exchanged via http REST calls. * * @author jdcoffre */ public class DbOrganization { public static final String DATA_MODEL_VERSION = "datamodelVersion"; private String datamodelVersion = DbCollections.datamodelVersion; @Id private String name; public static final String CORPORATE_GROUPID_PREFIXES_FIELD = "corporateGroupIdPrefixes"; private List<String> corporateGroupIdPrefixes = new ArrayList<String>(); public String getName() { return name; } public void setName(final String name) { this.name = name; } public List<String> getCorporateGroupIdPrefixes() { return corporateGroupIdPrefixes; } public void setCorporateGroupIdPrefixes(final List<String> corporateGroupIdPrefixes) { this.corporateGroupIdPrefixes = corporateGroupIdPrefixes; } public String getDatamodelVersion() { return datamodelVersion; } public void setDatamodelVersion(String datamodelVersion) { this.datamodelVersion = datamodelVersion; } }
package com.commercetools.pspadapter.payone; import com.commercetools.pspadapter.payone.domain.ctp.CommercetoolsQueryExecutor; import com.commercetools.pspadapter.payone.domain.ctp.PaymentWithCartLike; import com.commercetools.pspadapter.payone.domain.ctp.exceptions.NoCartLikeFoundException; import io.sphere.sdk.client.ErrorResponseException; import io.sphere.sdk.client.NotFoundException; import io.sphere.sdk.http.HttpStatusCode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import java.util.ConcurrentModificationException; import java.util.concurrent.CompletionException; import static com.commercetools.pspadapter.tenant.TenantLoggerUtil.createLoggerName; import static io.sphere.sdk.http.HttpStatusCode.INTERNAL_SERVER_ERROR_500; import static java.lang.String.format; import static java.util.Optional.ofNullable; public class PaymentHandler { /** * How many times to retry if {@link ConcurrentModificationException} happens. */ private static final int RETRIES_LIMIT = 20; private static final int RETRY_DELAY = 100; // msec private final String payoneInterfaceName; private final CommercetoolsQueryExecutor commercetoolsQueryExecutor; private final PaymentDispatcher paymentDispatcher; private final Logger logger; public PaymentHandler(String payoneInterfaceName, String tenantName, CommercetoolsQueryExecutor commercetoolsQueryExecutor, PaymentDispatcher paymentDispatcher) { this.payoneInterfaceName = payoneInterfaceName; this.commercetoolsQueryExecutor = commercetoolsQueryExecutor; this.paymentDispatcher = paymentDispatcher; this.logger = LoggerFactory.getLogger(createLoggerName(this.getClass(), tenantName)); } /** * Tries to handle the payment with the provided ID. * * @param paymentId identifies the payment to be processed * @return the result of handling the payment */ public PaymentHandleResult handlePayment(@Nonnull final String paymentId) { try { for (int i = 0; i < RETRIES_LIMIT; i++) { try { final PaymentWithCartLike paymentWithCartLike = commercetoolsQueryExecutor.getPaymentWithCartLike(paymentId); String paymentInterface = paymentWithCartLike.getPayment().getPaymentMethodInfo().getPaymentInterface(); if (!payoneInterfaceName.equals(paymentInterface)) { logger.warn("Wrong payment interface name: expected [{}], found [{}]", payoneInterfaceName, paymentInterface); return new PaymentHandleResult(HttpStatusCode.BAD_REQUEST_400); } paymentDispatcher.dispatchPayment(paymentWithCartLike); return new PaymentHandleResult(HttpStatusCode.OK_200); } catch (final ConcurrentModificationException cme) { logger.warn("Exception on dispatchPayment with id [{}]. Retry {} of {}", paymentId, i + 1, RETRIES_LIMIT); Thread.sleep(RETRY_DELAY); } } logger.error("The payment [{}] couldn't be processed after {} retries", paymentId, RETRIES_LIMIT); return new PaymentHandleResult(HttpStatusCode.ACCEPTED_202, format("The payment couldn't be processed after %s retries", RETRIES_LIMIT)); } catch (final NotFoundException | NoCartLikeFoundException e) { return handleNotFoundException(paymentId, e); } catch (final ErrorResponseException e) { return errorResponseHandler(e, paymentId); } catch (final CompletionException e) { return completionExceptionHandler(e, paymentId); } catch (final Exception e) { return handleThrowableInResponse(e, paymentId); } } private PaymentHandleResult handleNotFoundException(@Nonnull String paymentId, @Nonnull Exception exception ) { final String body = format("Error on processing payment with ID [%s] as payment or cart could not be found", paymentId); // Temporary adding the exception to error log to simplify debugging. logger.error(body, exception); return new PaymentHandleResult(HttpStatusCode.NOT_FOUND_404, body); } private PaymentHandleResult errorResponseHandler(@Nonnull ErrorResponseException e, @Nonnull String paymentId) { logger.warn("An Error Response from commercetools platform", e); return new PaymentHandleResult(e.getStatusCode(), format("An Error Response from commercetools platform when processing payment [%s]. Try again later.", paymentId)); } /** * Completion exceptions used to tell nothing, thus we should try to report the exception cause. * * @param e Exception to report * @return {@link PaymentHandleResult} with 500 status and message which refers to the logs. */ private PaymentHandleResult completionExceptionHandler(@Nonnull CompletionException e, @Nonnull String paymentId) { String causeMessage = ofNullable(e.getCause()).map(Throwable::toString).orElse("null"); logger.error("Completion exception error: {}\nCause: {}", e.toString(), causeMessage); return new PaymentHandleResult(INTERNAL_SERVER_ERROR_500, format("An error occurred during communication with the commercetools platform when processing [%s] payment. See the service logs", paymentId)); } private PaymentHandleResult handleThrowableInResponse(@Nonnull Throwable throwable, @Nonnull String paymentId) { logger.error("Error in response: ", throwable); return new PaymentHandleResult(INTERNAL_SERVER_ERROR_500, format("Unexpected error occurred when processing payment [%s]. See the service logs", paymentId)); } }
package io.flutter.plugin.platform; import android.annotation.TargetApi; import android.app.Presentation; import android.content.Context; import android.content.ContextWrapper; import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.*; import android.view.accessibility.AccessibilityEvent; import android.widget.FrameLayout; import java.lang.reflect.*; import static android.content.Context.WINDOW_SERVICE; import static android.view.View.OnFocusChangeListener; /* * A presentation used for hosting a single Android view in a virtual display. * * This presentation overrides the WindowManager's addView/removeView/updateViewLayout methods, such that views added * directly to the WindowManager are added as part of the presentation's view hierarchy (to fakeWindowViewGroup). * * The view hierarchy for the presentation is as following: * * rootView * / \ * / \ * / \ * container state.fakeWindowViewGroup * | * EmbeddedView */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) class SingleViewPresentation extends Presentation { /* * When an embedded view is resized in Flutterverse we move the Android view to a new virtual display * that has the new size. This class keeps the presentation state that moves with the view to the presentation of * the new virtual display. */ static class PresentationState { // The Android view we are embedding in the Flutter app. private PlatformView platformView; // The InvocationHandler for a WindowManager proxy. This is essentially the custom window manager for the // presentation. private WindowManagerHandler windowManagerHandler; // Contains views that were added directly to the window manager (e.g android.widget.PopupWindow). private FakeWindowViewGroup fakeWindowViewGroup; } private final PlatformViewFactory viewFactory; // A reference to the current accessibility bridge to which accessibility events will be delegated. private final AccessibilityEventsDelegate accessibilityEventsDelegate; private final OnFocusChangeListener focusChangeListener; // This is the view id assigned by the Flutter framework to the embedded view, we keep it here // so when we create the platform view we can tell it its view id. private int viewId; // This is the creation parameters for the platform view, we keep it here // so when we create the platform view we can tell it its view id. private Object createParams; // The root view for the presentation, it has 2 childs: container which contains the embedded view, and // fakeWindowViewGroup which contains views that were added directly to the presentation's window manager. private AccessibilityDelegatingFrameLayout rootView; // Contains the embedded platform view (platformView.getView()) when it is attached to the presentation. private FrameLayout container; private PresentationState state; private boolean startFocused = false; /** * Creates a presentation that will use the view factory to create a new * platform view in the presentation's onCreate, and attach it. */ public SingleViewPresentation( Context outerContext, Display display, PlatformViewFactory viewFactory, AccessibilityEventsDelegate accessibilityEventsDelegate, int viewId, Object createParams, OnFocusChangeListener focusChangeListener ) { super(outerContext, display); this.viewFactory = viewFactory; this.accessibilityEventsDelegate = accessibilityEventsDelegate; this.viewId = viewId; this.createParams = createParams; this.focusChangeListener = focusChangeListener; state = new PresentationState(); getWindow().setFlags( WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE ); } /** * Creates a presentation that will attach an already existing view as * its root view. * * <p>The display's density must match the density of the context used * when the view was created. */ public SingleViewPresentation( Context outerContext, Display display, AccessibilityEventsDelegate accessibilityEventsDelegate, PresentationState state, OnFocusChangeListener focusChangeListener, boolean startFocused ) { super(outerContext, display); this.accessibilityEventsDelegate = accessibilityEventsDelegate; viewFactory = null; this.state = state; this.focusChangeListener = focusChangeListener; getWindow().setFlags( WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE ); this.startFocused = startFocused; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // This makes sure we preserve alpha for the VD's content. getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); if (state.fakeWindowViewGroup == null) { state.fakeWindowViewGroup = new FakeWindowViewGroup(getContext()); } if (state.windowManagerHandler == null) { WindowManager windowManagerDelegate = (WindowManager) getContext().getSystemService(WINDOW_SERVICE); state.windowManagerHandler = new WindowManagerHandler(windowManagerDelegate, state.fakeWindowViewGroup); } container = new FrameLayout(getContext()); PresentationContext context = new PresentationContext(getContext(), state.windowManagerHandler); if (state.platformView == null) { state.platformView = viewFactory.create(context, viewId, createParams); } View embeddedView = state.platformView.getView(); container.addView(embeddedView); rootView = new AccessibilityDelegatingFrameLayout(getContext(), accessibilityEventsDelegate, embeddedView); rootView.addView(container); rootView.addView(state.fakeWindowViewGroup); embeddedView.setOnFocusChangeListener(focusChangeListener); rootView.setFocusableInTouchMode(true); if (startFocused) { embeddedView.requestFocus(); } else { rootView.requestFocus(); } setContentView(rootView); } public PresentationState detachState() { container.removeAllViews(); rootView.removeAllViews(); return state; } public PlatformView getView() { if (state.platformView == null) return null; return state.platformView; } /* * A view group that implements the same layout protocol that exist between the WindowManager and its direct * children. * * Currently only a subset of the protocol is supported (gravity, x, and y). */ static class FakeWindowViewGroup extends ViewGroup { // Used in onLayout to keep the bounds of the current view. // We keep it as a member to avoid object allocations during onLayout which are discouraged. private final Rect viewBounds; // Used in onLayout to keep the bounds of the child views. // We keep it as a member to avoid object allocations during onLayout which are discouraged. private final Rect childRect; public FakeWindowViewGroup(Context context) { super(context); viewBounds = new Rect(); childRect = new Rect(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { for(int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); WindowManager.LayoutParams params = (WindowManager.LayoutParams) child.getLayoutParams(); viewBounds.set(l, t, r, b); Gravity.apply(params.gravity, child.getMeasuredWidth(), child.getMeasuredHeight(), viewBounds, params.x, params.y, childRect); child.layout(childRect.left, childRect.top, childRect.right, childRect.bottom); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { for(int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); child.measure(atMost(widthMeasureSpec), atMost(heightMeasureSpec)); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } private static int atMost(int measureSpec) { return MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(measureSpec), MeasureSpec.AT_MOST); } } /** * Proxies a Context replacing the WindowManager with our custom instance. */ static class PresentationContext extends ContextWrapper { private WindowManager windowManager; private final WindowManagerHandler windowManagerHandler; PresentationContext(Context base, WindowManagerHandler windowManagerHandler) { super(base); this.windowManagerHandler = windowManagerHandler; } @Override public Object getSystemService(String name) { if (WINDOW_SERVICE.equals(name)) { return getWindowManager(); } return super.getSystemService(name); } private WindowManager getWindowManager() { if (windowManager == null) { windowManager = windowManagerHandler.getWindowManager(); } return windowManager; } } static class WindowManagerHandler implements InvocationHandler { private static final String TAG = "PlatformViewsController"; private final WindowManager delegate; FakeWindowViewGroup fakeWindowRootView; WindowManagerHandler(WindowManager delegate, FakeWindowViewGroup fakeWindowViewGroup) { this.delegate = delegate; fakeWindowRootView = fakeWindowViewGroup; } public WindowManager getWindowManager() { return (WindowManager) Proxy.newProxyInstance( WindowManager.class.getClassLoader(), new Class<?>[] { WindowManager.class }, this ); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { switch (method.getName()) { case "addView": addView(args); return null; case "removeView": removeView(args); return null; case "removeViewImmediate": removeViewImmediate(args); return null; case "updateViewLayout": updateViewLayout(args); return null; } try { return method.invoke(delegate, args); } catch (InvocationTargetException e) { throw e.getCause(); } } private void addView(Object[] args) { if (fakeWindowRootView == null) { Log.w(TAG, "Embedded view called addView while detached from presentation"); return; } View view = (View) args[0]; WindowManager.LayoutParams layoutParams = (WindowManager.LayoutParams) args[1]; fakeWindowRootView.addView(view, layoutParams); } private void removeView(Object[] args) { if (fakeWindowRootView == null) { Log.w(TAG, "Embedded view called removeView while detached from presentation"); return; } View view = (View) args[0]; fakeWindowRootView.removeView(view); } private void removeViewImmediate(Object[] args) { if (fakeWindowRootView == null) { Log.w(TAG, "Embedded view called removeViewImmediate while detached from presentation"); return; } View view = (View) args[0]; view.clearAnimation(); fakeWindowRootView.removeView(view); } private void updateViewLayout(Object[] args) { if (fakeWindowRootView == null) { Log.w(TAG, "Embedded view called updateViewLayout while detached from presentation"); return; } View view = (View) args[0]; WindowManager.LayoutParams layoutParams = (WindowManager.LayoutParams) args[1]; fakeWindowRootView.updateViewLayout(view, layoutParams); } } private static class AccessibilityDelegatingFrameLayout extends FrameLayout { private final AccessibilityEventsDelegate accessibilityEventsDelegate; private final View embeddedView; public AccessibilityDelegatingFrameLayout( Context context, AccessibilityEventsDelegate accessibilityEventsDelegate, View embeddedView ) { super(context); this.accessibilityEventsDelegate = accessibilityEventsDelegate; this.embeddedView = embeddedView; } @Override public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { return accessibilityEventsDelegate.requestSendAccessibilityEvent(embeddedView, child, event); } } }
package org.skyve.impl.report.freemarker; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.Map; import org.apache.commons.lang3.StringEscapeUtils; import org.skyve.CORE; import org.skyve.domain.Bean; import org.skyve.util.Binder; import freemarker.core.Environment; import freemarker.template.TemplateBooleanModel; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import freemarker.template.TemplateScalarModel; import freemarker.template.utility.DeepUnwrap; /** * FreeMarker user-defined directive that performs a Skyve display format on the specified value. * * <p> * <b>Directive info</b> * </p> * * <p> * Directive parameters: * <ul> * <li><code>bean</code>: The bean which the attribute to format belongs to * <li><code>binding</code>: The attribute name to format, can be a compound binding * </ul> * <p> * Loop variables: None * <p> * Directive nested content: No * * <p> * Usage: <code><@format bean=fund binding="dateEff" /></code>. * </p> */ public class FormatDirective implements TemplateDirectiveModel { private static final String PARAM_NAME_BEAN = "bean"; private static final String PARAM_NAME_BINDING = "binding"; private static final String PARAM_ESCAPE = "escape"; @SuppressWarnings("rawtypes") @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if (params.isEmpty()) { throw new TemplateModelException("This directive requires parameters."); } if (loopVars.length != 0) { throw new TemplateModelException("This directive doesn't allow loop variables."); } // If there is non-empty nested content: if (body != null) { throw new TemplateModelException("This directive doesn't allow nested content."); } // process the parameters Bean beanParam = null; String bindingParam = null; boolean escapeParam = true; Iterator<?> paramIter = params.entrySet().iterator(); while (paramIter.hasNext()) { Map.Entry<?, ?> ent = (Map.Entry<?, ?>) paramIter.next(); String paramName = (String) ent.getKey(); TemplateModel paramValue = (TemplateModel) ent.getValue(); if (paramName.equals(PARAM_NAME_BEAN)) { // unwrap to try get the skyve object Object beanObj = DeepUnwrap.permissiveUnwrap(paramValue); if (! (beanObj instanceof Bean)) { throw new TemplateModelException(String.format("The '%s' parameter must be a Skyve bean.", PARAM_NAME_BEAN)); } beanParam = (Bean) beanObj; } else if (paramName.equals(PARAM_NAME_BINDING)) { if (!(paramValue instanceof TemplateScalarModel)) { throw new TemplateModelException(String.format("The '%s' parameter must be a String.", PARAM_NAME_BINDING)); } bindingParam = ((TemplateScalarModel) paramValue).getAsString(); } else if (paramName.equals(PARAM_ESCAPE)) { if (paramValue instanceof TemplateBooleanModel) { escapeParam = ((TemplateBooleanModel) paramValue).getAsBoolean(); } else if(paramValue instanceof TemplateScalarModel) { escapeParam = Boolean.parseBoolean(((TemplateScalarModel) paramValue).getAsString()); } else { throw new TemplateModelException(String.format("The '%s' parameter must be a boolean.", PARAM_ESCAPE)); } } else { throw new TemplateModelException("Unsupported parameter: " + paramName); } } // do the actual directive execution Writer out = env.getOut(); if (beanParam != null && bindingParam != null) { String display = Binder.getDisplay(CORE.getCustomer(), beanParam, bindingParam); if (escapeParam) { display = StringEscapeUtils.escapeHtml4(display); } // replace /n with <br/> display = display.replace("\n", "<br/>"); out.write(display); } } }
package com.ztory.lib.sleek.base.element; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.util.Log; import android.view.MotionEvent; import com.ztory.lib.sleek.Sleek; import com.ztory.lib.sleek.SleekCanvasInfo; import com.ztory.lib.sleek.base.SleekBaseComposite; import com.ztory.lib.sleek.base.SleekColorArea; import com.ztory.lib.sleek.base.SleekParam; import com.ztory.lib.sleek.base.element.css.CSS; import com.ztory.lib.sleek.base.element.css.CSSblock; import com.ztory.lib.sleek.base.element.css.CSSblockBase; import com.ztory.lib.sleek.base.image.SleekBaseImage; import com.ztory.lib.sleek.base.text.SleekViewText; import com.ztory.lib.sleek.contract.ISleekAnimRun; import com.ztory.lib.sleek.contract.ISleekCallback; import com.ztory.lib.sleek.contract.ISleekData; import com.ztory.lib.sleek.layout.IComputeInt; import com.ztory.lib.sleek.layout.SL; import com.ztory.lib.sleek.util.Calc; import com.ztory.lib.sleek.util.UtilDownload; import com.ztory.lib.sleek.util.UtilExecutor; import com.ztory.lib.sleek.util.UtilResources; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.List; public class SleekElement extends SleekBaseComposite { protected final List<CSSblock> elementCSSlist = new ArrayList<>(4); /** * If CSS is updated at runtime, be sure to set this to true. */ protected boolean elementCSSneedsUpdate = false; protected final CSSblock elementCSS = new CSSblockBase(12); protected long elementCSSmodifiedTs; protected String elementString = null; protected final SleekColorArea elementBackground = new SleekColorArea( SleekColorArea.COLOR_TRANSPARENT, SleekColorArea.ANTI_ALIASED_FALSE, SleekParam.DEFAULT_TOUCHABLE ); protected final SleekColorArea elementBorder = new SleekColorArea( SleekColorArea.COLOR_TRANSPARENT, SleekColorArea.ANTI_ALIASED_FALSE, SleekParam.DEFAULT_TOUCHABLE ); protected SleekViewText elementText = null; protected Paint elementShadowBitmapPaint; protected final List<Bitmap> elementShadowBitmapList = new ArrayList<>(); protected volatile int shadowViewSizeW; protected volatile int shadowViewSizeH; protected int elementBackgroundColor = SleekColorArea.COLOR_TRANSPARENT; protected int elementBorderColor = SleekColorArea.COLOR_TRANSPARENT; protected final Rect elementBorderWidth = new Rect(); protected int elementBorderRadius = 0; protected float elementShadowRadius = 0; protected float elementShadowOffsetX = 0; protected float elementShadowOffsetY = 0; protected int elementShadowColor = 0; protected Rect paddingRect; protected String elementBackgroundSize = null; protected boolean localElementBackgroundImageUrl; protected String elementBackgroundImageUrl = null; protected SleekBaseImage elementBackgroundImage = null; protected boolean wrapTextWidth = false, wrapTextHeight = false; public SleekElement(SleekParam sleekParam) { super(sleekParam); setDimensionIgnoreBounds(true); } public void setWrapTextWidth(boolean shouldWrapTextWidth) { wrapTextWidth = shouldWrapTextWidth; if (elementText != null) { elementText.setWrapWidth(wrapTextWidth); } } public void setWrapTextHeight(boolean shouldWrapTextHeight) { wrapTextHeight = shouldWrapTextHeight; if (elementText != null) { elementText.setWrapHeight(wrapTextHeight); } } public void checkCSS() { if (!isAddedToParent()) { return;//do not apply css if element does not have a parent } // Add CSS blocks from elementCSSlist to elementCSS if (elementCSSneedsUpdate) { elementCSSneedsUpdate = false; if (elementCSS.size() > 0) { elementCSS.clear(); } for (CSSblock iterBlock : elementCSSlist) { elementCSS.putAll(iterBlock);//will overwrite existing keys } } // Apply new CSS if state in elementCSS has changed if (elementCSSmodifiedTs != elementCSS.getModifiedTimestamp()) { elementCSSmodifiedTs = elementCSS.getModifiedTimestamp(); applyCSS(); } } public void applyCSS() { // No need to apply CSS properties if there are none if (elementCSS.size() == 0) { return; } Integer backgroundColor = elementCSS.getBackgroundColor(); if (backgroundColor != null) { elementBackgroundColor = backgroundColor; } else { elementBackgroundColor = SleekColorArea.COLOR_TRANSPARENT; } elementBackground.getPaint().setColor(elementBackgroundColor); Integer borderColor = elementCSS.getBorderColor(); if (borderColor != null) { elementBorderColor = borderColor; } else { elementBorderColor = SleekColorArea.COLOR_TRANSPARENT; } elementBorder.getPaint().setColor(elementBorderColor); Rect borderWidth = elementCSS.getBorderWidth(); if (borderWidth != null) { elementBorderWidth.set(borderWidth); // elementBorder.getPaint().setStyle(Paint.Style.STROKE); // elementBorder.getPaint().setStrokeWidth(elementBorderWidth.left); //elementBorder.getPaint().setAlpha(120); } else { elementBorderWidth.set(0, 0, 0, 0); } Integer borderRadius = elementCSS.getBorderRadius(); if (borderRadius != null) { elementBorderRadius = borderRadius; } else { elementBorderRadius = 0; } if (elementBorderRadius > elementBorderWidth.left) { elementBackground.getPaint().setAntiAlias(true); elementBackground.setRounded(elementBorderRadius - elementBorderWidth.left); } else { elementBackground.getPaint().setAntiAlias(false); elementBackground.setRounded(0); } elementBorder.getPaint().setAntiAlias(elementBorderRadius > 0); elementBorder.setRounded(elementBorderRadius); Integer boxShadowBlurRadius = elementCSS.getBoxShadowBlurRadius(); if (boxShadowBlurRadius != null && boxShadowBlurRadius > 0) { Integer boxShadowOffsetX = elementCSS.getBoxShadowOffsetX(); Integer boxShadowOffsetY = elementCSS.getBoxShadowOffsetY(); Integer boxShadowColor = elementCSS.getBoxShadowColor(); if (boxShadowOffsetX != null && boxShadowOffsetY != null && boxShadowColor != null) { elementShadowRadius = boxShadowBlurRadius; elementShadowOffsetX = boxShadowOffsetX; elementShadowOffsetY = boxShadowOffsetY; elementShadowColor = boxShadowColor; elementShadowBitmapPaint = new Paint(); elementShadowBitmapPaint.setColor(elementBackgroundColor); } else { elementShadowRadius = 0; } } else { elementShadowRadius = 0; } Integer color = elementCSS.getColor(); if (color != null) { createText(); elementText.setTextColor(color); } Integer fontSize = elementCSS.getFontSize(); if (fontSize != null) { createText(); elementText.setTextSize(fontSize); } Integer lineHeight = elementCSS.getLineHeight(); if (lineHeight != null) { createText(); elementText.setTextLineHeight(lineHeight); } String textAlign = elementCSS.getTextAlign(); if (lineHeight != null) { createText(); if (textAlign.equals("center")) { elementText.setTextAlignInt(SleekViewText.ALIGN_CENTER); } else if (textAlign.equals("right")) { elementText.setTextAlignInt(SleekViewText.ALIGN_RIGHT); } else if (textAlign.equals("left")) { elementText.setTextAlignInt(SleekViewText.ALIGN_LEFT); } } String verticalAlign = elementCSS.getVerticalAlign(); if (verticalAlign != null) { createText(); if (verticalAlign.equals("middle")) { elementText.setTextAlignVertInt(SleekViewText.ALIGN_CENTER); } else if (verticalAlign.equals("bottom")) { elementText.setTextAlignVertInt(SleekViewText.ALIGN_BOTTOM); } else if (verticalAlign.equals("top")) { elementText.setTextAlignVertInt(SleekViewText.ALIGN_TOP); } } if (elementString != null) { createText(); elementText.setTextString(elementString); elementText.initText(); } paddingRect = elementCSS.getPadding(); String oldElementBackgroundImageUrl = elementBackgroundImageUrl; elementBackgroundImageUrl = elementCSS.getBackgroundImage(); if (elementBackgroundImageUrl != null) { createBackgroundImage(); if (!elementBackgroundImageUrl.equals(oldElementBackgroundImageUrl)) { localElementBackgroundImageUrl = !elementBackgroundImageUrl.startsWith("https: && !elementBackgroundImageUrl.startsWith("http: reloadBackgroundImage(); } } else if (elementBackgroundImage != null) { initBackgroundImageBitmapFetcher(); elementBackgroundImage.setBitmap(null); } elementBackgroundSize = elementCSS.getBackgroundSize(); } public void setCSSneedsUpdate() { elementCSSneedsUpdate = true; requestLayout(); } public SleekElement addCSSblock(CSSblock cssBlock) { elementCSSlist.add(cssBlock); setCSSneedsUpdate(); return this; } public SleekElement removeCSSblock(CSSblock cssBlock) { elementCSSlist.remove(cssBlock); setCSSneedsUpdate(); return this; } public void setElementString(String theElementString) { elementString = theElementString; } public String getElementString() { return elementString; } public Paint getBgPaint() { if (elementShadowRadius > 0) { return elementShadowBitmapPaint; } else { return elementBackground.getPaint(); } } public SleekColorArea getBackground() { return elementBackground; } public void createText() { if (elementText != null) { return; } elementText = new SleekViewText(SleekParam.DEFAULT); elementText.setWrapWidth(wrapTextWidth); elementText.setWrapHeight(wrapTextHeight); } public SleekViewText getText() { return elementText; } public void createBackgroundImage() { if (elementBackgroundImage != null) { return; } elementBackgroundImage = new SleekBaseImage(elementBorderRadius, SleekParam.DEFAULT); elementBackgroundImage.setFadeAnimOnLoad(false); elementBackgroundImage.setBitmapListener(new ISleekCallback<SleekBaseImage>() { @Override public void sleekCallback(SleekBaseImage sleekBaseImage) { positionBackgroundImage(); } }); } public void positionBackgroundImage() { if (elementBackgroundImage == null || elementBackgroundImage.getBitmap() == null) { return; } //NOTE: Background logic for "cover" and "contain" is calculated as if this CSS was set: // background-position: center center; final int bitmapW = elementBackgroundImage.getBitmap().getWidth(); final int bitmapH = elementBackgroundImage.getBitmap().getHeight(); int backgroundX = 0; int backgroundY = 0; int backgroundWidth = bitmapW; int backgroundHeight = bitmapH; // Reset source rect elementBackgroundImage.getSourceRect().set(0, 0, backgroundWidth, backgroundHeight); elementBackgroundImage.setShaderMatrix(); if (elementBackgroundSize != null) { if (elementBackgroundSize.equals(CSS.Value.CONTAIN)) { /* contain A keyword that scales the image as large as possible and maintains image aspect ratio (image doesn't get squished). Image is letterboxed within the container. When the image and container have different dimensions, the empty areas (either top/bottom of left/right) are filled with the background-color. */ float elementRatio = Calc.divide(sleekW, sleekH); float bitmapRatio = Calc.divide(backgroundWidth, backgroundHeight); if (bitmapRatio > elementRatio) { backgroundWidth = sleekW; backgroundHeight = Calc.divideToInt(sleekW, bitmapRatio); backgroundY = Calc.divideToInt(sleekH - backgroundHeight, 2.0f); } else { backgroundHeight = sleekH; backgroundWidth = Calc.multiplyToInt(sleekH, bitmapRatio); backgroundX = Calc.divideToInt(sleekW - backgroundWidth, 2.0f); } } else if (elementBackgroundSize.equals(CSS.Value.COVER)) { /* cover A keyword that is the inverse of contain. Scales the image as large as possible and maintains image aspect ratio (image doesn't get squished). The image "covers" the entire width or height of the container. When the image and container have different dimensions, the image is clipped either left/right or top/bottom. */ float bitmapScale; float elementRatio = Calc.divide(sleekW, sleekH); float bitmapRatio = Calc.divide(backgroundWidth, backgroundHeight); if (bitmapRatio > elementRatio) { bitmapScale = Calc.divide(sleekH, bitmapH); //backgroundHeight = sleekH; backgroundWidth = Calc.multiplyToInt(sleekH, bitmapRatio); backgroundX = Calc.divideToInt(sleekW - backgroundWidth, 2.0f); } else { bitmapScale = Calc.divide(sleekW, bitmapW); //backgroundWidth = sleekW; backgroundHeight = Calc.divideToInt(sleekW, bitmapRatio); backgroundY = Calc.divideToInt(sleekH - backgroundHeight, 2.0f); } int sourceTop = Calc.multiplyToInt(Calc.divide(backgroundY, bitmapScale), -1.0f); int sourceBottom = bitmapH - sourceTop; int sourceLeft = Calc.multiplyToInt(Calc.divide(backgroundX, bitmapScale), -1.0f); int sourceRight = bitmapW - sourceLeft; elementBackgroundImage.getSourceRect().set( sourceLeft, sourceTop, sourceRight, sourceBottom ); elementBackgroundImage.setShaderMatrix(); //Reset drawing position backgroundX = 0; backgroundY = 0; // Reset drawing size to element size backgroundWidth = sleekW; backgroundHeight = sleekH; } } if (backgroundX > elementBorderRadius || backgroundY > elementBorderRadius) { elementBackgroundImage.setRoundedRadius(0); } else { if (elementBorderColor == SleekColorArea.COLOR_TRANSPARENT) { elementBackgroundImage.setRoundedRadius(elementBorderRadius); } else if (elementBorderRadius > elementBorderWidth.left) { elementBackgroundImage.setRoundedRadius(elementBorderRadius - elementBorderWidth.left); } else { elementBackgroundImage.setRoundedRadius(0); } } elementBackgroundImage.setSleekBounds( backgroundX + elementBorderWidth.left, backgroundY + elementBorderWidth.top, backgroundWidth - elementBorderWidth.left - elementBorderWidth.right, backgroundHeight - elementBorderWidth.top - elementBorderWidth.bottom ); } public void reloadBackgroundImage() { initBackgroundImageBitmapFetcher(); if (elementBackgroundImageUrl != null) { if (loaded && addedToParent) { mSlkCanvas.loadSleek(elementBackgroundImage); checkSetLocalBackground(); } } } public void initBackgroundImageBitmapFetcher() { if (elementBackgroundImageUrl == null || localElementBackgroundImageUrl) { elementBackgroundImage.setBitmapFetcher(null, null, null);//clear fetcher } else { elementBackgroundImage.setBitmapFetcher(mSlkCanvas.getHandler(), UtilExecutor.NETWORK_EXECUTOR, new ISleekData<Bitmap>() { @Override public Bitmap getData(Sleek sleek) { File bmFile = UtilDownload.downloadUrl(elementBackgroundImageUrl); Bitmap bm = null; if (bmFile != null) { try { bm = BitmapFactory.decodeStream(new FileInputStream(bmFile)); } catch (Exception e) { e.printStackTrace(); } } return bm; } }); } } public void checkSetLocalBackground() { if (elementBackgroundImageUrl != null && localElementBackgroundImageUrl) { // DEBUG CODE, because we have no drawable resources in sleek library. // int resId = UtilPx.getDefaultContext().getResources().getIdentifier( // elementBackgroundImageUrl, // "drawable", // "android" // elementBackgroundImage.setBitmap(UtilResources.getBitmap(resId)); Bitmap bitmapResource = UtilResources.getBitmap( UtilResources.getResourceIdDrawable(elementBackgroundImageUrl) ); elementBackgroundImage.setBitmap(bitmapResource); } } public SleekBaseImage getBackgroundImage() { return elementBackgroundImage; } public void wrapBackgroundImageSize( final boolean wrapWidth, final boolean wrapHeight, final boolean executeSleekCanvasResize ) { createBackgroundImage();//ensure background image is created if null getBackgroundImage().setBitmapListener(new ISleekCallback<SleekBaseImage>() { @Override public void sleekCallback(SleekBaseImage sleekBaseImage) { if (sleekBaseImage.getBitmap() != null) { final int bitmapWidth = sleekBaseImage.getBitmap().getWidth(); final int bitmapHeight = sleekBaseImage.getBitmap().getHeight(); final float bitmapRatio = Calc.divide(bitmapWidth, bitmapHeight); if (wrapWidth && wrapHeight) { SleekElement.this.getLayout() .w(SL.W.ABSOLUTE, bitmapWidth, null) .h(SL.H.ABSOLUTE, bitmapHeight, null); } else if (wrapWidth) { SleekElement.this.getLayout().w(SL.W.COMPUTE, 0, null, 0, new IComputeInt() { @Override public int compute(SleekCanvasInfo info) { int computedH = SleekElement.this.getLayout().computeSizeH(SleekElement.this, info); return Calc.multiplyToInt(computedH, bitmapRatio); } }); } else if (wrapHeight) { SleekElement.this.getLayout().h(SL.H.COMPUTE, 0, null, 0, new IComputeInt() { @Override public int compute(SleekCanvasInfo info) { int computedW = SleekElement.this.getLayout().computeSizeW(SleekElement.this, info); return Calc.divideToInt(computedW, bitmapRatio); } }); } if (executeSleekCanvasResize) { SleekElement.this.executeSleekCanvasResize(); } else { SleekElement.this.requestLayout(); } } } }); } public CSSblock getCSS() { return elementCSS; } public void drawBorder(Canvas canvas, SleekCanvasInfo info) { if (elementBorderColor == SleekColorArea.COLOR_TRANSPARENT) { return; } elementBorder.onSleekDraw(canvas, info); } @Override public void drawView(Sleek view, Canvas canvas, SleekCanvasInfo info) { canvas.save(); canvas.translate(sleekX, sleekY); //TODO DEBUG // drawShadowBitmap(canvas, info); // elementBorder.getPaint().setColor(0x99ff0000); // drawBorder(canvas, info); //TODO DEBUG if (!drawShadowBitmap(canvas, info)) { // elementBorderColor != SleekColorArea.COLOR_TRANSPARENT // && elementBackgroundImage != null // && elementBackgroundImage.isBitmapLoaded() // // This prevents bg-color from bleeding through on elementBackgroundImage's Bitmap corners // elementBackground.getPaint().setColor(elementBorderColor); // } else if (elementBackground.getPaint().getColor() != elementBackgroundColor) { // elementBackground.getPaint().setColor(elementBackgroundColor); drawBorder(canvas, info); //elementBackground.onSleekDraw(canvas, info); if (elementBackgroundImage != null) { elementBackgroundImage.onSleekDraw(canvas, info); if (!elementBackgroundImage.isBitmapLoaded()) { elementBackground.onSleekDraw(canvas, info); } } else { elementBackground.onSleekDraw(canvas, info); } } else if (elementBackgroundImage != null) { elementBackgroundImage.onSleekDraw(canvas, info); } //drawBorder(canvas, info); if (elementText != null) { elementText.onSleekDraw(canvas, info); } for (Sleek iterView : views) { //if (iterView.shouldBeDrawn()) iterView.draw(canvas, info);// dont need to check this, if this view is loaded it should draw its children iterView.onSleekDraw(canvas, info); } canvas.restore(); } @Override public void setSleekBounds(float x, float y, int w, int h) { if (elementText != null) { if (paddingRect != null) { elementText.setSleekBounds( paddingRect.left + elementBorderWidth.left, paddingRect.top + elementBorderWidth.top, w - paddingRect.left - paddingRect.right - elementBorderWidth.left - elementBorderWidth.right, h - paddingRect.top - paddingRect.bottom - elementBorderWidth.top - elementBorderWidth.bottom ); } else { elementText.setSleekBounds( elementBorderWidth.left, elementBorderWidth.top, w - elementBorderWidth.left - elementBorderWidth.right, h - elementBorderWidth.top - elementBorderWidth.bottom ); } } int elementWidth = w; int elementHeight = h; if ((wrapTextWidth || wrapTextHeight) && elementText != null) { int paddingTopBottom = paddingRect != null ? paddingRect.top + paddingRect.bottom : 0; int paddingLeftRight = paddingRect != null ? paddingRect.left + paddingRect.right : 0; paddingTopBottom = paddingTopBottom + elementBorderWidth.top + elementBorderWidth.bottom; paddingLeftRight = paddingLeftRight + elementBorderWidth.left + elementBorderWidth.right; if (wrapTextWidth) {//wrap only width elementWidth = elementText.getSleekW() + paddingLeftRight; } if (wrapTextHeight) {//wrap only height elementHeight = elementText.getSleekH() + paddingTopBottom; } } super.setSleekBounds(x, y, elementWidth, elementHeight); elementBorder.setSleekBounds( 0, 0, elementWidth, elementHeight ); //SOLVES BG-EDGE-BLEED-THROUGH by decreasing elementBackground size when CSS-border is set elementBackground.setSleekBounds( elementBorder.getSleekX() + elementBorderWidth.left, elementBorder.getSleekY() + elementBorderWidth.top, elementBorder.getSleekW() - elementBorderWidth.left - elementBorderWidth.right, elementBorder.getSleekH() - elementBorderWidth.top - elementBorderWidth.bottom ); //elementBackground.setSleekBounds(0, 0, elementWidth, elementHeight); if (loaded && addedToParent) { // if (elementShadowRadius > 0) { // if (sleekW != shadowViewSizeW || sleekH != shadowViewSizeH) { // // TODO HOW TO AVOID LOADING THIS ON UI-THREAD ???? // // TODO THIS NEEDS TO BE CALLED ON UI-THREAD IF ANIMATIONS ARE GOING TO ANIMATE SHADOW !!! // //TODO POSSIBLE SOLUTION: // //TODO Maybe we can "stretch" north/south shadow when animating width, and... // //TODO ... west/east shadow when animating height // //reloadShadowBitmap(false);// param: allowBgThreadLoad // Log.d("SleekElement", // "SleekElement.reloadShadowBitmap on UI THREAD!" positionBackgroundImage(); } } protected void setElementShadowBitmap(List<Bitmap> theShadowBitmapList) { synchronized (SleekElement.this) { if (elementShadowBitmapList.size() > 0) { for (Bitmap iterShadowBitmap : elementShadowBitmapList) { if (iterShadowBitmap != null) { iterShadowBitmap.recycle(); } } elementShadowBitmapList.clear(); } if (theShadowBitmapList != null) { elementShadowBitmapList.addAll(theShadowBitmapList); } } } @Override public void onSleekCanvasResize(SleekCanvasInfo info) { checkCSS();//checks if changes have been made to CSS properties super.onSleekCanvasResize(info); } public void reloadShadowBitmap(boolean allowBgThreadLoad) { if (elementShadowRadius > 0) { if (allowBgThreadLoad) { //TODO Maybe exeute on UI-thread if view is within viewport when this method is called ? UtilExecutor.CPU_EXECUTOR_MULTI.execute(new Runnable() { @Override public void run() { final List<Bitmap> shadowBitmapList = generateShadowBitmap(); addPreDrawSafe(mSlkCanvas, new ISleekAnimRun() { @Override public void run(SleekCanvasInfo info) { if (loaded && addedToParent) { setElementShadowBitmap(shadowBitmapList); } } }); } }); } else { setElementShadowBitmap(generateShadowBitmap()); } } else { setElementShadowBitmap(null); } } @Override public void onSleekLoad(SleekCanvasInfo info) { final boolean alreadyLoaded = loaded; super.onSleekLoad(info); if (alreadyLoaded) { return; } reloadShadowBitmap(true); if (elementBackgroundImage != null) { elementBackgroundImage.onSleekLoad(info); checkSetLocalBackground(); } } @Override public void onSleekUnload() { super.onSleekUnload(); setElementShadowBitmap(null); if (elementBackgroundImage != null) { elementBackgroundImage.onSleekUnload(); } } @Override public boolean onSleekTouchEvent(MotionEvent event, SleekCanvasInfo info) { if (touchHandler.onSleekTouchEvent(event, info)) { return true; } event.offsetLocation(-sleekX, -sleekY); touchEventReturn = false; if (touchable) { for (int i = views.size() - 1; i >= 0; i if (views.get(i).isSleekTouchable() && views.get(i).onSleekTouchEvent(event, info)) { touchEventReturn = true; break; } } } if (!touchEventReturn) { touchEventReturn = elementBackground.getTouchHandler().onSleekTouchEvent(event, info); } event.offsetLocation(sleekX, sleekY); return touchEventReturn; } protected final Rect shadowSrcRect = new Rect(); protected final RectF shadowDstRectF = new RectF(); protected boolean drawShadowBitmap(Canvas canvas, SleekCanvasInfo info) { //TODO Add boolean that keeps track of if (elementShadowBitmapList.size() < 4) ! if (elementShadowBitmapList.size() < 4) { return false; } //TODO FIX SO THAT ALPHA ANIMATION WORKS AS IT SHOULD WITH MIDDLE AREA AND BORDER AREAS !!!! //TODO Maybe we can set bitmap-bg-paint to alpha==255, and shadow to delta of real... //TODO ... bg-alpha and its shadow-alpha ???? //TODO NEED TO add interface that is called HasAlpha and has getAlpha and setAlpha methods. if (elementBorderColor == SleekColorArea.COLOR_TRANSPARENT) { canvas.drawRect( elementBorderRadius, elementBorderRadius, sleekW - elementBorderRadius, sleekH - elementBorderRadius, elementShadowBitmapPaint ); } /* // LOW PRIO since why would we want alpha bg-elements with shadow? // If we implement alpha bg with shadow then shadowBitmaps need to contain "hidden" ... // ... shadow-edges as well, so that they shine through. // Draw middle area of shadow, if bg has alpha we need to draw this because otherwise... // ...there is a "hole" in the middle since shadow will only be drawn along edges. float shadowBgTopOffset = elementShadowOffsetY > 0 ? elementShadowOffsetY : 0; float shadowBgBottomOffset = elementShadowOffsetY < 0 ? elementShadowOffsetY : 0; float shadowBgLeftOffset = elementShadowOffsetX > 0 ? elementShadowOffsetX : 0; float shadowBgRightOffset = elementShadowOffsetX < 0 ? elementShadowOffsetX : 0; elementBackground.getPaint().setColor(0x99ff00ff); canvas.drawRect( elementBorderRadius + shadowBgLeftOffset, elementBorderRadius + shadowBgTopOffset, sleekW - elementBorderRadius + shadowBgRightOffset, sleekH - elementBorderRadius + shadowBgBottomOffset, elementBackground.getPaint()//using elementBackground.getPaint to have correct Alpha ); elementBackground.getPaint().setColor(elementBackgroundColor); */ //TODO REFACTOR CODE IN THIS METHOD TO BE EASIER TO READ ! float leftOffset = 0; if (elementShadowOffsetX < 0) { leftOffset = elementShadowOffsetX; } float topOffset = 0; if (elementShadowOffsetY < 0) { topOffset = elementShadowOffsetY; } //int stretchedWidthDelta = sleekW - shadowViewSizeW; int stretchedHeightDelta = sleekH - shadowViewSizeH; Bitmap currentBitmap; int currentBitmapW; int currentBitmapH; final Bitmap leftBitmap = elementShadowBitmapList.get(2); final int leftBitmapW = leftBitmap.getWidth(); final int leftBitmapH = leftBitmap.getHeight(); final Bitmap rightBitmap = elementShadowBitmapList.get(3); final int rightBitmapW = rightBitmap.getWidth(); final int rightBitmapH = rightBitmap.getHeight(); final int westCornerWidth; final int eastCornerWidth; final int rightEdgeModifier; if (rightBitmapW > leftBitmapW) { westCornerWidth = rightBitmapW + elementBorderWidth.left; eastCornerWidth = rightBitmapW + elementBorderWidth.right; rightEdgeModifier = elementBorderWidth.right; } else { westCornerWidth = leftBitmapW + elementBorderWidth.left; eastCornerWidth = leftBitmapW + elementBorderWidth.right; rightEdgeModifier = leftBitmapW - rightBitmapW + elementBorderWidth.right; } // Top Bitmap Init currentBitmap = elementShadowBitmapList.get(0); currentBitmapW = currentBitmap.getWidth(); currentBitmapH = currentBitmap.getHeight(); // Top-Left-Corner Bitmap shadowSrcRect.set(0, 0, westCornerWidth, currentBitmapH); shadowDstRectF.set( -elementShadowRadius + leftOffset, -elementShadowRadius + topOffset, -elementShadowRadius + leftOffset + westCornerWidth, -elementShadowRadius + topOffset + currentBitmapH ); canvas.drawBitmap( currentBitmap, shadowSrcRect, shadowDstRectF, elementShadowBitmapPaint ); // Top-Right-Corner Bitmap shadowSrcRect.set(currentBitmapW - eastCornerWidth, 0, currentBitmapW, currentBitmapH); shadowDstRectF.set( sleekW - elementBorderRadius - rightEdgeModifier, -elementShadowRadius + topOffset, sleekW + eastCornerWidth - elementBorderRadius - rightEdgeModifier, -elementShadowRadius + topOffset + currentBitmapH ); canvas.drawBitmap( currentBitmap, shadowSrcRect, shadowDstRectF, elementShadowBitmapPaint ); // Top-Center Bitmap shadowSrcRect.set(westCornerWidth, 0, currentBitmapW - eastCornerWidth, currentBitmapH); shadowDstRectF.set( -elementShadowRadius + leftOffset + westCornerWidth, -elementShadowRadius + topOffset, sleekW - elementBorderRadius - rightEdgeModifier, -elementShadowRadius + topOffset + currentBitmapH ); canvas.drawBitmap( currentBitmap, shadowSrcRect, shadowDstRectF, elementShadowBitmapPaint ); //DEBUG DRAW unscaled Top-Bitmap // canvas.drawBitmap( // elementShadowBitmapList.get(0), // -elementShadowRadius + leftOffset, // -elementShadowRadius + topOffset, // elementShadowBitmapPaint // Bottom Bitmap Init currentBitmap = elementShadowBitmapList.get(1); currentBitmapW = currentBitmap.getWidth(); currentBitmapH = currentBitmap.getHeight(); // Bottom-Left-Corner Bitmap shadowSrcRect.set(0, 0, westCornerWidth, currentBitmapH); shadowDstRectF.set( -elementShadowRadius + leftOffset, sleekH - elementBorderRadius, -elementShadowRadius + leftOffset + westCornerWidth, sleekH - elementBorderRadius + currentBitmapH ); canvas.drawBitmap( currentBitmap, shadowSrcRect, shadowDstRectF, elementShadowBitmapPaint ); // Bottom-Right-Corner Bitmap shadowSrcRect.set(currentBitmapW - eastCornerWidth, 0, currentBitmapW, currentBitmapH); shadowDstRectF.set( sleekW - elementBorderRadius - rightEdgeModifier, sleekH - elementBorderRadius, sleekW + eastCornerWidth - elementBorderRadius - rightEdgeModifier, sleekH - elementBorderRadius + currentBitmapH ); canvas.drawBitmap( currentBitmap, shadowSrcRect, shadowDstRectF, elementShadowBitmapPaint ); // Bottom-Center Bitmap shadowSrcRect.set(westCornerWidth, 0, currentBitmapW - eastCornerWidth, currentBitmapH); shadowDstRectF.set( -elementShadowRadius + leftOffset + westCornerWidth, sleekH - elementBorderRadius, sleekW - elementBorderRadius - rightEdgeModifier, sleekH - elementBorderRadius + currentBitmapH ); canvas.drawBitmap( currentBitmap, shadowSrcRect, shadowDstRectF, elementShadowBitmapPaint ); //DEBUG DRAW unscaled Bottom-Bitmap // canvas.drawBitmap( // elementShadowBitmapList.get(1), // -elementShadowRadius + leftOffset, // sleekH - elementBorderRadius, // elementShadowBitmapPaint // Left Bitmap currentBitmap = leftBitmap; currentBitmapW = leftBitmapW; currentBitmapH = leftBitmapH; shadowSrcRect.set(0, 0, currentBitmapW, currentBitmapH); shadowDstRectF.set( -elementShadowRadius + leftOffset, elementBorderRadius, -elementShadowRadius + leftOffset + currentBitmapW, elementBorderRadius + currentBitmapH + stretchedHeightDelta ); canvas.drawBitmap( currentBitmap, shadowSrcRect, shadowDstRectF, elementShadowBitmapPaint ); //DEBUG DRAW unscaled Left-Bitmap // canvas.drawBitmap( // elementShadowBitmapList.get(2), // -elementShadowRadius + leftOffset, // elementBorderRadius, // elementShadowBitmapPaint // Right Bitmap currentBitmap = rightBitmap; currentBitmapW = rightBitmapW; currentBitmapH = rightBitmapH; shadowSrcRect.set(0, 0, currentBitmapW, currentBitmapH); shadowDstRectF.set( sleekW - elementBorderRadius, elementBorderRadius, sleekW - elementBorderRadius + currentBitmapW, elementBorderRadius + currentBitmapH + stretchedHeightDelta ); canvas.drawBitmap( currentBitmap, shadowSrcRect, shadowDstRectF, elementShadowBitmapPaint ); //DEBUG DRAW unscaled Right-Bitmap // canvas.drawBitmap( // elementShadowBitmapList.get(3), // sleekW - elementBorderRadius, // elementBorderRadius, // elementShadowBitmapPaint if (elementBorderColor != SleekColorArea.COLOR_TRANSPARENT) { canvas.drawRoundRect( new RectF( elementBorderWidth.left, elementBorderWidth.top, sleekW - elementBorderWidth.right, sleekH - elementBorderWidth.bottom ), elementBackground.getRoundedRadius(), elementBackground.getRoundedRadius(), elementShadowBitmapPaint ); } //DEBUG DRAW regular background for position reference // elementBackground.getPaint().setColor(0x99ffffff); // elementBackground.onSleekDraw(canvas, info); // elementBackground.getPaint().setColor(elementBackgroundColor); return true; } protected List<Bitmap> generateShadowBitmap() { if (elementShadowRadius <= 0) { return null; } /* // LOW PRIO since why would we want alpha bg-elements with shadow? // If we implement alpha bg with shadow then shadowBitmaps need to contain "hidden" ... // ... shadow-edges as well, so that they shine through when y-offset is 100px for on a... // ... 400x400px box for example, in that example we want the shadow to be drawn behind... // ... background at pos Y==100px ! */ final int shadowSleekW = sleekW; final int shadowSleekH = sleekH; long timestamp = System.currentTimeMillis(); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setStyle(Paint.Style.FILL); if (elementBorderColor != SleekColorArea.COLOR_TRANSPARENT) { paint.setColor(elementBorderColor); } else { paint.setColor(elementBackgroundColor); } paint.setShadowLayer( elementShadowRadius, elementShadowOffsetX, elementShadowOffsetY, elementShadowColor ); List<Bitmap> returnList = new ArrayList<>(4); int bitmapW, bitmapH; Bitmap bitmap; Canvas canvas; final float cornerWidth = elementShadowRadius; final float cornerHeight = elementShadowRadius; float translateX, translateY; bitmapW = (int) (shadowSleekW + cornerWidth + cornerWidth + Math.abs(elementShadowOffsetX)); bitmapH = (int) (elementBorderRadius + cornerHeight); if (elementShadowOffsetY < 0) { bitmapH = bitmapH - (int) elementShadowOffsetY; } if (bitmapW < 1) { bitmapW = 1; } if (bitmapH < 1) { bitmapH = 1; } bitmap = Bitmap.createBitmap(bitmapW, bitmapH, Bitmap.Config.ARGB_8888); bitmap.eraseColor(Color.TRANSPARENT); //bitmap.eraseColor(0x66ff00ff); canvas = new Canvas(bitmap); translateX = 0; translateY = 0; if (elementShadowOffsetX < 0) { translateX = -elementShadowOffsetX; } if (elementShadowOffsetY < 0) { translateY = -elementShadowOffsetY; } canvas.translate(translateX, translateY); canvas.drawRoundRect( new RectF(cornerWidth, cornerHeight, cornerWidth + shadowSleekW, cornerHeight + shadowSleekH), elementBorderRadius, elementBorderRadius, paint ); returnList.add(bitmap); bitmapW = (int) (shadowSleekW + cornerWidth + cornerWidth + Math.abs(elementShadowOffsetX)); bitmapH = (int) (elementBorderRadius + cornerHeight); if (elementShadowOffsetY > 0) { bitmapH = bitmapH + (int) elementShadowOffsetY; } if (bitmapW < 1) { bitmapW = 1; } if (bitmapH < 1) { bitmapH = 1; } bitmap = Bitmap.createBitmap(bitmapW, bitmapH, Bitmap.Config.ARGB_8888); bitmap.eraseColor(Color.TRANSPARENT); //bitmap.eraseColor(0x66ff00ff); canvas = new Canvas(bitmap); if (elementShadowOffsetX < 0) { canvas.translate(-elementShadowOffsetX, -shadowSleekH - elementShadowRadius + elementBorderRadius); } else { canvas.translate(0, -shadowSleekH - elementShadowRadius + elementBorderRadius); } canvas.drawRoundRect( new RectF(cornerWidth, cornerHeight, cornerWidth + shadowSleekW, cornerHeight + shadowSleekH), elementBorderRadius, elementBorderRadius, paint ); returnList.add(bitmap); bitmapW = (int) (elementBorderRadius + cornerWidth);// - elementShadowOffsetX); if (elementShadowOffsetX < 0) { bitmapW = bitmapW - (int) elementShadowOffsetX; } bitmapH = (int) (shadowSleekH - elementBorderRadius - elementBorderRadius); if (bitmapW < 1) { bitmapW = 1; } if (bitmapH < 1) { bitmapH = 1; } bitmap = Bitmap.createBitmap(bitmapW, bitmapH, Bitmap.Config.ARGB_8888); bitmap.eraseColor(Color.TRANSPARENT); //bitmap.eraseColor(0x99ff0000); canvas = new Canvas(bitmap); if (elementShadowOffsetX < 0) { canvas.translate(-elementShadowOffsetX, -cornerHeight - elementBorderRadius); } else { canvas.translate(0, -cornerHeight - elementBorderRadius); } canvas.drawRoundRect( new RectF(cornerWidth, cornerHeight, cornerWidth + shadowSleekW, cornerHeight + shadowSleekH), elementBorderRadius, elementBorderRadius, paint ); returnList.add(bitmap); bitmapW = (int) (elementBorderRadius + cornerWidth); if (elementShadowOffsetX > 0) { bitmapW = bitmapW + (int) elementShadowOffsetX; } bitmapH = (int) (shadowSleekH - elementBorderRadius - elementBorderRadius); if (bitmapW < 1) { bitmapW = 1; } if (bitmapH < 1) { bitmapH = 1; } bitmap = Bitmap.createBitmap(bitmapW, bitmapH, Bitmap.Config.ARGB_8888); bitmap.eraseColor(Color.TRANSPARENT); //bitmap.eraseColor(0x66000000); canvas = new Canvas(bitmap); //canvas.translate(0, - elementBorderRadius - elementBorderRadius); canvas.translate( -shadowSleekW - elementShadowRadius + elementBorderRadius, -cornerHeight - elementBorderRadius ); canvas.drawRoundRect( new RectF(cornerWidth, cornerHeight, cornerWidth + shadowSleekW, cornerHeight + shadowSleekH), elementBorderRadius, elementBorderRadius, paint ); returnList.add(bitmap); shadowViewSizeW = shadowSleekW; shadowViewSizeH = shadowSleekH; Log.d("SleekElement", "SleekElement | took: " + (System.currentTimeMillis() - timestamp) + "ms"); return returnList; } }
/** * * $Id: TherapyPopulateAction.java,v 1.23 2007-10-31 18:34:50 pandyas Exp $ * * $Log: not supported by cvs2svn $ * Revision 1.22 2007/09/12 19:36:40 pandyas * modified debug statements for build to stage tier * * Revision 1.21 2007/06/18 19:53:53 pandyas * EVS preferred name does not work for Zebrafish tree so changed * Will add this item to EVS gforge to fix, if possilbe * * Revision 1.20 2007/05/16 12:29:24 pandyas * Added developmental stage evs tree to Therapy when species is Zebrafsih * * Revision 1.19 2006/05/08 13:43:00 georgeda * Reformat and clean up warnings * * Revision 1.18 2006/04/27 18:34:53 pandyas * Fixed incorrect header * * Revision 1.17 2006/04/18 17:55:10 pandyas * Fixed Therapy multi-select collections - populate issue * * Revision 1.16 2006/04/17 19:09:40 pandyas * caMod 2.1 OM changes * * Revision 1.15 2005/12/29 18:29:14 pandyas * Clean up - removed code for TumorResponse * * Revision 1.14 2005/11/28 13:50:47 georgeda * Defect #207, handle nulls for pages w/ uncontrolled vocab * * Revision 1.13 2005/11/18 22:50:02 georgeda * Defect #184. Cleanup editing of old models * * Revision 1.12 2005/11/16 19:29:13 pandyas * modified typo in comments * * Revision 1.11 2005/11/03 13:59:10 georgeda * Fixed delete functionality * * Revision 1.10 2005/10/31 13:46:28 georgeda * Updates to handle back arrow * * Revision 1.9 2005/10/28 12:47:26 georgeda * Added delete functionality * * Revision 1.8 2005/10/27 19:42:05 georgeda * Cleanup * * Revision 1.7 2005/10/26 14:10:49 georgeda * Added other administrative route to therapy * * Revision 1.6 2005/10/25 19:42:15 georgeda * Finished Therapy page * * Revision 1.5 2005/10/20 20:40:21 pandyas * added javadocs * * */ package gov.nih.nci.camod.webapp.action; import gov.nih.nci.camod.Constants; import gov.nih.nci.camod.domain.AgentTarget; import gov.nih.nci.camod.domain.BiologicalProcess; import gov.nih.nci.camod.domain.ChemicalClass; import gov.nih.nci.camod.domain.Therapy; import gov.nih.nci.camod.service.TherapyManager; import gov.nih.nci.camod.webapp.form.TherapyForm; import gov.nih.nci.camod.webapp.util.NewDropdownUtil; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class TherapyPopulateAction extends BaseAction { /** * Pre-populate all field values in the form <FormName> Used by <jspName> * */ public ActionForward populate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { log.trace("Entering TherapyPopulateAction.populate"); // Create a form to edit TherapyForm therapyForm = (TherapyForm) form; // Grab the current Therapy we are working with related to this // animalModel String aTherapyID = request.getParameter("aTherapyID"); TherapyManager therapyManager = (TherapyManager) getBean("therapyManager"); Therapy therapy = therapyManager.get(aTherapyID); if (therapy == null) { request.setAttribute(Constants.Parameters.DELETED, "true"); } else { request.setAttribute("aTherapyID", aTherapyID); if (therapy.getTreatment() != null) { if (therapy.getTreatment().getSexDistribution() != null) { therapyForm.setType(therapy.getTreatment().getSexDistribution().getType()); } if (therapy.getTreatment().getAgeAtTreatment() != null) { therapyForm.setAgeAtTreatment(therapy.getTreatment().getAgeAtTreatment()); therapyForm.setAgeAtTreatmentUnit(therapy.getTreatment().getAgeAtTreatmentUnit()); } therapyForm.setDosage(therapy.getTreatment().getDosage()); therapyForm.setDosageUnit(therapy.getTreatment().getDosageUnit()); if (therapy.getTreatment().getAdminRouteAlternEntry() != null) { therapyForm.setAdministrativeRoute(Constants.Dropdowns.OTHER_OPTION); therapyForm.setOtherAdministrativeRoute(therapy.getTreatment().getAdminRouteAlternEntry()); } else { therapyForm.setAdministrativeRoute(therapy.getTreatment().getAdministrativeRoute()); } } //therapy.agent attribute therapyForm.setName(therapy.getAgent().getName()); //agent attributes if (therapy.getAgent().getCasNumber() != null) { therapyForm.setCasNumber(therapy.getAgent().getCasNumber()); } if (therapy.getAgent().getNscNumber() != null) { therapyForm.setNscNumber(therapy.getAgent().getNscNumber().toString()); } if(therapy.getDevelopmentalStage() !=null){ // since we are always querying from concept code (save and edit), // simply display name, EVSPreferredDescription does not work for Zebrafish vocab (commented out in LexEVS 5.1 upgrade) therapyForm.setDevelopmentalStage(therapy.getDevelopmentalStage().getName()); log.debug("setDevelopmentalStage= " + therapy.getDevelopmentalStage().getName()); therapyForm.setDevelopmentalStageCode(therapy.getDevelopmentalStage().getConceptCode()); log.debug("setDevelopmentalStageCode= " + therapy.getDevelopmentalStage().getConceptCode()); } // Therapy object attributes therapyForm.setToxicityGrade(therapy.getToxicityGrade()); therapyForm.setBiomarker(therapy.getBiomarker()); therapyForm.setExperiment(therapy.getExperiment()); therapyForm.setResults(therapy.getResults()); therapyForm.setTumorResponse(therapy.getTumorResponse()); therapyForm.setComments(therapy.getComments()); // Get the collection/Set of agent targets List<AgentTarget> theAgentTargetsList = new ArrayList<AgentTarget>(therapy.getAgent().getAgentTargetCollection()); String[] theTargets = new String[theAgentTargetsList.size()]; for (int i = 0; i < theAgentTargetsList.size(); i++) { AgentTarget theAgentTarget = (AgentTarget) theAgentTargetsList.get(i); theTargets[i] = theAgentTarget.getName(); } therapyForm.setSelectedTargets(theTargets); // Get the collection/Set of biological processes List<BiologicalProcess> theProcessesList = new ArrayList<BiologicalProcess>(therapy.getAgent().getBiologicalProcessCollection()); String[] theProcesses = new String[theProcessesList.size()]; for (int i = 0; i < theProcessesList.size(); i++) { BiologicalProcess theBiologicalProcess = (BiologicalProcess) theProcessesList.get(i); theProcesses[i] = theBiologicalProcess.getName(); } therapyForm.setSelectedProcesses(theProcesses); // Get the collection/Set of Chemical Classes List<ChemicalClass> theChemicalClassesList = new ArrayList<ChemicalClass>(therapy.getAgent().getChemicalClassCollection()); String[] theChemicalClasses = new String[theChemicalClassesList.size()]; for (int i = 0; i < theChemicalClassesList.size(); i++) { ChemicalClass theChemicalClass = (ChemicalClass) theChemicalClassesList.get(i); theChemicalClasses[i] = theChemicalClass.getName(); } therapyForm.setSelectedChemicalClasses(theChemicalClasses); } // Prepopulate all dropdown fields, set the global Constants to the // following this.dropdown(request, response); log.trace("Exiting TherapyPopulateAction.populate"); return mapping.findForward("submitTherapy"); } /** * Populate the dropdown menus for submitTherapy * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward dropdown(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { log.debug("<TherapyPopulateAction dropdown> Entering ActionForward dropdown()"); // setup dropdown menus this.dropdown(request, response); log.debug("<TherapyPopulateAction dropdown> Exiting ActionForward dropdown()"); return mapping.findForward("submitTherapy"); } /** * Populate all drowpdowns for this type of form * * @param request * @param response * @throws Exception */ public void dropdown(HttpServletRequest request, HttpServletResponse response) throws Exception { log.debug("<TherapyPopulateAction dropdown> Entering void dropdown()"); // Prepopulate all dropdown fields, set the global Constants to the // following NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.CHEMICALCLASSESDROP, ""); NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.BIOLOGICALPROCESSDROP, ""); NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.THERAPEUTICTARGETSDROP, ""); NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.CHEMTHERAPYDOSEUNITSDROP, ""); NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.AGEUNITSDROP, ""); NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.SEXDISTRIBUTIONDROP, Constants.Dropdowns.ADD_BLANK); NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.TOXICITYGRADESDROP, Constants.Dropdowns.ADD_BLANK); NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.ADMINISTRATIVEROUTEDROP, Constants.Dropdowns.ADD_BLANK); log.debug("<TherapyPopulateAction dropdown> Exiting void dropdown()"); } }
package opendap.semantics.IRISail; import net.sf.saxon.s9api.*; import org.openrdf.model.*; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.*; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParseException; import org.slf4j.Logger; import javax.xml.transform.stream.StreamSource; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.*; public class RdfImporter { private Logger log; private HashSet<String> urlsToBeIgnored; private Vector<String> imports; private String resourceDir; public RdfImporter(String resourceDir) { log = org.slf4j.LoggerFactory.getLogger(this.getClass()); urlsToBeIgnored = new HashSet<String>(); imports = new Vector<String>(); this.resourceDir = resourceDir; } public void reset() { urlsToBeIgnored.clear(); imports.clear(); } public boolean importReferencedRdfDocs(Repository repository, Vector<String> doNotImportUrls) { boolean repositoryChanged = false; Vector<String> rdfDocList = new Vector<String>(); if (doNotImportUrls != null) urlsToBeIgnored.addAll(doNotImportUrls); findNeededRDFDocuments(repository, rdfDocList); while (!rdfDocList.isEmpty()) { if(addNeededRDFDocuments(repository, rdfDocList)){ repositoryChanged = true; } rdfDocList.clear(); findNeededRDFDocuments(repository, rdfDocList); } return repositoryChanged; } /** * Find all rdfcache:RDFDocuments that are referenced by existing documents in the repository. * * @param repository * @param rdfDocs */ private void findNeededRDFDocuments(Repository repository, Vector<String> rdfDocs) { TupleQueryResult result = null; List<String> bindingNames; RepositoryConnection con = null; try { con = repository.getConnection(); String queryString = "(SELECT doc " + "FROM {doc} rdf:type {rdfcache:"+Terms.startingPointType +"} " + "union " + "SELECT doc " + "FROM {tp} rdf:type {rdfcache:"+Terms.startingPointType +"}; rdfcache:"+Terms.dependsOnContext+" {doc}) " + "MINUS " + "SELECT doc " + "FROM CONTEXT "+"rdfcache:"+Terms.cacheContext+" {doc} rdfcache:"+Terms.lastModifiedContext+" {lastmod} " + "USING NAMESPACE " + "rdfcache = <" + Terms.rdfCacheNamespace + ">"; log.debug("Query for NeededRDFDocuments: " + queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString); result = tupleQuery.evaluate(); while (result.hasNext()) { BindingSet bindingSet = result.next(); Value firstValue = bindingSet.getValue("doc"); String doc = firstValue.stringValue(); if (!rdfDocs.contains(doc) && !imports.contains(doc) && !urlsToBeIgnored.contains(doc) && doc.startsWith("http: rdfDocs.add(doc); log.debug("Adding to rdfDocs: " + doc); } } } catch (QueryEvaluationException e) { log.error("Caught an QueryEvaluationException! Msg: " + e.getMessage()); } catch (RepositoryException e) { log.error("Caught RepositoryException! Msg: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught MalformedQueryException! Msg: " + e.getMessage()); } finally { if (result != null) { try { result.close(); } catch (QueryEvaluationException e) { log.error("Caught a QueryEvaluationException! Msg: " + e.getMessage()); } } try { con.close(); } catch (RepositoryException e) { log.error("Caught a RepositoryException! in findNeededRDFDocuments() Msg: " + e.getMessage()); } } log.info("Number of needed files identified: " + rdfDocs.size()); } /** * Add the each of the RDF documents whose URL's are in the passed Vector to the Repository. * * @param repository * @param rdfDocs */ private boolean addNeededRDFDocuments(Repository repository, Vector<String> rdfDocs) { URI uriaddress; long inferStartTime, inferEndTime; inferStartTime = new Date().getTime(); String importURL = null; RepositoryConnection con = null; int skipCount = 0; String contentType = ""; HttpURLConnection hc = null; InputStream importIS = null; boolean addedDocument = false; try { con = repository.getConnection(); log.debug("rdfDocs.size=" + rdfDocs.size()); skipCount = 0; while (!rdfDocs.isEmpty()) { importURL = rdfDocs.remove(0); try { log.debug("Checking import URL: " + importURL); if (urlsToBeIgnored.contains(importURL)) { log.error("Previous server error, Skipping " + importURL); } else { URL myurl = new URL(importURL); int rsCode; hc = (HttpURLConnection) myurl.openConnection(); log.debug("Connected to import URL: " + importURL); rsCode = hc.getResponseCode(); contentType = hc.getContentType(); importIS = hc.getInputStream(); log.debug("Got HTTP status code: " + rsCode); log.debug("Got Content Type: " + contentType); if (rsCode == -1) { log.error("Unable to get an HTTP status code for resource " + importURL + " WILL NOT IMPORT!"); urlsToBeIgnored.add(importURL); } else if (rsCode != 200) { log.error("Error! HTTP status code " + rsCode + " Skipping importURL " + importURL); urlsToBeIgnored.add(importURL); } else { log.debug("Import URL appears valid ( " + importURL + " )"); //@todo make this a more robust String transformFile = getXsltTransformation(repository, importURL); log.debug("Transformation = " + transformFile); if (transformFile != null){ ByteArrayInputStream inStream; log.info("Transforming " + importURL+" with "+transformFile); inStream = transform(importIS,transformFile); log.info("Finished transforming RDFa " + importURL); importUrl(con, importURL, contentType, inStream); addedDocument = true; }else if(importURL.endsWith(".owl") || importURL.endsWith(".rdf")) { importUrl(con, importURL, contentType, importIS); addedDocument = true; } else if (importURL.endsWith(".xsd")) { transformFile = "xsl/xsd2owl.xsl"; ByteArrayInputStream inStream; log.info("Transforming '" + importURL+"' with "+transformFile); inStream = transform(importIS,resourceDir+transformFile); log.info("Finished transforming URL " + importURL); importUrl(con, importURL, contentType, inStream); addedDocument = true; } else { if ((contentType != null) && (contentType.equalsIgnoreCase("text/plain") || contentType.equalsIgnoreCase("text/xml") || contentType.equalsIgnoreCase("application/xml") || contentType.equalsIgnoreCase("application/rdf+xml")) ) { importUrl(con, importURL, contentType, importIS); log.info("Imported non owl/xsd from " + importURL); addedDocument = true; } else { log.warn("SKIPPING Import URL '" + importURL + "' It does not appear to reference a " + "document that I know how to process."); urlsToBeIgnored.add(importURL); //skip this file skipCount++; } log.info("Total non owl/xsd files skipped: " + skipCount); } } } // while (!rdfDocs.isEmpty() } catch (Exception e) { log.error("addNeededRDFDocuments(): Caught " + e.getClass().getName() + " Message: " + e.getMessage()); if (importURL != null){ log.warn("SKIPPING Import URL '"+importURL+"' Because bad things haoppened when we tried to get it."); urlsToBeIgnored.add(importURL); //skip this file } } finally { if (importIS != null) try { importIS.close(); } catch (IOException e) { log.error("addNeededRDFDocuments(): Caught " + e.getClass().getName() + " Message: " + e.getMessage()); } if (hc != null) hc.disconnect(); } } } catch (RepositoryException e) { log.error("addNeededRDFDocuments(): Caught " + e.getClass().getName() + " Message: " + e.getMessage()); } finally { if (con != null) { try { con.close(); } catch (RepositoryException e) { log.error("Caught an RepositoryException! in addNeededRDFDocuments() Msg: " + e.getMessage()); } } inferEndTime = new Date().getTime(); double inferTime = (inferEndTime - inferStartTime) / 1000.0; log.debug("Import takes " + inferTime + " seconds"); } return addedDocument; } private void importUrl(RepositoryConnection con, String importURL, String contentType, InputStream importIS) throws IOException, RDFParseException, RepositoryException { if (!this.imports.contains(importURL)) { // not in the repository yet log.info("Importing URL " + importURL); ValueFactory valueFactory = con.getValueFactory(); URI importUri = new URIImpl(importURL); con.add(importIS, importURL, RDFFormat.RDFXML, (Resource) importUri); RepositoryOps.setLTMODContext(importURL, con, valueFactory); // set last modified time of the context RepositoryOps.setContentTypeContext(importURL, contentType, con, valueFactory); log.info("Finished importing URL " + importURL); imports.add(importURL); } else { log.error("Import URL '"+importURL+"' already has been imported! SKIPPING!"); } } /** * Take file to transform and the style sheet to apply, return transformed file as * ByteArrayInputStream * @param is * @param xsltFileName * @return * @throws SaxonApiException * @throws IOException */ public ByteArrayInputStream transform(InputStream is, String xsltFileName) throws SaxonApiException, IOException { return transform(new StreamSource(is),xsltFileName); } /** * Compile and execute a simple transformation that applies a style sheet to * an input stream, and serializing the result to an OutPutStream * * @param sourceURL * @return ByteArrayInputStream * @throws net.sf.saxon.s9api.SaxonApiException * @throws IOException */ public ByteArrayInputStream transform(StreamSource sourceURL, String xsltFileName) throws SaxonApiException, IOException { log.debug("Executing XSL Transform Operation."); log.debug("XSL Transform Filename: "+xsltFileName); String doc = sourceURL.getSystemId(); if(doc==null) doc = sourceURL.getPublicId(); if(doc==null) doc = "StreamSource"; log.debug("Document to transform: "+doc); Processor proc = new Processor(false); XsltCompiler comp = proc.newXsltCompiler(); XsltExecutable exp = null; if (xsltFileName.startsWith("http: URL myurl = new URL(xsltFileName); HttpURLConnection hc = (HttpURLConnection) myurl.openConnection(); exp = comp.compile(new StreamSource(hc.getInputStream())); } else{ exp = comp.compile(new StreamSource(new File(xsltFileName))); } XdmNode source = proc.newDocumentBuilder().build(sourceURL); Serializer out = new Serializer(); out.setOutputProperty(Serializer.Property.METHOD, "xml"); out.setOutputProperty(Serializer.Property.INDENT, "yes"); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); out.setOutputStream(outStream); XsltTransformer trans = exp.load(); trans.setInitialContextNode(source); trans.setDestination(out); trans.transform(); log.info(outStream.toString()); log.debug("XSL Transform complete."); return new ByteArrayInputStream(outStream.toByteArray()); } /** * Return URL of the transformation file. * @param String importUrl * @param Repository repository * @return String xsltTransformationFileUrl */ private String getXsltTransformation(Repository repository, String importUrl){ TupleQueryResult result = null; RepositoryConnection con = null; String xsltTransformationFileUrl = null; try { con = repository.getConnection(); String queryString = "SELECT file, xslt " + "FROM {file} rdfcache:" + Terms.hasXsltTransformation + "{xslt}, " + "[{xslt} dcterm:" + Terms.isReplacedBy + "{newxslt}] " + "WHERE newxslt=NULL " + "using namespace " + "dcterm = <" +Terms.dcTermNamespace+ ">, " + "rdfcache = <" + Terms.rdfCacheNamespace + ">"; log.debug("Query for transformation file: " + queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString); result = tupleQuery.evaluate(); while (result.hasNext()) { BindingSet bindingSet = result.next(); Value firstValue = bindingSet.getValue("file"); Value secondValue = bindingSet.getValue("xslt"); if (firstValue.stringValue().equals(importUrl)){ xsltTransformationFileUrl= secondValue.stringValue(); } } } catch (RepositoryException e) { log.error("Caught a RepositoryException! in getXsltTransformation Msg: " +e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught a ! MalformedQueryException in getXsltTransformation Msg: " +e.getMessage()); } catch (QueryEvaluationException e) { log.error("Caught a QueryEvaluationException! in getXsltTransformation Msg: " +e.getMessage()); }finally { if (result != null) { try { result.close(); } catch (QueryEvaluationException e) { log.error("Caught a QueryEvaluationException! in getXsltTransformation Msg: " + e.getMessage()); } } try { con.close(); } catch (RepositoryException e) { log.error("Caught a RepositoryException! in getXsltTransformation Msg: " + e.getMessage()); } } return xsltTransformationFileUrl; } }
package edu.wustl.cab2b.common.util; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import edu.wustl.cab2b.common.exception.RuntimeException; import edu.wustl.common.util.logger.Logger; /** * This is a singleton class which parses the ResultConfiguration.xml file and * stores the mapping information into an internal map. * * @author Deepak Shingan * */ public class ResultConfigurationParser { /** * Self reference */ private static ResultConfigurationParser resultConfigurationMapper = null; /** * Map to store the application_entity to attribute object mapping KEY for * map = ApplicationName_EntityName */ private Map<String, EntityTransformerInfo> applicationEntityNameMap = new HashMap<String, EntityTransformerInfo>(); /** * Name of the Entity Service Mapper file */ private static final String RESULT_CONFIGURATION_MAPPER_FILENAME = "ResultConfiguration.xml"; /** * Application tag */ private static final String APPLICATION = "application"; /** * Entity tag */ private static final String ENTITY = "entity"; /** * Default tag */ private static final String DEFAULT = "default"; /** * Name tag */ private static final String NAME = "name"; /** * Result Transformer tag */ private static final String RESULT_TRANSFORMER = "result-transformer"; /** * Result Renderer tag */ private static final String RESULT_RENDERER = "result-renderer"; /** * Datalist Transformer tag */ private static final String DATALIST_TRANSFORMERS = "data-list-transformers"; private static final String DATALIST_SAVER = "saver"; private static final String DATALIST_RETRIEVER = "retriever"; private static final String DEFAULT_ELEMENT_KEY = new String("default"); private static final String KEY_DELIM = ":_:_:"; /** * Constructor */ private ResultConfigurationParser() { parseResultConfigurationMapperXMLFile(); } /** * This method returns an instance of this class * * @return an instance of this class */ public static synchronized ResultConfigurationParser getInstance() { if (resultConfigurationMapper == null) { resultConfigurationMapper = new ResultConfigurationParser(); } return resultConfigurationMapper; } /** * This method parses the ResultConfiguration.XML file and stores the parsed * data into an internally maintained Maps. */ private void parseResultConfigurationMapperXMLFile() { // Read the xml file InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream( RESULT_CONFIGURATION_MAPPER_FILENAME); if (inputStream == null) { throw new RuntimeException("File not found: " + RESULT_CONFIGURATION_MAPPER_FILENAME); } // Parse xml into the Document Document document = null; try { document = new SAXReader().read(inputStream); } catch (DocumentException e) { throw new RuntimeException("Unable to parse XML file: " + RESULT_CONFIGURATION_MAPPER_FILENAME, e); } // Traverse and fetch the data from the Document Element applicationsElement = document.getRootElement(); if (applicationsElement != null) { List<Element> applicationElementList = applicationsElement.elements(APPLICATION); if (applicationElementList == null || applicationElementList.isEmpty()) { throw new RuntimeException("Invalid XML file: Application entries not found."); } registerDefaultElement(applicationsElement, DEFAULT_ELEMENT_KEY); registerApplicationElements(applicationElementList); } else { throw new RuntimeException("Invalid XML file: Root element not found."); } } /** * Method to parse Attribute values under entity tag and store them in map */ private void setElementData(List<Element> elementList, String parentMapKey) { for (Element entityElement : elementList) { String mapKey = parentMapKey; if (entityElement.attributeValue(NAME) != null) { mapKey = mapKey + KEY_DELIM + entityElement.attributeValue(NAME); } Element resultTransformer = entityElement.element(RESULT_TRANSFORMER); Element resultRenderer = entityElement.element(RESULT_RENDERER); Element dataListTransformer = entityElement.element(DATALIST_TRANSFORMERS); String resultTransformerValue = null; String resultRendererValue = null; if (resultTransformer != null) { resultTransformerValue = resultTransformer.getTextTrim(); } if (resultRenderer != null) { resultRendererValue = resultRenderer.getTextTrim(); } DataListTransformer dataListTransformerValue = null; if (dataListTransformer != null) { Element saverElem = dataListTransformer.element(DATALIST_SAVER); Element retrieverElem = dataListTransformer.element(DATALIST_RETRIEVER); dataListTransformerValue = new DataListTransformer(saverElem.getTextTrim(), retrieverElem.getTextTrim()); } EntityTransformerInfo entityAttributes = new EntityTransformerInfo(resultTransformerValue, resultRendererValue, dataListTransformerValue); applicationEntityNameMap.put(mapKey, entityAttributes); } } /** * This method stores the data of all the application tags into * applicationEntityNameMap * * @param applicationElementList the root element of the XML document */ private void registerApplicationElements(List<Element> applicationElementList) { for (Element applicationElement : applicationElementList) { List<Element> entityElementList = applicationElement.elements(ENTITY); String mapKey = applicationElement.attributeValue(NAME); setElementData(entityElementList, mapKey); registerDefaultElement(applicationElement, mapKey); } } private void registerDefaultElement(Element parentElem, String mapKey) { List<Element> defaultElementList = parentElem.elements(DEFAULT); if (defaultElementList.size() > 1) { throw new IllegalArgumentException("only one default permitted."); } setElementData(defaultElementList, mapKey); } /** * Method to get default DataListTransformer value for given application * name * * @param String applicationName */ private DataListTransformer getDataListTransformer(String applicationName) { if (applicationEntityNameMap.get(applicationName) != null) { return applicationEntityNameMap.get(applicationName).getDataListTransformer(); } return null; } /** * Method to get default ResultRenderer value for given application name * * @param String applicationName */ private String getResultRenderer(String applicationName) { if (applicationEntityNameMap.get(applicationName) != null) { return applicationEntityNameMap.get(applicationName).getResultRenderer(); } return null; } /** * Method to get default ResultTransformer value for given application name * * @param String applicationName */ private String getResultTransformer(String applicationName) { if (applicationEntityNameMap.get(applicationName) != null) { return applicationEntityNameMap.get(applicationName).getResultTransformer(); } return null; } /** * Method to get ResultRenderer value for given application name and * entityName * * @param String applicationName * @param String entityName */ public String getResultRenderer(String applicationName, String entityName) { if (applicationEntityNameMap.get(applicationName + KEY_DELIM + entityName) != null) return applicationEntityNameMap.get(applicationName + KEY_DELIM + entityName).getResultRenderer(); String res = getResultRenderer(applicationName); if (res == null) { res = getDefault().getResultRenderer(); } return res; } /** * Method to get ResultTransformer value for given application name and * entityName * * @param applicationName * @param entityName * */ public String getResultTransformer(String applicationName, String entityName) { if (applicationEntityNameMap.get(applicationName + KEY_DELIM + entityName) != null) return applicationEntityNameMap.get(applicationName + KEY_DELIM + entityName).getResultTransformer(); String res = getResultTransformer(applicationName); if (res == null) { res = getDefault().getResultTransformer(); } return res; } /** * Method to get DataListTransformer value for given application name and * entityName * * @param applicationName * @param entityName * */ private DataListTransformer getDataListTransformer(String applicationName, String entityName) { if (applicationEntityNameMap.get(applicationName + KEY_DELIM + entityName) != null) return applicationEntityNameMap.get(applicationName + KEY_DELIM + entityName).getDataListTransformer(); DataListTransformer res = getDataListTransformer(applicationName); if (res == null) { res = getDefault().getDataListTransformer(); } return res; } public String getDataListSaver(String applicationName, String entityName) { return getDataListTransformer(applicationName, entityName).getSaver(); } public String getDataListRetriever(String applicationName, String entityName) { return getDataListTransformer(applicationName, entityName).getRetriever(); } private EntityTransformerInfo getDefault() { return applicationEntityNameMap.get(DEFAULT_ELEMENT_KEY); } private class DataListTransformer { String saver; String retriever; public DataListTransformer(String saver, String retriever) { this.saver = saver; this.retriever = retriever; } public String getRetriever() { return retriever; } public String getSaver() { return saver; } } /** * Class to store parsed resultTransformer, resultRenderer and * dataListTransformer values * * @author Deepak_Shingan * */ private class EntityTransformerInfo { String resultTransformer; String resultRenderer; DataListTransformer dataListTransformer; EntityTransformerInfo( String resultTransformer, String resultRenderer, DataListTransformer dataListTransformer) { this.resultTransformer = resultTransformer; this.resultRenderer = resultRenderer; this.dataListTransformer = dataListTransformer; } /** * Method to get datalistTransfarmer value * * @return String dataListTransformer */ public DataListTransformer getDataListTransformer() { return dataListTransformer; } /** * Method to get ResultRenderer value * * @return String resultRenderer */ public String getResultRenderer() { return resultRenderer; } /** * Method to get ResultTransformer value * * @return String ResultTransformer */ public String getResultTransformer() { return resultTransformer; } } public static void main(String[] args) { Logger.configure(); ResultConfigurationParser entityServiceMapper = ResultConfigurationParser.getInstance(); Logger.out.info(entityServiceMapper.getDataListSaver("CategoryEntityGroup", "foobar")); Logger.out.info(entityServiceMapper.getResultRenderer("caArray","gov.nih.nci.mageom.domain.BioAssayData.DerivedBioAssayData")); Logger.out.info(entityServiceMapper.getResultRenderer("caArray", "foobar")); Logger.out.info(entityServiceMapper.getResultRenderer(null, null)); Logger.out.info(entityServiceMapper.getDataListRetriever("foo", "bar")); Logger.out.info(entityServiceMapper.getDataListRetriever(null, null)); } }
package org.anddev.andengine.util.color; public class Color { // Constants public static final Color WHITE = new Color(1, 1, 1, 1); public static final Color BLACK = new Color(0, 0, 0, 1); public static final Color RED = new Color(1, 0, 0, 1); public static final Color YELLOW = new Color(1, 1, 0, 1); public static final Color GREEN = new Color(0, 1, 0, 1); public static final Color CYAN = new Color(0, 1, 1, 1); public static final Color BLUE = new Color(0, 0, 1, 1); public static final Color PINK = new Color(1, 0, 1, 1); public static final Color TRANSPARENT = new Color(1, 1, 1, 0); public static final float WHITE_PACKED = Color.WHITE.getPacked(); public static final float BLACK_PACKED = Color.BLACK.getPacked(); public static final float RED_PACKED = Color.RED.getPacked(); public static final float YELLOW_PACKED = Color.YELLOW.getPacked(); public static final float GREEN_PACKED = Color.GREEN.getPacked(); public static final float CYAN_PACKED = Color.CYAN.getPacked(); public static final float BLUE_PACKED = Color.BLUE.getPacked(); public static final float PINK_PACKED = Color.PINK.getPacked(); public static final float TRANSPARENT_PACKED = Color.TRANSPARENT.getPacked(); // Fields private float mRed; private float mGreen; private float mBlue; private float mAlpha; private float mPacked; // Constructors public Color(final float pRed, final float pGreen, final float pBlue) { this(pRed, pGreen, pBlue, 1); } public Color(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.set(pRed, pGreen, pBlue, pAlpha); } // Getter & Setter public float getRed() { return this.mRed; } public float getGreen() { return this.mGreen; } public float getBlue() { return this.mBlue; } public float getAlpha() { return this.mAlpha; } public void setRed(final float pRed) { this.mRed = pRed; this.pack(); } public boolean setRedChecking(final float pRed) { if(this.mRed != pRed) { this.mRed = pRed; this.pack(); return true; } return false; } public void setGreen(final float pGreen) { this.mGreen = pGreen; this.pack(); } public boolean setGreenChecking(final float pGreen) { if(this.mGreen != pGreen) { this.mGreen = pGreen; this.pack(); return true; } return false; } public void setBlue(final float pBlue) { this.mBlue = pBlue; this.pack(); } public boolean setBlueChecking(final float pBlue) { if(this.mBlue != pBlue) { this.mBlue = pBlue; this.pack(); return true; } return false; } public void setAlpha(final float pAlpha) { this.mAlpha = pAlpha; this.pack(); } public boolean setAlphaChecking(final float pAlpha) { if(this.mAlpha != pAlpha) { this.mAlpha = pAlpha; this.pack(); return true; } return false; } public void set(final float pRed, final float pGreen, final float pBlue) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; this.pack(); } public boolean setChanging(final float pRed, final float pGreen, final float pBlue) { if(this.mRed != pRed || this.mGreen != pGreen || this.mBlue != pBlue) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; this.pack(); return true; } return false; } public void set(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; this.mAlpha = pAlpha; this.pack(); } public boolean setChanging(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { if(this.mAlpha != pAlpha || this.mRed != pRed || this.mGreen != pGreen || this.mBlue != pBlue) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; this.pack(); return true; } return false; } public void set(final Color pColor) { this.mRed = pColor.mRed; this.mGreen = pColor.mGreen; this.mBlue = pColor.mBlue; this.mAlpha = pColor.mAlpha; this.mPacked = pColor.mPacked; } public boolean setChecking(final Color pColor) { if(this.mAlpha != pColor.mAlpha || this.mRed != pColor.mRed || this.mGreen != pColor.mGreen || this.mBlue != pColor.mBlue) { this.mRed = pColor.mRed; this.mGreen = pColor.mGreen; this.mBlue = pColor.mBlue; this.mAlpha = pColor.mAlpha; this.mPacked = pColor.mPacked; return true; } return false; } public float getPacked() { return this.mPacked; } public void reset() { this.set(1, 1, 1, 1); } // Methods for/from SuperClass/Interfaces @Override public String toString() { return new StringBuilder() .append("[Red: ") .append(this.mRed) .append(", Green: ") .append(this.mGreen) .append(", Blue: ") .append(this.mBlue) .append("]") .toString(); } // Methods private void pack() { final int packed = ((int)(255 * this.mAlpha) << 24) | ((int)(255 * this.mBlue) << 16) | ((int)(255 * this.mGreen) << 8) | ((int)(255 * this.mRed)); this.mPacked = Float.intBitsToFloat(packed & 0XFEFFFFFF); } public static float pack(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { final int packed = ((int)(255 * pAlpha) << 24) | ((int)(255 * pBlue) << 16) | ((int)(255 * pGreen) << 8) | ((int)(255 * pRed)); return Float.intBitsToFloat(packed & 0XFEFFFFFF); } public void mix(final Color pColorA, final float pPercentageA, final Color pColorB, final float pPercentageB) { final float red = pColorA.mRed * pPercentageA + pColorB.mRed * pPercentageB; final float green = pColorA.mGreen * pPercentageA + pColorB.mGreen * pPercentageB; final float blue = pColorA.mBlue * pPercentageA + pColorB.mBlue * pPercentageB; final float alpha = pColorA.mAlpha * pPercentageA + pColorB.mAlpha * pPercentageB; this.set(red, green, blue, alpha); } // Inner and Anonymous Classes }
package org.apache.fop.render.pdf; // FOP import org.apache.fop.render.PrintRenderer; import org.apache.fop.render.RendererContext; import org.apache.fop.fo.FOUserAgent; import org.apache.fop.image.FopImage; import org.apache.fop.image.XMLImage; import org.apache.fop.image.ImageFactory; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.Version; import org.apache.fop.fo.properties.RuleStyle; import org.apache.fop.fo.properties.BackgroundRepeat; import org.apache.fop.pdf.PDFStream; import org.apache.fop.pdf.PDFDocument; import org.apache.fop.pdf.PDFInfo; import org.apache.fop.pdf.PDFResources; import org.apache.fop.pdf.PDFXObject; import org.apache.fop.pdf.PDFPage; import org.apache.fop.pdf.PDFState; import org.apache.fop.pdf.PDFLink; import org.apache.fop.pdf.PDFOutline; import org.apache.fop.pdf.PDFAnnotList; import org.apache.fop.pdf.PDFColor; import org.apache.fop.extensions.BookmarkData; import org.apache.fop.area.Trait; import org.apache.fop.area.TreeExt; import org.apache.fop.area.CTM; import org.apache.fop.area.Title; import org.apache.fop.area.PageViewport; import org.apache.fop.area.Page; import org.apache.fop.area.RegionReference; import org.apache.fop.area.Area; import org.apache.fop.area.Block; import org.apache.fop.area.BlockViewport; import org.apache.fop.area.LineArea; import org.apache.fop.area.inline.Character; import org.apache.fop.area.inline.Word; import org.apache.fop.area.inline.Viewport; import org.apache.fop.area.inline.ForeignObject; import org.apache.fop.area.inline.Image; import org.apache.fop.area.inline.Leader; import org.apache.fop.area.inline.InlineParent; import org.apache.fop.layout.FontState; import org.apache.fop.layout.FontMetric; import org.apache.fop.traits.BorderProps; import org.apache.fop.datatypes.ColorType; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.w3c.dom.Document; // Java import java.io.IOException; import java.io.OutputStream; import java.awt.geom.Rectangle2D; import java.awt.geom.AffineTransform; import java.util.HashMap; import java.util.List; import java.util.ArrayList; /* todo: word rendering and optimistion pdf state optimisation line and border background pattern writing mode text decoration */ /** * Renderer that renders areas to PDF * */ public class PDFRenderer extends PrintRenderer { /** * The mime type for pdf */ public static final String MIME_TYPE = "application/pdf"; /** * the PDF Document being created */ protected PDFDocument pdfDoc; /** * Map of pages using the PageViewport as the key * this is used for prepared pages that cannot be immediately * rendered */ protected HashMap pages = null; /** * Page references are stored using the PageViewport as the key * when a reference is made the PageViewport is used * for pdf this means we need the pdf page reference */ protected HashMap pageReferences = new HashMap(); protected HashMap pvReferences = new HashMap(); private String producer; /** * The output stream to write the document to */ protected OutputStream ostream; /** * the /Resources object of the PDF document being created */ protected PDFResources pdfResources; /** * the current stream to add PDF commands to */ protected PDFStream currentStream; /** * the current annotation list to add annotations to */ protected PDFAnnotList currentAnnotList; /** * the current page to add annotations to */ protected PDFPage currentPage; // drawing state protected PDFState currentState = null; protected PDFColor currentColor; protected String currentFontName = ""; protected int currentFontSize = 0; protected int pageHeight; protected HashMap filterMap = new HashMap(); /** * true if a TJ command is left to be written */ protected boolean textOpen = false; /** * the previous Y coordinate of the last word written. * Used to decide if we can draw the next word on the same line. */ protected int prevWordY = 0; /** * the previous X coordinate of the last word written. * used to calculate how much space between two words */ protected int prevWordX = 0; /** * The width of the previous word. Used to calculate space between */ protected int prevWordWidth = 0; /** * reusable word area string buffer to reduce memory usage */ private StringBuffer wordAreaPDF = new StringBuffer(); /** * create the PDF renderer */ public PDFRenderer() { } /** * Configure the PDF renderer. * Get the configuration to be used for pdf stream filters, * fonts etc. */ public void configure(Configuration conf) throws ConfigurationException { Configuration filters = conf.getChild("filterList"); Configuration[] filt = filters.getChildren("value"); ArrayList filterList = new ArrayList(); for (int i = 0; i < filt.length; i++) { String name = filt[i].getValue(); filterList.add(name); } filterMap.put(PDFStream.DEFAULT_FILTER, filterList); Configuration[] font = conf.getChildren("font"); for (int i = 0; i < font.length; i++) { Configuration[] triple = font[i].getChildren("font-triplet"); ArrayList tripleList = new ArrayList(); for (int j = 0; j < triple.length; j++) { tripleList.add(new FontTriplet(triple[j].getAttribute("name"), triple[j].getAttribute("style"), triple[j].getAttribute("weight"))); } EmbedFontInfo efi; efi = new EmbedFontInfo(font[i].getAttribute("metrics-url"), font[i].getAttributeAsBoolean("kerning"), tripleList, font[i].getAttribute("embed-url")); if(fontList == null) { fontList = new ArrayList(); } fontList.add(efi); } } /** * set the PDF document's producer * * @param producer string indicating application producing PDF */ public void setProducer(String prod) { producer = prod; } public void setUserAgent(FOUserAgent agent) { super.setUserAgent(agent); PDFXMLHandler xmlHandler = new PDFXMLHandler(); //userAgent.setDefaultXMLHandler(MIME_TYPE, xmlHandler); String svg = "http: userAgent.addXMLHandler(MIME_TYPE, svg, xmlHandler); } public void startRenderer(OutputStream stream) throws IOException { ostream = stream; this.pdfDoc = new PDFDocument(Version.getVersion()); this.pdfDoc.setProducer(producer); this.pdfDoc.setFilterMap(filterMap); pdfDoc.outputHeader(stream); } public void stopRenderer() throws IOException { FontSetup.addToResources(pdfDoc, pdfDoc.getResources(), fontInfo); pdfDoc.outputTrailer(ostream); this.pdfDoc = null; ostream = null; } public boolean supportsOutOfOrder() { return true; } public void renderExtension(TreeExt ext) { // render bookmark extension if (ext instanceof BookmarkData) { renderRootExtensions((BookmarkData)ext); } } protected void renderRootExtensions(BookmarkData bookmarks) { for (int i = 0; i < bookmarks.getCount(); i++) { BookmarkData ext = bookmarks.getSubData(i); renderOutline(ext, null); } } private void renderOutline(BookmarkData outline, PDFOutline parentOutline) { PDFOutline outlineRoot = pdfDoc.getOutlineRoot(); PDFOutline pdfOutline = null; PageViewport pv = outline.getPage(); if(pv != null) { Rectangle2D bounds = pv.getViewArea(); double h = bounds.getHeight(); float yoffset = (float)h / 1000f; String intDest = (String)pageReferences.get(pv.getKey()); if (parentOutline == null) { pdfOutline = pdfDoc.makeOutline(outlineRoot, outline.getLabel(), intDest, yoffset); } else { PDFOutline pdfParentOutline = parentOutline; pdfOutline = pdfDoc.makeOutline(pdfParentOutline, outline.getLabel(), intDest, yoffset); } } for (int i = 0; i < outline.getCount(); i++) { renderOutline(outline.getSubData(i), pdfOutline); } } public void startPageSequence(Title seqTitle) { if (seqTitle != null) { String str = convertTitleToString(seqTitle); PDFInfo info = this.pdfDoc.getInfo(); info.setTitle(str); } } /** * The pdf page is prepared by making the page. * The page is made in the pdf document without any contents * and then stored to add the contents later. * The page objects is stored using the area tree PageViewport * as a key. */ public void preparePage(PageViewport page) { this.pdfResources = this.pdfDoc.getResources(); Rectangle2D bounds = page.getViewArea(); double w = bounds.getWidth(); double h = bounds.getHeight(); currentPage = this.pdfDoc.makePage(this.pdfResources, (int) Math.round(w / 1000), (int) Math.round(h / 1000)); if (pages == null) { pages = new HashMap(); } pages.put(page, currentPage); pageReferences.put(page.getKey(), currentPage.referencePDF()); pvReferences.put(page.getKey(), page); } /** * This method creates a pdf stream for the current page * uses it as the contents of a new page. The page is written * immediately to the output stream. */ public void renderPage(PageViewport page) throws IOException, FOPException { if (pages != null && (currentPage = (PDFPage) pages.get(page)) != null) { pages.remove(page); Rectangle2D bounds = page.getViewArea(); double h = bounds.getHeight(); pageHeight = (int) h; } else { this.pdfResources = this.pdfDoc.getResources(); Rectangle2D bounds = page.getViewArea(); double w = bounds.getWidth(); double h = bounds.getHeight(); pageHeight = (int) h; currentPage = this.pdfDoc.makePage(this.pdfResources, (int) Math.round(w / 1000), (int) Math.round(h / 1000)); pageReferences.put(page.getKey(), currentPage.referencePDF()); pvReferences.put(page.getKey(), page); } currentStream = this.pdfDoc.makeStream(PDFStream.CONTENT_FILTER, false); currentState = new PDFState(); currentState.setTransform(new AffineTransform(1, 0, 0, -1, 0, (int) Math.round(pageHeight / 1000))); // Transform origin at top left to origin at bottom left currentStream.add("1 0 0 -1 0 " + (int) Math.round(pageHeight / 1000) + " cm\n"); //currentStream.add("BT\n"); currentFontName = ""; Page p = page.getPage(); renderPageAreas(p); //currentStream.add("ET\n"); this.pdfDoc.addStream(currentStream); currentPage.setContents(currentStream); this.pdfDoc.addPage(currentPage); this.pdfDoc.output(ostream); } protected void startVParea(CTM ctm) { // Set the given CTM in the graphics state currentState.push(); currentState.setTransform( new AffineTransform(CTMHelper.toPDFArray(ctm))); currentStream.add("q\n"); // multiply with current CTM currentStream.add(CTMHelper.toPDFString(ctm) + " cm\n"); // Set clip? currentStream.add("BT\n"); } protected void endVParea() { currentStream.add("ET\n"); currentStream.add("Q\n"); currentState.pop(); } protected void renderRegion(RegionReference region) { // Draw a rectangle so we can see it! // x=0,y=0,w=ipd,h=bpd currentFontName = ""; super.renderRegion(region); } /** * Handle block traits. * The block could be any sort of block with any positioning * so this should render the traits such as border and background * in its position. * * @param block the block to render the traits */ protected void handleBlockTraits(Block block) { float startx = currentIPPosition / 1000f; float starty = currentBPPosition / 1000f; drawBackAndBorders(block, startx, starty, block.getWidth() / 1000f, block.getHeight() / 1000f); } /** * Draw the background and borders. * This draws the background and border traits for an area given * the position. * * @param block the area to get the traits from * @param startx the start x position * @param starty the start y position * @param width the width of the area * @param height the height of the area */ protected void drawBackAndBorders(Area block, float startx, float starty, float width, float height) { // draw background then border closeText(); boolean started = false; Trait.Background back; back = (Trait.Background)block.getTrait(Trait.BACKGROUND); if(back != null) { started = true; currentStream.add("ET\n"); currentStream.add("q\n"); if (back.color != null) { updateColor(back.color, true, null); currentStream.add(startx + " " + starty + " " + width + " " + height + " re\n"); currentStream.add("f\n"); } if (back.url != null) { ImageFactory fact = ImageFactory.getInstance(); FopImage fopimage = fact.getImage(back.url, userAgent); if (fopimage != null && fopimage.load(FopImage.DIMENSIONS, userAgent)) { if (back.repeat == BackgroundRepeat.REPEAT) { // create a pattern for the image } else { // place once Rectangle2D pos; pos = new Rectangle2D.Float((startx + back.horiz) * 1000, (starty + back.vertical) * 1000, fopimage.getWidth() * 1000, fopimage.getHeight() * 1000); putImage(back.url, pos); } } } } BorderProps bps = (BorderProps)block.getTrait(Trait.BORDER_BEFORE); if(bps != null) { float endx = startx + width; if(!started) { started = true; currentStream.add("ET\n"); currentStream.add("q\n"); } updateColor(bps.color, false, null); currentStream.add(bps.width / 1000f + " w\n"); drawLine(startx, starty, endx, starty); } bps = (BorderProps)block.getTrait(Trait.BORDER_START); if(bps != null) { float endy = starty + height; if(!started) { started = true; currentStream.add("ET\n"); currentStream.add("q\n"); } updateColor(bps.color, false, null); currentStream.add(bps.width / 1000f + " w\n"); drawLine(startx, starty, startx, endy); } bps = (BorderProps)block.getTrait(Trait.BORDER_AFTER); if(bps != null) { float sy = starty + height; float endx = startx + width; if(!started) { started = true; currentStream.add("ET\n"); currentStream.add("q\n"); } updateColor(bps.color, false, null); currentStream.add(bps.width / 1000f + " w\n"); drawLine(startx, sy, endx, sy); } bps = (BorderProps)block.getTrait(Trait.BORDER_END); if(bps != null) { float sx = startx + width; float endy = starty + height; if(!started) { started = true; currentStream.add("ET\n"); currentStream.add("q\n"); } updateColor(bps.color, false, null); currentStream.add(bps.width / 1000f + " w\n"); drawLine(sx, starty, sx, endy); } if(started) { currentStream.add("Q\n"); currentStream.add("BT\n"); // font last set out of scope in text section currentFontName = ""; } } /** * Draw a line. * * @param startx the start x position * @param starty the start y position * @param endx the x end position * @param endy the y end position */ private void drawLine(float startx, float starty, float endx, float endy) { currentStream.add(startx + " " + starty + " m\n"); currentStream.add(endx + " " + endy + " l\n"); currentStream.add("S\n"); } protected void renderBlockViewport(BlockViewport bv, List children) { // clip and position viewport if necessary // save positions int saveIP = currentIPPosition; int saveBP = currentBPPosition; String saveFontName = currentFontName; CTM ctm = bv.getCTM(); closeText(); if (bv.getPositioning() == Block.ABSOLUTE) { currentIPPosition = 0; currentBPPosition = 0; currentStream.add("ET\n"); if (bv.getClip()) { currentStream.add("q\n"); float x = (float)(bv.getXOffset() + containingIPPosition) / 1000f; float y = (float)(bv.getYOffset() + containingBPPosition) / 1000f; float width = (float)bv.getWidth() / 1000f; float height = (float)bv.getHeight() / 1000f; clip(x, y, width, height); } CTM tempctm = new CTM(containingIPPosition, containingBPPosition); ctm = tempctm.multiply(ctm); startVParea(ctm); handleBlockTraits(bv); renderBlocks(children); endVParea(); if (bv.getClip()) { currentStream.add("Q\n"); } currentStream.add("BT\n"); // clip if necessary currentIPPosition = saveIP; currentBPPosition = saveBP; } else { if (ctm != null) { currentIPPosition = 0; currentBPPosition = 0; currentStream.add("ET\n"); double[] vals = ctm.toArray(); boolean aclock = vals[2] == 1.0; if (vals[2] == 1.0) { ctm = ctm.translate(-saveBP - bv.getHeight(), -saveIP); } else if (vals[0] == -1.0) { ctm = ctm.translate(-saveIP - bv.getWidth(), -saveBP - bv.getHeight()); } else { ctm = ctm.translate(saveBP, saveIP - bv.getWidth()); } } if (bv.getClip()) { currentStream.add("q\n"); float x = (float)bv.getXOffset() / 1000f; float y = (float)bv.getYOffset() / 1000f; float width = (float)bv.getWidth() / 1000f; float height = (float)bv.getHeight() / 1000f; clip(x, y, width, height); } if (ctm != null) { startVParea(ctm); } handleBlockTraits(bv); renderBlocks(children); if (ctm != null) { endVParea(); } if (bv.getClip()) { currentStream.add("Q\n"); } if (ctm != null) { currentStream.add("BT\n"); } // clip if necessary currentIPPosition = saveIP; currentBPPosition = saveBP; currentBPPosition += (int)(bv.getHeight()); } currentFontName = saveFontName; } /** * Clip an area. * write a clipping operation given coordinates in the current * transform. * @param x the x coordinate * @param y the y coordinate * @param width the width of the area * @param height the height of the area */ protected void clip(float x, float y, float width, float height) { currentStream.add(x + " " + y + " m\n"); currentStream.add((x + width) + " " + y + " l\n"); currentStream.add((x + width) + " " + (y + height) + " l\n"); currentStream.add(x + " " + (y + height) + " l\n"); currentStream.add("h\n"); currentStream.add("W\n"); currentStream.add("n\n"); } protected void renderLineArea(LineArea line) { super.renderLineArea(line); closeText(); } /** * Render inline parent area. * For pdf this handles the inline parent area traits such as * links, border, background. * @param ip the inline parent area */ public void renderInlineParent(InlineParent ip) { float start = currentBlockIPPosition / 1000f; float top = (ip.getOffset() + currentBPPosition) / 1000f; float width = ip.getWidth() / 1000f; float height = ip.getHeight() / 1000f; drawBackAndBorders(ip, start, top, width, height); // render contents super.renderInlineParent(ip); // place the link over the top Object tr = ip.getTrait(Trait.INTERNAL_LINK); boolean internal = false; String dest = null; float yoffset = 0; if (tr == null) { dest = (String)ip.getTrait(Trait.EXTERNAL_LINK); } else { String pvKey = (String)tr; dest = (String)pageReferences.get(pvKey); if(dest != null) { PageViewport pv = (PageViewport)pvReferences.get(pvKey); Rectangle2D bounds = pv.getViewArea(); double h = bounds.getHeight(); yoffset = (float)h / 1000f; internal = true; } } if (dest != null) { // add link to pdf document Rectangle2D rect = new Rectangle2D.Float(start, top, width, height); // transform rect to absolute coords AffineTransform transform = currentState.getTransform(); rect = transform.createTransformedShape(rect).getBounds(); int type = internal ? PDFLink.INTERNAL : PDFLink.EXTERNAL; PDFLink pdflink = pdfDoc.makeLink(rect, dest, type, yoffset); currentPage.addAnnotation(pdflink); } } public void renderCharacter(Character ch) { super.renderCharacter(ch); } public void renderWord(Word word) { StringBuffer pdf = new StringBuffer(); String name = (String) word.getTrait(Trait.FONT_NAME); int size = ((Integer) word.getTrait(Trait.FONT_SIZE)).intValue(); // This assumes that *all* CIDFonts use a /ToUnicode mapping Font f = (Font) fontInfo.getFonts().get(name); boolean useMultiByte = f.isMultiByte(); // String startText = useMultiByte ? "<FEFF" : "("; String startText = useMultiByte ? "<" : "("; String endText = useMultiByte ? "> " : ") "; updateFont(name, size, pdf); ColorType ct = (ColorType)word.getTrait(Trait.COLOR); if(ct != null) { updateColor(ct, true, pdf); } int rx = currentBlockIPPosition; // int bl = pageHeight - currentBPPosition; int bl = currentBPPosition + word.getOffset(); // Set letterSpacing //float ls = fs.getLetterSpacing() / this.currentFontSize; //pdf.append(ls).append(" Tc\n"); if (!textOpen || bl != prevWordY) { closeText(); pdf.append("1 0 0 -1 " + (rx / 1000f) + " " + (bl / 1000f) + " Tm [" + startText); prevWordY = bl; textOpen = true; } else { // express the space between words in thousandths of an em int space = prevWordX - rx + prevWordWidth; float emDiff = (float) space / (float) currentFontSize * 1000f; // this prevents a problem in Acrobat Reader and other viewers // where large numbers cause text to disappear or default to // a limit if (emDiff < -33000) { closeText(); pdf.append("1 0 0 1 " + (rx / 1000f) + " " + (bl / 1000f) + " Tm [" + startText); textOpen = true; } else { pdf.append(Float.toString(emDiff)); pdf.append(" "); pdf.append(startText); } } prevWordWidth = word.getWidth(); prevWordX = rx; String s = word.getWord(); FontMetric metrics = fontInfo.getMetricsFor(name); FontState fs = new FontState(name, metrics, size); escapeText(s, fs, useMultiByte, pdf); pdf.append(endText); currentStream.add(pdf.toString()); super.renderWord(word); } public void escapeText(String s, FontState fs, boolean useMultiByte, StringBuffer pdf) { String startText = useMultiByte ? "<" : "("; String endText = useMultiByte ? "> " : ") "; boolean kerningAvailable = false; HashMap kerning = null; kerning = fs.getKerning(); if (kerning != null && !kerning.isEmpty()) { kerningAvailable = true; } int l = s.length(); for (int i = 0; i < l; i++) { char ch = fs.mapChar(s.charAt(i)); if (!useMultiByte) { if (ch > 127) { pdf.append("\\"); pdf.append(Integer.toOctalString((int) ch)); } else { switch (ch) { case '(': case ')': case '\\': pdf.append("\\"); break; } pdf.append(ch); } } else { pdf.append(getUnicodeString(ch)); } if (kerningAvailable && (i + 1) < l) { addKerning(pdf, (new Integer((int) ch)), (new Integer((int) fs.mapChar(s.charAt(i + 1))) ), kerning, startText, endText); } } } /** * Convert a char to a multibyte hex representation */ private String getUnicodeString(char c) { StringBuffer buf = new StringBuffer(4); byte[] uniBytes = null; try { char[] a = {c}; uniBytes = new String(a).getBytes("UnicodeBigUnmarked"); } catch (java.io.UnsupportedEncodingException e) { // This should never fail } for (int i = 0; i < uniBytes.length; i++) { int b = (uniBytes[i] < 0) ? (int)(256 + uniBytes[i]) : (int) uniBytes[i]; String hexString = Integer.toHexString(b); if (hexString.length() == 1) { buf = buf.append("0" + hexString); } else { buf = buf.append(hexString); } } return buf.toString(); } private void addKerning(StringBuffer buf, Integer ch1, Integer ch2, HashMap kerning, String startText, String endText) { HashMap kernPair = (HashMap) kerning.get(ch1); if (kernPair != null) { Integer width = (Integer) kernPair.get(ch2); if (width != null) { buf.append(endText).append(-width.intValue()); buf.append(' ').append(startText); } } } /** * Checks to see if we have some text rendering commands open * still and writes out the TJ command to the stream if we do */ private void closeText() { if (textOpen) { currentStream.add("] TJ\n"); textOpen = false; prevWordX = 0; prevWordY = 0; } } private void updateColor(ColorType col, boolean fill, StringBuffer pdf) { PDFColor areaColor = null; //if (this.currentFill instanceof PDFColor) { // areaColor = (PDFColor)this.currentFill; if (areaColor == null || areaColor.red() != (double)col.red() || areaColor.green() != (double)col.green() || areaColor.blue() != (double)col.blue()) { areaColor = new PDFColor((double)col.red(), (double)col.green(), (double)col.blue()); closeText(); //this.currentFill = areaColor; if(pdf != null) { pdf.append(areaColor.getColorSpaceOut(fill)); } else { currentStream.add(areaColor.getColorSpaceOut(fill)); } } } private void updateFont(String name, int size, StringBuffer pdf) { if ((!name.equals(this.currentFontName)) || (size != this.currentFontSize)) { closeText(); this.currentFontName = name; this.currentFontSize = size; pdf = pdf.append("/" + name + " " + ((float) size / 1000f) + " Tf\n"); } } public void renderImage(Image image, Rectangle2D pos) { String url = image.getURL(); putImage(url, pos); } protected void putImage(String url, Rectangle2D pos) { PDFXObject xobject = pdfDoc.getImage(url); if (xobject != null) { int w = (int) pos.getWidth() / 1000; int h = (int) pos.getHeight() / 1000; placeImage((int) pos.getX() / 1000, (int) pos.getY() / 1000, w, h, xobject.getXNumber()); return; } ImageFactory fact = ImageFactory.getInstance(); FopImage fopimage = fact.getImage(url, userAgent); if (fopimage == null) { return; } if (!fopimage.load(FopImage.DIMENSIONS, userAgent)) { return; } String mime = fopimage.getMimeType(); if ("text/xml".equals(mime)) { if (!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) { return; } Document doc = ((XMLImage) fopimage).getDocument(); String ns = ((XMLImage) fopimage).getNameSpace(); renderDocument(doc, ns, pos); } else if ("image/svg+xml".equals(mime)) { if (!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) { return; } Document doc = ((XMLImage) fopimage).getDocument(); String ns = ((XMLImage) fopimage).getNameSpace(); renderDocument(doc, ns, pos); } else if ("image/eps".equals(mime)) { if (!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) { return; } FopPDFImage pdfimage = new FopPDFImage(fopimage, url); int xobj = pdfDoc.addImage(null, pdfimage).getXNumber(); fact.releaseImage(url, userAgent); } else if ("image/jpeg".equals(mime)) { if (!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) { return; } FopPDFImage pdfimage = new FopPDFImage(fopimage, url); int xobj = pdfDoc.addImage(null, pdfimage).getXNumber(); fact.releaseImage(url, userAgent); int w = (int) pos.getWidth() / 1000; int h = (int) pos.getHeight() / 1000; placeImage((int) pos.getX() / 1000, (int) pos.getY() / 1000, w, h, xobj); } else { if (!fopimage.load(FopImage.BITMAP, userAgent)) { return; } FopPDFImage pdfimage = new FopPDFImage(fopimage, url); int xobj = pdfDoc.addImage(null, pdfimage).getXNumber(); fact.releaseImage(url, userAgent); int w = (int) pos.getWidth() / 1000; int h = (int) pos.getHeight() / 1000; placeImage((int) pos.getX() / 1000, (int) pos.getY() / 1000, w, h, xobj); } // output new data try { this.pdfDoc.output(ostream); } catch (IOException ioe) { // ioexception will be caught later } } protected void placeImage(int x, int y, int w, int h, int xobj) { currentStream.add("q\n" + ((float) w) + " 0 0 " + ((float) -h) + " " + (((float) currentBlockIPPosition) / 1000f + x) + " " + (((float)(currentBPPosition + 1000 * h)) / 1000f + y) + " cm\n" + "/Im" + xobj + " Do\nQ\n"); } public void renderForeignObject(ForeignObject fo, Rectangle2D pos) { Document doc = fo.getDocument(); String ns = fo.getNameSpace(); renderDocument(doc, ns, pos); } public void renderDocument(Document doc, String ns, Rectangle2D pos) { RendererContext context; context = new RendererContext(MIME_TYPE); context.setUserAgent(userAgent); context.setProperty(PDFXMLHandler.PDF_DOCUMENT, pdfDoc); context.setProperty(PDFXMLHandler.OUTPUT_STREAM, ostream); context.setProperty(PDFXMLHandler.PDF_STATE, currentState); context.setProperty(PDFXMLHandler.PDF_PAGE, currentPage); context.setProperty(PDFXMLHandler.PDF_STREAM, currentStream); context.setProperty(PDFXMLHandler.PDF_XPOS, new Integer(currentBlockIPPosition + (int) pos.getX())); context.setProperty(PDFXMLHandler.PDF_YPOS, new Integer(currentBPPosition + (int) pos.getY())); context.setProperty(PDFXMLHandler.PDF_FONT_INFO, fontInfo); context.setProperty(PDFXMLHandler.PDF_FONT_NAME, currentFontName); context.setProperty(PDFXMLHandler.PDF_FONT_SIZE, new Integer(currentFontSize)); context.setProperty(PDFXMLHandler.PDF_WIDTH, new Integer((int) pos.getWidth())); context.setProperty(PDFXMLHandler.PDF_HEIGHT, new Integer((int) pos.getHeight())); userAgent.renderXML(context, doc, ns); } /** * Render an inline viewport. * This renders an inline viewport by clipping if necessary. * @param viewport the viewport to handle */ public void renderViewport(Viewport viewport) { closeText(); currentStream.add("ET\n"); if (viewport.getClip()) { currentStream.add("q\n"); float x = currentBlockIPPosition / 1000f; float y = (currentBPPosition + viewport.getOffset()) / 1000f; float width = viewport.getWidth() / 1000f; float height = viewport.getHeight() / 1000f; clip(x, y, width, height); } super.renderViewport(viewport); if (viewport.getClip()) { currentStream.add("Q\n"); } currentStream.add("BT\n"); } /** * Render leader area. * This renders a leader area which is an area with a rule. * @param area the leader area to render */ public void renderLeader(Leader area) { closeText(); currentStream.add("ET\n"); currentStream.add("q\n"); int style = area.getRuleStyle(); boolean alt = false; switch(style) { case RuleStyle.SOLID: currentStream.add("[] 0 d\n"); break; case RuleStyle.DOTTED: currentStream.add("[2] 0 d\n"); break; case RuleStyle.DASHED: currentStream.add("[6 4] 0 d\n"); break; case RuleStyle.DOUBLE: case RuleStyle.GROOVE: case RuleStyle.RIDGE: alt = true; break; } float startx = ((float) currentBlockIPPosition) / 1000f; float starty = ((currentBPPosition + area.getOffset()) / 1000f); float endx = (currentBlockIPPosition + area.getWidth()) / 1000f; if (!alt) { currentStream.add(area.getRuleThickness() / 1000f + " w\n"); drawLine(startx, starty, endx, starty); } else { if (style == RuleStyle.DOUBLE) { float third = area.getRuleThickness() / 3000f; currentStream.add(third + " w\n"); drawLine(startx, starty, endx, starty); drawLine(startx, (starty + 2 * third), endx, (starty + 2 * third)); } else { float half = area.getRuleThickness() / 2000f; currentStream.add("1 g\n"); currentStream.add(startx + " " + starty + " m\n"); currentStream.add(endx + " " + starty + " l\n"); currentStream.add(endx + " " + (starty + 2 * half) + " l\n"); currentStream.add(startx + " " + (starty + 2 * half) + " l\n"); currentStream.add("h\n"); currentStream.add("f\n"); if (style == RuleStyle.GROOVE) { currentStream.add("0 g\n"); currentStream.add(startx + " " + starty + " m\n"); currentStream.add(endx + " " + starty + " l\n"); currentStream.add(endx + " " + (starty + half) + " l\n"); currentStream.add((startx + half) + " " + (starty + half) + " l\n"); currentStream.add(startx + " " + (starty + 2 * half) + " l\n"); } else { currentStream.add("0 g\n"); currentStream.add(endx + " " + starty + " m\n"); currentStream.add(endx + " " + (starty + 2 * half) + " l\n"); currentStream.add(startx + " " + (starty + 2 * half) + " l\n"); currentStream.add(startx + " " + (starty + half) + " l\n"); currentStream.add((endx - half) + " " + (starty + half) + " l\n"); } currentStream.add("h\n"); currentStream.add("f\n"); } } currentStream.add("Q\n"); currentStream.add("BT\n"); super.renderLeader(area); } }
package org.apache.xerces.framework; import java.io.InputStream; import java.io.IOException; import java.io.Reader; import java.util.Locale; import org.apache.xerces.readers.DefaultEntityHandler; import org.apache.xerces.readers.XMLDeclRecognizer; import org.apache.xerces.readers.XMLEntityHandler; import org.apache.xerces.readers.XMLEntityReaderFactory; import org.apache.xerces.utils.ChunkyCharArray; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.XMLMessageProvider; import org.apache.xerces.utils.XMLMessages; import org.apache.xerces.utils.ImplementationMessages; import org.apache.xerces.validators.common.GrammarResolver; import org.apache.xerces.validators.common.GrammarResolverImpl; import org.apache.xerces.validators.common.XMLValidator; import org.apache.xerces.validators.datatype.DatatypeMessageProvider; import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl; import org.apache.xerces.validators.schema.SchemaMessageProvider; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; /** * This is the base class of all standard parsers. * * @version $Id$ */ public abstract class XMLParser implements XMLErrorReporter, XMLDocumentHandler.DTDHandler { // Constants // protected protected static final String SAX2_FEATURES_PREFIX = "http://xml.org/sax/features/"; protected static final String SAX2_PROPERTIES_PREFIX = "http://xml.org/sax/properties/"; protected static final String XERCES_FEATURES_PREFIX = "http://apache.org/xml/features/"; protected static final String XERCES_PROPERTIES_PREFIX = "http://apache.org/xml/properties/"; // private /** Features recognized by this parser. */ private static final String RECOGNIZED_FEATURES[] = { // SAX2 core "http://xml.org/sax/features/validation", "http://xml.org/sax/features/external-general-entities", "http://xml.org/sax/features/external-parameter-entities", "http://xml.org/sax/features/namespaces", // Xerces "http://apache.org/xml/features/validation/schema", "http://apache.org/xml/features/validation/dynamic", "http://apache.org/xml/features/validation/default-attribute-values", "http://apache.org/xml/features/validation/validate-content-models", "http://apache.org/xml/features/validation/validate-datatypes", "http://apache.org/xml/features/validation/warn-on-duplicate-attdef", "http://apache.org/xml/features/validation/warn-on-undeclared-elemdef", "http://apache.org/xml/features/allow-java-encodings", "http://apache.org/xml/features/continue-after-fatal-error", "http://apache.org/xml/features/nonvalidating/load-dtd-grammar", "http://apache.org/xml/features/nonvalidating/load-external-dtd" }; /** Properties recognized by this parser. */ private static final String RECOGNIZED_PROPERTIES[] = { // SAX2 core "http://xml.org/sax/properties/xml-string", // Xerces }; // debugging /** Set to true and recompile to print exception stack trace. */ private static final boolean PRINT_EXCEPTION_STACK_TRACE = false; // Data protected GrammarResolver fGrammarResolver = null; // state protected boolean fParseInProgress = false; private boolean fNeedReset = false; // features /** Continue after fatal error. */ private boolean fContinueAfterFatalError = false; // properties /** Error handler. */ private ErrorHandler fErrorHandler = null; // other private Locale fLocale = null; // error information private static XMLMessageProvider fgXMLMessages = new XMLMessages(); private static XMLMessageProvider fgImplementationMessages = new ImplementationMessages(); private static XMLMessageProvider fgSchemaMessages = new SchemaMessageProvider(); private static XMLMessageProvider fgDatatypeMessages= new DatatypeMessageProvider(); protected StringPool fStringPool = null; protected XMLErrorReporter fErrorReporter = null; protected DefaultEntityHandler fEntityHandler = null; protected XMLDocumentScanner fScanner = null; protected XMLValidator fValidator = null; // Constructors /** * Constructor */ protected XMLParser() { this(new StringPool()); } protected XMLParser(StringPool stringPool) { fStringPool = stringPool; fErrorReporter = this; fEntityHandler = new DefaultEntityHandler(fStringPool, fErrorReporter); fScanner = new XMLDocumentScanner(fStringPool, fErrorReporter, fEntityHandler, new ChunkyCharArray(fStringPool)); fValidator = new XMLValidator(fStringPool, fErrorReporter, fEntityHandler, fScanner); fGrammarResolver = new GrammarResolverImpl(); fScanner.setGrammarResolver(fGrammarResolver); fValidator.setGrammarResolver(fGrammarResolver); try { //JR-defect 48 fix - turn on Namespaces setNamespaces(true); } catch (Exception e) { // ignore } } /** * Set char data processing preference and handlers. */ protected void initHandlers(boolean sendCharDataAsCharArray, XMLDocumentHandler docHandler, XMLDocumentHandler.DTDHandler dtdHandler) { fValidator.initHandlers(sendCharDataAsCharArray, docHandler, dtdHandler); fScanner.setDTDHandler(this); } // Public methods // features and properties /** * Returns a list of features that this parser recognizes. * This method will never return null; if no features are * recognized, this method will return a zero length array. * * @see #isFeatureRecognized * @see #setFeature * @see #getFeature */ public String[] getFeaturesRecognized() { return RECOGNIZED_FEATURES; } /** * Returns true if the specified feature is recognized. * * @see #getFeaturesRecognized * @see #setFeature * @see #getFeature */ public boolean isFeatureRecognized(String featureId) { String[] recognizedFeatures = getFeaturesRecognized(); for (int i = 0; i < recognizedFeatures.length; i++) { if (featureId.equals(recognizedFeatures[i])) return true; } return false; } /** * Returns a list of properties that this parser recognizes. * This method will never return null; if no properties are * recognized, this method will return a zero length array. * * @see #isPropertyRecognized * @see #setProperty * @see #getProperty */ public String[] getPropertiesRecognized() { return RECOGNIZED_PROPERTIES; } /** * Returns true if the specified property is recognized. * * @see #getPropertiesRecognized * @see #setProperty * @see #getProperty */ public boolean isPropertyRecognized(String propertyId) { String[] recognizedProperties = getPropertiesRecognized(); for (int i = 0; i < recognizedProperties.length; i++) { if (propertyId.equals(recognizedProperties[i])) return true; } return false; } // initialization /** * Setup for application-driven parsing. * * @param source the input source to be parsed. * @see #parseSome */ public boolean parseSomeSetup(InputSource source) throws Exception { if (fNeedReset) resetOrCopy(); fParseInProgress = true; fNeedReset = true; return fEntityHandler.startReadingFromDocument(source); } /** * Application-driven parsing. * * @see #parseSomeSetup */ public boolean parseSome() throws Exception { if (!fScanner.parseSome(false)) { fParseInProgress = false; return false; } return true; } // resetting /** Reset parser instance so that it can be reused. */ public void reset() throws Exception { fGrammarResolver.clearGrammarResolver(); fStringPool.reset(); fEntityHandler.reset(fStringPool); fScanner.reset(fStringPool, new ChunkyCharArray(fStringPool)); fValidator.reset(fStringPool); fNeedReset = false; } // properties (the normal kind) /** * return the locator being used by the parser * * @return the parser's active locator */ public final Locator getLocator() { return fEntityHandler; } /** * return the locale * * @return the locale */ public final Locale getfLocale() { return fLocale; } /** * return the XML Messages object * * @return the parser's messages object */ public final XMLMessageProvider getfgXMLMessages() { return fgXMLMessages; } /** * return the Implementation Messages object * * @return the parser's implementation messages */ public final XMLMessageProvider getfgImplementationMessages() { return fgImplementationMessages; } /** * return the Schema Messages object * * @return the parser's schema messages */ public final XMLMessageProvider getfgSchemaMessages() { return fgSchemaMessages; } /** * return the Datatypes Messages object * * @return the parser's datatypes messages */ public final XMLMessageProvider getfgDatatypeMessages() { return fgDatatypeMessages; } /** * Set the reader factory. */ public void setReaderFactory(XMLEntityReaderFactory readerFactory) { fEntityHandler.setReaderFactory(readerFactory); } /** * Adds a recognizer. * * @param recognizer The XML recognizer to add. */ public void addRecognizer(XMLDeclRecognizer recognizer) { fEntityHandler.addRecognizer(recognizer); } // Protected methods // SAX2 core features protected void setValidation(boolean validate) throws SAXNotRecognizedException, SAXNotSupportedException { if (fParseInProgress) { throw new SAXNotSupportedException("PAR004 Cannot setFeature(http://xml.org/sax/features/validation): parse is in progress.\n"+ "http://xml.org/sax/features/validation"); } try { // REVISIT: [Q] Should the scanner tell the validator that // validation is on? -Ac fScanner.setValidationEnabled(validate); fValidator.setValidationEnabled(validate); } catch (Exception ex) { throw new SAXNotSupportedException(ex.getMessage()); } } /** * Returns true if validation is turned on. * * @see #setValidation */ protected boolean getValidation() throws SAXNotRecognizedException, SAXNotSupportedException { return fValidator.getValidationEnabled(); } protected void setExternalGeneralEntities(boolean expand) throws SAXNotRecognizedException, SAXNotSupportedException { if (fParseInProgress) { throw new SAXNotSupportedException("PAR004 Cannot setFeature(http://xml.org/sax/features/external-general-entities): parse is in progress.\n"+ "http://xml.org/sax/features/external-general-entities"); } if (!expand) { throw new SAXNotSupportedException("http://xml.org/sax/features/external-general-entities"); } } /** * <b>Note: This feature is always true.</b> * <p> * Returns true if external general entities are expanded. * * @see #setExternalGeneralEntities */ protected boolean getExternalGeneralEntities() throws SAXNotRecognizedException, SAXNotSupportedException { return true; } protected void setExternalParameterEntities(boolean expand) throws SAXNotRecognizedException, SAXNotSupportedException { if (fParseInProgress) { throw new SAXNotSupportedException("PAR004 Cannot setFeature(http://xml.org/sax/features/external-general-entities): parse is in progress.\n"+ "http://xml.org/sax/features/external-general-entities"); } if (!expand) { throw new SAXNotSupportedException("http://xml.org/sax/features/external-parameter-entities"); } } /** * <b>Note: This feature is always true.</b> * <p> * Returns true if external parameter entities are expanded. * * @see #setExternalParameterEntities */ protected boolean getExternalParameterEntities() throws SAXNotRecognizedException, SAXNotSupportedException { return true; } protected void setNamespaces(boolean process) throws SAXNotRecognizedException, SAXNotSupportedException { if (fParseInProgress) { throw new SAXNotSupportedException("PAR004 Cannot setFeature(http://xml.org/sax/features/namespaces): parse is in progress.\n"+ "http://xml.org/sax/features/namespaces"); } fScanner.setNamespacesEnabled(process); // REVISIT: [Q] Should the scanner tell the validator that namespace // processing is on? -Ac fValidator.setNamespacesEnabled(process); } /** * Returns true if the parser preprocesses namespaces. * * @see #setNamespaces */ protected boolean getNamespaces() throws SAXNotRecognizedException, SAXNotSupportedException { return fValidator.getNamespacesEnabled(); } // Xerces features protected void setValidationSchema(boolean schema) throws SAXNotRecognizedException, SAXNotSupportedException { if (fParseInProgress) { // REVISIT: Localize message throw new SAXNotSupportedException("http://apache.org/xml/features/validation/schema: parse is in progress"); } fValidator.setSchemaValidationEnabled(schema); } /** * Returns true if Schema support is turned on. * * @see #setValidationSchema */ protected boolean getValidationSchema() throws SAXNotRecognizedException, SAXNotSupportedException { return fValidator.getSchemaValidationEnabled(); } protected void setValidationDynamic(boolean dynamic) throws SAXNotRecognizedException, SAXNotSupportedException { if (fParseInProgress) { // REVISIT: Localize message throw new SAXNotSupportedException("http://apache.org/xml/features/validation/dynamic: parse is in progress"); } try { fValidator.setDynamicValidationEnabled(dynamic); } catch (Exception ex) { throw new SAXNotSupportedException(ex.getMessage()); } } /** * Returns true if validation is based on whether a document * contains a grammar. * * @see #setValidationDynamic */ protected boolean getValidationDynamic() throws SAXNotRecognizedException, SAXNotSupportedException { return fValidator.getDynamicValidationEnabled(); } protected void setNormalizeAttributeValues(boolean normalize) { fValidator.setNormalizeAttributeValues(normalize); } protected void setLoadDTDGrammar(boolean loadDTDGrammar) throws SAXNotRecognizedException, SAXNotSupportedException { if (fParseInProgress) { // REVISIT: Localize message throw new SAXNotSupportedException("http://apache.org/xml/features/nonvalidating/load-dtd-grammar: parse is in progress"); } try { fValidator.setLoadDTDGrammar(loadDTDGrammar); } catch (Exception ex) { throw new SAXNotSupportedException(ex.getMessage()); } } /** * Returns true if load DTD grammar is turned on in the XMLValiator. * * @see #setLoadDTDGrammar */ protected boolean getLoadDTDGrammar() throws SAXNotRecognizedException, SAXNotSupportedException { return fValidator.getLoadDTDGrammar(); } protected void setLoadExternalDTD(boolean loadExternalDTD) throws SAXNotRecognizedException, SAXNotSupportedException { if (fParseInProgress) { // REVISIT: Localize message throw new SAXNotSupportedException("http://apache.org/xml/features/nonvalidating/load-external-dtd: parse is in progress"); } try { fScanner.setLoadExternalDTD(loadExternalDTD); } catch (Exception ex) { throw new SAXNotSupportedException(ex.getMessage()); } } /** * Returns true if loading of the external DTD is on. * * @see #setLoadExternalDTD */ protected boolean getLoadExternalDTD() throws SAXNotRecognizedException, SAXNotSupportedException { return fScanner.getLoadExternalDTD(); } protected void setValidationWarnOnDuplicateAttdef(boolean warn) throws SAXNotRecognizedException, SAXNotSupportedException { fValidator.setWarningOnDuplicateAttDef(warn); } /** * Returns true if an error is emitted when an attribute is redefined * in the grammar. * * @see #setValidationWarnOnDuplicateAttdef */ protected boolean getValidationWarnOnDuplicateAttdef() throws SAXNotRecognizedException, SAXNotSupportedException { return fValidator.getWarningOnDuplicateAttDef(); } protected void setValidationWarnOnUndeclaredElemdef(boolean warn) throws SAXNotRecognizedException, SAXNotSupportedException { fValidator.setWarningOnUndeclaredElements(warn); } /** * Returns true if the parser emits an error when an undeclared * element is referenced in the grammar. * * @see #setValidationWarnOnUndeclaredElemdef */ protected boolean getValidationWarnOnUndeclaredElemdef() throws SAXNotRecognizedException, SAXNotSupportedException { return fValidator.getWarningOnUndeclaredElements(); } protected void setAllowJavaEncodings(boolean allow) throws SAXNotRecognizedException, SAXNotSupportedException { fEntityHandler.setAllowJavaEncodings(allow); } /** * Returns true if Java encoding names are allowed in the XML document. * * @see #setAllowJavaEncodings */ protected boolean getAllowJavaEncodings() throws SAXNotRecognizedException, SAXNotSupportedException { return fEntityHandler.getAllowJavaEncodings(); } protected void setContinueAfterFatalError(boolean continueAfterFatalError) throws SAXNotRecognizedException, SAXNotSupportedException { fContinueAfterFatalError = continueAfterFatalError; } /** * Returns true if the parser continues after a fatal error. * * @see #setContinueAfterFatalError */ protected boolean getContinueAfterFatalError() throws SAXNotRecognizedException, SAXNotSupportedException { return fContinueAfterFatalError; } // SAX2 core properties /** * Returns the namespace separator. * * @see #setNamespaceSep */ protected String getXMLString() throws SAXNotRecognizedException, SAXNotSupportedException { throw new SAXNotSupportedException("http://xml.org/sax/properties/xml-string"); } // resetting /** * Reset or copy parser * Allows parser instance reuse */ protected void resetOrCopy() throws Exception { fStringPool = new StringPool(); fEntityHandler.reset(fStringPool); fScanner.reset(fStringPool, new ChunkyCharArray(fStringPool)); fValidator.resetOrCopy(fStringPool); fNeedReset = false; fGrammarResolver = new GrammarResolverImpl(); fGrammarResolver.clearGrammarResolver(); fScanner.setGrammarResolver(fGrammarResolver); fValidator.setGrammarResolver(fGrammarResolver); } // Parser/XMLReader methods // NOTE: This class does *not* implement the org.xml.sax.Parser // interface but it does share some common methods. -Ac // handlers /** * Sets the resolver used to resolve external entities. The EntityResolver * interface supports resolution of public and system identifiers. * * @param resolver The new entity resolver. Passing a null value will * uninstall the currently installed resolver. */ public void setEntityResolver(EntityResolver resolver) { fEntityHandler.setEntityResolver(resolver); } /** * Return the current entity resolver. * * @return The current entity resolver, or null if none * has been registered. * @see #setEntityResolver */ public EntityResolver getEntityResolver() { return fEntityHandler.getEntityResolver(); } /** * Sets the error handler. * * @param handler The new error handler. */ public void setErrorHandler(ErrorHandler handler) { fErrorHandler = handler; } /** * Return the current error handler. * * @return The current error handler, or null if none * has been registered. * @see #setErrorHandler */ public ErrorHandler getErrorHandler() { return fErrorHandler; } // parsing /** * Parses the specified input source. * * @param source The input source. * * @exception org.xml.sax.SAXException Throws exception on SAX error. * @exception java.io.IOException Throws exception on i/o error. */ public void parse(InputSource source) throws SAXException, IOException { if (fParseInProgress) { throw new org.xml.sax.SAXException("FWK005 parse may not be called while parsing."); // REVISIT - need to add new error message } try { if (parseSomeSetup(source)) { fScanner.parseSome(true); } } catch (org.xml.sax.SAXException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (IOException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (Exception ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw new org.xml.sax.SAXException(ex); } finally { fParseInProgress = false; } } // parse(InputSource) /** * Parses the input source specified by the given system identifier. * <p> * This method is <em>almost</em> equivalent to the following: * <pre> * parse(new InputSource(systemId)); * </pre> * The only difference is that this method will attempt to close * the stream that was opened. * * @param source The input source. * * @exception org.xml.sax.SAXException Throws exception on SAX error. * @exception java.io.IOException Throws exception on i/o error. */ public void parse(String systemId) throws SAXException, IOException { InputSource source = new InputSource(systemId); try { parse(source); } finally { // NOTE: Changed code to attempt to close the stream // even after parsing failure. -Ac try { Reader reader = source.getCharacterStream(); if (reader != null) { reader.close(); } else { InputStream is = source.getByteStream(); if (is != null) { is.close(); } } } catch (IOException e) { // ignore } } } // parse(String) // locale /** * Set the locale to use for messages. * * @param locale The locale object to use for localization of messages. * * @exception SAXException An exception thrown if the parser does not * support the specified locale. * * @see org.xml.sax.Parser */ public void setLocale(Locale locale) throws SAXException { if (fParseInProgress) { throw new org.xml.sax.SAXException("FWK006 setLocale may not be called while parsing"); // REVISIT - need to add new error message } fLocale = locale; fgXMLMessages.setLocale(locale); fgImplementationMessages.setLocale(locale); } // setLocale(Locale) // XMLErrorReporter methods /** * Report an error. * * @param locator Location of error. * @param errorDomain The error domain. * @param majorCode The major code of the error. * @param minorCode The minor code of the error. * @param args Arguments for replacement text. * @param errorType The type of the error. * * @exception Exception Thrown on error. * * @see XMLErrorReporter#ERRORTYPE_WARNING * @see XMLErrorReporter#ERRORTYPE_FATAL_ERROR */ public void reportError(Locator locator, String errorDomain, int majorCode, int minorCode, Object args[], int errorType) throws Exception { // create the appropriate message SAXParseException spe; if (errorDomain.equals(XMLMessages.XML_DOMAIN)) { spe = new SAXParseException(fgXMLMessages.createMessage(fLocale, majorCode, minorCode, args), locator); } else if (errorDomain.equals(XMLMessages.XMLNS_DOMAIN)) { spe = new SAXParseException(fgXMLMessages.createMessage(fLocale, majorCode, minorCode, args), locator); } else if (errorDomain.equals(ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN)) { spe = new SAXParseException(fgImplementationMessages.createMessage(fLocale, majorCode, minorCode, args), locator); } else if (errorDomain.equals(SchemaMessageProvider.SCHEMA_DOMAIN)) { spe = new SAXParseException(fgSchemaMessages.createMessage(fLocale, majorCode, minorCode, args), locator); } else if (errorDomain.equals(DatatypeMessageProvider.DATATYPE_DOMAIN)) { spe = new SAXParseException(fgDatatypeMessages.createMessage(fLocale, majorCode, minorCode, args), locator); } else { throw new RuntimeException("FWK007 Unknown error domain \"" + errorDomain + "\"."+"\n"+errorDomain); } // default error handling if (fErrorHandler == null) { if (errorType == XMLErrorReporter.ERRORTYPE_FATAL_ERROR && !fContinueAfterFatalError) { throw spe; } return; } // make appropriate callback if (errorType == XMLErrorReporter.ERRORTYPE_WARNING) { fErrorHandler.warning(spe); } else if (errorType == XMLErrorReporter.ERRORTYPE_FATAL_ERROR) { fErrorHandler.fatalError(spe); if (!fContinueAfterFatalError) { Object[] fatalArgs = { spe.getMessage() }; throw new SAXException(fgImplementationMessages.createMessage(fLocale, ImplementationMessages.FATAL_ERROR, 0, fatalArgs)); } } else { fErrorHandler.error(spe); } } // reportError(Locator,String,int,int,Object[],int) // XMLReader methods /** * Set the state of a feature. * * Set the state of any feature in a SAX2 parser. The parser * might not recognize the feature, and if it does recognize * it, it might not be able to fulfill the request. * * @param featureId The unique identifier (URI) of the feature. * @param state The requested state of the feature (true or false). * * @exception org.xml.sax.SAXNotRecognizedException If the * requested feature is not known. * @exception org.xml.sax.SAXNotSupportedException If the * requested feature is known, but the requested * state is not supported. * @exception org.xml.sax.SAXException If there is any other * problem fulfilling the request. */ public void setFeature(String featureId, boolean state) throws SAXNotRecognizedException, SAXNotSupportedException { // SAX2 Features if (featureId.startsWith(SAX2_FEATURES_PREFIX)) { String feature = featureId.substring(SAX2_FEATURES_PREFIX.length()); // Validate (true) or don't validate (false). if (feature.equals("validation")) { setValidation(state); return; } // Expand external general entities (true) or don't expand (false). if (feature.equals("external-general-entities")) { setExternalGeneralEntities(state); return; } // Expand external parameter entities (true) or don't expand (false). if (feature.equals("external-parameter-entities")) { setExternalParameterEntities(state); return; } // Preprocess namespaces (true) or don't preprocess (false). See also if (feature.equals("namespaces")) { setNamespaces(state); return; } // Not recognized } // Xerces Features else if (featureId.startsWith(XERCES_FEATURES_PREFIX)) { String feature = featureId.substring(XERCES_FEATURES_PREFIX.length()); // Lets the user turn Schema validation support on/off. if (feature.equals("validation/schema")) { setValidationSchema(state); return; } // Allows the parser to validate a document only when it // contains a grammar. Validation is turned on/off based // on each document instance, automatically. if (feature.equals("validation/dynamic")) { setValidationDynamic(state); return; } if (feature.equals("validation/default-attribute-values")) { // REVISIT throw new SAXNotSupportedException(featureId); } if (feature.equals("validation/normalize-attribute-values")) { setNormalizeAttributeValues(state); } if (feature.equals("validation/validate-content-models")) { // REVISIT throw new SAXNotSupportedException(featureId); } if (feature.equals("nonvalidating/load-dtd-grammar")) { setLoadDTDGrammar(state); return; } if (feature.equals("nonvalidating/load-external-dtd")) { setLoadExternalDTD(state); return; } if (feature.equals("validation/validate-datatypes")) { // REVISIT throw new SAXNotSupportedException(featureId); } // Emits an error when an attribute is redefined. if (feature.equals("validation/warn-on-duplicate-attdef")) { setValidationWarnOnDuplicateAttdef(state); return; } // Emits an error when an element's content model // references an element, by name, that is not declared // in the grammar. if (feature.equals("validation/warn-on-undeclared-elemdef")) { setValidationWarnOnUndeclaredElemdef(state); return; } // Allows the use of Java encoding names in the XML // and TextDecl lines. if (feature.equals("allow-java-encodings")) { setAllowJavaEncodings(state); return; } // Allows the parser to continue after a fatal error. // Normally, a fatal error would stop the parse. if (feature.equals("continue-after-fatal-error")) { setContinueAfterFatalError(state); return; } // Not recognized } // Not recognized throw new SAXNotRecognizedException(featureId); } // setFeature(String,boolean) /** * Query the state of a feature. * * Query the current state of any feature in a SAX2 parser. The * parser might not recognize the feature. * * @param featureId The unique identifier (URI) of the feature * being set. * @return The current state of the feature. * @exception org.xml.sax.SAXNotRecognizedException If the * requested feature is not known. * @exception org.xml.sax.SAXException If there is any other * problem fulfilling the request. */ public boolean getFeature(String featureId) throws SAXNotRecognizedException, SAXNotSupportedException { // SAX2 Features if (featureId.startsWith(SAX2_FEATURES_PREFIX)) { String feature = featureId.substring(SAX2_FEATURES_PREFIX.length()); // Validate (true) or don't validate (false). if (feature.equals("validation")) { return getValidation(); } // Expand external general entities (true) or don't expand (false). if (feature.equals("external-general-entities")) { return getExternalGeneralEntities(); } // Expand external parameter entities (true) or don't expand (false). if (feature.equals("external-parameter-entities")) { return getExternalParameterEntities(); } // Preprocess namespaces (true) or don't preprocess (false). See also if (feature.equals("namespaces")) { return getNamespaces(); } // Not recognized } // Xerces Features else if (featureId.startsWith(XERCES_FEATURES_PREFIX)) { String feature = featureId.substring(XERCES_FEATURES_PREFIX.length()); // Lets the user turn Schema validation support on/off. if (feature.equals("validation/schema")) { return getValidationSchema(); } // Allows the parser to validate a document only when it // contains a grammar. Validation is turned on/off based // on each document instance, automatically. if (feature.equals("validation/dynamic")) { return getValidationDynamic(); } if (feature.equals("validation/default-attribute-values")) { // REVISIT throw new SAXNotRecognizedException(featureId); } if (feature.equals("validation/validate-content-models")) { // REVISIT throw new SAXNotRecognizedException(featureId); } if (feature.equals("nonvalidating/load-dtd-grammar")) { return getLoadDTDGrammar(); } if (feature.equals("nonvalidating/load-external-dtd")) { return getLoadExternalDTD(); } if (feature.equals("validation/validate-datatypes")) { // REVISIT throw new SAXNotRecognizedException(featureId); } // Emits an error when an attribute is redefined. if (feature.equals("validation/warn-on-duplicate-attdef")) { return getValidationWarnOnDuplicateAttdef(); } // Emits an error when an element's content model // references an element, by name, that is not declared // in the grammar. if (feature.equals("validation/warn-on-undeclared-elemdef")) { return getValidationWarnOnUndeclaredElemdef(); } // Allows the use of Java encoding names in the XML // and TextDecl lines. if (feature.equals("allow-java-encodings")) { return getAllowJavaEncodings(); } // Allows the parser to continue after a fatal error. // Normally, a fatal error would stop the parse. if (feature.equals("continue-after-fatal-error")) { return getContinueAfterFatalError(); } // Not recognized } // Not recognized throw new SAXNotRecognizedException(featureId); } // getFeature(String):boolean /** * Set the value of a property. * * Set the value of any property in a SAX2 parser. The parser * might not recognize the property, and if it does recognize * it, it might not support the requested value. * * @param propertyId The unique identifier (URI) of the property * being set. * @param Object The value to which the property is being set. * @exception org.xml.sax.SAXNotRecognizedException If the * requested property is not known. * @exception org.xml.sax.SAXNotSupportedException If the * requested property is known, but the requested * value is not supported. * @exception org.xml.sax.SAXException If there is any other * problem fulfilling the request. */ public void setProperty(String propertyId, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { // SAX2 Properties if (propertyId.startsWith(SAX2_PROPERTIES_PREFIX)) { String property = propertyId.substring(SAX2_PROPERTIES_PREFIX.length()); // Value type: String // Access: read/write, pre-parse only // Set the separator to be used between the URI part of a name and the // local part of a name when namespace processing is being performed // default, the separator is a single space. This property may not be // set while a parse is in progress (throws a SAXNotSupportedException). /* else if (propertyId.startsWith(XERCES_PROPERTIES_PREFIX)) { // // No properties defined yet that are common to all parsers. // } */ // Not recognized throw new SAXNotRecognizedException(propertyId); } // setProperty(String,Object) /** * Query the value of a property. * * Return the current value of a property in a SAX2 parser. * The parser might not recognize the property. * * @param propertyId The unique identifier (URI) of the property * being set. * @return The current value of the property. * @exception org.xml.sax.SAXNotRecognizedException If the * requested property is not known. * @exception org.xml.sax.SAXException If there is any other * problem fulfilling the request. * @see org.xml.sax.XMLReader#getProperty */ public Object getProperty(String propertyId) throws SAXNotRecognizedException, SAXNotSupportedException { // SAX2 Properties if (propertyId.startsWith(SAX2_PROPERTIES_PREFIX)) { String property = propertyId.substring(SAX2_PROPERTIES_PREFIX.length()); // Value type: String // Access: read/write, pre-parse only // Set the separator to be used between the URI part of a name and the // local part of a name when namespace processing is being performed // default, the separator is a single space. This property may not be // set while a parse is in progress (throws a SAXNotSupportedException). /* else if (propertyId.startsWith(XERCES_PROPERTIES_PREFIX)) { // // No properties defined yet that are common to all parsers. // } */ // Not recognized throw new SAXNotRecognizedException(propertyId); } // getProperty(String):Object }
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 { public void readSequence(StreamReader.Context context, SymbolParser symParser, SeqIOListener listener) throws IllegalSymbolException, IOException { final BufferedReader in = context.getReader(); String line; StreamParser sparser = null; listener.startSequence(); while ((line = in.readLine()) != null) { if (line.startsWith(" if (sparser != null) { // End of symbol data sparser.close(); sparser = null; } in.mark(2); if (in.read() == -1) context.streamEmpty(); else in.reset(); listener.endSequence(); return; } 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 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.bouncycastle.mail.smime; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.Security; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.Enumeration; import javax.mail.BodyPart; import javax.mail.MessagingException; import javax.mail.internet.ContentType; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMultipart; import org.bouncycastle.asn1.cms.IssuerAndSerialNumber; import org.bouncycastle.cms.CMSTypedStream; import org.bouncycastle.jce.PrincipalUtil; import org.bouncycastle.mail.smime.util.CRLFOutputStream; import org.bouncycastle.mail.smime.util.FileBackedMimeBodyPart; public class SMIMEUtil { private static final int BUF_SIZE = 32760; static boolean isCanonicalisationRequired( MimeBodyPart bodyPart, String defaultContentTransferEncoding) throws MessagingException { String[] cte = bodyPart.getHeader("Content-Transfer-Encoding"); String contentTransferEncoding; if (cte == null) { contentTransferEncoding = defaultContentTransferEncoding; } else { contentTransferEncoding = cte[0]; } return !contentTransferEncoding.equalsIgnoreCase("binary"); } public static Provider getProvider(String providerName) throws NoSuchProviderException { if (providerName != null) { Provider prov = Security.getProvider(providerName); if (prov != null) { return prov; } throw new NoSuchProviderException("provider " + providerName + " not found."); } return null; } static class LineOutputStream extends FilterOutputStream { private static byte newline[]; public LineOutputStream(OutputStream outputstream) { super(outputstream); } public void writeln(String s) throws MessagingException { try { byte abyte0[] = getBytes(s); super.out.write(abyte0); super.out.write(newline); } catch(Exception exception) { throw new MessagingException("IOException", exception); } } public void writeln() throws MessagingException { try { super.out.write(newline); } catch(Exception exception) { throw new MessagingException("IOException", exception); } } static { newline = new byte[2]; newline[0] = 13; newline[1] = 10; } private static byte[] getBytes(String s) { char ac[] = s.toCharArray(); int i = ac.length; byte abyte0[] = new byte[i]; int j = 0; while (j < i) { abyte0[j] = (byte)ac[j++]; } return abyte0; } } /** * internal preamble is generally included in signatures, while this is technically wrong, * if we find internal preamble we include it by default. */ static void outputPreamble(LineOutputStream lOut, MimeBodyPart part, String boundary) throws MessagingException, IOException { InputStream in; try { in = part.getRawInputStream(); } catch (MessagingException e) { return; // no underlying content rely on default generation } String line; while ((line = readLine(in)) != null) { if (line.equals(boundary)) { break; } lOut.writeln(line); } in.close(); if (line == null) { throw new MessagingException("no boundary found"); } } /** * internal postamble is generally included in signatures, while this is technically wrong, * if we find internal postamble we include it by default. */ static void outputPostamble(LineOutputStream lOut, MimeBodyPart part, int count, String boundary) throws MessagingException, IOException { InputStream in; try { in = part.getRawInputStream(); } catch (MessagingException e) { return; // no underlying content rely on default generation } String line; int boundaries = count + 1; while ((line = readLine(in)) != null) { if (line.startsWith(boundary)) { boundaries if (boundaries == 0) { break; } } } while ((line = readLine(in)) != null) { lOut.writeln(line); } in.close(); if (boundaries != 0) { throw new MessagingException("all boundaries not found for: " + boundary); } } static void outputPostamble(LineOutputStream lOut, BodyPart parent, String parentBoundary, BodyPart part) throws MessagingException, IOException { InputStream in; try { in = ((MimeBodyPart)parent).getRawInputStream(); } catch (MessagingException e) { return; // no underlying content rely on default generation } MimeMultipart multipart = (MimeMultipart)part.getContent(); ContentType contentType = new ContentType(multipart.getContentType()); String boundary = "--" + contentType.getParameter("boundary"); int count = multipart.getCount() + 1; String line; while (count != 0 && (line = readLine(in)) != null) { if (line.startsWith(boundary)) { count } } while ((line = readLine(in)) != null) { if (line.startsWith(parentBoundary)) { break; } lOut.writeln(line); } in.close(); } /* * read a line of input stripping of the tailing \r\n */ private static String readLine(InputStream in) throws IOException { StringBuffer b = new StringBuffer(); int ch; while ((ch = in.read()) >= 0 && ch != '\n') { if (ch != '\r') { b.append((char)ch); } } if (ch < 0 && b.length() == 0) { return null; } return b.toString(); } static void outputBodyPart( OutputStream out, BodyPart bodyPart, String defaultContentTransferEncoding) throws MessagingException, IOException { if (bodyPart instanceof MimeBodyPart) { MimeBodyPart mimePart = (MimeBodyPart)bodyPart; String[] cte = mimePart.getHeader("Content-Transfer-Encoding"); String contentTransferEncoding; if (mimePart.getContent() instanceof MimeMultipart) { MimeMultipart mp = (MimeMultipart)bodyPart.getContent(); ContentType contentType = new ContentType(mp.getContentType()); String boundary = "--" + contentType.getParameter("boundary"); SMIMEUtil.LineOutputStream lOut = new SMIMEUtil.LineOutputStream(out); Enumeration headers = mimePart.getAllHeaderLines(); while (headers.hasMoreElements()) { String header = (String)headers.nextElement(); lOut.writeln(header); } lOut.writeln(); // CRLF separator outputPreamble(lOut, mimePart, boundary); for (int i = 0; i < mp.getCount(); i++) { lOut.writeln(boundary); BodyPart part = mp.getBodyPart(i); outputBodyPart(out, part, defaultContentTransferEncoding); if (!(part.getContent() instanceof MimeMultipart)) { lOut.writeln(); // CRLF terminator needed } else { outputPostamble(lOut, mimePart, boundary, part); } } lOut.writeln(boundary + " outputPostamble(lOut, mimePart, mp.getCount(), boundary); return; } if (cte == null) { contentTransferEncoding = defaultContentTransferEncoding; } else { contentTransferEncoding = cte[0]; } if (!contentTransferEncoding.equalsIgnoreCase("base64") && !contentTransferEncoding.equalsIgnoreCase("quoted-printable")) { if (!contentTransferEncoding.equalsIgnoreCase("binary")) { out = new CRLFOutputStream(out); } bodyPart.writeTo(out); out.flush(); return; } boolean base64 = contentTransferEncoding.equalsIgnoreCase("base64"); // Write raw content, performing canonicalization InputStream inRaw; try { inRaw = mimePart.getRawInputStream(); } catch (MessagingException e) { // this is less than ideal, but if the raw output stream is unavailable it's the // best option we've got. out = new CRLFOutputStream(out); bodyPart.writeTo(out); out.flush(); return; } // Write headers LineOutputStream outLine = new LineOutputStream(out); for (Enumeration e = mimePart.getAllHeaderLines(); e.hasMoreElements();) { String header = (String)e.nextElement(); outLine.writeln(header); } outLine.writeln(); outLine.flush(); OutputStream outCRLF; if (base64) { outCRLF = new Base64CRLFOutputStream(out); } else { outCRLF = new CRLFOutputStream(out); } byte[] buf = new byte[BUF_SIZE]; int len; while ((len = inRaw.read(buf, 0, buf.length)) > 0) { outCRLF.write(buf, 0, len); } outCRLF.flush(); } else { if (!defaultContentTransferEncoding.equalsIgnoreCase("binary")) { out = new CRLFOutputStream(out); } bodyPart.writeTo(out); out.flush(); } } /** * return the MimeBodyPart described in the raw bytes provided in content */ public static MimeBodyPart toMimeBodyPart( byte[] content) throws SMIMEException { return toMimeBodyPart(new ByteArrayInputStream(content)); } /** * return the MimeBodyPart described in the input stream content */ public static MimeBodyPart toMimeBodyPart( InputStream content) throws SMIMEException { try { return new MimeBodyPart(content); } catch (MessagingException e) { throw new SMIMEException("exception creating body part.", e); } } static FileBackedMimeBodyPart toWriteOnceBodyPart( CMSTypedStream content) throws SMIMEException { try { return new WriteOnceFileBackedMimeBodyPart(content.getContentStream(), File.createTempFile("bcMail", ".mime")); } catch (IOException e) { throw new SMIMEException("IOException creating tmp file:" + e.getMessage(), e); } catch (MessagingException e) { throw new SMIMEException("can't create part: " + e, e); } } /** * return a file backed MimeBodyPart described in {@link CMSTypedStream} content. * </p> */ public static FileBackedMimeBodyPart toMimeBodyPart( CMSTypedStream content) throws SMIMEException { try { return toMimeBodyPart(content, File.createTempFile("bcMail", ".mime")); } catch (IOException e) { throw new SMIMEException("IOException creating tmp file:" + e.getMessage(), e); } } /** * Return a file based MimeBodyPart represented by content and backed * by the file represented by file. * * @param content content stream containing body part. * @param file file to store the decoded body part in. * @return the decoded body part. * @throws SMIMEException */ public static FileBackedMimeBodyPart toMimeBodyPart( CMSTypedStream content, File file) throws SMIMEException { try { return new FileBackedMimeBodyPart(content.getContentStream(), file); } catch (IOException e) { throw new SMIMEException("can't save content to file: " + e, e); } catch (MessagingException e) { throw new SMIMEException("can't create part: " + e, e); } } /** * Return a CMS IssuerAndSerialNumber structure for the passed in X.509 certificate. * * @param cert the X.509 certificate to get the issuer and serial number for. * @return an IssuerAndSerialNumber structure representing the certificate. */ public static IssuerAndSerialNumber createIssuerAndSerialNumberFor( X509Certificate cert) throws CertificateParsingException { try { return new IssuerAndSerialNumber(PrincipalUtil.getIssuerX509Principal(cert), cert.getSerialNumber()); } catch (Exception e) { throw new CertificateParsingException("exception extracting issuer and serial number: " + e); } } private static class WriteOnceFileBackedMimeBodyPart extends FileBackedMimeBodyPart { public WriteOnceFileBackedMimeBodyPart(InputStream content, File file) throws MessagingException, IOException { super(content, file); } public void writeTo(OutputStream out) throws MessagingException, IOException { super.writeTo(out); this.dispose(); } } static class Base64CRLFOutputStream extends FilterOutputStream { protected int lastb; protected static byte newline[]; private boolean isCrlfStream; public Base64CRLFOutputStream(OutputStream outputstream) { super(outputstream); lastb = -1; } public void write(int i) throws IOException { if (i == '\r') { out.write(newline); } else if (i == '\n') { if (lastb != '\r') { // imagine my joy... if (!(isCrlfStream && lastb == '\n')) { out.write(newline); } } else { isCrlfStream = true; } } else { out.write(i); } lastb = i; } public void write(byte[] buf) throws IOException { this.write(buf, 0, buf.length); } public void write(byte buf[], int off, int len) throws IOException { for (int i = off; i != off + len; i++) { this.write(buf[i]); } } public void writeln() throws IOException { super.out.write(newline); } static { newline = new byte[2]; newline[0] = '\r'; newline[1] = '\n'; } } }
package org.broad.igv.ui.action; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.annotations.ForTesting; import org.broad.igv.dev.api.NamedFeatureSearcher; import org.broad.igv.feature.*; import org.broad.igv.feature.genome.Genome; import org.broad.igv.feature.genome.GenomeManager; import org.broad.igv.lists.GeneList; import org.broad.igv.ui.IGV; import org.broad.igv.ui.event.ViewChange; import org.broad.igv.ui.panel.ReferenceFrame; import org.broad.igv.ui.util.MessageUtils; import htsjdk.tribble.Feature; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.*; import java.util.List; /** * A class for performing search actions. The class takes a view context and * search string as parameters. The search string can be either * (a) a feature (e.g. gene), or * (b) a locus string in the UCSC form, e.g. chr1:100,000-200,000 * <p/> * Note: Currently the only recognized features are genes * <p/> * Custom searchers can be registered, see {@link #registerNamedFeatureSearcher(org.broad.igv.dev.api.NamedFeatureSearcher)} * * @author jrobinso */ public class SearchCommand { private static Logger log = Logger.getLogger(SearchCommand.class); public static int SEARCH_LIMIT = 20; private boolean askUser = false; String searchString; ReferenceFrame referenceFrame; boolean recordHistory = true; Genome genome; private static Set<NamedFeatureSearcher> nameSearchers; private static HashMap<ResultType, String> tokenMatchers; static { resetNamedFeatureSearchers(); //Regexp for a number with commas in it (no periods) String num_withcommas = "(((\\d)+,?)+)"; //chromosome can include anything except whitespace String chromo_string = "(\\S)+"; String chromo = chromo_string; //This will match chr1:1-100, chr1:1, chr1 1, chr1 1 100 String chromo_range = chromo_string + "(:|(\\s)+)" + num_withcommas + "(-|(\\s)+)?" + num_withcommas + "?(\\s)*"; //Simple feature String feature = chromo_string; //Amino acid mutation notation. e.g. KRAS:G12C. * is stop codon String featureMutAA = chromo_string + ":[A-Z,a-z,*]" + num_withcommas + "[A-Z,a-z,*]"; //Nucleotide mutation notation. e.g. KRAS:123A>T String nts = "[A,C,G,T,a,c,g,t]"; String featureMutNT = chromo_string + ":" + num_withcommas + nts + "\\>" + nts; tokenMatchers = new HashMap<ResultType, String>(); tokenMatchers.put(ResultType.CHROMOSOME, chromo); tokenMatchers.put(ResultType.FEATURE, feature); tokenMatchers.put(ResultType.LOCUS, chromo_range); tokenMatchers.put(ResultType.FEATURE_MUT_AA, featureMutAA); tokenMatchers.put(ResultType.FEATURE_MUT_NT, featureMutNT); } public SearchCommand(ReferenceFrame referenceFrame, String searchString) { this(referenceFrame, searchString, GenomeManager.getInstance().getCurrentGenome()); } public SearchCommand(ReferenceFrame referenceFrame, String searchString, boolean recordHistory) { this(referenceFrame, searchString); this.recordHistory = recordHistory; } SearchCommand(ReferenceFrame referenceFrame, String searchString, Genome genome) { this.referenceFrame = referenceFrame; this.searchString = searchString.trim(); this.genome = genome; } public void execute() { if (log.isDebugEnabled()) { log.debug("Run search: " + searchString); } List<SearchResult> results = runSearch(searchString); if (askUser) { results = askUserFeature(results); if (results == null) { if (log.isDebugEnabled()) { log.debug("Multiple results, show cancelled: " + searchString); } return; } } showSearchResult(results); if (log.isDebugEnabled()) { log.debug("End search: " + searchString); } } /** * Given a string, search for the appropriate data to show the user. * Different syntaxes are accepted. * <p/> * In general, whitespace delimited tokens are treated separately and each are shown. * There is 1 exception to this. A locus of form chr1 1 10000 will be treated the same * as chr1:1-10000. Only one entry of this form can be entered, chr1 1 10000 chr2:1-1000 will * not be recognized. * * @param searchString Feature name (EGFR), chromosome (chr1), or locus string (chr1:1-100 or chr1:6) * Partial matches to a feature name (EG) will return multiple results, and * ask the user which they want. * @return result * List<SearchResult> describing the results of the search. Will never * be null, field type will equal ResultType.ERROR if something went wrong. */ public List<SearchResult> runSearch(String searchString) { List<SearchResult> results = new ArrayList<SearchResult>(); searchString = searchString.replace("\"", ""); Set<ResultType> wholeStringType = checkTokenType(searchString); if (wholeStringType.contains(ResultType.LOCUS)) { results.add(calcChromoLocus(searchString)); return results; } // Space delimited? String[] tokens = searchString.split("\\s+"); for (String s : tokens) { results.addAll(parseToken(s)); } if (results.size() == 0) { SearchResult result = new SearchResult(); result.setMessage("Invalid Search String: " + searchString); results.add(result); } return results; } public void showSearchResult(List<SearchResult> results) { int origZoom = referenceFrame.getZoom(); if (results == null || results.size() == 0) { results = new ArrayList<SearchResult>(); results.add(new SearchResult()); } boolean showMessage = false; boolean success = true; String message = "Invalid search string: " + searchString; if (results.size() == 1) { SearchResult result = results.get(0); if (result.type != ResultType.ERROR) {//FrameManager.isGeneListMode()) { IGV.getInstance().getSession().setCurrentGeneList(null); } switch (result.type) { case FEATURE: showFlankedRegion(result.chr, result.start, result.end); break; case LOCUS: referenceFrame.jumpTo(result.chr, result.start, result.end); break; case CHROMOSOME: referenceFrame.getEventBus().post(new ViewChange.ChromosomeChangeCause(this, result.chr)); referenceFrame.getEventBus().post(new ViewChange.ZoomCause(0)); break; case ERROR: default: { message = "Cannot find feature or locus: " + searchString; success = false; showMessage = true; } } } else { List<String> loci = new ArrayList<String>(results.size()); message = ""; for (SearchResult res : results) { if (res.type != ResultType.ERROR) { loci.add(res.getLocus()); } else { message = message + res.getMessage() + "\n"; showMessage = true; } } GeneList geneList = new GeneList("", loci, false); IGV.getInstance().getSession().setCurrentGeneList(geneList); } IGV.getInstance().resetFrames(); if (success && recordHistory) { IGV.getInstance().getSession().getHistory().push(searchString, origZoom); } if (showMessage) { MessageUtils.showMessage(message); } } /** * Get a list of strings of feature names suitable for display, containing only * those search results which were not an error * * @param results * @param longName Whether to use the long (true) or short (false) * of search results. * @return Array of strings of results found. */ public static Object[] getSelectionList(List<SearchResult> results, boolean longName) { ArrayList<String> options = new ArrayList<String>(Math.min(results.size(), SEARCH_LIMIT)); for (SearchResult result : results) { if (result.type == ResultType.ERROR) { continue; } if (longName) { options.add(result.getLongName()); } else options.add(result.getShortName()); } return options.toArray(); } /** * Display a dialog asking user which search result they want * to display. Number of results are limited to SEARCH_LIMIT. * The user can select multiple options, in which case all * are displayed. * * @param results * @return SearchResults which the user has selected. * Will be null if cancelled */ private List<SearchResult> askUserFeature(List<SearchResult> results) { Object[] list = getSelectionList(results, true); JList ls = new JList(list); ls.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //ls.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); final JOptionPane pane = new JOptionPane(ls, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); final Dialog dialog = pane.createDialog("Features"); dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); //On double click, show that option ls.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() >= 2) { dialog.setVisible(false); pane.setValue(JOptionPane.OK_OPTION); dialog.dispose(); } } }); dialog.setVisible(true); int resp = (Integer) pane.getValue(); List<SearchResult> val = null; if (resp == JOptionPane.OK_OPTION) { int[] selected = ls.getSelectedIndices(); val = new ArrayList<SearchResult>(selected.length); for (int ii = 0; ii < selected.length; ii++) { val.add(ii, results.get(selected[ii])); } } return val; } /** * Check token type using regex. * Intended to be inclusive, returns all possible matches * * @param token * @return */ Set<ResultType> checkTokenType(String token) { token = token.trim(); Set<ResultType> possibles = new HashSet<ResultType>(); for (ResultType type : tokenMatchers.keySet()) { if (token.matches(tokenMatchers.get(type))) { //note: entire string must match possibles.add(type); } } return possibles; } /** * Determine searchResult for white-space delimited search query. * * @param token * @return searchResult */ private List<SearchResult> parseToken(String token) { List<SearchResult> results = new ArrayList<SearchResult>(); List<NamedFeature> features; //Guess at token type via regex. //We don't assume success Set<ResultType> types = checkTokenType(token); SearchResult result; if (types.contains(ResultType.LOCUS) || types.contains(ResultType.CHROMOSOME)) { //Check if a full or partial locus string result = calcChromoLocus(token); if (result.type != ResultType.ERROR) { results.add(result); return results; } } //2 possible mutation notations, either amino acid (A123B) or nucleotide (123G>C) if (types.contains(ResultType.FEATURE_MUT_AA) || types.contains(ResultType.FEATURE_MUT_NT)) { //We know it has the right form, but may //not be valid feature name or mutation //which exists. String[] items = token.toUpperCase().split(":"); String name = items[0].trim().toUpperCase(); String coords = items[1]; int coordLength = coords.length(); Map<Integer, BasicFeature> genomePosList; //Should never match both mutation notations if (types.contains(ResultType.FEATURE_MUT_AA)) { String refSymbol = coords.substring(0, 1); String mutSymbol = coords.substring(coordLength - 1); String strLoc = coords.substring(1, coordLength - 1); int location = Integer.parseInt(strLoc) - 1; genomePosList = FeatureDB.getMutationAA(name, location + 1, refSymbol, mutSymbol, genome); } else if (types.contains(ResultType.FEATURE_MUT_NT)) { //Exclude the "A>T" at end String strLoc = coords.substring(0, coordLength - 3); String refSymbol = coords.substring(coordLength - 3, coordLength - 2); int location = Integer.parseInt(strLoc) - 1; genomePosList = FeatureDB.getMutationNT(name, location + 1, refSymbol, genome); } else { //This should never happen throw new IllegalArgumentException("Something went wrong parsing input token"); } askUser |= genomePosList.size() >= 2; for (int genomePos : genomePosList.keySet()) { Feature feat = genomePosList.get(genomePos); //Zoom in on mutation of interest //The +2 accounts for centering on the center of the amino acid, not beginning //and converting from 0-based to 1-based (which getStartEnd expects) int[] locs = getStartEnd("" + (genomePos + 2)); result = new SearchResult(ResultType.LOCUS, feat.getChr(), locs[0], locs[1]); results.add(result); } return results; } if (types.contains(ResultType.FEATURE)) { //Check if we have an exact name for the feature name NamedFeature feat = FeatureDB.getFeature(token.toUpperCase().trim()); if (feat != null) { results.add(new SearchResult(feat)); return results; } //Check inexact match //We will later want to ask the user which of these to keep features = comprehensiveFeatureSearch(token); if (features.size() > 0) { askUser |= features.size() >= 2; return getResults(features); } } result = new SearchResult(); result.setMessage("Invalid token: " + token); results.add(result); return results; } /** * Register a {@link org.broad.igv.dev.api.NamedFeatureSearcher} to be used when searching for features, * such as when the user enters text in the box. * This is idempotent, registering the same searcher multiple times is the same as * adding it once. * * @param searcher * @return Whether the searcher was added * @api */ public static boolean registerNamedFeatureSearcher(NamedFeatureSearcher searcher) { return nameSearchers.add(searcher); } /** * @param searcher * @return Whether the searcher was removed * @api */ public static boolean unregisterNamedFeatureSearcher(NamedFeatureSearcher searcher) { return nameSearchers.remove(searcher); } static void resetNamedFeatureSearchers() { nameSearchers = new LinkedHashSet<NamedFeatureSearcher>(); registerNamedFeatureSearcher(new InexactLoadedFeatureSearcher()); } /** * Search all known sources for features with the provided name. * This means our own database which gets updated when files are loaded, * as well as others (possibly plugins) * * @param searchString * @return */ private List<NamedFeature> comprehensiveFeatureSearch(String searchString) { List<NamedFeature> features = new ArrayList<NamedFeature>(); for (NamedFeatureSearcher searcher : nameSearchers) { Collection<? extends NamedFeature> tmp = searcher.search(searchString, SEARCH_LIMIT); if (tmp == null) { log.warn("Error searching with " + searcher); } else { features.addAll(tmp); } } return features; } /** * Parse a string of locus coordinates. * Can have whitespace delimiters, and be missing second coordinate, * but must have 1st coordinate. * * @param searchString * @return */ private SearchResult calcChromoLocus(String searchString) { /* chromosome can have whitespace or : delimiter chromosome also might have : in the name */ int[] startEnd = null; String[] tokens = searchString.split("\\s+"); String chr = tokens[0]; boolean whitespace_delim = tokens.length >= 2; if (whitespace_delim) { String posString = tokens[1]; if (tokens.length >= 3) { posString += "-" + tokens[2]; } startEnd = getStartEnd(posString); } else { //Not whitespace delimited //Could be chromoname:1-100, chromoname:1, chromoname int colonIdx = searchString.lastIndexOf(":"); if (colonIdx > 0) { chr = searchString.substring(0, colonIdx); String posString = searchString.substring(colonIdx).replace(":", ""); startEnd = getStartEnd(posString); //This MAY for case of chromoname having semicolon in it if (startEnd == null) { chr = searchString; } } } //startEnd will have coordinates if found. chr = genome.getChromosomeAlias(chr); Chromosome chromosome = genome.getChromosome(chr); //If we couldn't find chromosome, check //whole string if (chromosome == null) { chr = genome.getChromosomeAlias(tokens[0]); chromosome = genome.getChromosome(chr); if (chromosome != null) { //Found chromosome startEnd = null; } } if (chromosome != null && !searchString.equals(Globals.CHR_ALL)) { if (startEnd != null) { if(startEnd[1] >= startEnd[0]) { return new SearchResult(ResultType.LOCUS, chr, startEnd[0], startEnd[1]); } else { SearchResult error = new SearchResult(ResultType.ERROR, chr, startEnd[0], startEnd[1]); error.setMessage("End must be greater than start"); return error; } } return new SearchResult(ResultType.CHROMOSOME, chr, 0, chromosome.getLength() - 1); } return new SearchResult(ResultType.ERROR, chr, -1, -1); } private void showFlankedRegion(String chr, int start, int end) { int flankingRegion = PreferenceManager.getInstance().getAsInt(PreferenceManager.FLANKING_REGION); int delta; if((end - start) == 1) { delta = 20; // Don't show flanking region for single base jumps, use 40bp window } else if (flankingRegion < 0) { delta = (-flankingRegion * (end - start)) / 100; } else { delta = flankingRegion; } start = Math.max(0, start - delta); end = end + delta; if (PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SEARCH_ZOOM)) { referenceFrame.jumpTo(chr, start, end); } else { int center = (start + end) / 2; referenceFrame.centerOnLocation(chr, center); } } /** * Return the start and end positions as a 2 element array for the input * position string. UCSC conventions are followed for coordinates, * specifically the internal representation is "zero" based (first base is * numbered 0) and end-exclusive, but the display representation is "one" based (first base is * numbered 1) and end-inclusive. Consequently 1 is subtracted from the parsed positions */ private static int[] getStartEnd(String posString) { try { String[] posTokens = posString.split("-"); String startString = posTokens[0].replaceAll(",", ""); int start = Math.max(0, Integer.parseInt(startString)); // Default value for end int end = start + 1; if (posTokens.length > 1) { String endString = posTokens[1].replaceAll(",", ""); end = Integer.parseInt(endString); } if (posTokens.length == 1 || (end >= start && (end - start) < 10)) { int center = (start + end) / 2; int widen = 20; start = center - widen; start = Math.max(0, start); end = center + widen + 1; } return new int[]{Math.min(start, end)-1, Math.max(start, end)}; } catch (NumberFormatException numberFormatException) { return null; } } public enum ResultType { FEATURE, FEATURE_MUT_AA, FEATURE_MUT_NT, LOCUS, CHROMOSOME, ERROR } private static class InexactLoadedFeatureSearcher implements NamedFeatureSearcher { @Override public Collection<NamedFeature> search(String name, int limit) { return FeatureDB.getFeaturesList(name, limit); } } /* Container class for search results */ public static class SearchResult { String chr; private int start; private int end; ResultType type; private String locus; private String message; private NamedFeature feature; private String coords; public SearchResult() { this(ResultType.ERROR, null, -1, -1); } public SearchResult(ResultType type, String chr, int start, int end) { this.type = type; this.chr = chr; this.start = start; this.end = end; this.coords = Locus.getFormattedLocusString(chr, start + 1, end); this.locus = this.coords; } public SearchResult(NamedFeature feature) { this(ResultType.FEATURE, feature.getChr(), feature.getStart(), feature.getEnd()); this.feature = feature; this.locus = this.feature.getName(); } void setMessage(String message) { this.message = message; } public String getMessage() { return this.message; } /** * Always a coordinate string. * eg chr1:1-100 * * @return */ private String getCoordinates() { return this.coords; } /** * Either a feature name, or coordinates * * @return */ String getLocus() { return this.locus; } String getShortName() { if (this.type == ResultType.FEATURE) { return this.feature.getName(); } else { return this.getLocus(); } } /** * Format for display. If a feature, * Featurename (chromosome:start-end) * eg EGFR (chr7:55,054,218-55,242,525) * <p/> * Otherwise, just locus * * @return */ String getLongName() { if (this.type == ResultType.FEATURE) { return feature.getName() + " (" + this.getCoordinates() + ")"; } else { return this.getLocus(); } } public ResultType getType() { return type; } public String getChr() { return chr; } public int getStart() { return start; } public int getEnd() { return end; } //May be null @ForTesting public NamedFeature getFeature() { return feature; } } /** * Get a list of search results from the provided objects, * which must be NamedFeature objects. * * @param objects * @return */ public static List<SearchResult> getResults(List<NamedFeature> objects) { List<SearchResult> results = new ArrayList<SearchResult>(objects.size()); for (NamedFeature f : objects) { results.add(new SearchCommand.SearchResult(f)); } return results; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.ui.panel; import com.google.common.eventbus.AsyncEventBus; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.data.Interval; import org.broad.igv.feature.Chromosome; import org.broad.igv.feature.Locus; import org.broad.igv.feature.genome.Genome; import org.broad.igv.feature.genome.GenomeManager; import org.broad.igv.ui.IGV; import org.broad.igv.ui.event.DragStoppedEvent; import org.broad.igv.ui.event.ViewChange; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.util.LongRunningTask; /** * @author jrobinso */ public class ReferenceFrame { private static Logger log = Logger.getLogger(ReferenceFrame.class); /** * The nominal viewport width in pixels. */ public static int binsPerTile = 700; private String name; /** * The chromosome currently in view */ protected String chrName = "chrAll"; /** * The minimum zoom level for the current screen size + chromosome combination. */ private int minZoom = 0; /** * The maximum zoom level. Set to prevent integer overflow. This is a function * of chromosome length. */ public int maxZoom = 23; /** * Minimum allowed scale in base pairs / pixel * TODO Does this ever change, couldn't it be static and/or final? */ private double minScale = 1.0 / 14; /** * The current zoom level. Zoom level -1 corresponds to the whole * genome view (chromosome "all") */ protected int zoom = minZoom; /** * X location of the frame in pixels */ volatile int pixelX; /** * Width of the frame in pixels */ protected int widthInPixels; /** * The number of tiles for this zoom level, = 2^zoom */ protected double nTiles = 1; /** * The maximum virtual pixel value. */ //private double maxPixel; /** * The origin in bp */ protected volatile double origin = 0; /** * The location (x axis) locationScale in base pairs / virtual pixel */ protected volatile double locationScale; protected Locus initialLocus = null; /** * A temporary holder. We set the end location and then * later zoom/origin/etc. calculations are made */ //protected int setEnd = 0; public ReferenceFrame(String name) { this.name = name; Genome genome = getGenome(); this.chrName = genome == null ? "" : genome.getHomeChromosome(); } public ReferenceFrame(ReferenceFrame otherFrame) { this.chrName = otherFrame.chrName; this.initialLocus = otherFrame.initialLocus; this.locationScale = otherFrame.locationScale; this.minScale = otherFrame.minScale; this.minZoom = otherFrame.minZoom; this.name = otherFrame.name; this.nTiles = otherFrame.nTiles; this.origin = otherFrame.origin; this.pixelX = otherFrame.pixelX; //this.setEnd = otherFrame.setEnd; this.widthInPixels = otherFrame.widthInPixels; this.zoom = otherFrame.zoom; } private EventBus eventBus; public EventBus getEventBus() { if (eventBus == null) { eventBus = new AsyncEventBus(LongRunningTask.getThreadExecutor()); eventBus.register(this); } //if(eventBus == null) eventBus = new EventBus("IGV"); return eventBus; } /** * Set the position and width of the frame, in pixels * The origin/end positions are kept fixed iff valid * * @param pixelX * @param widthInPixels */ public synchronized void setBounds(int pixelX, int widthInPixels) { this.pixelX = pixelX; if (this.widthInPixels != widthInPixels) { //If we have what looks like a valid end position we keep it if (this.widthInPixels > 0 && this.initialLocus == null) { int start = (int) getOrigin(); int end = (int) getEnd(); if (start >= 0 && end >= 1) { this.initialLocus = new Locus(getChrName(), start, end); } } this.widthInPixels = widthInPixels; computeLocationScale(); computeZoom(); } } /** * Sets zoom level and recomputes scale, iff newZoom != oldZoom * min/maxZoom are recalculated and respected, * and the locationScale is recomputed * * @param newZoom */ protected void setZoom(int newZoom) { if (zoom != newZoom) { synchronized (this) { setZoomWithinLimits(newZoom); computeLocationScale(); } } } /** * Set the origin of the frame, guarding against chromosome boundaries * * @param position */ public void setOrigin(double position) { int windowLengthBP = (int) (widthInPixels * getScale()); double newOrigin; if (PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_SOFT_CLIPPED)) { newOrigin = Math.max(-1000, Math.min(position, getChromosomeLength() + 1000 - windowLengthBP)); } else { newOrigin = Math.max(0, Math.min(position, getChromosomeLength() - windowLengthBP)); } origin = newOrigin; } private synchronized void setZoomWithinLimits(int newZoom) { computeMinZoom(); computeMaxZoom(); zoom = Math.max(minZoom, Math.min(maxZoom, newZoom)); nTiles = Math.pow(2, zoom); } /** * Increment the zoom level by {@code zoomIncrement}, leaving * the center the same * * @param zoomIncrement */ public void doZoomIncrement(int zoomIncrement) { double currentCenter = getGenomeCenterPosition(); doIncrementZoom(zoomIncrement, currentCenter); } /** * Set the zoom level to {@code newZoom}, leaving * the center the same * * @param newZoom */ public void doSetZoom(int newZoom) { double currentCenter = getGenomeCenterPosition(); doSetZoomCenter(newZoom, currentCenter); } @Subscribe public void receiveZoomChange(ViewChange.ZoomCause e) { doSetZoom(e.newZoom); ViewChange.Result result = new ViewChange.Result(); result.setRecordHistory(false); getEventBus().post(result); } @Subscribe public void receiveDragStopped(DragStoppedEvent e) { this.snapToGrid(); getEventBus().post(new ViewChange.Result()); } public void doIncrementZoom(final int zoomIncrement, final double newCenter) { doSetZoomCenter(getZoom() + zoomIncrement, newCenter); } /** * Intended to be called by UI elements, this method * performs all actions necessary to set a new zoom * and center location * * @param newZoom * @param newCenter */ public void doSetZoomCenter(final int newZoom, final double newCenter) { if (chrName.equals(Globals.CHR_ALL)) { chrName = getGenome().getHomeChromosome(); } if (chrName.equals(Globals.CHR_ALL)) { // Translate the location to chromosome number synchronized (this) { jumpToChromosomeForGenomeLocation(newCenter); } //IGV.getInstance().chromosomeChangeEvent(chrName); } else { setZoom(newZoom); // Adjust origin so newCenter is centered centerOnLocation(newCenter); } } protected double getGenomeCenterPosition() { return origin + ((widthInPixels / 2) * getScale()); } /** * Return the current locationScale in base pairs / pixel * * @return */ public double getScale() { if (locationScale <= 0) { computeLocationScale(); } return locationScale; } /** * Calls {@link #setChromosomeName(String, boolean)} with force = false * It is preferred that you post an event to the EventBus instead, this is public * as an implementation side effect * * @param name */ public void setChromosomeName(String name) { setChromosomeName(name, false); } /** * Change the frame to the specified chromosome, clearing all * view parameters (zoom, locationScale) in the process * * @param name Name of the new chromosome * @param force Whether to force a change to the new chromosome, even if it's * the same name as the old one */ public synchronized void setChromosomeName(String name, boolean force) { if ((chrName == null) || !name.equals(chrName) || force) { chrName = name; origin = 0; this.locationScale = -1; this.zoom = -1; setZoom(0); //chromoObservable.setChangedAndNotify(); } } /** * Recalculate the locationScale, based on {@link #initialLocus}, {@link #origin}, and * {@link #widthInPixels} * DOES NOT alter zoom value */ private synchronized void computeLocationScale() { Genome genome = getGenome(); //Should consider getting rid of this. We don't have //a chromosome length without a genome, not always a problem if (genome != null) { // The end location, in base pairs. // If negative, we use the whole chromosome int setEnd = -1; if (this.initialLocus != null) setEnd = this.initialLocus.getEnd(); if (setEnd > 0 && widthInPixels > 0) { this.locationScale = ((setEnd - origin) / widthInPixels); this.initialLocus = null; } else { double virtualPixelSize = getTilesTimesBinsPerTile(); double nPixel = Math.max(virtualPixelSize, widthInPixels); this.locationScale = (((double) getChromosomeLength()) / nPixel); } } } /** * Recalculate the zoom value based on current start/end * locationScale is not altered */ private void computeZoom() { int newZoom = calculateZoom(getOrigin(), getEnd()); setZoomWithinLimits(newZoom); } /** * Compute the minimum zoom level for the data panel width. This is defined as the maximum * zoom level for which all data bins will fit in the window without loss of * data, i.e. the maximum zoom level for which nBins < nPixels. The number * of bins is defined as * nBins = 2^z * so minZoom is the value z such that nBins < dataPanelWidth */ protected void computeMinZoom() { if (this.chrName.equals(Globals.CHR_ALL)) { minZoom = 0; } else { minZoom = Math.max(0, (int) (Math.log((widthInPixels / binsPerTile)) / Globals.log2)); } } /** * Record the current state of the frame in history. * It is recommended that this NOT be called from within ReferenceFrame, * and callers use it after making all changes * <p/> * //TODO Should we save history by receiving events in History? */ public void recordHistory() { IGV.getInstance().getSession().getHistory().push(getFormattedLocusString(), zoom); } private void jumpToChromosomeForGenomeLocation(double locationMB) { double startMB = 0; for (String chr : getGenome().getLongChromosomeNames()) { double endMB = startMB + getGenome().getChromosome(chr).getLength() / 1000.0; if ((locationMB > startMB) && (locationMB <= endMB)) { this.setChromosomeName(chr); break; } startMB = endMB; } } public void shiftOriginPixels(int delta) { double shiftBP = delta * getScale(); setOrigin(origin + shiftBP); getEventBus().post(new ViewChange.Result()); // The event bus is not having the desired affect when in multi-locus view (no repaint). Adding explicit repaint // as a workaround. IGV.getInstance().repaintDataAndHeaderPanels(); } public void snapToGrid() { setOrigin(Math.round(origin)); getEventBus().post(new ViewChange.Result()); } public void centerOnLocation(String chr, double chrLocation) { if (!chrName.equals(chr)) { setChromosomeName(chr); } centerOnLocation(chrLocation); } public void centerOnLocation(double chrLocation) { double windowWidth = (widthInPixels * getScale()) / 2; setOrigin(Math.round(chrLocation - windowWidth)); getEventBus().post(new ViewChange.Result()); } public boolean windowAtEnd() { double windowLengthBP = widthInPixels * getScale(); return origin + windowLengthBP + 1 > getChromosomeLength(); } /** * Move the frame to the specified position. New zoom is calculated * based on limits. * * @param chr * @param start * @param end */ public void jumpTo(String chr, int start, int end) { Locus locus = new Locus(chr, start, end); this.jumpTo(locus); } public void jumpTo(Locus locus) { String chr = locus.getChr(); int start = locus.getStart(); int end = locus.getEnd(); Genome genome = getGenome(); if (chr != null) { if (genome.getChromosome(chr) == null && !chr.contains(Globals.CHR_ALL)) { MessageUtils.showMessage(chr + " is not a valid chromosome."); return; } } Chromosome chromosome = genome == null ? null : genome.getChromosome(chr); if (chromosome != null) { end = Math.min(chromosome.getLength(), end); } synchronized (this) { this.initialLocus = locus; this.chrName = chr; if (start >= 0 && end >= 0) { this.origin = start; computeLocationScale(); setZoomWithinLimits(calculateZoom(this.getOrigin(), this.getEnd())); } } if (log.isDebugEnabled()) { log.debug("Data panel width = " + widthInPixels); log.debug("New start = " + (int) origin); log.debug("New end = " + (int) getEnd()); log.debug("New center = " + (int) getCenter()); log.debug("Scale = " + locationScale); } getEventBus().post(new ViewChange.Result()); } /** * Compute the maximum zoom level, which is a function of chromosome length. */ private void computeMaxZoom() { Genome genome = getGenome(); // Compute max zoom. Assume window size @ max zoom of ~ 50 bp if (genome != null && chrName != null && genome.getChromosome(chrName) != null) { if (chrName.equals(Globals.CHR_ALL)) { maxZoom = 0; } else { int chrLength = genome.getChromosome(chrName).getLength(); maxZoom = (int) (Math.log(chrLength / 50.0) / Globals.log2) + 1; } } } /** * Calculate the zoom level given start/end in bp. * Doesn't change anything * * @param start * @param end * @return */ protected int calculateZoom(double start, double end) { return (int) (Math.log(getChromosomeLength() / (end - start)) / Globals.log2) + 1; } protected Genome getGenome() { return GenomeManager.getInstance().getCurrentGenome(); } public double getOrigin() { return origin; } public double getCenter() { return origin + getScale() * widthInPixels / 2; } public double getEnd() { return origin + getScale() * widthInPixels; } protected double getnTiles() { return nTiles; } public int getZoom() { return zoom; } /** * Return the maximum zoom level * * @return */ public int getMaxZoom() { return maxZoom; } public int getAdjustedZoom() { return zoom - minZoom; } public double getMaxPixel() { return getTilesTimesBinsPerTile(); } @Subscribe public void receiveChromosomeChange(ViewChange.ChromosomeChangeCause chromoChangeCause) { if (!chromoChangeCause.chrName.equals(chrName)) { setChromosomeName(chromoChangeCause.chrName, false); ViewChange.ChromosomeChangeResult resultEvent = new ViewChange.ChromosomeChangeResult(chromoChangeCause.source, chrName); resultEvent.setRecordHistory(chromoChangeCause.recordHistory()); getEventBus().post(resultEvent); } } public String getChrName() { return chrName; } // TODO -- this parameter shouldn't be stored here. Maybe in a specialized // layout manager? public int getWidthInPixels() { return widthInPixels; } /** * Return the chromosome position corresponding to the pixel index. The * pixel index is the pixel "position" translated by -origin. * * @param screenPosition * @return */ public double getChromosomePosition(int screenPosition) { return origin + getScale() * screenPosition; } /** * Return the screen position corresponding to the chromosomal position. * * @param chromosomePosition * @return */ public int getScreenPosition(double chromosomePosition) { return (int) ((chromosomePosition - origin) / getScale()); } public Chromosome getChromosome() { Genome genome = getGenome(); if (genome == null) { return null; } return genome.getChromosome(chrName); } public int getChromosomeLength() { Genome genome = getGenome(); if (genome == null) { return 1; } if (chrName.equals("All")) { // TODO -- remove the hardcoded unit divider ("1000") return (int) (genome.getNominalLength() / 1000); // return genome.getLength(); } else { if (getChromosome() == null) { log.error("Null chromosome: " + chrName); if (genome == null || genome.getChromosomes().size() == 0) { return 1; } else { return genome.getChromosomes().iterator().next().getLength(); } } return getChromosome().getLength(); } } public double getTilesTimesBinsPerTile() { return nTiles * (double) binsPerTile; } public int getMidpoint() { return pixelX + widthInPixels / 2; } /** * Get the UCSC style locus string corresponding to the current view. THe UCSC * conventions are followed for coordinates, specifically the internal representation * is "zero" based (first base is numbered 0) but the display representation is * "one" based (first base is numbered 1). Consequently 1 is added to the * computed positions. * * @return */ public String getFormattedLocusString() { if (zoom == 0) { return getChrName(); } else { Range range = getCurrentRange(); return Locus.getFormattedLocusString(range.getChr(), range.getStart(), range.getEnd()); } } public Range getCurrentRange() { int start = 0; int end = widthInPixels; int startLoc = (int) getChromosomePosition(start) + 1; int endLoc = (int) getChromosomePosition(end); Range range = new Range(getChrName(), startLoc, endLoc); return range; } public void reset() { jumpTo(FrameManager.getLocus(name)); } public String getName() { return name; } public Locus getInitialLocus() { return initialLocus; } public int getMinZoom() { return minZoom; } public boolean isExomeMode() { return false; } public void setName(String name) { this.name = name; } public boolean overlaps(Interval interval) { return this.getChrName().equals(interval.getChr()) && this.getOrigin() <= interval.getEnd() && this.getEnd() >= interval.getStart(); } public static class Range { private String chr; private int start; private int end; public Range(String chr, int start, int end) { this.chr = chr; this.start = start; this.end = end; } public String getChr() { return chr; } public int getStart() { return start; } public int getEnd() { return end; } public int getLength() { return end - start; } } }
package org.connectbot; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import org.connectbot.bean.PubkeyBean; import org.connectbot.util.EntropyDialog; import org.connectbot.util.EntropyView; import org.connectbot.util.OnEntropyGatheredListener; import org.connectbot.util.PubkeyDatabase; import org.connectbot.util.PubkeyUtils; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.SeekBar; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.SeekBar.OnSeekBarChangeListener; public class GeneratePubkeyActivity extends Activity implements OnEntropyGatheredListener { public final static String TAG = "ConnectBot.GeneratePubkeyActivity"; final static int DEFAULT_BITS = 1024; private LayoutInflater inflater = null; private EditText nickname; private RadioGroup keyTypeGroup; private SeekBar bitsSlider; private EditText bitsText; private CheckBox unlockAtStartup; private CheckBox confirmUse; private Button save; private Dialog entropyDialog; private ProgressDialog progress; private EditText password1, password2; private String keyType = PubkeyDatabase.KEY_TYPE_RSA; private int minBits = 768; private int bits = DEFAULT_BITS; private byte[] entropy; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.act_generatepubkey); nickname = (EditText) findViewById(R.id.nickname); keyTypeGroup = (RadioGroup) findViewById(R.id.key_type); bitsText = (EditText) findViewById(R.id.bits); bitsSlider = (SeekBar) findViewById(R.id.bits_slider); password1 = (EditText) findViewById(R.id.password1); password2 = (EditText) findViewById(R.id.password2); unlockAtStartup = (CheckBox) findViewById(R.id.unlock_at_startup); confirmUse = (CheckBox) findViewById(R.id.confirm_use); save = (Button) findViewById(R.id.save); inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); nickname.addTextChangedListener(textChecker); password1.addTextChangedListener(textChecker); password2.addTextChangedListener(textChecker); keyTypeGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == R.id.rsa) { minBits = 768; bitsSlider.setEnabled(true); bitsSlider.setProgress(DEFAULT_BITS - minBits); bitsText.setText(String.valueOf(DEFAULT_BITS)); bitsText.setEnabled(true); keyType = PubkeyDatabase.KEY_TYPE_RSA; } else if (checkedId == R.id.dsa) { // DSA keys can only be 1024 bits bitsSlider.setEnabled(false); bitsSlider.setProgress(DEFAULT_BITS - minBits); bitsText.setText(String.valueOf(DEFAULT_BITS)); bitsText.setEnabled(false); keyType = PubkeyDatabase.KEY_TYPE_DSA; } } }); bitsSlider.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { // Stay evenly divisible by 8 because it looks nicer to have // 2048 than 2043 bits. int leftover = progress % 8; int ourProgress = progress; if (leftover > 0) ourProgress += 8 - leftover; bits = minBits + ourProgress; bitsText.setText(String.valueOf(bits)); } public void onStartTrackingTouch(SeekBar seekBar) { // We don't care about the start. } public void onStopTrackingTouch(SeekBar seekBar) { // We don't care about the stop. } }); bitsText.setOnFocusChangeListener(new OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { try { bits = Integer.parseInt(bitsText.getText().toString()); if (bits < minBits) { bits = minBits; bitsText.setText(String.valueOf(bits)); } } catch (NumberFormatException nfe) { bits = DEFAULT_BITS; bitsText.setText(String.valueOf(bits)); } bitsSlider.setProgress(bits - minBits); } } }); save.setOnClickListener(new OnClickListener() { public void onClick(View view) { GeneratePubkeyActivity.this.save.setEnabled(false); GeneratePubkeyActivity.this.startEntropyGather(); } }); } private void checkEntries() { boolean allowSave = true; if (!password1.getText().toString().equals(password2.getText().toString())) allowSave = false; if (nickname.getText().length() == 0) allowSave = false; save.setEnabled(allowSave); } private void startEntropyGather() { final View entropyView = inflater.inflate(R.layout.dia_gatherentropy, null, false); ((EntropyView)entropyView.findViewById(R.id.entropy)).addOnEntropyGatheredListener(GeneratePubkeyActivity.this); entropyDialog = new EntropyDialog(GeneratePubkeyActivity.this, entropyView); entropyDialog.show(); } public void onEntropyGathered(byte[] entropy) { // For some reason the entropy dialog was aborted, exit activity if (entropy == null) { finish(); return; } this.entropy = entropy.clone(); int numSetBits = 0; for (int i = 0; i < 20; i++) numSetBits += measureNumberOfSetBits(this.entropy[i]); Log.d(TAG, "Entropy distribution=" + (int)(100.0 * numSetBits / 160.0) + "%"); Log.d(TAG, "entropy gathered; attemping to generate key..."); startKeyGen(); } private void startKeyGen() { progress = new ProgressDialog(GeneratePubkeyActivity.this); progress.setMessage(GeneratePubkeyActivity.this.getResources().getText(R.string.pubkey_generating)); progress.setIndeterminate(true); progress.setCancelable(false); progress.show(); Thread keyGenThread = new Thread(mKeyGen); keyGenThread.setName("KeyGen"); keyGenThread.start(); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { progress.dismiss(); GeneratePubkeyActivity.this.finish(); } }; final private Runnable mKeyGen = new Runnable() { public void run() { try { boolean encrypted = false; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(entropy); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(keyType); keyPairGen.initialize(bits, random); KeyPair pair = keyPairGen.generateKeyPair(); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); String secret = password1.getText().toString(); if (secret.length() > 0) encrypted = true; Log.d(TAG, "private: " + PubkeyUtils.formatKey(priv)); Log.d(TAG, "public: " + PubkeyUtils.formatKey(pub)); PubkeyBean pubkey = new PubkeyBean(); pubkey.setNickname(nickname.getText().toString()); pubkey.setType(keyType); pubkey.setPrivateKey(PubkeyUtils.getEncodedPrivate(priv, secret)); pubkey.setPublicKey(PubkeyUtils.getEncodedPublic(pub)); pubkey.setEncrypted(encrypted); pubkey.setStartup(unlockAtStartup.isChecked()); pubkey.setConfirmUse(confirmUse.isChecked()); PubkeyDatabase pubkeydb = new PubkeyDatabase(GeneratePubkeyActivity.this); pubkeydb.savePubkey(pubkey); pubkeydb.close(); } catch (Exception e) { Log.e(TAG, "Could not generate key pair"); e.printStackTrace(); } handler.sendEmptyMessage(0); } }; final private TextWatcher textChecker = new TextWatcher() { public void afterTextChanged(Editable s) {} public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void onTextChanged(CharSequence s, int start, int before, int count) { checkEntries(); } }; private int measureNumberOfSetBits(byte b) { int numSetBits = 0; for (int i = 0; i < 8; i++) { if ((b & 1) == 1) numSetBits++; b >>= 1; } return numSetBits; } }
// $Id: ConnectionTable1_4.java,v 1.9 2005/03/23 15:42:40 belaban Exp $ package org.jgroups.blocks; import org.jgroups.Address; import org.jgroups.Message; import org.jgroups.stack.IpAddress; import org.jgroups.util.Util; import org.jgroups.util.Util1_4; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; /** * Manages incoming and outgoing TCP connections. For each outgoing message to destination P, if there * is not yet a connection for P, one will be created. Subsequent outgoing messages will use this * connection. For incoming messages, one server socket is created at startup. For each new incoming * client connecting, a new thread from a thread pool is allocated and listens for incoming messages * until the socket is closed by the peer.<br>Sockets/threads with no activity will be killed * after some time.<br> Incoming messages from any of the sockets can be received by setting the * message listener. * * @author Bela Ban */ public class ConnectionTable1_4 extends ConnectionTable implements Runnable { private ServerSocketChannel srv_sock_ch=null; private Selector selector=null; private ArrayList pendingSocksList=null; /** * @param srv_port * @throws Exception */ public ConnectionTable1_4(int srv_port) throws Exception { super(srv_port); } /** * @param srv_port * @param reaper_interval * @param conn_expire_time * @throws Exception */ public ConnectionTable1_4(int srv_port, long reaper_interval, long conn_expire_time) throws Exception { super(srv_port, reaper_interval, conn_expire_time); } /** * @param r * @param bind_addr * @param external_addr * @param srv_port * @param max_port * @throws Exception */ public ConnectionTable1_4(Receiver r, InetAddress bind_addr, InetAddress external_addr, int srv_port, int max_port) throws Exception { super(r, bind_addr, external_addr, srv_port, max_port); } /** * @param r * @param bind_addr * @param external_addr * @param srv_port * @param max_port * @param reaper_interval * @param conn_expire_time * @throws Exception */ public ConnectionTable1_4(Receiver r, InetAddress bind_addr, InetAddress external_addr, int srv_port, int max_port, long reaper_interval, long conn_expire_time) throws Exception { super(r, bind_addr, external_addr, srv_port, max_port, reaper_interval, conn_expire_time); } /** * Try to obtain correct Connection (or create one if not yet existent) */ ConnectionTable.Connection getConnection(Address dest) throws Exception { Connection conn=null; SocketChannel sock_ch; synchronized(conns) { conn=(Connection)conns.get(dest); if(conn == null) { InetSocketAddress destAddress= new InetSocketAddress(((IpAddress)dest).getIpAddress(), ((IpAddress)dest).getPort()); sock_ch=SocketChannel.open(destAddress); conn=new Connection(sock_ch, dest); conn.sendLocalAddress(local_addr); // conns.put(dest, conn); addConnection(dest, conn); pendingSocksList.add(conn); selector.wakeup(); notifyConnectionOpened(dest); if(log.isInfoEnabled()) log.info("created socket to " + dest); } return conn; } } /** * Closes all open sockets, the server socket and all threads waiting for incoming messages */ public void stop() { if(srv_sock_ch != null) { try { ServerSocketChannel temp=srv_sock_ch; srv_sock_ch=null; temp.close(); } catch(Exception ex) { } } super.stop(); } /** * Acceptor thread. Continuously accept new connections. Create a new * thread for each new connection and put it in conns. When the thread * should stop, it is interrupted by the thread creator. */ public void run() { Socket client_sock; Connection conn=null; Address peer_addr; while(srv_sock_ch != null) { try { if(selector.select() > 0) { Set readyKeys=selector.selectedKeys(); for(Iterator i=readyKeys.iterator(); i.hasNext();) { SelectionKey key=(SelectionKey)i.next(); i.remove(); if((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) { ServerSocketChannel readyChannel= (ServerSocketChannel)key.channel(); SocketChannel client_sock_ch= readyChannel.accept(); client_sock=client_sock_ch.socket(); if(log.isInfoEnabled()) log.info("accepted connection, client_sock=" + client_sock); conn=new Connection(client_sock_ch, null); // will call receive(msg) // get peer's address peer_addr=conn.readPeerAddress(client_sock); conn.setPeerAddress(peer_addr); synchronized(conns) { if(conns.containsKey(peer_addr)) { if(log.isWarnEnabled()) log.warn(peer_addr + " is already there, will terminate connection"); conn.destroy(); return; } addConnection(peer_addr, conn); } conn.init(); notifyConnectionOpened(peer_addr); } else if( (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { conn=(Connection)key.attachment(); ByteBuffer buff=conn.getNIOMsgReader().readCompleteMsgBuffer(); if(buff != null) { receive((Message)Util.objectFromByteBuffer(buff.array())); conn.getNIOMsgReader().reset(); } } } } else { /*In addition to the accepted Sockets, we must registe * sockets opend by this for OP_READ, because peer may * use the same socket to sends data using the same socket, * instead of opening a new connection. We can not register * with this selectior from a different thread. set pending * and wakeup this selector. */ synchronized(conns) { Connection pendingConnection; while((pendingSocksList.size() > 0) && (null != (pendingConnection=(Connection)pendingSocksList.remove(0)))) { pendingConnection.init(); } } } } catch(SocketException sock_ex) { if(log.isInfoEnabled()) log.info("exception is " + sock_ex); if(conn != null) conn.destroy(); if(srv_sock == null) break; // socket was closed, therefore stop } catch(Throwable ex) { if(log.isWarnEnabled()) log.warn("exception is " + ex); } } } /** * Finds first available port starting at start_port and returns server socket. Sets srv_port */ protected ServerSocket createServerSocket(int start_port) throws Exception { this.selector=Selector.open(); srv_sock_ch=ServerSocketChannel.open(); srv_sock_ch.configureBlocking(false); while(true) { try { if(bind_addr == null) srv_sock_ch.socket().bind(new InetSocketAddress(start_port)); else srv_sock_ch.socket().bind(new InetSocketAddress(bind_addr, start_port), backlog); } catch(BindException bind_ex) { start_port++; continue; } catch(IOException io_ex) { if(log.isErrorEnabled()) log.error("exception is " + io_ex); } srv_port=start_port; break; } pendingSocksList=new ArrayList(); srv_sock_ch.register(this.selector, SelectionKey.OP_ACCEPT); return srv_sock_ch.socket(); } class Connection extends ConnectionTable.Connection { private SocketChannel sock_ch=null; private static final int HEADER_SIZE=4; private static final int DEFAULT_BUFF_SIZE=256; final ByteBuffer headerBuffer=ByteBuffer.allocate(HEADER_SIZE); NBMessageForm1_4 nioMsgReader=null; Connection(SocketChannel s, Address peer_addr) { super(s.socket(), peer_addr); sock_ch=s; } void init() { in=null; out=null; try { sock_ch.configureBlocking(false); nioMsgReader=new NBMessageForm1_4(DEFAULT_BUFF_SIZE, sock_ch); sock_ch.register(selector, SelectionKey.OP_READ, this); } catch(IOException e) { } if(log.isInfoEnabled()) log.info("connection was created to " + peer_addr); } void destroy() { closeSocket(); nioMsgReader=null; } void doSend(Message msg) throws Exception { IpAddress dst_addr=(IpAddress)msg.getDest(); byte[] buffie=null; if(dst_addr == null || dst_addr.getIpAddress() == null) { if(log.isErrorEnabled()) log.error("the destination address is null; aborting send"); return; } try { // set the source address if not yet set if(msg.getSrc() == null) msg.setSrc(local_addr); buffie=Util.objectToByteBuffer(msg); if(buffie.length <= 0) { if(log.isErrorEnabled()) log.error("buffer.length is 0. Will not send message"); return; } headerBuffer.clear(); headerBuffer.putInt(buffie.length); headerBuffer.flip(); Util1_4.writeFully(headerBuffer, sock_ch); ByteBuffer sendBuffer=ByteBuffer.wrap(buffie); Util1_4.writeFully(sendBuffer, sock_ch); } catch(Exception ex) { if(log.isErrorEnabled()) log.error("to " + dst_addr + ", exception is " + ex + ", stack trace:\n" + Util.printStackTrace(ex)); remove(dst_addr); throw ex; } } void closeSocket() { if(sock != null) { try { sock_ch.close(); } catch(Exception e) { } sock=null; } } NBMessageForm1_4 getNIOMsgReader() { return nioMsgReader; } } }
package org.objectweb.proactive.core; import org.apache.log4j.Logger; /** * <p> * UniqueID is a unique object identifier across all jvm. It is made of a unique VMID combined * with a unique UID on that VM. * </p><p> * The UniqueID is used to identify object globally, even in case of migration. * </p> * @author ProActive Team * @version 1.0, 2001/10/23 * @since ProActive 0.9 * */ public class UniqueID implements java.io.Serializable { private java.rmi.server.UID id; private java.rmi.dgc.VMID vmID; //the Unique ID of the JVM private static java.rmi.dgc.VMID uniqueVMID = new java.rmi.dgc.VMID(); protected static Logger logger = Logger.getLogger(UniqueID.class.getName()); /** * Creates a new UniqueID */ public UniqueID() { this.id = new java.rmi.server.UID(); this.vmID = uniqueVMID; } /** * Returns the VMID of the current VM in which this class has been loaded. * @return the VMID of the current VM */ public static java.rmi.dgc.VMID getCurrentVMID() { return uniqueVMID; } /** * Returns the VMID of this UniqueID. Note that the VMID of one UniqueID may differ * from the local VMID (that one can get using <code>getCurrentVMID()</code> in case * this UniqueID is attached to an object that has migrated. * @return the VMID part of this UniqueID */ public java.rmi.dgc.VMID getVMID() { return vmID; } /** * Returns the UID part of this UniqueID. * @return the UID part of this UniqueID */ public java.rmi.server.UID getUID() { return id; } /** * Returns a string representation of this UniqueID. * @return a string representation of this UniqueID */ public String toString() { if (logger.isDebugEnabled()) { return "<" + vmID.toString().substring(vmID.toString().length() - 9, vmID.toString().length() - 6) + ">"; } else { return "" + id + " " + vmID; } } /** * Overrides hashCode to take into account the two part of this UniqueID. * @return the hashcode of this object */ public int hashCode() { return id.hashCode() + vmID.hashCode(); } /** * Overrides equals to take into account the two part of this UniqueID. * @return the true if and only if o is an UniqueID equals to this UniqueID */ public boolean equals(Object o) { //System.out.println("Now checking for equality"); if (o instanceof UniqueID) { return ((id.equals(((UniqueID) o).id)) && (vmID.equals(((UniqueID) o).vmID))); } else { return false; } } /** * for debug purpose */ public void echo() { logger.info("UniqueID The Id is " + id + " and the address is " + vmID); } }
package org.opencms.ui.apps.user; import org.opencms.db.CmsUserSettings; import org.opencms.file.CmsObject; import org.opencms.file.CmsUser; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.CmsSessionInfo; import org.opencms.main.OpenCms; import org.opencms.security.CmsRole; import org.opencms.security.CmsRoleViolationException; import org.opencms.ui.A_CmsUI; import org.opencms.ui.CmsCssIcon; import org.opencms.ui.CmsVaadinUtils; import org.opencms.ui.apps.Messages; import org.opencms.ui.apps.sessions.CmsKillSessionDialog; import org.opencms.ui.apps.sessions.CmsUserInfoDialog; import org.opencms.ui.components.CmsBasicDialog; import org.opencms.ui.components.CmsBasicDialog.DialogWidth; import org.opencms.ui.components.CmsConfirmationDialog; import org.opencms.ui.components.OpenCmsTheme; import org.opencms.ui.contextmenu.CmsContextMenu; import org.opencms.ui.contextmenu.CmsMenuItemVisibilityMode; import org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry; import org.opencms.util.CmsDateUtil; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import com.vaadin.server.Resource; import com.vaadin.shared.MouseEventDetails.MouseButton; import com.vaadin.ui.Component; import com.vaadin.ui.Window; import com.vaadin.ui.themes.ValoTheme; import com.vaadin.v7.data.Item; import com.vaadin.v7.data.util.IndexedContainer; import com.vaadin.v7.data.util.filter.Or; import com.vaadin.v7.data.util.filter.SimpleStringFilter; import com.vaadin.v7.event.ItemClickEvent; import com.vaadin.v7.event.ItemClickEvent.ItemClickListener; import com.vaadin.v7.ui.Table; import com.vaadin.v7.ui.VerticalLayout; /** * Table for user.<p> * */ public class CmsUserTable extends Table implements I_CmsFilterableTable, I_CmsToggleTable { /**Table properties. */ public enum TableProperty { /**Last login. */ Created(Messages.GUI_USERMANAGEMENT_USER_DATE_CREATED_0, Long.class, new Long(0L)), /**Is the user disabled? */ DISABLED("", Boolean.class, new Boolean(false)), /**From Other ou?. */ FROMOTHEROU("", Boolean.class, new Boolean(false)), /**Description. */ FullName(Messages.GUI_USERMANAGEMENT_USER_NAME_0, String.class, ""), /**Icon. */ Icon(null, Resource.class, new CmsCssIcon("oc-icon-24-user")), /**IsIndirect?. */ INDIRECT("", Boolean.class, new Boolean(false)), /**Last login. */ LastLogin(Messages.GUI_USERMANAGEMENT_USER_LAST_LOGIN_0, Long.class, new Long(0L)), /**Name. */ Name(Messages.GUI_USERMANAGEMENT_USER_USER_0, String.class, ""), /**Is the user new? */ NEWUSER("", Boolean.class, new Boolean(false)), OU(Messages.GUI_USERMANAGEMENT_USER_OU_0, String.class, ""), /**Status. */ STATUS("", Integer.class, new Integer(0)), /**Full system Name. */ SystemName("", String.class, ""); /**Default value for column.*/ private Object m_defaultValue; /**Header Message key.*/ private String m_headerMessage; /**Type of column property.*/ private Class<?> m_type; /** * constructor.<p> * * @param name Name * @param type type * @param defaultValue value */ TableProperty(String name, Class<?> type, Object defaultValue) { m_headerMessage = name; m_type = type; m_defaultValue = defaultValue; } /** * The default value.<p> * * @return the default value object */ Object getDefault() { return m_defaultValue; } /** * Gets the name of the property.<p> * * @return a name */ String getName() { if (!CmsStringUtil.isEmptyOrWhitespaceOnly(m_headerMessage)) { return CmsVaadinUtils.getMessageText(m_headerMessage); } return ""; } /** * Gets the type of property.<p> * * @return the type */ Class<?> getType() { return m_type; } } /** *Entry to addition info dialog.<p> */ class EntryAddInfos implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(Set<String> context) { Window window = CmsBasicDialog.prepareWindow(DialogWidth.max); CmsAdditionalInfosDialog dialog = new CmsAdditionalInfosDialog( m_cms, new CmsUUID(context.iterator().next()), window, m_app); window.setContent(dialog); A_CmsUI.get().addWindow(window); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_ADDITIONAL_INFOS_MENU_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> context) { if (context.size() > 1) { return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE; } return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } } /** * Menu entry to delete user.<p> */ class EntryDelete implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(final Set<String> context) { Window window = CmsBasicDialog.prepareWindow(); CmsBasicDialog dialog = null; dialog = new CmsDeleteMultiplePrincipalDialog(m_cms, context, window, m_app); window.setContent(dialog); window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DELETE_0)); A_CmsUI.get().addWindow(window); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DELETE_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> context) { return onlyVisibleForOU(context); } } /** * Menu entry to edit user.<p> */ class EntryEdit implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(Set<String> context) { Window window = CmsBasicDialog.prepareWindow(DialogWidth.wide); window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_EDIT_USER_0)); window.setContent(new CmsUserEditDialog(m_cms, new CmsUUID(context.iterator().next()), window, m_app)); A_CmsUI.get().addWindow(window); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_EDIT_USER_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> context) { CmsUUID id = new CmsUUID(context.iterator().next()); return CmsMenuItemVisibilityMode.activeInactive( m_app.canEditUser(id) && onlyVisibleForOU(id) && (context.size() <= 1)); } } /** * Menu entry to edit groups.<p> */ class EntryEditGroup implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(Set<String> context) { Window window = CmsBasicDialog.prepareWindow(DialogWidth.max); window.setContent( new CmsUserEditGroupsDialog(m_cms, new CmsUUID(context.iterator().next()), window, m_app)); A_CmsUI.get().addWindow(window); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_EDIT_USERGROUP_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> context) { return CmsMenuItemVisibilityMode.activeInactive( onlyVisibleForOU(new CmsUUID(context.iterator().next())) && (context.size() <= 1)); } } /** * Menu entry for editing roles of user.<p> */ class EntryEditRole implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(Set<String> context) { Window window = CmsBasicDialog.prepareWindow(DialogWidth.max); window.setContent(new CmsUserEditRoleDialog(m_cms, new CmsUUID(context.iterator().next()), window, m_app)); A_CmsUI.get().addWindow(window); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_EDIT_USERROLES_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> context) { return CmsMenuItemVisibilityMode.activeInactive( onlyVisibleForOU(new CmsUUID(context.iterator().next())) && (context.size() <= 1)); } } /** *Entry to enable after password was entered wrong.<p> */ class EntryEnable implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(Set<String> context) { final Window window = CmsBasicDialog.prepareWindow(); try { final CmsUser user = m_cms.readUser(new CmsUUID(context.iterator().next())); CmsConfirmationDialog dialog = new CmsConfirmationDialog( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_UNLOCK_USER_LABEL_0), new Runnable() { public void run() { OpenCms.getLoginManager().resetUserTempDisable(user.getName()); window.close(); m_app.reload(); } }, new Runnable() { public void run() { window.close(); } }); window.setCaption( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_UNLOCK_USER_CAPTION_1, user.getName())); window.setContent(dialog); A_CmsUI.get().addWindow(window); } catch (CmsException e) { LOG.error("Unable to read user", e); } } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_UNLOCK_USER_CONTEXT_MENU_TITLE_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> context) { try { CmsUser user = m_cms.readUser(new CmsUUID(context.iterator().next())); if (OpenCms.getLoginManager().isUserTempDisabled(user.getName())) { return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } else { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } } catch (CmsException e) { LOG.error("Can not read user.", e); } return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } } /** *Entry to info dialog.<p> */ class EntryInfo implements I_CmsSimpleContextMenuEntry<Set<String>>, I_CmsSimpleContextMenuEntry.I_HasCssStyles { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(Set<String> context) { try { openInfoDialog(new CmsUUID(context.iterator().next())); } catch (CmsException e) { LOG.error("Error on opening user info dialog", e); } } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry.I_HasCssStyles#getStyles() */ public String getStyles() { return ValoTheme.LABEL_BOLD; } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_SHOW_USER_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> context) { if (context.size() > 1) { return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE; } return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } } /** *Entry to kill Session.<p> */ class EntryKillSession implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(Set<String> context) { final Window window = CmsBasicDialog.prepareWindow(); window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_DESTROY_SESSION_0)); Set<String> sessionIds = new HashSet<String>(); for (CmsSessionInfo info : OpenCms.getSessionManager().getSessionInfos( new CmsUUID(context.iterator().next()))) { sessionIds.add(info.getSessionId().getStringValue()); } CmsKillSessionDialog dialog = new CmsKillSessionDialog(sessionIds, new Runnable() { public void run() { window.close(); } }); window.setContent(dialog); A_CmsUI.get().addWindow(window); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_DESTROY_SESSION_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> context) { if (context.size() > 1) { return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE; } if (!OpenCms.getSessionManager().getSessionInfos(new CmsUUID(context.iterator().next())).isEmpty()) { return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE; } } /** * Menu entry to move user to another ou.<p> */ class EntryMoveOU implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(final Set<String> context) { Window window = CmsBasicDialog.prepareWindow(DialogWidth.wide); CmsBasicDialog dialog = null; dialog = new CmsMoveUserToOU(m_cms, new CmsUUID(context.iterator().next()), window, m_app); window.setContent(dialog); window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_MOVE_OU_0)); A_CmsUI.get().addWindow(window); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_MOVE_OU_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> context) { try { if (OpenCms.getOrgUnitManager().readOrganizationalUnit(m_cms, m_ou).hasFlagWebuser()) { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } } catch (CmsException e) { LOG.error("Unable to read OU", e); } return onlyVisibleForOU(context); } } /** * Menu entry to remove user from group.<p> */ class EntryRemoveFromGroup implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(final Set<String> context) { try { final Window window = CmsBasicDialog.prepareWindow(DialogWidth.wide); final String user = m_cms.readUser(new CmsUUID(context.iterator().next())).getName(); String confirmText = ""; String caption = ""; Runnable okRunnable = null; if (m_type.isGroup()) { caption = CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_REMOVE_USER_FROM_GROUP_0); confirmText = CmsVaadinUtils.getMessageText( Messages.GUI_USERMANAGEMENT_REMOVE_USER_FROM_GROUP_CONFIRM_2, user, m_group); okRunnable = new Runnable() { public void run() { try { m_cms.removeUserFromGroup(user, m_group); } catch (CmsException e) { } window.close(); m_app.reload(); } }; } if (m_type.equals(CmsOuTreeType.ROLE)) { caption = CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_REMOVE_USER_FROM_ROLE_0); confirmText = CmsVaadinUtils.getMessageText( Messages.GUI_USERMANAGEMENT_REMOVE_USER_FROM_ROLE_CONFIRM_2, user, m_group); okRunnable = new Runnable() { public void run() { try { OpenCms.getRoleManager().removeUserFromRole( m_cms, CmsRole.valueOfRoleName(m_group), user); } catch (CmsException e) { } window.close(); m_app.reload(); } }; } window.setCaption(caption); window.setContent(new CmsConfirmationDialog(confirmText, okRunnable, new Runnable() { public void run() { window.close(); } })); A_CmsUI.get().addWindow(window); } catch (CmsException e) { } } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { if (m_type.isGroup()) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_REMOVE_USER_FROM_GROUP_0); } return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_REMOVE_USER_FROM_ROLE_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> context) { if (!m_app.canRemoveGroupMemebers(m_group)) { return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE; } if (context.size() > 1) { return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE; } if (m_group == null) { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } try { CmsUser user = m_cms.readUser(context.iterator().next()); return ((Boolean)(getItem(user).getItemProperty(TableProperty.INDIRECT).getValue())).booleanValue() ? CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE : CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } catch (CmsException e) { } return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } } /** * Menu entry for show resources of user.<p> */ class EntryShowResources implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(Set<String> context) { Window window = CmsBasicDialog.prepareWindow(DialogWidth.wide); window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_SHOW_RESOURCES_0)); window.setContent(new CmsShowResourcesDialog(context.iterator().next(), window)); A_CmsUI.get().addWindow(window); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_SHOW_RESOURCES_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> context) { if (context.size() > 1) { return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE; } return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } } /** *Entry to switch user.<p> */ class EntrySwitchUser implements I_CmsSimpleContextMenuEntry<Set<String>> { /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#executeAction(java.lang.Object) */ public void executeAction(Set<String> context) { final Window window = CmsBasicDialog.prepareWindow(); final CmsUUID userID = new CmsUUID(context.iterator().next()); window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_SWITCH_USER_0)); CmsConfirmationDialog dialog = new CmsConfirmationDialog( CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_SWITCH_USER_CONFIRM_0), new Runnable() { public void run() { try { String path = OpenCms.getSessionManager().switchUser( A_CmsUI.getCmsObject(), CmsVaadinUtils.getRequest(), m_cms.readUser(userID)); if (path == null) { path = CmsVaadinUtils.getWorkplaceLink() + "?_lrid=" + (new Date()).getTime(); } A_CmsUI.get().getPage().setLocation(path); if (path.contains("workplace A_CmsUI.get().getPage().reload(); } window.close(); } catch (CmsException e) { LOG.error("Unable to swith user", e); } } }, new Runnable() { public void run() { window.close(); } }); window.setContent(dialog); A_CmsUI.get().addWindow(window); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { return CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_SWITCH_USER_0); } /** * @see org.opencms.ui.contextmenu.I_CmsSimpleContextMenuEntry#getVisibility(java.lang.Object) */ public CmsMenuItemVisibilityMode getVisibility(Set<String> context) { try { OpenCms.getRoleManager().checkRole(m_cms, CmsRole.ADMINISTRATOR); return CmsMenuItemVisibilityMode.activeInactive( onlyVisibleForOU(new CmsUUID(context.iterator().next())) && (context.size() <= 1)); } catch (CmsRoleViolationException e) { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } } } /**Map for password status of user. */ protected static final Map<CmsUUID, Boolean> USER_PASSWORD_STATUS = new HashMap<CmsUUID, Boolean>(); /** Log instance for this class. */ static final Log LOG = CmsLog.getLog(CmsUserTable.class); /**vaadin serial id.*/ private static final long serialVersionUID = 7863356514060544048L; /**Name of group to show user for, or null. */ protected String m_group; /**Type to be shown. */ protected I_CmsOuTreeType m_type; /**The app.*/ CmsAccountsApp m_app; /**CmsObject.*/ CmsObject m_cms; /**List of indirect user. */ List<CmsUser> m_indirects; /** The context menu. */ CmsContextMenu m_menu; String m_ou; /**Black list of user from higher OU than current user.*/ private HashSet<CmsUser> m_blackList = new HashSet<CmsUser>(); /**Set of user with Flag to reset password. */ private Set<CmsUUID> m_checkedUserPasswordReset; /**Indexed container. */ private IndexedContainer m_container; /**vaadin component.*/ private VerticalLayout m_emptyLayout; /**flag indicates if all indirect items (for roles or sub OUs) are loaded. */ private boolean m_fullyLoaded; /** The available menu entries. */ private List<I_CmsSimpleContextMenuEntry<Set<String>>> m_menuEntries; /**List of user. */ private List<CmsUser> m_users; /** * puiblic constructor.<p> * * @param ou ou name * @param groupID id of group * @param cmsOuTreeType type to be shown * @param showAll show all user including inherited? * @param app the app */ public CmsUserTable( String ou, CmsUUID groupID, I_CmsOuTreeType cmsOuTreeType, boolean showAll, CmsAccountsApp app) { m_ou = ou.equals("/") ? "" : ou; m_app = app; try { m_cms = getCmsObject(); m_type = cmsOuTreeType; m_indirects = new ArrayList<CmsUser>(); if (m_type.isGroup()) { m_group = m_cms.readGroup(groupID).getName(); m_users = m_cms.getUsersOfGroup(m_group, true); m_fullyLoaded = true; } if (m_type.isRole()) { m_group = CmsRole.valueOfId(groupID).forOrgUnit(ou).getFqn(); List<CmsUser> directs = OpenCms.getRoleManager().getUsersOfRole( m_cms, CmsRole.valueOfId(groupID).forOrgUnit(ou), true, true); if (showAll) { setAllUsers(directs); } else { m_users = directs; } } init(showAll); } catch (CmsException e) { LOG.error("Unable to read user", e); } } /** * public constructor.<p> * * @param ou name * @param type the tree type * @param app the app * @param showAll boolean */ public CmsUserTable(String ou, I_CmsOuTreeType type, CmsAccountsApp app, boolean showAll) { m_ou = ou.equals("/") ? "" : ou; m_app = app; try { m_cms = getCmsObject(); m_type = type; List<CmsUser> directs = m_app.getUsersWithoutAdditionalInfo(m_cms, type, ou, false); m_indirects = new ArrayList<CmsUser>(); if (showAll) { setAllUsers(directs); } else { m_users = directs; } init(showAll); } catch (CmsException e) { LOG.error("Unable to read user.", e); } } /** * @see org.opencms.ui.apps.user.I_CmsFilterableTable#filter(java.lang.String) */ public void filter(String data) { m_container.removeAllContainerFilters(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(data)) { m_container.addContainerFilter( new Or( new SimpleStringFilter(TableProperty.SystemName, data, true, false), new SimpleStringFilter(TableProperty.FullName, data, true, false))); } } /** * @see org.opencms.ui.apps.user.I_CmsToggleTable#getCurrentSize() */ public int getCurrentSize() { return this.size(); } /** * Layout which gets displayed if table is empty. * * @see org.opencms.ui.apps.user.I_CmsFilterableTable#getEmptyLayout() */ public VerticalLayout getEmptyLayout() { m_emptyLayout = CmsVaadinUtils.getInfoLayout(CmsOuTreeType.USER.getEmptyMessageKey()); setVisible(size() > 0); m_emptyLayout.setVisible(size() == 0); return m_emptyLayout; } /** * Gets currently visible user. * * @return List of user */ public List<CmsUser> getVisibleUser() { if (!m_fullyLoaded) { return m_users; } if (size() == m_users.size()) { return m_users; } List<CmsUser> directs = new ArrayList<CmsUser>(); for (CmsUser user : m_users) { if (!m_indirects.contains(user)) { directs.add(user); } } return directs; } /** * @see org.opencms.ui.apps.user.I_CmsToggleTable#toggle(boolean) */ public void toggle(boolean pressed) { try { if (pressed && !m_fullyLoaded) { setAllUsers(m_users); } } catch (CmsException e) { m_fullyLoaded = false; LOG.error("Error loading user", e); } fillContainer(pressed); } /** * Adds given user to given IndexedContainer.<p> * * @param container to add the user to * @param user to add */ protected void addUserToContainer(IndexedContainer container, CmsUser user) { if (m_blackList.contains(user)) { return; } Item item = container.addItem(user); fillItem(item, user); } /** * Fills the container.<p> * * @param showIndirect true-> show all user, false -> only direct user */ protected void fillContainer(boolean showIndirect) { m_container.removeAllContainerFilters(); m_container.removeAllItems(); m_checkedUserPasswordReset = new HashSet<CmsUUID>(); for (CmsUser user : m_users) { if (showIndirect || !m_indirects.contains(user)) { addUserToContainer(m_container, user); } } setVisibilities(); } /** * Fills the container item for a user.<p> * * @param item the item * @param user the user */ protected void fillItem(Item item, CmsUser user) { item.getItemProperty(TableProperty.Name).setValue(user.getSimpleName()); item.getItemProperty(TableProperty.FullName).setValue(user.getFullName()); item.getItemProperty(TableProperty.SystemName).setValue(user.getName()); boolean disabled = !user.isEnabled(); item.getItemProperty(TableProperty.DISABLED).setValue(new Boolean(disabled)); boolean newUser = user.getLastlogin() == 0L; item.getItemProperty(TableProperty.NEWUSER).setValue(new Boolean(newUser)); try { item.getItemProperty(TableProperty.OU).setValue( OpenCms.getOrgUnitManager().readOrganizationalUnit(m_cms, user.getOuFqn()).getDisplayName( A_CmsUI.get().getLocale())); } catch (CmsException e) { LOG.error("Can't read OU", e); } item.getItemProperty(TableProperty.LastLogin).setValue(new Long(user.getLastlogin())); item.getItemProperty(TableProperty.Created).setValue(new Long(user.getDateCreated())); item.getItemProperty(TableProperty.INDIRECT).setValue(new Boolean(m_indirects.contains(user))); item.getItemProperty(TableProperty.FROMOTHEROU).setValue(new Boolean(!user.getOuFqn().equals(m_ou))); item.getItemProperty(TableProperty.STATUS).setValue(getStatusInt(disabled, newUser)); } /** * initializes table. * @param showAll boolean */ protected void init(boolean showAll) { m_menu = new CmsContextMenu(); m_menu.setAsTableContextMenu(this); m_container = new IndexedContainer(); for (TableProperty prop : TableProperty.values()) { m_container.addContainerProperty(prop, prop.getType(), prop.getDefault()); setColumnHeader(prop, prop.getName()); } m_app.addUserContainerProperties(m_container); setContainerDataSource(m_container); setItemIconPropertyId(TableProperty.Icon); setRowHeaderMode(RowHeaderMode.ICON_ONLY); setColumnWidth(null, 40); setColumnWidth(TableProperty.STATUS, 100); setSelectable(true); setMultiSelect(true); setVisibleColumns(TableProperty.Name, TableProperty.OU); fillContainer(showAll); addItemClickListener(new ItemClickListener() { private static final long serialVersionUID = 4807195510202231174L; @SuppressWarnings("unchecked") public void itemClick(ItemClickEvent event) { changeValueIfNotMultiSelect(event.getItemId()); if (event.getButton().equals(MouseButton.RIGHT) || (event.getPropertyId() == null)) { Set<String> userIds = new HashSet<String>(); for (CmsUser user : (Set<CmsUser>)getValue()) { userIds.add(user.getId().getStringValue()); } m_menu.setEntries(getMenuEntries(), userIds); m_menu.openForTable(event, event.getItemId(), event.getPropertyId(), CmsUserTable.this); } else if (event.getButton().equals(MouseButton.LEFT) && TableProperty.Name.equals(event.getPropertyId())) { CmsUser user = ((Set<CmsUser>)getValue()).iterator().next(); try { openInfoDialog(user.getId()); } catch (CmsException e) { LOG.error("Error on opening user info dialog", e); } } } }); setCellStyleGenerator(new CellStyleGenerator() { private static final long serialVersionUID = 4685652851810828147L; public String getStyle(Table source, Object itemId, Object propertyId) { if (TableProperty.STATUS.equals(propertyId)) { return getStatusStyleForItem(source.getItem(itemId), (CmsUser)itemId); } String css = " "; if (((Boolean)(source.getItem(itemId).getItemProperty( TableProperty.FROMOTHEROU).getValue())).booleanValue()) { css += OpenCmsTheme.EXPIRED; } if (TableProperty.Name.equals(propertyId)) { css += " " + OpenCmsTheme.HOVER_COLUMN; } if (((Boolean)source.getItem(itemId).getItemProperty( TableProperty.INDIRECT).getValue()).booleanValue()) { return css + " " + OpenCmsTheme.TABLE_CELL_DISABLED; } return css.length() == 1 ? null : css; } private String getStatusStyleForItem(Item item, CmsUser user) { if (((Boolean)item.getItemProperty(TableProperty.DISABLED).getValue()).booleanValue()) { return OpenCmsTheme.TABLE_COLUMN_BOX_GRAY; } if (OpenCms.getLoginManager().isUserTempDisabled(user.getName())) { return OpenCmsTheme.TABLE_COLUMN_BOX_RED; } if (((Boolean)item.getItemProperty(TableProperty.NEWUSER).getValue()).booleanValue()) { return OpenCmsTheme.TABLE_COLUMN_BOX_BLUE; } if (isUserPasswordReset(user)) { return OpenCmsTheme.TABLE_COLUMN_BOX_ORANGE; } return OpenCmsTheme.TABLE_COLUMN_BOX_GREEN; } }); addGeneratedColumn(TableProperty.STATUS, new ColumnGenerator() { private static final long serialVersionUID = -2144476865774782965L; public Object generateCell(Table source, Object itemId, Object columnId) { return getStatus( (CmsUser)itemId, ((Boolean)source.getItem(itemId).getItemProperty(TableProperty.DISABLED).getValue()).booleanValue(), ((Boolean)source.getItem(itemId).getItemProperty(TableProperty.NEWUSER).getValue()).booleanValue()); } }); addGeneratedColumn(TableProperty.LastLogin, new ColumnGenerator() { private static final long serialVersionUID = -6781906011584975559L; public Object generateCell(Table source, Object itemId, Object columnId) { long lastLogin = ((Long)source.getItem(itemId).getItemProperty( TableProperty.LastLogin).getValue()).longValue(); return lastLogin == 0L ? CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_NEVER_LOGGED_IN_0) : CmsDateUtil.getDateTime(new Date(lastLogin), DateFormat.SHORT, A_CmsUI.get().getLocale()); } }); addGeneratedColumn(TableProperty.Created, new ColumnGenerator() { private static final long serialVersionUID = -6781906011584975559L; public Object generateCell(Table source, Object itemId, Object columnId) { long created = ((Long)source.getItem(itemId).getItemProperty( TableProperty.Created).getValue()).longValue(); return created == 0L ? "" : CmsDateUtil.getDateTime(new Date(created), DateFormat.SHORT, A_CmsUI.get().getLocale()); } }); setItemDescriptionGenerator(new ItemDescriptionGenerator() { private static final long serialVersionUID = 7367011213487089661L; public String generateDescription(Component source, Object itemId, Object propertyId) { if (TableProperty.STATUS.equals(propertyId)) { return getStatusHelp( (CmsUser)itemId, ((Boolean)((Table)source).getItem(itemId).getItemProperty( TableProperty.DISABLED).getValue()).booleanValue(), ((Boolean)((Table)source).getItem(itemId).getItemProperty( TableProperty.NEWUSER).getValue()).booleanValue()); } return null; } }); setVisibleColumns( TableProperty.STATUS, TableProperty.Name, TableProperty.FullName, TableProperty.OU, TableProperty.LastLogin, TableProperty.Created); } /** * Visibility which is only active if user is in right ou.<p> * * @param userId to be checked * @return CmsMenuItemVisibilityMode */ protected boolean onlyVisibleForOU(CmsUUID userId) { try { if (m_app.isOUManagable(m_cms.readUser(userId).getOuFqn())) { return true; } } catch (CmsException e) { } return false; } /** * Checks if all selected items are editable.<p> * * @param context items * @return CmsMenuItemVisibilityMode */ protected CmsMenuItemVisibilityMode onlyVisibleForOU(Set<String> context) { for (String id : context) { if (!onlyVisibleForOU(new CmsUUID(id))) { return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE; } } return CmsMenuItemVisibilityMode.VISIBILITY_ACTIVE; } /** * Opens the user info dialog.<p> * * @param id of user * @throws CmsException exception */ protected void openInfoDialog(CmsUUID id) throws CmsException { CmsUserInfoDialog.showUserInfo(m_cms.readUser(id)); } /** * Checks value of table and sets it new if needed:<p> * if multiselect: new itemId is in current Value? -> no change of value<p> * no multiselect and multiselect, but new item not selected before: set value to new item<p> * * @param itemId if of clicked item */ void changeValueIfNotMultiSelect(Object itemId) { @SuppressWarnings("unchecked") Set<String> value = (Set<String>)getValue(); if (value == null) { select(itemId); } else if (!value.contains(itemId)) { setValue(null); select(itemId); } } /** * Returns the available menu entries.<p> * * @return the menu entries */ List<I_CmsSimpleContextMenuEntry<Set<String>>> getMenuEntries() { if (m_menuEntries == null) { m_menuEntries = new ArrayList<I_CmsSimpleContextMenuEntry<Set<String>>>(); m_menuEntries.add(new EntryInfo()); m_menuEntries.add(new EntryEdit()); m_menuEntries.add(new EntryEditRole()); m_menuEntries.add(new EntryEditGroup()); m_menuEntries.add(new EntryAddInfos()); m_menuEntries.add(new EntryShowResources()); m_menuEntries.add(new EntrySwitchUser()); m_menuEntries.add(new EntryRemoveFromGroup()); m_menuEntries.add(new EntryMoveOU()); m_menuEntries.add(new EntryDelete()); m_menuEntries.add(new EntryKillSession()); m_menuEntries.add(new EntryEnable()); } return m_menuEntries; } /** * Returns status message. * * @param user CmsUser * @param disabled boolean * @param newUser boolean * @return String */ String getStatus(CmsUser user, boolean disabled, boolean newUser) { if (disabled) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DISABLED_0); } if (OpenCms.getLoginManager().isUserTempDisabled(user.getName())) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_UNLOCK_USER_STATUS_0); } if (newUser) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_INACTIVE_0); } if (isUserPasswordReset(user)) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_PASSWORT_RESET_0); } return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_ACTIVE_0); } /** * Returns status help message. * * @param user CmsUser * @param disabled boolean * @param newUser boolean * @return String */ String getStatusHelp(CmsUser user, boolean disabled, boolean newUser) { if (disabled) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DISABLED_HELP_0); } if (newUser) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_INACTIVE_HELP_0); } if (isUserPasswordReset(user)) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_PASSWORT_RESET_HELP_0); } long lastLogin = user.getLastlogin(); return CmsVaadinUtils.getMessageText( Messages.GUI_USERMANAGEMENT_USER_ACTIVE_HELP_1, CmsDateUtil.getDateTime(new Date(lastLogin), DateFormat.SHORT, A_CmsUI.get().getLocale())); } /** * Integer value for status (allows to sort column). * * @param disabled boolean * @param newUser boolean * @return Integer */ Integer getStatusInt(boolean disabled, boolean newUser) { if (disabled) { return new Integer(2); } if (newUser) { return new Integer(1); } return new Integer(0); } /** * Is the user password reset? * * @param user User to check * @return boolean */ boolean isUserPasswordReset(CmsUser user) { if (USER_PASSWORD_STATUS.containsKey(user.getId())) { //Check if user was checked before if (!USER_PASSWORD_STATUS.get(user.getId()).booleanValue()) { // was false before, false->true is never done without changing map return false; } if (m_checkedUserPasswordReset.contains(user.getId())) { //was true before, true->false happens when user resets password. Only check one time per table load. return true; //Set gets flushed on reloading table } } CmsUser currentUser = user; if (user.getAdditionalInfo().size() < 3) { try { currentUser = m_cms.readUser(user.getId()); } catch (CmsException e) { LOG.error("Can not read user", e); } } if (currentUser.getAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET) != null) { USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(true)); m_checkedUserPasswordReset.add(currentUser.getId()); return true; } USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(false)); return false; } /** * Gets list of indirect users to show.<p> * * @param allUsers all users * @param directUsers direct user * @return indirect user */ private List<CmsUser> getAllowedIndirects(List<CmsUser> allUsers, List<CmsUser> directUsers) { List<CmsUser> res = new ArrayList<CmsUser>(); for (CmsUser u : allUsers) { if (!directUsers.contains(u)) { res.add(u); } } return res; } /** * Gets CmsObject.<p> * * @return cmsobject */ private CmsObject getCmsObject() { CmsObject cms; try { cms = OpenCms.initCmsObject(A_CmsUI.getCmsObject()); //m_cms.getRequestContext().setSiteRoot(""); } catch (CmsException e) { cms = A_CmsUI.getCmsObject(); } return cms; } /** * Checks is it is allown for the current user to see given user.<p> * * @param user to be checked * @return boolean * @throws CmsException exception */ private boolean isAllowedUser(CmsUser user) throws CmsException { if (user.getOuFqn().startsWith(m_cms.getRequestContext().getOuFqn())) { return true; } return OpenCms.getRoleManager().getRolesOfUser(m_cms, user.getName(), m_ou, true, true, false).size() > 0; } /** * Sets all user, including indirect user for roles.<p> * * @param directs direct user * @throws CmsException exception */ private void setAllUsers(List<CmsUser> directs) throws CmsException { m_fullyLoaded = true; if (m_type.equals(CmsOuTreeType.ROLE)) { m_users = OpenCms.getRoleManager().getUsersOfRole( m_cms, CmsRole.valueOfRoleName(m_group).forOrgUnit(m_ou), true, false); } else if (m_type.equals(CmsOuTreeType.USER)) { m_users = m_app.getUsersWithoutAdditionalInfo(m_cms, m_type, m_ou, true); } Iterator<CmsUser> it = m_users.iterator(); while (it.hasNext()) { CmsUser u = it.next(); if (!isAllowedUser(u)) { m_blackList.add(u); } } m_indirects.addAll(getAllowedIndirects(m_users, directs)); } /** * Sets the visibility of table and empty info panel.<p> * */ private void setVisibilities() { setVisible(size() > 0); if (m_emptyLayout != null) { m_emptyLayout.setVisible(size() == 0); } } }
package org.opencms.ui.components; import org.opencms.file.CmsObject; import org.opencms.file.CmsUser; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.ui.A_CmsUI; import org.opencms.ui.CmsUserIconHelper; import org.opencms.ui.CmsVaadinUtils; import org.opencms.ui.FontOpenCms; import org.opencms.ui.I_CmsDialogContext; import org.opencms.ui.actions.CmsPreferencesDialogAction; import org.opencms.ui.apps.CmsAppWorkplaceUi; import org.opencms.ui.components.CmsUploadButton.I_UploadListener; import org.opencms.ui.dialogs.CmsEmbeddedDialogContext; import org.opencms.ui.dialogs.CmsUserDataDialog; import org.opencms.ui.login.CmsChangePasswordDialog; import org.opencms.ui.login.CmsLoginController; import org.opencms.ui.shared.components.CmsUploadState.UploadType; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.workplace.CmsAccountInfo; import org.opencms.workplace.CmsAccountInfo.Field; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.apache.commons.logging.Log; import com.vaadin.server.ExternalResource; import com.vaadin.server.Resource; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Component; import com.vaadin.ui.CssLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Image; import com.vaadin.ui.Label; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; /** * Displays the current user info.<p> */ public class CmsUserInfo extends VerticalLayout { /** The HTML line break. */ private static final String LINE_BREAK = "<br />"; /** The serial version id. */ private static final long serialVersionUID = 7215454442218119869L; /** The logger for this class. */ static Log LOG = CmsLog.getLog(CmsUserInfo.class.getName()); /**HTML open div tag.*/ static final String DIV_HTML = "<div style=\"vertical-align:middle;\">"; /**Html close div tag.*/ static final String DIV_END = "</div>"; /** The dialog context. */ I_CmsDialogContext m_context; /** The current user. */ CmsUser m_user; /** The info. */ private Label m_info; /** The details. */ private Label m_details; /** The info panel. */ private HorizontalLayout m_infoPanel; /** The user menu. */ private CmsVerticalMenu m_menu; /** The upload listener. */ private I_UploadListener m_uploadListener; /** * Constructor.<p> * * @param cmsUUID uuid of user to show info for */ public CmsUserInfo(CmsUUID cmsUUID) { CmsVaadinUtils.readAndLocalizeDesign(this, CmsVaadinUtils.getWpMessagesForCurrentLocale(), null); try { CmsObject cms = A_CmsUI.getCmsObject(); m_user = cms.readUser(cmsUUID); m_info.setContentMode(ContentMode.HTML); m_info.setValue(generateInfo(cms, UI.getCurrent().getLocale())); m_details.setContentMode(ContentMode.HTML); m_details.setValue(generateInfoDetails(cms, UI.getCurrent().getLocale())); m_infoPanel.addComponent(createImageButton(), 0); m_menu.setVisible(false); } catch (CmsException e) { LOG.error("Unable to read user", e); } } /** * Constructor.<p> * * @param uploadListener the user image upload listener * @param context the dialog context */ public CmsUserInfo(I_UploadListener uploadListener, I_CmsDialogContext context) { CmsVaadinUtils.readAndLocalizeDesign(this, CmsVaadinUtils.getWpMessagesForCurrentLocale(), null); CmsObject cms = A_CmsUI.getCmsObject(); m_uploadListener = uploadListener; m_user = cms.getRequestContext().getCurrentUser(); m_context = context; m_info.setContentMode(ContentMode.HTML); m_info.setValue(generateInfo(cms, UI.getCurrent().getLocale())); m_details.setContentMode(ContentMode.HTML); m_details.setValue(generateInfoDetails(cms, UI.getCurrent().getLocale())); m_infoPanel.addComponent(createImageButton(), 0); initUserMenu(); } /** * Adds a line to the details label.<p> * * @param lineHtml the line to be added */ public void addDetailLine(String lineHtml) { m_details.setValue(m_details.getValue() + DIV_HTML + lineHtml + DIV_END); } /** * Adds an element behind user name (used in session management app to attach status box).<p> * * @param statusHTML html to be added */ public void addUserStatus(String statusHTML) { int pos = m_info.getValue().indexOf("</p>"); m_info.setValue(m_info.getValue().substring(0, pos) + statusHTML + "</p>"); } /** * Shows the user preferences dialog.<p> */ void editUserData() { if (m_context instanceof CmsEmbeddedDialogContext) { ((CmsEmbeddedDialogContext)m_context).closeWindow(true); } else { A_CmsUI.get().closeWindows(); } CmsUserDataDialog dialog = new CmsUserDataDialog(m_context); m_context.start(CmsVaadinUtils.getMessageText(Messages.GUI_USER_EDIT_0), dialog); } /** * Executes the logout.<p> */ void logout() { CmsLoginController.logout(); } /** * Creates the user image button.<p> * * @return the created button */ private Component createImageButton() { CssLayout layout = new CssLayout(); layout.addStyleName(OpenCmsTheme.USER_IMAGE); Image userImage = new Image(); userImage.setSource( new ExternalResource( OpenCms.getWorkplaceAppManager().getUserIconHelper().getBigIconPath(A_CmsUI.getCmsObject(), m_user))); layout.addComponent(userImage); if (!CmsAppWorkplaceUi.isOnlineProject() & (m_uploadListener != null)) { CmsUploadButton uploadButton = createImageUploadButton( null, FontOpenCms.UPLOAD_SMALL, m_user, m_uploadListener); layout.addComponent(uploadButton); if (CmsUserIconHelper.hasUserImage(m_user)) { Button deleteButton = new Button(FontOpenCms.TRASH_SMALL); deleteButton.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { OpenCms.getWorkplaceAppManager().getUserIconHelper().deleteUserImage(A_CmsUI.getCmsObject()); m_context.updateUserInfo(); } }); layout.addComponent(deleteButton); } } return layout; } /** * Creates an user image upload button.<p> * * @param label the label to use * @param icon the icon to use * @param user the user * @param uploadListener the upload listener * * @return the button */ private CmsUploadButton createImageUploadButton( String label, Resource icon, CmsUser user, I_UploadListener uploadListener) { CmsUploadButton uploadButton = new CmsUploadButton( CmsUserIconHelper.USER_IMAGE_FOLDER + CmsUserIconHelper.TEMP_FOLDER); if (label != null) { uploadButton.setCaption(label); } if (icon != null) { uploadButton.setIcon(icon); } uploadButton.getState().setUploadType(UploadType.singlefile); uploadButton.getState().setTargetFileNamePrefix(user.getId().toString()); uploadButton.getState().setDialogTitle( CmsVaadinUtils.getMessageText(Messages.GUI_USER_INFO_UPLOAD_IMAGE_DIALOG_TITLE_0)); uploadButton.addUploadListener(uploadListener); return uploadButton; } /** * Generates the info data HTML.<p> * * @param cms the cms context * @param locale the locale * * @return the info data HTML */ private String generateInfo(CmsObject cms, Locale locale) { StringBuffer infoHtml = new StringBuffer(128); infoHtml.append("<p>").append(CmsStringUtil.escapeHtml(m_user.getSimpleName())).append("</p>"); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_user.getFirstname())) { infoHtml.append(CmsStringUtil.escapeHtml(m_user.getFirstname())).append("&nbsp;"); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_user.getLastname())) { infoHtml.append(CmsStringUtil.escapeHtml(m_user.getLastname())); } infoHtml.append(LINE_BREAK); return infoHtml.toString(); } /** * Generates the user info details.<p> * * @param cms the cms context * @param locale the locale * * @return the user info details */ private String generateInfoDetails(CmsObject cms, Locale locale) { StringBuffer infoHtml = new StringBuffer(128); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_user.getEmail())) { infoHtml.append(CmsStringUtil.escapeHtml(m_user.getEmail())).append(LINE_BREAK); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_user.getOuFqn())) { infoHtml.append(CmsStringUtil.escapeHtml(m_user.getOuFqn())).append(LINE_BREAK); } for (CmsAccountInfo info : OpenCms.getWorkplaceManager().getAccountInfos()) { if (!info.getField().equals(Field.firstname) && !info.getField().equals(Field.lastname) && !Field.email.equals(info.getField())) { String value = info.getValue(m_user); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(value)) { infoHtml.append(CmsStringUtil.escapeHtml(value)).append(LINE_BREAK); } } } if (OpenCms.getSessionManager().getSessionInfos(m_user.getId()).size() > 0) { infoHtml.append( Messages.get().getBundle(locale).key( Messages.GUI_USER_INFO_ONLINE_SINCE_1, DateFormat.getTimeInstance(DateFormat.DEFAULT, locale).format( new Date(m_user.getLastlogin())))).append(LINE_BREAK); } return infoHtml.toString(); } /** * Initializes the use menu.<p> */ private void initUserMenu() { if (!m_user.isManaged()) { m_menu.addMenuEntry( CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_CHANGE_PASSWORD_BUTTON_0), null).addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { m_context.start( CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_PWCHANGE_HEADER_0) + m_user.getSimpleName(), new CmsChangePasswordDialog(m_context)); } }); } final CmsPreferencesDialogAction preferencesAction = new CmsPreferencesDialogAction(); m_menu.addMenuEntry(preferencesAction.getTitle(A_CmsUI.get().getLocale()), null).addClickListener( new ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { preferencesAction.executeAction(m_context); } }); if (!m_user.isManaged()) { m_menu.addMenuEntry(CmsVaadinUtils.getMessageText(Messages.GUI_USER_EDIT_0), null).addClickListener( new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { editUserData(); } }); } m_menu.addMenuEntry( CmsVaadinUtils.getMessageText(org.opencms.workplace.explorer.Messages.GUI_EXPLORER_CONTEXT_LOGOUT_0), null).addClickListener(new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { logout(); } }); } }
package org.opendroidphp.app; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.actionbarsherlock.app.SherlockActivity; import org.opendroidphp.app.common.utils.ShellOutputFormatter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; public class SQLShellActivity extends SherlockActivity { private Button runCommand; private TextView shellResult; private static Process proc; private static InputStream stdout; private static OutputStream stdin; //private static Shell.Interactive sqlSession; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sqlshell); handler = new Handler(); runCommand = (Button) findViewById(R.id.run_cmd); shellResult = (TextView) findViewById(R.id.shell_result); if (proc == null) { initialize(); } runCommand.setOnClickListener(executeQuery); (new SyncSQLResultTask()).execute(); } protected void initialize() { if (proc != null) { return; } String username = "root"; String password = ""; String[] baseShell = new String[]{ Constants.MYSQL_MONITOR_SBIN_LOCATION, "-h", "127.0.0.1", "-T", "-f", "-r", "-t", "-E", "--disable-pager", "-n", "--user=" + username, "--password=" + password, "--default-character-set=utf8", "-L"}; try { proc = new ProcessBuilder(baseShell). redirectErrorStream(true). start(); stdin = proc.getOutputStream(); stdout = proc.getInputStream(); } catch (IOException e) { e.printStackTrace(); } /*sqlSession = new Shell.Builder(). useSH(). //setShell(baseShell). setWantSTDERR(true). setWatchdogTimeout(5). setMinimalLogging(true). open(new Shell.OnCommandResultListener() { @Override public void onCommandResult(int commandCode, final int exitCode, final List<String> output) { if (exitCode != Shell.OnCommandResultListener.SHELL_RUNNING) { handler.post(new Runnable() { @Override public void run() { if (output != null) { for (String error : output) { shellResult.append(error); } } } }); } else { } } });*/ } private class SyncSQLResultTask extends AsyncTask<Void, String, Void> { @Override protected Void doInBackground(Void... params) { BufferedReader buff = new BufferedReader( new InputStreamReader(stdout)); try { while (true) { String READ = ShellOutputFormatter.toHTML(buff.readLine()); if (READ == null) { break; } publishProgress(READ); } buff.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); shellResult.setText(ShellOutputFormatter.toHTML(values[0])); } } private final View.OnClickListener executeQuery = new View.OnClickListener() { @Override public void onClick(View view) { try { String command = ((EditText) findViewById(R.id.command)) .getText() .toString(); try { stdin.write((command + "\r\n").getBytes()); stdin.flush(); } catch (Exception e) { } /* sqlSession.addCommand(command, new Shell.OnCommandResultListener() { @Override public void onCommandResult(int commandCode, int exitCode, final List<String> output) { handler.post(new Runnable() { @Override public void run() { if (output != null) { for (String error : output) { shellResult.append(error); } } } }); } });*/ } catch (NullPointerException e) { } } }; }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc2811.RecycleRush; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Preferences; import edu.wpi.first.wpilibj.Sendable; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.networktables.NetworkTable; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc2811.RecycleRush.commands.*; import org.usfirst.frc2811.RecycleRush.subsystems.*; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { Command autonomousCommand; Command joystickDrive; public static OI oi; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static Chassis chassis; public static ToteIntake toteIntake; public static ToteElevator toteElevator; public static Bident bident; public static Map map; public static Lights lights; public static UnderGlow underGlow; public static DriverStation lcd; public static Logger logger; private Preferences powerPanelReadout; public static BidentHoming bidentHoming; public static ToteElevatorHoming toteElevatorHoming; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { RobotMap.init(); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS chassis = new Chassis(); toteIntake = new ToteIntake(); toteElevator = new ToteElevator(); bident = new Bident(); map = new Map(); lights = new Lights(); underGlow = new UnderGlow(); SmartDashboard.putNumber("Yaw", Robot.chassis.adjustedYaw()); //SmartDashboard.putNumber("GyroYaw", RobotMap.chassisGyro.updateTable(); ); lcd = DriverStation.getInstance(); powerPanelReadout = Preferences.getInstance(); logger = new Logger(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS // OI must be constructed after subsystems. If the OI creates Commands //(which it very likely will), subsystems are not guaranteed to be // constructed yet. Thus, their requires() statements may grab null // pointers. Bad news. Don't move it. oi = new OI(); // instantiate the command used for the autonomous period // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS autonomousCommand = new AutonomousCommand(); joystickDrive = new ManualDrive(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS } /** * This function is called when the disabled button is hit. * You can use it to reset subsystems before shutting down. */ public void disabledInit(){ //Ensure that if we stop the robot, the lifters stop what they're doing bident.stop(); toteElevator.stop(); } public void disabledPeriodic() { Scheduler.getInstance().run(); //print lifter status toteElevator.disable(); logger.setChannel("TALON", false); toteElevator.printStatus(); logger.setChannel("TALON", false); //Bident Status bident.disable(); logger.setChannel("TALON", false); bident.printStatus(); logger.setChannel("TALON", false); } public void autonomousInit() { // schedule the autonomous command (example) if (autonomousCommand != null) autonomousCommand.start(); Camera.init(); //Simple command for testing the homing state RobotMap.compressor.stop(); //FIXME enable the compressor at some point Command totehoming = new ToteElevatorHoming(); Command homing=new BidentHoming(); homing.start(); homing.cancel(); totehoming.start(); totehoming.cancel(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); // TODO: Add camera code to Auto mode //Robot.logger.setChannel("CAMERA",false); //disable camera loggers Robot.logger.channel("CAMERA","Getting Values"); //getX and getY return the doubles x (COG_X) and y (COG_Y) Robot.logger.channel("CAMERA","X = " + Camera.getX()); //from the Camera subsystem. Robot.logger.channel("CAMERA","Y = " + Camera.getY()); //RoboRealm draws a bounding box around yellow objects, Robot.logger.channel("CAMERA","Got Values"); //and records the coordinates of the center of gravity of said box //in the variables COG_X and COG_Y. if (bident.onTarget()){ bident.set(25); } } public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand != null) autonomousCommand.cancel(); joystickDrive.start(); bident.enable(); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { Scheduler.getInstance().run(); //SmartDashboard.putData("Robot Front",RobotMap.chassisGyro ); //SmartDashboard.putData("PDP", RobotMap.powerPanel); //SmartDashboard.putData("Accelerometer",RobotMap.onboardAccelerometer); //SmartDashboard.putData("Compressor", RobotMap.compressor); //bident.printStatus(); } /** * This function is called periodically during test mode */ public void testPeriodic() { //LiveWindow.run(); //System.out.println("Bident Switch pressed?"+bident.isReverseSwitchPressed() +" "+bident.getRawEncoder()); //bident.printStatus(); LiveWindow.run(); //underGlow.setColor(); // System.out.println(bident.getDistanceBumper()); //System.out.println("range finder"); //*/
package info.tregmine.chat; import info.tregmine.Tregmine; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; public class Chat implements Listener { private final Tregmine plugin; public Chat(Tregmine instance) { plugin = instance; } @EventHandler public void onPlayerChat(AsyncPlayerChatEvent event) { info.tregmine.api.TregminePlayer sender = this.plugin.getPlayer(event.getPlayer()); Player[] players = plugin.getServer().getOnlinePlayers(); String channel = sender.getChatChannel(); ChatColor txtColor = ChatColor.WHITE; String newtext = info.tregmine.api.url.Url.getURL(event.getMessage()); sender.sendMessage(""+ newtext); for (Player player : players) { info.tregmine.api.TregminePlayer to = this.plugin.getPlayer(player); if(sender.equals(to)) { txtColor = ChatColor.GRAY; } else { txtColor = ChatColor.WHITE; } if (sender.getChatChannel().equals(to.getChatChannel())) { if (sender.getChatChannel().matches("GLOBAL")) { channel = ""; } player.sendMessage(channel+"<" + sender.getChatName() + ChatColor.WHITE + "> " + txtColor + event.getMessage()); } } this.plugin.log.info(channel+"<" + sender.getName() + "> " + event.getMessage()); event.setCancelled(true); } }
package com.newsblur.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import android.widget.ImageView; import com.newsblur.R; import com.newsblur.network.APIConstants; public class ImageLoader { private final MemoryCache memoryCache = new MemoryCache(); private final FileCache fileCache; private final ExecutorService executorService; private final Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>()); private String TAG = "ImageLoader"; public ImageLoader(Context context) { fileCache = new FileCache(context); executorService = Executors.newFixedThreadPool(5); } public void displayImage(String url, ImageView imageView) { displayImage(url, imageView, true); } public void displayImage(String url, ImageView imageView, boolean doRound) { imageViews.put(imageView, url); Bitmap bitmap = memoryCache.get(url); if ((bitmap == null) && (url != null)) { File f = fileCache.getFile(url); bitmap = decodeBitmap(f); } if (bitmap != null) { if (doRound) { bitmap = UIUtils.roundCorners(bitmap, 5); } imageView.setImageBitmap(bitmap); } else { queuePhoto(url, imageView); imageView.setImageResource(R.drawable.world); } } public void displayImage(String url, ImageView imageView, float roundRadius) { imageViews.put(imageView, url); Bitmap bitmap = memoryCache.get(url); if ((bitmap == null) && (url != null)) { File f = fileCache.getFile(url); bitmap = decodeBitmap(f); } if (bitmap != null) { if (roundRadius > 0) { bitmap = UIUtils.roundCorners(bitmap, roundRadius); } imageView.setImageBitmap(bitmap); } else { queuePhoto(url, imageView); imageView.setImageResource(R.drawable.world); } } // Display an image assuming it's in cache public void displayImageByUid(String uid, ImageView imageView) { Bitmap bitmap = memoryCache.get(uid); if (bitmap != null) { bitmap = UIUtils.roundCorners(bitmap, 5); imageView.setImageBitmap(bitmap); } else { if (uid != null ) { File f = fileCache.getFile(uid); bitmap = decodeBitmap(f); } if (bitmap != null) { memoryCache.put(uid, bitmap); bitmap = UIUtils.roundCorners(bitmap, 5); imageView.setImageBitmap(bitmap); } else { imageView.setImageResource(R.drawable.world); } } } private void queuePhoto(String url, ImageView imageView) { PhotoToLoad p = new PhotoToLoad(url, imageView); executorService.submit(new PhotosLoader(p)); } public boolean hasImage(String uid) { if (uid == null ) return false; if (memoryCache.get(uid) == null) { return (fileCache.getFile(uid) != null); } return true; } private Bitmap getBitmap(String url) { if (url == null) return null; File f = fileCache.getFile(url); Bitmap bitmap = decodeBitmap(f); if (bitmap != null) { memoryCache.put(url, bitmap); bitmap = UIUtils.roundCorners(bitmap, 5); return bitmap; } try { if (url.startsWith("/")) { url = APIConstants.NEWSBLUR_URL + url; } final URL imageUrl = new URL(url); final HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); final InputStream inputStream = conn.getInputStream(); final OutputStream outputStream = new FileOutputStream(f); byte[] b = new byte[1024]; int read; while ((read = inputStream.read(b)) != -1) { outputStream.write(b, 0, read); } outputStream.close(); bitmap = BitmapFactory.decodeStream(new FileInputStream(f)); memoryCache.put(url, bitmap); if (bitmap == null) return null; bitmap = UIUtils.roundCorners(bitmap, 5); return bitmap; } catch (Exception e) { Log.e(this.getClass().getName(), "Error loading image from network: " + url, e); return null; } } private class PhotoToLoad { public String url; public ImageView imageView; public PhotoToLoad(final String u, final ImageView i) { url = u; imageView = i; } } private class PhotosLoader implements Runnable { PhotoToLoad photoToLoad; public PhotosLoader(PhotoToLoad photoToLoad) { this.photoToLoad = photoToLoad; } @Override public void run() { if (imageViewReused(photoToLoad)) { return; } Bitmap bmp = getBitmap(photoToLoad.url); memoryCache.put(photoToLoad.url, bmp); if (imageViewReused(photoToLoad)) { return; } BitmapDisplayer bitmapDisplayer = new BitmapDisplayer(bmp, photoToLoad); Activity a = (Activity) photoToLoad.imageView.getContext(); a.runOnUiThread(bitmapDisplayer); } } private boolean imageViewReused(PhotoToLoad photoToLoad){ final String tag = imageViews.get(photoToLoad.imageView); return (tag == null || !tag.equals(photoToLoad.url)); } private class BitmapDisplayer implements Runnable { Bitmap bitmap; PhotoToLoad photoToLoad; public BitmapDisplayer(Bitmap b, PhotoToLoad p) { bitmap = b; photoToLoad = p; } public void run() { if (imageViewReused(photoToLoad)) { return; } else if (bitmap != null) { photoToLoad.imageView.setImageBitmap(bitmap); } else { photoToLoad.imageView.setImageResource(R.drawable.world); } } } public void clearCache() { memoryCache.clear(); fileCache.clear(); } private Bitmap decodeBitmap(File f) { // is is perfectly normal for files not to exist on cache misses or low // device memory. this class will handle nulls with a queued action or // placeholder image. if (!f.exists()) return null; try { return BitmapFactory.decodeFile(f.getAbsolutePath()); } catch (Exception e) { return null; } } }
package cn.codeforfun.service; import cn.codeforfun.dao.UserDao; import cn.codeforfun.entity.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; @Service @Transactional public class UserService { @Resource private UserDao userDao; public Page<User> findPage(int page, int size) { return userDao.findAll(new PageRequest(page - 1, size)); } }
package life.catalogue.release; import com.google.common.io.Files; import freemarker.template.*; import life.catalogue.WsServerConfig; import life.catalogue.api.model.Dataset; import life.catalogue.api.model.Page; import life.catalogue.api.search.DatasetSearchRequest; import life.catalogue.api.vocab.Country; import life.catalogue.api.vocab.Language; import life.catalogue.common.io.CompressionUtil; import life.catalogue.common.io.Resources; import life.catalogue.common.io.UTF8IOUtils; import life.catalogue.db.mapper.DatasetMapper; import life.catalogue.img.ImgConfig; import life.catalogue.postgres.PgCopyUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.gbif.nameparser.api.Rank; import org.postgresql.jdbc.PgConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.time.LocalDate; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AcExporter { private static final Logger LOG = LoggerFactory.getLogger(AcExporter.class); private static final String EXPORT_SQL = "/exporter/ac-export.sql"; private static final String CLEANUP_SQL = "exporter/ac-export-cleanup.sql"; private static final String COPY_WITH = "CSV HEADER NULL '\\N' ENCODING 'UTF8' "; private static final Pattern COPY_START = Pattern.compile("^\\s*COPY\\s*\\("); private static final Pattern COPY_END = Pattern.compile("^\\s*\\)\\s*TO\\s*'(.+)'"); private static final Pattern VAR_DATASET_KEY = Pattern.compile("\\{\\{datasetKey}}", Pattern.CASE_INSENSITIVE); private static final Version freemarkerVersion = Configuration.VERSION_2_3_28; private static final Configuration fmk = new Configuration(freemarkerVersion); static { fmk.setClassForTemplateLoading(AcExporter.class, "/exporter"); fmk.setDefaultEncoding("UTF-8"); fmk.setDateFormat("yyyy-MM-dd"); fmk.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); fmk.setLogTemplateExceptions(false); fmk.setWrapUncheckedExceptions(true); // allow the use of java8 dates fmk.setObjectWrapper(new LocalDateObjectWrapper(freemarkerVersion)); } private final WsServerConfig cfg; private final SqlSessionFactory factory; private life.catalogue.release.Logger logger; // we only allow a single export to run at a time private static boolean LOCK = false; public AcExporter(WsServerConfig cfg, SqlSessionFactory factory) { this.cfg = cfg; this.factory = factory; } /** * @return final archive */ public File export(int catalogueKey, life.catalogue.release.Logger logger) throws IOException, SQLException, IllegalStateException { File expDir = new File(cfg.normalizer.scratchDir(catalogueKey), "exports"); if (!aquireLock()) { throw new IllegalStateException("There is a running export already"); } try { LOG.info("Export catalogue {} to {}", catalogueKey, expDir.getAbsolutePath()); logger.setLog(LOG); this.logger = logger; // create csv files try (Connection c = cfg.db.connect()) { c.setAutoCommit(false); setupTables(c); InputStream sql = AcExporter.class.getResourceAsStream(EXPORT_SQL); executeAcExportSql(catalogueKey, (PgConnection)c, new BufferedReader(new InputStreamReader(sql, StandardCharsets.UTF_8)), expDir); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } // include images exportLogos(catalogueKey, expDir); // export citation.ini exportCitations(catalogueKey, expDir); // zip up archive in download directory File arch = new File(cfg.downloadDir, "export-"+catalogueKey+".zip"); logger.log("Zip up archive and move to download"); if (arch.exists()) { LOG.debug("Remove previous export file {}", arch.getAbsolutePath()); } LOG.info("Creating final export archive {}", arch.getAbsolutePath()); CompressionUtil.zipDir(expDir, arch, true); // create sym link to point to latest export File symlink = new File(cfg.downloadDir, "ac-export.zip"); if (symlink.exists()) { symlink.delete(); } java.nio.file.Files.createSymbolicLink(symlink.toPath(), arch.toPath()); return arch; } finally { logger.log("Clean up temp files"); LOG.debug("Remove temp export directory {}", expDir.getAbsolutePath()); FileUtils.deleteQuietly(expDir); LOG.debug("Remove temp tables & sequences from postgres"); logger.log("Clean up tables & sequences from postgres"); try (PgConnection c = cfg.db.connect()) { c.setAutoCommit(false); String sql = Resources.toString(CLEANUP_SQL); executeSql(c, sql); } finally { releaseLock(); } logger.log("Export completed"); this.logger = null; } } private static synchronized boolean aquireLock(){ if (!LOCK) { LOCK = true; return true; } return false; } private static synchronized void releaseLock(){ LOCK = false; } private void exportCitations(int catalogueKey, File dir) throws IOException { logger.log("Export citations"); File cf = new File(dir, "credits.ini"); Map<String, Object> data = new HashMap<>(); try (SqlSession session = factory.openSession(true)) { DatasetMapper dm = session.getMapper(DatasetMapper.class); Dataset d = dm.get(catalogueKey); if (d.getReleased()==null) { // use today as default release date if missing d.setReleased(LocalDate.now()); } data.put("d", d); Template temp = fmk.getTemplate("credits.ftl"); Writer out = UTF8IOUtils.writerFromFile(cf); temp.process(data, out); } catch (TemplateException e) { LOG.error("Failed to write credits", e); throw new RuntimeException(e); } } private void exportLogos(int catalogueKey, File expDir) throws IOException { logger.log("Export logos for sources of catalogue " + catalogueKey); File logoDir = new File(expDir, "logos"); logoDir.mkdir(); int counter = 0; try (SqlSession session = factory.openSession(true)) { DatasetMapper dm = session.getMapper(DatasetMapper.class); DatasetSearchRequest req = new DatasetSearchRequest(); req.setContributesTo(catalogueKey); List<Dataset> resp = dm.search(req, new Page(0,1000)); logger.log("Found " +resp.size()+ " source datasets of catalogue " + catalogueKey); for (Dataset d : resp) { Path p = cfg.img.datasetLogo(d.getKey(), ImgConfig.Scale.MEDIUM); if (java.nio.file.Files.exists(p)) { File img = new File(logoDir, (d.getKey()-1000) + ".png"); Files.copy(p.toFile(), img); p = cfg.img.datasetLogo(d.getKey(), ImgConfig.Scale.SMALL); img = new File(logoDir, (d.getKey()-1000) + "-sm.png"); Files.copy(p.toFile(), img); counter++; } else { LOG.warn("Missing logo for dataset {}: {}", d.getKey(), d.getTitle()); logger.log("Missing logo for dataset " + d.getTitle()); } } } logger.log(counter + " logos exported"); } private static void setupTables(Connection c) throws SQLException, IOException { try (Statement st = c.createStatement()) { st.execute("CREATE TABLE __ranks (key rank PRIMARY KEY, marker TEXT)"); st.execute("CREATE TABLE __country (code text PRIMARY KEY, title TEXT)"); st.execute("CREATE TABLE __language (code text PRIMARY KEY, title TEXT)"); } try (PreparedStatement pstR = c.prepareStatement("INSERT INTO __ranks (key, marker) values (?::rank, ?)"); PreparedStatement pstC = c.prepareStatement("INSERT INTO __country (code, title) values (?, ?)"); PreparedStatement pstL = c.prepareStatement("INSERT INTO __language (code, title) values (?, ?)") ) { for (Rank r : Rank.values()) { if (r.isUncomparable()) continue; pstR.setString(1, r.name()); pstR.setString(2, r.getMarker()); pstR.execute(); } for (Country cn : Country.values()) { pstC.setString(1, cn.getIso2LetterCode()); pstC.setString(2, cn.getTitle()); pstC.execute(); } for (Language l : Language.values()) { pstL.setString(1, l.getCode()); pstL.setString(2, l.getTitle()); pstL.execute(); } c.commit(); } } /** * @return directory with all CSV dump files */ private void executeAcExportSql(int datasetKey, PgConnection con, BufferedReader sql, File csvDir) throws IOException, SQLException { StringBuilder sb = new StringBuilder(); String line; while ((line = sql.readLine()) != null) { Matcher m = COPY_END.matcher(line); if (COPY_START.matcher(line).find()) { executeSql(con, sb.toString()); sb = new StringBuilder(); } else if (m.find()) { // copy to file File f = new File(csvDir, m.group(1).trim()); Files.createParentDirs(f); logger.log("Exporting " + f.getName()); LOG.info("Exporting {}", f.getAbsolutePath()); PgCopyUtils.dump(con, sb.toString(), f, COPY_WITH); sb = new StringBuilder(); } else { if (sb.length() > 0) { sb.append("\n"); } // substitute datasetKey variable sb.append(VAR_DATASET_KEY.matcher(line).replaceAll(String.valueOf(datasetKey))); } } if (sb.length() > 0) { executeSql(con, sb.toString()); } con.commit(); } private void executeSql(PgConnection con, String sql) throws SQLException, IOException { try (Statement stmnt = con.createStatement()) { if (sql.startsWith(" if (sql.contains("\n")) { logger.log(StringUtils.capitalize(sql.substring(3, sql.indexOf('\n')))); } } else if (sql.contains(" ")){ logger.log("Execute " + sql.substring(0, sql.indexOf(' ')) + " SQL"); } stmnt.execute(sql); con.commit(); } } }
package bitronix.tm.gui; import bitronix.tm.utils.Decoder; import bitronix.tm.journal.TransactionLogRecord; import javax.swing.*; import java.awt.*; import java.util.Date; import java.util.Set; import java.util.Iterator; public class TransactionLogDialog extends JDialog { private JPanel labelPanel = new JPanel(); private JLabel statusLabel = new JLabel("Status"); private JLabel recordLengthLabel = new JLabel("Record length"); private JLabel headerLengthLabel = new JLabel("Header length"); private JLabel timeLabel = new JLabel("Time"); private JLabel sequenceNumberLabel = new JLabel("Sequence number"); private JLabel crc32Label = new JLabel("CRC"); private JLabel gtridLabel = new JLabel("GTRID"); private JLabel uniqueNamesLabel = new JLabel("Resources"); private JPanel fieldPanel = new JPanel(); private JTextField statusField = new JTextField(); private JTextField recordLengthField = new JTextField(); private JTextField headerLengthField = new JTextField(); private JTextField timeField = new JTextField(); private JTextField sequenceNumberField = new JTextField(); private JTextField crc32Field = new JTextField(); private JTextField gtridField = new JTextField(); private JTextField uniqueNamesField = new JTextField(); public TransactionLogDialog(JFrame frame, TransactionLogRecord tlog) { super(frame, "Transaction log details", true); statusField.setText(Decoder.decodeStatus(tlog.getStatus())); recordLengthField.setText(""+tlog.getRecordLength()); headerLengthField.setText(""+tlog.getHeaderLength()); timeField.setText(Console.dateFormatter.format(new Date(tlog.getTime()))); sequenceNumberField.setText(""+tlog.getSequenceNumber()); if (tlog.isCrc32Correct()) { crc32Field.setText(""+tlog.getCrc32()); } else { crc32Field.setText(tlog.getCrc32() + " (should be: " + tlog.calculateCrc32() + ")"); crc32Field.setBackground(Color.RED); } gtridField.setText(tlog.getGtrid().toString()); uniqueNamesField.setText(buildString(tlog.getUniqueNames())); statusField.setEditable(false); recordLengthField.setEditable(false); headerLengthField.setEditable(false); timeField.setEditable(false); sequenceNumberField.setEditable(false); crc32Field.setEditable(false); gtridField.setEditable(false); uniqueNamesField.setEditable(false); labelPanel.add(statusLabel); fieldPanel.add(statusField); labelPanel.add(recordLengthLabel); fieldPanel.add(recordLengthField); labelPanel.add(headerLengthLabel); fieldPanel.add(headerLengthField); labelPanel.add(timeLabel); fieldPanel.add(timeField); labelPanel.add(sequenceNumberLabel); fieldPanel.add(sequenceNumberField); labelPanel.add(crc32Label); fieldPanel.add(crc32Field); labelPanel.add(gtridLabel); fieldPanel.add(gtridField); labelPanel.add(uniqueNamesLabel); fieldPanel.add(uniqueNamesField); labelPanel.setLayout(new GridLayout(8, 1)); fieldPanel.setLayout(new GridLayout(8, 1)); getContentPane().add(labelPanel); getContentPane().add(fieldPanel); getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS)); pack(); int xPos = (frame.getBounds().width - 600) / 2; int yPos = (frame.getBounds().height - getSize().height) / 2; setBounds(xPos, yPos, 600, getSize().height); } private String buildString(Set uniqueNames) { StringBuffer sb = new StringBuffer(); Iterator it = uniqueNames.iterator(); while (it.hasNext()) { Object o = it.next(); sb.append(o); if (it.hasNext()) sb.append(", "); } return sb.toString(); } }
package ch.unizh.ini.jaer.chip.retina; import ch.unizh.ini.jaer.chip.retina.DVS128.*; import java.beans.PropertyChangeSupport; import java.util.Observable; import net.sf.jaer.aemonitor.*; import net.sf.jaer.biasgen.*; import net.sf.jaer.chip.*; import net.sf.jaer.event.*; import net.sf.jaer.graphics.*; import net.sf.jaer.hardwareinterface.*; import java.awt.BorderLayout; import java.awt.event.*; import java.io.*; import java.util.Observer; import javax.swing.*; import javax.swing.JPanel; import net.sf.jaer.Description; import net.sf.jaer.hardwareinterface.usb.cypressfx2.CypressFX2DVS128HardwareInterface; import net.sf.jaer.hardwareinterface.usb.cypressfx2.HasResettablePixelArray; import net.sf.jaer.hardwareinterface.usb.cypressfx2.HasSyncEventOutput; import net.sf.jaer.util.HexString; import net.sf.jaer.util.RemoteControlCommand; import net.sf.jaer.util.RemoteControlled; /** * Describes DVS128 retina and its event extractor and bias generator. * This camera is the Tmpdiff128 chip with certain biases tied to the rails to enhance AE bus bandwidth and * it achieves about 2 Meps, as opposed to the approx 500 keps using the on-chip Tmpdiff128 biases. * <p> * Two constructors ara available, the vanilla constructor is used for event playback and the *one with a HardwareInterface parameter is useful for live capture. * {@link #setHardwareInterface} is used when the hardware interface is constructed after the retina object. *The constructor that takes a hardware interface also constructs the biasgen interface. * * @author tobi */ @Description("DVS128 Dynamic Vision Sensor") public class DVS128 extends AETemporalConstastRetina implements Serializable, Observer, RemoteControlled { private JMenu dvs128Menu = null; private JMenuItem arrayResetMenuItem = null, syncEnabledMenuItem = null; private JMenuItem setArrayResetMenuItem = null; private PropertyChangeSupport support=new PropertyChangeSupport(this); public static final String CMD_TWEAK_THESHOLD="threshold", CMD_TWEAK_ONOFF_BALANCE="balance", CMD_TWEAK_BANDWIDTH="bandwidth", CMD_TWEAK_MAX_FIRING_RATE="maxfiringrate"; private Biasgen dvs128Biasgen; JComponent helpMenuItem=null; public static final String HELP_URL_RETINA = "http://siliconretina.ini.uzh.ch"; /** Creates a new instance of DVS128. No biasgen is constructed for this constructor, because there is no hardware interface defined. */ public DVS128() { setName("DVS128"); setSizeX(128); setSizeY(128); setNumCellTypes(2); setPixelHeightUm(40); setPixelWidthUm(40); setEventExtractor(new Extractor(this)); setBiasgen((dvs128Biasgen = new DVS128.Biasgen(this))); if (getRemoteControl() != null) { getRemoteControl().addCommandListener(this, CMD_TWEAK_BANDWIDTH, CMD_TWEAK_BANDWIDTH + " val - tweaks bandwidth. val in range -1.0 to 1.0."); getRemoteControl().addCommandListener(this, CMD_TWEAK_ONOFF_BALANCE, CMD_TWEAK_ONOFF_BALANCE + " val - tweaks on/off balance; increase for more ON events. val in range -1.0 to 1.0."); getRemoteControl().addCommandListener(this, CMD_TWEAK_MAX_FIRING_RATE, CMD_TWEAK_MAX_FIRING_RATE + " val - tweaks max firing rate; increase to reduce refractory period. val in range -1.0 to 1.0."); getRemoteControl().addCommandListener(this, CMD_TWEAK_THESHOLD, CMD_TWEAK_THESHOLD + " val - tweaks threshold; increase to raise threshold. val in range -1.0 to 1.0."); } // ChipCanvas c = getCanvas(); addObserver(this); // if(c!=null)c.setBorderSpacePixels(5);// make border smaller than default } /** Creates a new instance of DVS128 * @param hardwareInterface an existing hardware interface. This constructor is preferred. It makes a new Biasgen object to talk to the on-chip biasgen. */ public DVS128(HardwareInterface hardwareInterface) { this(); setHardwareInterface(hardwareInterface); } /** Updates AEViewer specialized menu items according to capabilities of HardwareInterface. * * @param o the observable, i.e. this Chip. * @param arg the argument (e.g. the HardwareInterface). */ public void update(Observable o, Object arg) { if (!(arg instanceof HardwareInterface)) { return; } if (arrayResetMenuItem == null && getHardwareInterface() != null && getHardwareInterface() instanceof HasResettablePixelArray) { arrayResetMenuItem = new JMenuItem("Momentarily reset pixel array"); arrayResetMenuItem.setToolTipText("Applies a momentary reset to the pixel array"); arrayResetMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { HardwareInterface hw = getHardwareInterface(); if (hw == null || !(hw instanceof HasResettablePixelArray)) { log.warning("cannot reset pixels with hardware interface=" + hw + " (class " + (hw!=null?hw.getClass():null) + "), interface doesn't implement HasResettablePixelArray"); return; } log.info("resetting pixels"); ((HasResettablePixelArray) hw).resetPixelArray(); setArrayResetMenuItem.setSelected(false); // after this reset, the array will not be held in reset } }); dvs128Menu.add(arrayResetMenuItem); setArrayResetMenuItem = new JCheckBoxMenuItem("Hold array in reset"); setArrayResetMenuItem.setToolTipText("Sets the entire pixel array in reset"); setArrayResetMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { HardwareInterface hw = getHardwareInterface(); if (hw == null || !(hw instanceof HasResettablePixelArray)) { log.warning("cannot reset pixels with hardware interface=" + hw + " (class " + hw.getClass() + "), interface doesn't implement HasResettablePixelArray"); return; } log.info("setting pixel array reset=" + setArrayResetMenuItem.isSelected()); ((HasResettablePixelArray) hw).setArrayReset(setArrayResetMenuItem.isSelected()); } }); dvs128Menu.add(setArrayResetMenuItem); } if (syncEnabledMenuItem == null && getHardwareInterface() != null && getHardwareInterface() instanceof HasSyncEventOutput) { syncEnabledMenuItem = new JCheckBoxMenuItem("Enable sync event output"); syncEnabledMenuItem.setToolTipText("<html>Enables sync event generation on external IN pin rising edges (disables slave clock input).<br>Rising edges inject special sync events with bitmask "+HexString.toString(CypressFX2DVS128HardwareInterface.SYNC_EVENT_BITMASK)+" set<br>These events are not rendered but are logged and can be used to synchronize an external signal to the recorded data."); HasSyncEventOutput h = (HasSyncEventOutput) getHardwareInterface(); syncEnabledMenuItem.setSelected(h.isSyncEventEnabled()); syncEnabledMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { HardwareInterface hw = getHardwareInterface(); if (hw == null || !(hw instanceof HasSyncEventOutput)) { log.warning("cannot change sync enabled state of " + hw + " (class " + hw.getClass() + "), interface doesn't implement HasSyncEventOutput"); return; } log.info("setting sync enabled"); ((HasSyncEventOutput) hw).setSyncEventEnabled(((AbstractButton) evt.getSource()).isSelected()); } }); dvs128Menu.add(syncEnabledMenuItem); } // if hw interface is not correct type then disable menu items if (getHardwareInterface() == null) { if (arrayResetMenuItem != null) { arrayResetMenuItem.setEnabled(false); } if (setArrayResetMenuItem != null) { setArrayResetMenuItem.setEnabled(false); } if (syncEnabledMenuItem != null) { syncEnabledMenuItem.setEnabled(false); } } else { if (!(getHardwareInterface() instanceof HasResettablePixelArray)) { if (arrayResetMenuItem != null) { arrayResetMenuItem.setEnabled(false); } if (setArrayResetMenuItem != null) { setArrayResetMenuItem.setEnabled(false); } } else { arrayResetMenuItem.setEnabled(true); setArrayResetMenuItem.setEnabled(true); } if (!(getHardwareInterface() instanceof HasSyncEventOutput)) { if (syncEnabledMenuItem != null) { syncEnabledMenuItem.setEnabled(false); } } else { syncEnabledMenuItem.setEnabled(true); } } } @Override public void onDeregistration() { super.onRegistration(); if(helpMenuItem==null) return; if(getAeViewer()!=null) getAeViewer().removeHelpItem(helpMenuItem); } @Override public void onRegistration() { super.onRegistration(); if(getAeViewer()!=null) helpMenuItem=getAeViewer().addHelpURLItem(HELP_URL_RETINA, "DVS128 wiki", "Opens user guide wiki for DVS128 silicon retina"); } @Override public String processRemoteControlCommand(RemoteControlCommand command, String input) { log.info("processing RemoteControlCommand "+command+" with input="+input); if(command==null) return null; String[] tokens=input.split(" "); if(tokens.length<2){ return input+ ": unknown command - did you forget the argument?"; } if(tokens[1]==null || tokens[1].length()==0){ return input+ ": argument too short - need a number"; } float v=0; try{ v=Float.parseFloat(tokens[1]); }catch(NumberFormatException e){ return input+ ": bad argument? Caught "+ e.toString(); } String c=command.getCmdName(); if(c.equals(CMD_TWEAK_BANDWIDTH)){ dvs128Biasgen.setBandwidthTweak(v); }else if(c.equals(CMD_TWEAK_ONOFF_BALANCE)){ dvs128Biasgen.setOnOffBalanceTweak(v); }else if(c.equals(CMD_TWEAK_MAX_FIRING_RATE)){ dvs128Biasgen.setMaxFiringRateTweak(v); }else if(c.equals(CMD_TWEAK_THESHOLD)){ dvs128Biasgen.setThresholdTweak(v); }else { return input+ ": unknown command"; } return "successfully processed command "+input; } /** the event extractor for DVS128. DVS128 has two polarities 0 and 1. Here the polarity is flipped by the extractor so that the raw polarity 0 becomes 1 in the extracted event. The ON events have raw polarity 0. 1 is an ON event after event extraction, which flips the type. Raw polarity 1 is OFF event, which becomes 0 after extraction. */ public class Extractor extends RetinaExtractor { final short XMASK = 0xfe, XSHIFT = 1, YMASK = 0x7f00, YSHIFT = 8; public Extractor(DVS128 chip) { super(chip); setXmask((short) 0x00fe); setXshift((byte) 1); setYmask((short) 0x7f00); setYshift((byte) 8); setTypemask((short) 1); setTypeshift((byte) 0); setFlipx(true); setFlipy(false); setFliptype(true); } /** extracts the meaning of the raw events. *@param in the raw events, can be null *@return out the processed events. these are partially processed in-place. empty packet is returned if null is supplied as in. This event packet is reused * and should only be used by a single thread of execution or for a single input stream, or mysterious results may occur! */ @Override synchronized public EventPacket extractPacket(AEPacketRaw in) { if (out == null) { out = new EventPacket<PolarityEvent>(chip.getEventClass()); } else { out.clear(); } extractPacket(in, out); return out; } private int printedSyncBitWarningCount=3; /** * Extracts the meaning of the raw events. This form is used to supply an output packet. This method is used for real time * event filtering using a buffer of output events local to data acquisition. An AEPacketRaw may contain multiple events, * not all of them have to sent out as EventPackets. An AEPacketRaw is a set(!) of addresses and corresponding timing moments. * * A first filter (independent from the other ones) is implemented by subSamplingEnabled and getSubsampleThresholdEventCount. * The latter may limit the amount of samples in one package to say 50,000. If there are 160,000 events and there is a sub sample * threshold of 50,000, a "skip parameter" set to 3. Every so now and then the routine skips with 4, so we end up with 50,000. * It's an approximation, the amount of events may be less than 50,000. The events are extracted uniform from the input. * * @param in the raw events, can be null * @param out the processed events. these are partially processed in-place. empty packet is returned if null is * supplied as input. */ @Override synchronized public void extractPacket(AEPacketRaw in, EventPacket out) { if (in == null) { return; } int n = in.getNumEvents(); //addresses.length; int skipBy = 1; if (isSubSamplingEnabled()) { while (n / skipBy > getSubsampleThresholdEventCount()) { skipBy++; } } int sxm = sizeX - 1; int[] a = in.getAddresses(); int[] timestamps = in.getTimestamps(); OutputEventIterator outItr = out.outputIterator(); for (int i = 0; i < n; i += skipBy) { // TODO bug here? int addr = a[i]; // TODO handle sync events from hardware correctly if (addr > 0xefff) { if(printedSyncBitWarningCount>0){ log.warning("raw address "+addr+" is >32767 (0xefff); either sync or stereo bit is set, clearing the msb"); printedSyncBitWarningCount if(printedSyncBitWarningCount==0) log.warning("suppressing futher warnings about msb of raw address"); } // TODO handle this by outputting SyncEvent's instead of PolarityEvent's. Some files recorded earlier in 2.0 format have the msb set by hardware. // here we restrict the addresses to 32767 max. addr=addr&0xefff; } else { PolarityEvent e = (PolarityEvent) outItr.nextOutput(); e.address=addr; e.timestamp = (timestamps[i]); e.type = (byte) (1 - addr & 1); e.polarity = e.type == 0 ? PolarityEvent.Polarity.Off : PolarityEvent.Polarity.On; e.x = (short) (sxm - ((short) ((addr & XMASK) >>> XSHIFT))); e.y = (short) ((addr & YMASK) >>> YSHIFT); } } } } /** overrides the Chip setHardware interface to construct a biasgen if one doesn't exist already. * Sets the hardware interface and the bias generators hardware interface *@param hardwareInterface the interface */ @Override public void setHardwareInterface(final HardwareInterface hardwareInterface) { super.setHardwareInterface(hardwareInterface); this.hardwareInterface = hardwareInterface; try { if (getBiasgen() == null) { setBiasgen(new DVS128.Biasgen(this)); } else { getBiasgen().setHardwareInterface((BiasgenHardwareInterface) hardwareInterface); } } catch (ClassCastException e) { System.err.println(e.getMessage() + ": probably this chip object has a biasgen but the hardware interface doesn't, ignoring"); } setChanged(); notifyObservers(hardwareInterface); } // /** Called when this DVS128 notified, e.g. by having its AEViewer set // @param the calling object // @param arg the argument passed // */ // public void update(Observable o, Object arg) { // log.info("DVS128: received update from Observable="+o+", arg="+arg); /** Called when the AEViewer is set for this AEChip. Here we add the menu to the AEViewer. * * @param v the viewer */ @Override public void setAeViewer(AEViewer v) { super.setAeViewer(v); if (v != null) { dvs128Menu = new JMenu("DVS128"); dvs128Menu.getPopupMenu().setLightWeightPopupEnabled(false); // to paint on GLCanvas dvs128Menu.setToolTipText("Specialized menu for DVS128 chip"); v.setMenuItem(dvs128Menu); } } /** * Describes IPots on DVS128 retina chip. These are configured by a shift register as shown here: *<p> *<img src="doc-files/tmpdiff128biasgen.gif" alt="tmpdiff128 shift register arrangement"/> <p> This bias generator also offers an abstracted ChipControlPanel interface that is used for a simplified user interface. * * @author tobi */ public class Biasgen extends net.sf.jaer.biasgen.Biasgen implements ChipControlPanel, DVSTweaks { private IPot diffOn, diffOff, refr, pr, sf, diff; /** Creates a new instance of Biasgen for DVS128 with a given hardware interface *@param chip the chip this biasgen belongs to */ public Biasgen(Chip chip) { super(chip); setName("DVS128"); // /** Creates a new instance of IPot // *@param biasgen // *@param name // *@param shiftRegisterNumber the position in the shift register, 0 based, starting on end from which bits are loaded // *@param type (NORMAL, CASCODE) // *@param sex Sex (N, P) // * @param bitValue initial bitValue // *@param displayPosition position in GUI from top (logical order) // *@param tooltipString a String to display to user of GUI telling them what the pots does // */ //// public IPot(Biasgen biasgen, String name, int shiftRegisterNumber, final Type type, Sex sex, int bitValue, int displayPosition, String tooltipString) { // create potArray according to our needs setPotArray(new IPotArray(this)); getPotArray().addPot(new IPot(this, "cas", 11, IPot.Type.CASCODE, IPot.Sex.N, 0, 2, "Photoreceptor cascode")); getPotArray().addPot(new IPot(this, "injGnd", 10, IPot.Type.CASCODE, IPot.Sex.P, 0, 7, "Differentiator switch level, higher to turn on more")); getPotArray().addPot(new IPot(this, "reqPd", 9, IPot.Type.NORMAL, IPot.Sex.N, 0, 12, "AER request pulldown")); getPotArray().addPot(new IPot(this, "puX", 8, IPot.Type.NORMAL, IPot.Sex.P, 0, 11, "2nd dimension AER static pullup")); getPotArray().addPot(diffOff = new IPot(this, "diffOff", 7, IPot.Type.NORMAL, IPot.Sex.N, 0, 6, "OFF threshold, lower to raise threshold")); getPotArray().addPot(new IPot(this, "req", 6, IPot.Type.NORMAL, IPot.Sex.N, 0, 8, "OFF request inverter bias")); getPotArray().addPot(refr = new IPot(this, "refr", 5, IPot.Type.NORMAL, IPot.Sex.P, 0, 9, "Refractory period")); getPotArray().addPot(new IPot(this, "puY", 4, IPot.Type.NORMAL, IPot.Sex.P, 0, 10, "1st dimension AER static pullup")); getPotArray().addPot(diffOn = new IPot(this, "diffOn", 3, IPot.Type.NORMAL, IPot.Sex.N, 0, 5, "ON threshold - higher to raise threshold")); getPotArray().addPot(diff = new IPot(this, "diff", 2, IPot.Type.NORMAL, IPot.Sex.N, 0, 4, "Differentiator")); getPotArray().addPot(sf = new IPot(this, "foll", 1, IPot.Type.NORMAL, IPot.Sex.P, 0, 3, "Src follower buffer between photoreceptor and differentiator")); getPotArray().addPot(pr = new IPot(this, "Pr", 0, IPot.Type.NORMAL, IPot.Sex.P, 0, 1, "Photoreceptor")); loadPreferences(); } /** sends the ipot values over the hardware interface if there is not a batch edit occuring. *@param biasgen the bias generator object. * This parameter is necessary because the same method is used in the hardware interface, * which doesn't know about the particular bias generator instance. *@throws HardwareInterfaceException if there is a hardware error. If there is no interface, prints a message and just returns. *@see #startBatchEdit *@see #endBatchEdit **/ public void sendConfiguration(Biasgen biasgen) throws HardwareInterfaceException { if (hardwareInterface == null) { // log.warning("Biasgen.sendIPotValues(): no hardware interface"); return; } if (!isBatchEditOccurring() && hardwareInterface != null) { // log.info("calling hardwareInterface.sendConfiguration"); // hardwareInterface.se(this); } } /** the change in current from an increase* or decrease* call */ public final float RATIO = 1.05f; /** the minimum on/diff or diff/off current allowed by decreaseThreshold */ public final float MIN_THRESHOLD_RATIO = 4f; public final float MAX_DIFF_ON_CURRENT = 12e-6f; public final float MIN_DIFF_OFF_CURRENT = 1e-10f; synchronized public void increaseThreshold() { if (diffOn.getCurrent() * RATIO > MAX_DIFF_ON_CURRENT) { return; } if (diffOff.getCurrent() / RATIO < MIN_DIFF_OFF_CURRENT) { return; } diffOn.changeByRatio(RATIO); diffOff.changeByRatio(1 / RATIO); } synchronized public void decreaseThreshold() { float diffI = diff.getCurrent(); if (diffOn.getCurrent() / MIN_THRESHOLD_RATIO < diffI) { return; } if (diffOff.getCurrent() > diffI / MIN_THRESHOLD_RATIO) { return; } diffOff.changeByRatio(RATIO); diffOn.changeByRatio(1 / RATIO); } synchronized public void increaseRefractoryPeriod() { refr.changeByRatio(1 / RATIO); } synchronized public void decreaseRefractoryPeriod() { refr.changeByRatio(RATIO); } synchronized public void increaseBandwidth() { pr.changeByRatio(RATIO); sf.changeByRatio(RATIO); } synchronized public void decreaseBandwidth() { pr.changeByRatio(1 / RATIO); sf.changeByRatio(1 / RATIO); } synchronized public void moreONType() { diffOn.changeByRatio(1 / RATIO); diffOff.changeByRatio(RATIO); } synchronized public void moreOFFType() { diffOn.changeByRatio(RATIO); diffOff.changeByRatio(1 / RATIO); } JComponent expertTab, basicTab; /** @return a new panel for controlling this bias generator functionally */ @Override public JPanel buildControlPanel() { JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); final JTabbedPane pane = new JTabbedPane(); pane.addTab("Basic controls", basicTab = new DVSFunctionalControlPanel(DVS128.this)); pane.addTab("Expert controls", expertTab = super.buildControlPanel()); panel.add(pane, BorderLayout.CENTER); pane.setSelectedIndex(getPrefs().getInt("DVS128.selectedBiasgenControlTab", 0)); pane.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { getPrefs().putInt("DVS128.selectedBiasgenControlTab", pane.getSelectedIndex()); } }); return panel; } private float bandwidth=1, maxFiringRate=1, threshold=1, onOffBalance=1; /** Tweaks bandwidth around nominal value. * * @param val -1 to 1 range */ public void setBandwidthTweak(float val) { if(val>1)val=1; else if(val<-1) val=-1; float old=bandwidth; bandwidth=val; final float MAX = 300; pr.changeByRatioFromPreferred(PotTweakerUtilities.getRatioTweak(val, MAX)); sf.changeByRatioFromPreferred(PotTweakerUtilities.getRatioTweak(val, MAX)); getSupport().firePropertyChange(DVSTweaks.BANDWIDTH,old,val); } /** * Tweaks max firing rate (refractory period), larger is shorter refractory period. * * @param val -1 to 1 range */ public void setMaxFiringRateTweak(float val) { if(val>1)val=1; else if(val<-1) val=-1; float old=maxFiringRate; maxFiringRate=val; final float MAX = 300; refr.changeByRatioFromPreferred(PotTweakerUtilities.getRatioTweak(val, MAX)); getSupport().firePropertyChange(DVSTweaks.MAX_FIRING_RATE,old,val); } /** * Tweaks threshold, larger is higher threshold. * @param val -1 to 1 range */ public void setThresholdTweak(float val) { if(val>1)val=1; else if(val<-1) val=-1; float old=threshold; final float MAX = 100; threshold=val; diffOn.changeByRatioFromPreferred(PotTweakerUtilities.getRatioTweak(val, MAX)); diffOff.changeByRatioFromPreferred(1 / PotTweakerUtilities.getRatioTweak(val, MAX)); getSupport().firePropertyChange(DVSTweaks.THRESHOLD,old,val); } /** * Tweaks balance of on/off events. Increase for more ON events. * * @param val -1 to 1 range. */ public void setOnOffBalanceTweak(float val) { if(val>1)val=1; else if(val<-1) val=-1; float old=onOffBalance; onOffBalance=val; final float MAX = 100; diff.changeByRatioFromPreferred(PotTweakerUtilities.getRatioTweak(val, MAX)); getSupport().firePropertyChange(DVSTweaks.ON_OFF_BALANCE,old,val); } @Override public float getBandwidthTweak() { return bandwidth; } @Override public float getThresholdTweak() { return threshold; } @Override public float getMaxFiringRateTweak() { return maxFiringRate; } @Override public float getOnOffBalanceTweak() { return onOffBalance; } } // DVS128Biasgen /** * Fires PropertyChangeEvents when biases are tweaked according to {@link ch.unizh.ini.jaer.chip.retina.DVSTweaks}. * * @return the support */ public PropertyChangeSupport getSupport() { return support; } }
package ch.usi.dag.disl.util.stack; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.VarInsnNode; import org.objectweb.asm.tree.analysis.Analyzer; import org.objectweb.asm.tree.analysis.BasicInterpreter; import org.objectweb.asm.tree.analysis.BasicValue; import org.objectweb.asm.tree.analysis.Frame; import org.objectweb.asm.tree.analysis.SourceInterpreter; import org.objectweb.asm.tree.analysis.SourceValue; import org.objectweb.asm.tree.analysis.Value; public class StackUtil { // generate a basic analyzer public static Analyzer<BasicValue> getBasicAnalyzer() { return new Analyzer<BasicValue>(new BasicInterpreter()); } // calculate the stack size public static int getOffset(Frame<BasicValue> frame) { int offset = 0; for (int i = frame.getStackSize() - 1; i >= 0; i BasicValue v = frame.getStack(i); offset += v.getSize(); } return offset; } // generate an instruction list to backup the stack public static InsnList enter(Frame<BasicValue> frame, int offset) { InsnList ilst = new InsnList(); for (int i = frame.getStackSize() - 1; i >= 0; i BasicValue v = frame.getStack(i); ilst.add(new VarInsnNode(v.getType().getOpcode(Opcodes.ISTORE), offset)); offset += v.getSize(); } return ilst; } // generate an instruction list to restore the stack public static InsnList exit(Frame<BasicValue> frame, int offset) { InsnList ilst = new InsnList(); ilst.add(new LabelNode()); for (int i = frame.getStackSize() - 1; i >= 0; i BasicValue v = frame.getStack(i); ilst.insertBefore(ilst.getFirst(), new VarInsnNode(v.getType() .getOpcode(Opcodes.ILOAD), offset)); offset += v.getSize(); } return ilst; } // generate a source analyzer public static Analyzer<SourceValue> getSourceAnalyzer() { return new Analyzer<SourceValue>(new SourceInterpreter()); } public static <T extends Value> T getStack(Frame<T> frame, int depth) { int index = 0; while (depth > 0) { depth -= frame.getStack(frame.getStackSize() - 1 - index).getSize(); index++; } return frame.getStack(frame.getStackSize() - 1 - index); } public static <T extends Value> T getStackByIndex(Frame<T> frame, int index) { return frame.getStack(frame.getStackSize() - 1 - index); } // find out where a stack operand is pushed onto stack, and duplicate the // operand and store into a local slot. public static int dupStack(Frame<SourceValue> frame, MethodNode method, int operand, int sopcode, int slot) { SourceValue source = StackUtil.getStackByIndex(frame, operand); for (AbstractInsnNode itr : source.insns) { // if the instruction duplicates two-size operand(s), weaver should // be careful that the operand might be either 2 one-size operands, // or 1 two-size operand. switch (itr.getOpcode()) { case Opcodes.DUP2: if (source.size != 1) { break; } dupStack(frame, method, operand + 2, sopcode, slot); continue; case Opcodes.DUP2_X1: if (source.size != 1) { break; } dupStack(frame, method, operand + 3, sopcode, slot); continue; case Opcodes.DUP2_X2: if (source.size != 1) { break; } SourceValue x2 = StackUtil.getStackByIndex(frame, operand + 2); dupStack(frame, method, operand + (4 - x2.size), sopcode, slot); continue; case Opcodes.SWAP: if (operand > 0 && StackUtil.getStackByIndex(frame, operand - 1).insns .contains(itr)) { // insert 'dup' instruction and then store to a local slot method.instructions.insertBefore(itr, new InsnNode( Opcodes.DUP)); method.instructions.insertBefore(itr, new VarInsnNode( sopcode, slot)); continue; } default: break; } // insert 'dup' instruction and then store to a local slot method.instructions.insert(itr, new VarInsnNode(sopcode, slot)); method.instructions.insert(itr, new InsnNode( source.size == 2 ? Opcodes.DUP2 : Opcodes.DUP)); } return source.size; } }
package loci.formats.utests; import static org.testng.AssertJUnit.*; import java.io.IOException; import loci.formats.FormatTools; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class FormatToolsTest { @Test public void testDefaultMinMaxInt8() { long[] lim = FormatTools.defaultMinMax(FormatTools.INT8); assertEquals(lim[0], -128); assertEquals(lim[1], 127); } @Test public void testDefaultMinMaxInt16() { long[] lim = FormatTools.defaultMinMax(FormatTools.INT16); assertEquals(lim[0], -32768); assertEquals(lim[1], 32767); } @Test public void testDefaultMinMaxInt32() { long[] lim = FormatTools.defaultMinMax(FormatTools.INT32); assertEquals(lim[0], -2147483648); assertEquals(lim[1], 2147483647); } @Test public void testDefaultMinMaxUint8() { long[] lim = FormatTools.defaultMinMax(FormatTools.UINT8); assertEquals(lim[0], 0); assertEquals(lim[1], 255); } @Test public void testDefaultMinMaxUint16() { long[] lim = FormatTools.defaultMinMax(FormatTools.UINT16); assertEquals(lim[0], 0); assertEquals(lim[1], 65535); } @Test public void testDefaultMinMaxUint32() { long[] lim = FormatTools.defaultMinMax(FormatTools.UINT32); assertEquals(lim[0], 0); assertEquals(lim[1], 4294967295L); } public void testDefaultMinMaxFloat() throws IllegalArgumentException { long[] lim = FormatTools.defaultMinMax(FormatTools.FLOAT); assertEquals(lim[0], -2147483648); assertEquals(lim[1], 2147483647); } public void testDefaultMinMaxDouble() throws IllegalArgumentException { long[] lim = FormatTools.defaultMinMax(FormatTools.DOUBLE); assertEquals(lim[0], -9223372036854775808L); assertEquals(lim[1], 9223372036854775807L); } @Test(expectedExceptions={IllegalArgumentException.class}) public void testDefaultMinMaxInvalid() throws IllegalArgumentException { long[] lim = FormatTools.defaultMinMax(9999); // Invalid pixel type number } }
package org.cinchapi.concourse.util; import org.cinchapi.concourse.util.RandomStringGenerator; import com.google.common.base.Strings; /** * Random generators. * * @author jnelson */ public abstract class Random { private static final java.util.Random rand = new java.util.Random(); private static final RandomStringGenerator strand = new RandomStringGenerator(); /** * Return a random boolean value. * * @return the boolean. */ public static boolean getBoolean() { int seed = rand.nextInt(); if(seed % 2 == 0) { return true; } else { return false; } } /** * Return a random double value. * * @return the double. */ public static double getDouble() { return rand.nextDouble(); } /** * Return a random float value. * * @return the float. */ public static float getFloat() { return rand.nextFloat(); } /** * Return a random integer value. * * @return the int. */ public static int getInt() { return rand.nextInt(); } /** * Return a random long value. * * @return the long. */ public static long getLong() { return rand.nextLong(); } /** * Return a random negative number. * * @return the number. */ public static Number getNegativeNumber() { int seed = getInt(); if(seed % 5 == 0) { return (float) -1 * Math.abs(getFloat()); } else if(seed % 4 == 0) { return (double) -1 * Math.abs(getDouble()); } else if(seed % 3 == 0) { return (long) -1 * Math.abs(getLong()); } else { return (int) -1 * Math.abs(getInt()); } } /** * Return a random number value. * * @return the number */ public static Number getNumber() { int seed = getInt(); if(seed % 5 == 0) { return getFloat(); } else if(seed % 4 == 0) { return getDouble(); } else if(seed % 3 == 0) { return getLong(); } else { return getInt(); } } /** * Return a random object value. * * @return the object */ public static Object getObject() { int seed = rand.nextInt(); if(seed % 5 == 0) { return getBoolean(); } else if(seed % 2 == 0) { return getNumber(); } else { return getString(); } } /** * Return a random positive long value. * * @return the long */ public static Number getPositiveNumber() { int seed = getInt(); if(seed % 5 == 0) { return Math.abs(getFloat()); } else if(seed % 4 == 0) { return (double) Math.abs(getDouble()); } else if(seed % 3 == 0) { return (long) Math.abs(getLong()); } else { return (int) Math.abs(getInt()); } } /** * Pause execution for a random number of milliseconds between 0 and 1000 (1 * second). */ public static void sleep() { try { Thread.sleep(rand.nextInt(1000) + 1); // between 0 and 1 second } catch (InterruptedException e) { e.printStackTrace(); } } /** * Pause execution for a random number of milliseconds between 100 and 200. */ public static void tinySleep() { try { Thread.sleep(rand.nextInt(200) + 100); // between a and 100 ms } catch (InterruptedException e) { e.printStackTrace(); } } public static int getScaleCount() { return rand.nextInt(90) + 10; } /** * Return a get string, possibly with digits. * * @return the string */ public static String getString() { String string = null; while (Strings.isNullOrEmpty(string.trim())) { string = strand.nextStringAllowDigits(); } return string; } /** * Return a get string, with no digits. * * @return the string. */ public static String getStringNoDigits() { return strand.nextString(); } }
import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import org.jsoup.nodes.Element; import java.sql.*; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultSet; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; public class futureLearn { public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { ArrayList<String> pgcrs = new ArrayList<String>(); //Array which will store each course URLs pgcrs.add("https: pgcrs.add("https: pgcrs.add("https: pgcrs.add("https: pgcrs.add("https: pgcrs.add("https: pgcrs.add("https: pgcrs.add("https: pgcrs.add("https: pgcrs.add("https: pgcrs.add("https: pgcrs.add("https: pgcrs.add("https: ArrayList<String> pgcrsNames = new ArrayList<String>(); pgcrsNames.add("Business and Management"); pgcrsNames.add("Creative Arts and Media" ); pgcrsNames.add("Health and Psychology" ); pgcrsNames.add("History" ); pgcrsNames.add("Languages and Cultures" ); pgcrsNames.add("Law" ); pgcrsNames.add("Literature" ); pgcrsNames.add("Nature and Environment" ); pgcrsNames.add("Online and Digital" ); pgcrsNames.add("Politics and the Modern World" ); pgcrsNames.add("Science Maths and Technology"); pgcrsNames.add("Sport and Leisure" ); pgcrsNames.add("Teaching and Studying" ); ArrayList<Course> allCourses = new ArrayList<Course>(); Set<String> courseLinks = new HashSet<String>(); int i = 10000; //for course id for(int a=0; a<pgcrs.size();a++) { //String furl = (String) pgcrs.get(a); //Document doc = Jsoup.connect(furl).get(); Document doc = Jsoup.connect(pgcrs.get(a)).get(); Elements ele = doc.select("a[href]");//get all the a tags for(Element ax: ele){ String link = ax.attr("href"); if(link.length() > 9){ if(link.substring(0, 9).equals("/courses/")){ courseLinks.add(link); } } } for(String l : courseLinks){ //go to each course Course course1 = new Course(i);//create the course. we will add it at the end //course URL String crsurl = "https: course1.setUrl(crsurl); Document doc2 = Jsoup.connect(crsurl).get(); Elements ele2 = doc2.select("div[class]"); //course teacher for(Element ay: ele2){ if(ay.attr("class").equals("educator")){ Elements ele3 = ay.select("img"); course1.addInstructorName(ele3.attr("alt"));//save the teacher's name course1.addInstructorImage(ele3.attr("src"));//save the teacher's picture } } //course name String crsName = doc2.select("h1").text(); course1.setCourseName(crsName);//save the course name //shortDesc Elements shortDesc = doc2.select("meta[content]"); for(Element sdhold : shortDesc){ if(sdhold.attr("itemprop").equals("description")){ String sdtemp = sdhold.attr("content"); course1.setShortDesc(sdtemp); } } //longDesc String longdescription = doc2.select("section[class=small").text(); course1.setLongDescription(longdescription); //University String university = doc2.select(".run-organisation__logo").attr("alt"); university = university.replace("logo", "").trim(); course1.setUniversity(university); //video link String videoLink = doc2.select("source[src]").attr("src"); if(videoLink.startsWith(" course1.setVideoLink(videoLink); } else{ course1.setVideoLink(""); } //certificate String certificates = doc2.select("p[class=run-data]").text(); if(certificates.contains("Certificates")){ course1.setCertificate("Yes"); } else{ course1.setCertificate("No"); } //course length String duration = doc2.select("time[itemprop=duration]").text(); String durationSplit[] = duration.split(" "); //split on space if(!durationSplit[0].equals("")){ int durationNum = Integer.parseInt(durationSplit[0]);//get the first duration in weeks and make it an int duration = Integer.toString(durationNum);//go from in to string } if(duration.length() > 0){ course1.addCourseLength(duration); //save the duration of the course } else { course1.addCourseLength("0"); } String startDate = doc2.select("time[itemprop=startDate]").text(); //[number]<space>[month] String startDateSplit[] = startDate.split(" "); //split on space if(startDateSplit.length>2){ startDate = startDateSplit[0]+" "+startDateSplit[1]; } course1.addStartDate(startDate); //course image Elements ele4 = doc2.select("meta"); for(Element ay: ele4){ if(ay.attr("content").contains("https://ugc")){ String crsImgLink = ay.attr("content"); course1.addCourseImage(crsImgLink); } } //course category //course category is determined by the current index of the course page course1.setCategory(pgcrsNames.get(a));//get the corresponding name for the category course1.setTimeScraped( LocalDate.now().toString()+" "+LocalTime.now().toString()); allCourses.add(course1); //we add the course to the arraylist of all courses System.out.println(course1.toString()); //store each course to database // storeToMySQL(course1); i++;//increment course_id } } } private static void storeToMySQL(Course crs){ try{ //connection to MySQL Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/cs160","root",""); String query1 = "INSERT INTO coursedetails (id, profname, profimage, course_id)" + " VALUES (\"" + 1 + "\", \"" + crs.getInstructorNames() + "\", \"" + crs.getInstructorImages() + "\", \"" + crs.getCourseId() + "\")"; String query2 = "INSERT INTO course_data (id, title,short_desc,long_desc, course_link, video_link, start_date, startDates, courseLengths, course_image, category, courseImages, site, course_fee, language, certificate, university, time_scraped)" + " VALUES (\"" + crs.getCourseId() + "\", \"" + crs.getCourseName() + "\", \"" + crs.getShortDesc() + "\", \"" + crs.getLongDescription() + "\", \"" + crs.getUrl() + "\", \"" + crs.getVideoLink() + "\", \"" + crs.getStartDates() + "\", \"" + crs.getCourseLength() + "\", \"" + crs.getCourseImages() + "\", \"" + crs.getCategory() + "\", \"" + crs.site + "\", \"" + crs.getCourse_fee() + "\", \"" + crs.getLanguage() + "\", \"" + crs.getCertificate() + "\", \"" + crs.getUniversity() + "\", \"" + crs.getTimeScraped() + "\")"; Statement stat = conn.createStatement(); stat.executeUpdate(query1); //stat.executeUpdate(query2); } catch(Exception e) { System.out.println(e); } } }
package com.axelby.podax; import android.app.ListActivity; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; import android.widget.ResourceCursorAdapter; import android.widget.TextView; public class PodcastListActivity extends ListActivity { static final int OPTION_ADDTOQUEUE = 3; static final int OPTION_REMOVEFROMQUEUE = 1; static final int OPTION_PLAY = 2; private int _subscriptionId; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = this.getIntent(); _subscriptionId = intent.getIntExtra("subscriptionId", -1); if (_subscriptionId == -1) { finish(); return; } if (!setTitle()) { finish(); return; } setContentView(R.layout.podcast_list); Uri uri = ContentUris.withAppendedId(SubscriptionProvider.URI, _subscriptionId); uri = Uri.withAppendedPath(uri, "podcasts"); String[] projection = { PodcastProvider.COLUMN_ID, PodcastProvider.COLUMN_TITLE, PodcastProvider.COLUMN_MEDIA_URL, PodcastProvider.COLUMN_FILE_SIZE, PodcastProvider.COLUMN_QUEUE_POSITION, }; Cursor cursor = getContentResolver().query(uri, projection, null, null, null); getListView().setAdapter(new PodcastAdapter(this, cursor)); getListView().setOnCreateContextMenuListener(new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Cursor cursor = (Cursor) getListView().getItemAtPosition(info.position); PodcastCursor podcast = new PodcastCursor(PodcastListActivity.this, cursor); try { if (podcast.getQueuePosition() == null) menu.add(ContextMenu.NONE, OPTION_ADDTOQUEUE, ContextMenu.NONE, R.string.add_to_queue); else menu.add(ContextMenu.NONE, OPTION_REMOVEFROMQUEUE, ContextMenu.NONE, R.string.remove_from_queue); if (podcast.isDownloaded()) menu.add(ContextMenu.NONE, OPTION_PLAY, ContextMenu.NONE, R.string.play); } catch (MissingFieldException e) { e.printStackTrace(); } } }); } public boolean setTitle() { // set the title before loading the layout Uri subscriptionUri = ContentUris.withAppendedId(SubscriptionProvider.URI, _subscriptionId); String[] subscriptionProjection = { SubscriptionProvider.COLUMN_ID, SubscriptionProvider.COLUMN_TITLE, }; Cursor subscriptionCursor = getContentResolver().query(subscriptionUri, subscriptionProjection, null, null, null); if (!subscriptionCursor.moveToNext()) { return false; } SubscriptionCursor subscription = new SubscriptionCursor(this, subscriptionCursor); try { setTitle(subscription.getTitle() + " Podcasts"); } catch (MissingFieldException e1) { e1.printStackTrace(); return false; } finally { subscriptionCursor.close(); } return true; } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo(); Cursor cursor = (Cursor) getListView().getItemAtPosition(info.position); PodcastCursor podcast = new PodcastCursor(this, cursor); try { switch (item.getItemId()) { case OPTION_ADDTOQUEUE: podcast.addToQueue(); break; case OPTION_REMOVEFROMQUEUE: podcast.removeFromQueue(); break; case OPTION_PLAY: PodaxApp.getApp().play(podcast); } } catch (MissingFieldException e) { e.printStackTrace(); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.podcast_list, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.refresh_subscription: UpdateService.updateSubscription(this, _subscriptionId); default: return super.onOptionsItemSelected(item); } } @Override protected void onListItemClick(ListView list, View view, int position, long id) { Intent intent = new Intent(this, PodcastDetailActivity.class); Cursor cursor = (Cursor) list.getItemAtPosition(position); PodcastCursor podcast = new PodcastCursor(this, cursor); try { intent.putExtra(Constants.EXTRA_PODCAST_ID, (int)(long)podcast.getId()); startActivity(intent); } catch (MissingFieldException e) { e.printStackTrace(); } } private class PodcastAdapter extends ResourceCursorAdapter { public PodcastAdapter(Context context, Cursor cursor) { super(context, R.layout.list_item, cursor); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView textview = (TextView)view; try { String podcastTitle = new PodcastCursor(context, cursor).getTitle(); textview.setText(podcastTitle); } catch (MissingFieldException e) { e.printStackTrace(); } } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.logging.Level; import org.lwjgl.input.Mouse; import java.util.logging.Logger; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import com.google.gson.Gson; import com.sun.security.ntlm.Client; import sun.print.resources.serviceui; public class SimpleSlickGame extends BasicGame implements Runnable { PrintStream pStream; BufferedReader bufInput; String answer = null; String textString; static Socket s; static Socket Sock; public static PrintStream ps; public static Train t; public static Stack t2; public static Stack t6; public static Stack t8; public static Connection t9; public static PlayerPiece t10; public static Card m1; // public static Town townA, townB; //commented these out, as the already // existed in SimpleSlick public static Card missionCard; public static ArrayList<Integer> arrayTest; public static Town tempCityB, tempCityA; public static Card tempCard; // Color counters static int blueColorCounter, redColorCounter, orangeColorCounter, whiteColorCounter, yellowColorCounter, blackColorCounter, greenColorCounter, pinkColorCounter; static Board board; private Image summaryBackImage = null; private Image summaryFrontImage = null; private Image missionCardBack = null; private Image trainCardBack = null; private Image blackTrainCard = null; private Image blueTrainCard = null; private Image greenTrainCard = null; private Image orangeTrainCard = null; private Image pinkTrainCard = null; private Image redTrainCard = null; private Image whiteTrainCard = null; private Image yellowTrainCard = null; // private Image rainbowTrainCard = null; without jokers private Image[] missions = null; private Color red, green, blue, yellow; private Image map = null; private boolean completedActions = false; private boolean isYourTurn = true; private boolean youPickedTrainCards = false; private boolean youPickedMissionCards = false; private boolean youPlayedAConnection = false; int xpos; int ypos; Input input; private Town townA = null; private Town townB = null; String activater = null; public ArrayList<Connection> connectionsToDraw = new ArrayList<Connection>(); Players player1 = new Players(1, board.colors[0]); Players player2 = new Players(2, board.colors[1]); Players player3 = new Players(3, board.colors[2]); Players player4 = new Players(4, board.colors[3]); ArrayList<Card> myHand; public Connection selectedConnection = null; public SimpleSlickGame(String gamename) { super("TicketToRide"); } @Override public void init(GameContainer gc) throws SlickException { // I don't know where this has to be loaded, but for now we can load all // images here // for (int flf = 0; flf < board.connections.size(); flf++) // connectionsToDraw.add(board.connections.get(5)); map = new Image("/pics/Map.jpg"); board.setBoardPic(map); // Setting som colors for the playerpieces red = new Color(255, 0, 0); green = new Color(0, 255, 0); blue = new Color(0, 0, 255); yellow = new Color(255, 255, 0); board.playerPieces[0].setColor(new Color(red)); board.playerPieces[1].setColor(new Color(green)); board.playerPieces[2].setColor(new Color(blue)); board.playerPieces[3].setColor(new Color(yellow)); // Setting the images for the summaryCard summaryBackImage = new Image("/pics/summaryBack.jpg"); summaryFrontImage = new Image("/pics/summaryFront.jpg"); board.summaryCard.setBackImage(summaryBackImage); board.summaryCard.setFrontImage(summaryFrontImage); /* * Setting cardback and cardfront for the trainCards * Cardback is the same for all the trainCards */ trainCardBack = new Image("/pics/trainCardBack.png"); for (int i = 0; i < board.trainCards.length; i++) { board.trainCards[i].setBackImage(trainCardBack); } // Applying the cardback for the stationary image for train cards board.stationaryCardT.setBackImage(trainCardBack); // Loading all the trainCardImages blackTrainCard = new Image("/pics/blackTrainCard.png"); blueTrainCard = new Image("/pics/blueTrainCard.png"); greenTrainCard = new Image("/pics/greenTrainCard.png"); orangeTrainCard = new Image("/pics/orangeTrainCard.png"); pinkTrainCard = new Image("/pics/pinkTrainCard.png"); redTrainCard = new Image("/pics/redTrainCard.png"); whiteTrainCard = new Image("/pics/whiteTrainCard.png"); yellowTrainCard = new Image("/pics/yellowTrainCard.png"); // rainbowTrainCard = new Image("/rainbowTrainCard.png"); without jokers // Applying the trainCardImages to the correct spot within the array. for (int i = 0; i < 12; i++) { board.trainCards[i].setFrontImage(blueTrainCard); } for (int i = 12; i < 24; i++) { board.trainCards[i].setFrontImage(redTrainCard); } for (int i = 24; i < 36; i++) { board.trainCards[i].setFrontImage(orangeTrainCard); } for (int i = 36; i < 48; i++) { board.trainCards[i].setFrontImage(whiteTrainCard); } for (int i = 48; i < 60; i++) { board.trainCards[i].setFrontImage(yellowTrainCard); } for (int i = 60; i < 72; i++) { board.trainCards[i].setFrontImage(blackTrainCard); } for (int i = 72; i < 84; i++) { board.trainCards[i].setFrontImage(greenTrainCard); } for (int i = 84; i < 96; i++) { board.trainCards[i].setFrontImage(pinkTrainCard); } // for (int i = 96; i < 110; i++) { // board.trainCards[i].setFrontImage(rainbowTrainCard); // no jokers atm missions = new Image[30]; missionCardBack = new Image("/pics/missionCardBack.png"); // Loading and applying the missionCards and setting the cardback for // the missioncards for (int i = 0; i < board.missionCards.length; i++) { missions[i] = new Image("/pics/misssion(" + i + ").jpg"); board.missionCards[i].setFrontImage(missions[i]); board.missionCards[i].setBackImage(missionCardBack); } // Applying the cardback for the stationary image for mission cards board.stationaryCardM.setBackImage(missionCardBack); } @Override public void update(GameContainer gc, int i) throws SlickException { Input input = gc.getInput(); xpos = Mouse.getX(); ypos = Mouse.getY(); // Will implement what happens when you click a city in here. if (isYourTurn) { if (input.isMousePressed(0)) { for (int j = 0; j < board.towns.length; j++) { if (xpos < board.towns[j].getxPos() + 10 && xpos >= board.towns[j].getxPos() - 10 && ypos < board.towns[j].getyPos() + 10 && ypos > board.towns[j].getyPos() - 10) { System.out.println("You have selected " + board.towns[j].getName()); if (townA == null) { townA = board.towns[j]; System.out.println(townA.getName() + " has been clicked as town A"); } else if (townB == null) { townB = board.towns[j]; System.out.println(townB.getName() + " has been clicked as town B"); } } } if (townA != null && townB != null) { if (findConnectionToBuild(townA, townB) == null) { townA = null; townB = null; } else { selectedConnection = findConnectionToBuild(townA, townB); connectionsToDraw.add(selectedConnection); // playCards(); completedActions = true; youPlayedAConnection = true; System.out.println("The selected connection require " + selectedConnection.getLength() + " trains with the color " + selectedConnection.getColor().getColorName()); } } // System.out.println(townB.getName() + " " + townA.getName()); /* * SUMMARY CARD FLIP CARD */ if (xpos < board.summaryCard.xPos + board.summaryCard.width && xpos > board.summaryCard.xPos && ypos > 768 - board.summaryCard.height) { board.summaryCard.flipCard(); } /* * SUMMARY CARD FLIP CARD * Mouse input conditions to flip the summary card */ if (xpos < board.summaryCard.xPos + Card.width && xpos > board.summaryCard.xPos && ypos > 768 - Card.height) { board.summaryCard.flipCard(); } /* * MISSIONCARDSTACK FUNCTIONALITY * MISSIONCARDSTACK TO HANDSTACK * Mouse input conditions to do the following * add the top card of the drawable mission card stack to the mission card hand stack for player 1 * remove that card from the drawable mission card stack * this will make the mission cards in the array list move 1 room to the left (decrease by 1) */ if (xpos < board.missionCardStack.xPos + Card.width && xpos > board.missionCardStack.xPos && ypos > 768 - Card.height) { System.out.println("mission stack clicked"); board.player1MissionHandStack.add(board.arrayOfMissionCards.get(0)); board.arrayOfMissionCards.remove(0); System.out.println(board.player1MissionHandStack.size()); } /* * TRAINCARDSTACK FUNCTIONALITY * TRAINCARDSTACK TO HANDSTACK * Mouse input conditions to do the following * add the top card of the drawable train card stack to the train card hand stack for player 1 * remove that card from the drawable train card stack * this will make the train cards in the array list move 1 room to the left (decrease by 1) */ if (xpos < board.trainCardStack.xPos + Card.width && xpos > board.trainCardStack.xPos && ypos < 768 - Card.height && ypos > 768 - 2 * Card.height) { System.out.println("face-down train card stack has been clicked"); if (board.arrayOfTrainCards.get(0).getColor().getColorName() == board.colors[0].getColorName()) { blueColorCounter ++; } else if (board.arrayOfTrainCards.get(0).getColor().getColorName() == board.colors[1].getColorName()) { redColorCounter++; } else if (board.arrayOfTrainCards.get(0).getColor().getColorName() == board.colors[2].getColorName()) { orangeColorCounter++; } else if (board.arrayOfTrainCards.get(0).getColor().getColorName() == board.colors[3].getColorName()) { whiteColorCounter++; } else if (board.arrayOfTrainCards.get(0).getColor().getColorName() == board.colors[4].getColorName()) { yellowColorCounter++; } else if (board.arrayOfTrainCards.get(0).getColor().getColorName() == board.colors[5].getColorName()) { blackColorCounter++; } else if (board.arrayOfTrainCards.get(0).getColor().getColorName() == board.colors[7].getColorName()) { greenColorCounter++; } else if (board.arrayOfTrainCards.get(0).getColor().getColorName() == board.colors[8].getColorName()) { pinkColorCounter++; } board.player1TrainHandStack.add(board.arrayOfTrainCards.get(0)); board.arrayOfTrainCards.remove(0); for (int j = 0; j < board.player1TrainHandStack.size(); j++) { System.out.println(board.player1TrainHandStack.get(j).getColor().getColorName()); } System.out.println(board.player1TrainHandStack.size()); } /* * DISPLAYED STACK OF TRAINCARDS FUNCTIONALITY. * The following is the structure for all the 5 rooms in the displayed hand stack array list * Mouse input conditions to do the following * check what color the card is and increment the proper color counter * add the top card of the drawable train card stack to the train card hand stack for player 1 * remove that card from the drawable train card stack * reassign y positions for the cards in the drawable/displayed train stack * this will make the train cards in the array list move 1 room to the left (decrease by 1) */ /* * 1ST ROOM: FUNCTIONALITY IN DISPLAYED CARD TO HANDSTACK */ if (xpos < board.trainCardStack.xPos + Card.width && xpos > board.trainCardStack.xPos && ypos < 768 - 2 * Card.height && ypos > 768 - 3 * Card.height) { System.out.println("Displayed train card #0 has been clicked"); if (board.displayedTrainStack.get(0).getColor().getColorName() == board.colors[0].getColorName()) { blueColorCounter ++; } else if (board.displayedTrainStack.get(0).getColor().getColorName() == board.colors[1].getColorName()) { redColorCounter++; } else if (board.displayedTrainStack.get(0).getColor().getColorName() == board.colors[2].getColorName()) { orangeColorCounter++; } else if (board.displayedTrainStack.get(0).getColor().getColorName() == board.colors[3].getColorName()) { whiteColorCounter++; } else if (board.displayedTrainStack.get(0).getColor().getColorName() == board.colors[4].getColorName()) { yellowColorCounter++; } else if (board.displayedTrainStack.get(0).getColor().getColorName() == board.colors[5].getColorName()) { blackColorCounter++; } else if (board.displayedTrainStack.get(0).getColor().getColorName() == board.colors[7].getColorName()) { greenColorCounter++; } else if (board.displayedTrainStack.get(0).getColor().getColorName() == board.colors[8].getColorName()) { pinkColorCounter++; } board.player1TrainHandStack.add(board.displayedTrainStack.get(0)); board.displayedTrainStack.remove(0); board.displayedTrainStack.add(0, board.arrayOfTrainCards.get(0)); board.arrayOfTrainCards.remove(0); board.displayedTrainStack.get(0).yPos = 170; board.displayedTrainStack.get(1).yPos = 255; board.displayedTrainStack.get(2).yPos = 340; board.displayedTrainStack.get(3).yPos = 425; board.displayedTrainStack.get(4).yPos = 510; for (int j = 0; j < board.player1TrainHandStack.size(); j++) { System.out.println(board.player1TrainHandStack.get(j).getColor().getColorName()); } System.out.println(board.player1TrainHandStack.size()); System.out.println("b:"+ blueColorCounter + " r:" + redColorCounter + " o:" +orangeColorCounter + " w:" +whiteColorCounter + " y:" + yellowColorCounter + " b:" +blackColorCounter + " g:" +greenColorCounter + " p:" + pinkColorCounter); } /* * 2ND ROOM: FUNCTIONALITY IN 2ND DISPLAYED CARD TO HANDSTACK */ if (xpos < board.trainCardStack.xPos + Card.width && xpos > board.trainCardStack.xPos && ypos < 768 - 3 * Card.height && ypos > 768 - 4 * Card.height) { System.out.println("Displayed train card #1 has been clicked"); if (board.displayedTrainStack.get(1).getColor().getColorName() == board.colors[0].getColorName()) { blueColorCounter ++; } else if (board.displayedTrainStack.get(1).getColor().getColorName() == board.colors[1].getColorName()) { redColorCounter++; } else if (board.displayedTrainStack.get(1).getColor().getColorName() == board.colors[2].getColorName()) { orangeColorCounter++; } else if (board.displayedTrainStack.get(1).getColor().getColorName() == board.colors[3].getColorName()) { whiteColorCounter++; } else if (board.displayedTrainStack.get(1).getColor().getColorName() == board.colors[4].getColorName()) { yellowColorCounter++; } else if (board.displayedTrainStack.get(1).getColor().getColorName() == board.colors[5].getColorName()) { blackColorCounter++; } else if (board.displayedTrainStack.get(1).getColor().getColorName() == board.colors[7].getColorName()) { greenColorCounter++; } else if (board.displayedTrainStack.get(1).getColor().getColorName() == board.colors[8].getColorName()) { pinkColorCounter++; } board.player1TrainHandStack.add(board.displayedTrainStack.get(1)); board.displayedTrainStack.remove(1); board.displayedTrainStack.add(1, board.arrayOfTrainCards.get(0)); board.arrayOfTrainCards.remove(0); board.displayedTrainStack.get(0).yPos = 170; board.displayedTrainStack.get(1).yPos = 255; board.displayedTrainStack.get(2).yPos = 340; board.displayedTrainStack.get(3).yPos = 425; board.displayedTrainStack.get(4).yPos = 510; for (int j = 0; j < board.player1TrainHandStack.size(); j++) { System.out.println(board.player1TrainHandStack.get(j).getColor().getColorName()); } System.out.println(board.player1TrainHandStack.size()); } /* * 3RD ROOM: FUNCTIONALITY IN 3RD DISPLAYED CARD TO HANDSTACK */ if (xpos < board.trainCardStack.xPos + Card.width && xpos > board.trainCardStack.xPos && ypos < 768 - 4 * Card.height && ypos > 768 - 5 * Card.height) { System.out.println("Displayed train card #2 has been clicked"); if (board.displayedTrainStack.get(2).getColor().getColorName() == board.colors[0].getColorName()) { blueColorCounter ++; } else if (board.displayedTrainStack.get(2).getColor().getColorName() == board.colors[1].getColorName()) { redColorCounter++; } else if (board.displayedTrainStack.get(2).getColor().getColorName() == board.colors[2].getColorName()) { orangeColorCounter++; } else if (board.displayedTrainStack.get(2).getColor().getColorName() == board.colors[3].getColorName()) { whiteColorCounter++; } else if (board.displayedTrainStack.get(2).getColor().getColorName() == board.colors[4].getColorName()) { yellowColorCounter++; } else if (board.displayedTrainStack.get(2).getColor().getColorName() == board.colors[5].getColorName()) { blackColorCounter++; } else if (board.displayedTrainStack.get(2).getColor().getColorName() == board.colors[7].getColorName()) { greenColorCounter++; } else if (board.displayedTrainStack.get(2).getColor().getColorName() == board.colors[8].getColorName()) { pinkColorCounter++; } board.player1TrainHandStack.add(board.displayedTrainStack.get(2)); board.displayedTrainStack.remove(2); board.displayedTrainStack.add(2, board.arrayOfTrainCards.get(0)); board.arrayOfTrainCards.remove(0); board.displayedTrainStack.get(0).yPos = 170; board.displayedTrainStack.get(1).yPos = 255; board.displayedTrainStack.get(2).yPos = 340; board.displayedTrainStack.get(3).yPos = 425; board.displayedTrainStack.get(4).yPos = 510; for (int j = 0; j < board.player1TrainHandStack.size(); j++) { System.out.println(board.player1TrainHandStack.get(j).getColor().getColorName()); } System.out.println(board.player1TrainHandStack.size()); } /* * 4TH ROOM: FUNCTIONALITY IN DISPLAYED CARD TO HANDSTACK */ if (xpos < board.trainCardStack.xPos + Card.width && xpos > board.trainCardStack.xPos && ypos < 768 - 5 * Card.height && ypos > 768 - 6 * Card.height) { System.out.println("Displayed train card #3 has been clicked"); if (board.displayedTrainStack.get(3).getColor().getColorName() == board.colors[0].getColorName()) { blueColorCounter ++; } else if (board.displayedTrainStack.get(3).getColor().getColorName() == board.colors[1].getColorName()) { redColorCounter++; } else if (board.displayedTrainStack.get(3).getColor().getColorName() == board.colors[2].getColorName()) { orangeColorCounter++; } else if (board.displayedTrainStack.get(3).getColor().getColorName() == board.colors[3].getColorName()) { whiteColorCounter++; } else if (board.displayedTrainStack.get(3).getColor().getColorName() == board.colors[4].getColorName()) { yellowColorCounter++; } else if (board.displayedTrainStack.get(3).getColor().getColorName() == board.colors[5].getColorName()) { blackColorCounter++; } else if (board.displayedTrainStack.get(3).getColor().getColorName() == board.colors[7].getColorName()) { greenColorCounter++; } else if (board.displayedTrainStack.get(3).getColor().getColorName() == board.colors[8].getColorName()) { pinkColorCounter++; } board.player1TrainHandStack.add(board.displayedTrainStack.get(3)); board.displayedTrainStack.remove(3); board.displayedTrainStack.add(3, board.arrayOfTrainCards.get(0)); board.arrayOfTrainCards.remove(0); board.displayedTrainStack.get(0).yPos = 170; board.displayedTrainStack.get(1).yPos = 255; board.displayedTrainStack.get(2).yPos = 340; board.displayedTrainStack.get(3).yPos = 425; board.displayedTrainStack.get(4).yPos = 510; for (int j = 0; j < board.player1TrainHandStack.size(); j++) { System.out.println(board.player1TrainHandStack.get(j).getColor().getColorName()); } System.out.println(board.player1TrainHandStack.size()); } /* * 5RD ROOM: FUNCTIONALITY IN 5TH DISPLAYED CARD TO HANDSTACK */ if (xpos < board.trainCardStack.xPos + Card.width && xpos > board.trainCardStack.xPos && ypos < 768 - 6 * Card.height && ypos > 768 - 7 * Card.height) { System.out.println("Displayed train card #4 has been clicked"); if (board.displayedTrainStack.get(4).getColor().getColorName() == board.colors[0].getColorName()) { blueColorCounter ++; } else if (board.displayedTrainStack.get(4).getColor().getColorName() == board.colors[1].getColorName()) { redColorCounter++; } else if (board.displayedTrainStack.get(4).getColor().getColorName() == board.colors[2].getColorName()) { orangeColorCounter++; } else if (board.displayedTrainStack.get(4).getColor().getColorName() == board.colors[3].getColorName()) { whiteColorCounter++; } else if (board.displayedTrainStack.get(4).getColor().getColorName() == board.colors[4].getColorName()) { yellowColorCounter++; } else if (board.displayedTrainStack.get(4).getColor().getColorName() == board.colors[5].getColorName()) { blackColorCounter++; } else if (board.displayedTrainStack.get(4).getColor().getColorName() == board.colors[7].getColorName()) { greenColorCounter++; } else if (board.displayedTrainStack.get(4).getColor().getColorName() == board.colors[8].getColorName()) { pinkColorCounter++; } board.player1TrainHandStack.add(board.displayedTrainStack.get(4)); board.displayedTrainStack.remove(4); board.displayedTrainStack.add(4, board.arrayOfTrainCards.get(0)); board.arrayOfTrainCards.remove(0); board.displayedTrainStack.get(0).yPos = 170; board.displayedTrainStack.get(1).yPos = 255; board.displayedTrainStack.get(2).yPos = 340; board.displayedTrainStack.get(3).yPos = 425; board.displayedTrainStack.get(4).yPos = 510; for (int j = 0; j < board.player1TrainHandStack.size(); j++) { System.out.println(board.player1TrainHandStack.get(j).getColor().getColorName()); } System.out.println(board.player1TrainHandStack.size()); } if (xpos < board.button.getxPos() + board.button.getWidth() && xpos > board.button.getxPos() && ypos < 768 - board.button.getyPos() && ypos > 768 - board.button.getyPos() - board.button.getHeight() && completedActions == true) { if (youPickedMissionCards) { System.out.println("YouPickedMissionCards"); // Space for what should be send to the client activater = "state1"; run(); isYourTurn = false; } if (youPickedTrainCards) { System.out.println("YouPickedTrainCards"); // Space for what should be send to the client activater = "state2"; run(); isYourTurn = false; } if (youPlayedAConnection) { System.out.println("youPlayedAConnection"); // Space for what should be send to the client activater = "state3"; run(); isYourTurn = false; } } } } } private Connection findConnectionToBuild(Town town1, Town town2) { for (int i = 0; i < board.connections.size(); i++) { if (board.connections.get(i).getTownA().getName() == town1.getName() || board.connections.get(i).getTownA().getName() == town2.getName()) { // Keeps looking for the right connection if (board.connections.get(i).getTownB().getName() == town1.getName() || board.connections.get(i).getTownB().getName() == town2.getName()) { System.out.println("These are neighbours"); if (!board.connections.get(i).getIsTaken()) return board.connections.get(i); } } /* * else { System.out.println( * "You probably didnt click two neighbouring cities, or no connections are available between these two cities" * ); } */ } return null; } @Override public void render(GameContainer gc, Graphics g) throws SlickException { // Loads the placement Map image used to detect cities board.getBoardPic().draw(); // Place it in (0,0) board.summaryCard.setVisible(); board.stationaryCardT.setVisible(); board.stationaryCardM.setVisible(); // board.connections.get(2).setTakenByPlayer(player1, g); for (int i = 0; i < 5; i++) { board.displayedTrainStack.get(i).setVisible1(); } // for the mission cards visualization // for (int i = 0; i < board.player1MissionHandStack.size(); i++) { // board.player1MissionHandStack.get(i).setVisible1(); // Setting the visibility of the playerpieces for (int i = 0; i < board.playerPieces.length; i++) { board.playerPieces[i].setVisible(g); } // Drawing the string counters for the cards determined by color board.button.setVisible(g, 0); g.drawString("" + pinkColorCounter, 250, 750); g.drawString("" + whiteColorCounter, 322, 750); g.drawString("" + blueColorCounter, 394, 750); g.drawString("" + yellowColorCounter, 466, 750); g.drawString("" + orangeColorCounter, 538, 750); g.drawString("" + blackColorCounter, 610, 750); g.drawString("" + redColorCounter, 682, 750); g.drawString("" + greenColorCounter, 744, 750); // We have to loop through all the players and display their cards in these areas.! if (board.player2TrainHandStack.size()!=0) { g.drawString("Player? tcards: " + board.player2TrainHandStack.size(), 20, 15); } else { g.drawString("Player? tcards: 0", 20, 15); } if (board.player2MissionHandStack.size()!=0) { g.drawString("Player? mcards: " + board.player2MissionHandStack.size(), 20, 30); } else { g.drawString("Player? mcards: 0", 20, 30); } if (/*Something with the trains*/ 50<20) { //g.drawString("Player? trains: " + board.player2trains.size(), 20, 45); } else { g.drawString("Player? tcards: 0", 20, 45); } board.button.setVisible(g, 0); if (completedActions) board.button.setVisible(g, 1); for (int j = 0; j < connectionsToDraw.size(); j++) { connectionsToDraw.get(j).drawConnection(player2, g); board.playerPieces[player1.playerNum].move(connectionsToDraw.get(j).getPoint()); } } public static void main(String[] args) throws SlickException, UnknownHostException, IOException { board = new Board(4); s = new Socket("172.20.10.2", 2222); SimpleSlickGame client = new SimpleSlickGame("Ticket to Ride"); Thread t1 = new Thread(client); t1.start(); try { AppGameContainer appgc; appgc = new AppGameContainer(new SimpleSlickGame("Simple Slick Game")); appgc.setDisplayMode(1024, 768, false); appgc.start(); } catch (SlickException ex) { Logger.getLogger(SimpleSlickGame.class.getName()).log(Level.SEVERE, null, ex); } } public void run() { try { PrintStream ps = new PrintStream(s.getOutputStream()); Gson serializer = new Gson(); if (activater != null) { ps.println(activater); activater = null; } // This is where we start sending the JSONS InputStreamReader ir = new InputStreamReader(s.getInputStream()); BufferedReader br = new BufferedReader(ir); String whoAmI = br.readLine(); while (true) { //This is what all clients should receive on gamestart if (whoAmI.contains("1")) { for (int i=0; i<4; i++) { String temp = br.readLine(); Card c = new Gson().fromJson(temp, Card.class); board.player1TrainHandStack.add(c); System.out.println(board.player1TrainHandStack.size()); } } else if (whoAmI.contains("2")) { for (int i=0; i<4; i++) { String temp = br.readLine(); Card c = new Gson().fromJson(temp, Card.class); board.player1TrainHandStack.add(c); System.out.println("I am 2" + board.player1TrainHandStack.size()); } } else if (whoAmI.contains("3")) { for (int i=0; i<4; i++) { String temp = br.readLine(); Card c = new Gson().fromJson(temp, Card.class); board.player1TrainHandStack.add(c); System.out.println("I am 3" + board.player1TrainHandStack.size()); } } else if (whoAmI.contains("4")) { for (int i=0; i<4; i++) { String temp = br.readLine(); Card c = new Gson().fromJson(temp, Card.class); board.player1TrainHandStack.add(c); System.out.println("I am 4" + board.player1TrainHandStack.size()); } } String Message = br.readLine(); System.out.println(Message); if (br.readLine().contains("CanAct")) { isYourTurn = true; } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package model; import static lookup.Pieces.*; import static lookup.Masks.*; import static lookup.Coordinates.*; import static lookup.PieceTables.*; import java.util.ArrayList; /** * A Chess Board implementation using the 0x88 board representation. * * @author Gary Blackwood */ public class Board { private byte[] squares = null; private byte turnColour = 0; private Move previousMove = null; private int whiteKingPosition = 0; private int blackKingPosition = 0; private ArrayList<Move> validMoves = new ArrayList<Move>(); private ArrayList<Byte> whitePiecesCaptured = new ArrayList<Byte>(); private ArrayList<Byte> blackPiecesCaptured = new ArrayList<Byte>(); private int score = 0; private int amountOfMoves = 0; /** * Initialise and create the board to contain chess pieces arranged in an order such that the resulting positions represent * a valid chess starting position. */ public Board() { this.squares = new byte[]{ ROOK, KNIGHT, BISHOP, QUEEN, KING, BISHOP, KNIGHT, ROOK, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, BPAWN, BPAWN, BPAWN, BPAWN, BPAWN, BPAWN, BPAWN, BPAWN, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, BROOK, BKNIGHT, BBISHOP, BQUEEN, BKING, BBISHOP, BKNIGHT, BROOK, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY }; this.turnColour = WHITE; this.previousMove = null; this.whiteKingPosition = E1; this.blackKingPosition = E8; this.validMoves = generateValidMoves(); this.whitePiecesCaptured = new ArrayList<Byte>(); this.blackPiecesCaptured = new ArrayList<Byte>(); this.score = 0; this.amountOfMoves = 0; } /** * Construct a new chess board which is a copy of a supplied board. * * @param board - The chess board to copy. */ public Board( Board board ) { this.squares = board.getSquares(); this.turnColour = board.getTurnColour(); this.previousMove = board.getPreviousMove(); this.whiteKingPosition = board.getWhiteKingPosition(); this.blackKingPosition = board.getBlackKingPosition(); this.validMoves = board.getValidMoves(); this.whitePiecesCaptured = board.getWhitePiecesCaptured(); this.blackPiecesCaptured = board.getBlackPiecesCaptured(); this.score = board.getScore(); this.amountOfMoves = board.getAmountOfMoves(); } /** * Returns a list of all white pieces captured by the black player. * * @return A list of all white pieces captured. */ private ArrayList<Byte> getWhitePiecesCaptured() { return ( new ArrayList<Byte>( this.whitePiecesCaptured ) ); } /** * Returns a list of all black pieces captured by the white player. * * @return A list of all black pieces captured. */ private ArrayList<Byte> getBlackPiecesCaptured() { return ( new ArrayList<Byte>( this.blackPiecesCaptured ) ); } /** * Return the zero sum material score of the board. * * @return The zero sum material score. */ private int getScore() { return ( this.score ); } /** * Return the byte array of chess board squares. * * @return The array of chess board squares as bytes. */ public byte[] getSquares() { return ( this.squares.clone() ); } /** * What is the colour of the player to move? * * @return A byte representing the colour of the player whos turn it is currently. */ public byte getTurnColour() { return ( this.turnColour ); } /** * How many moves have been made since board creation? * * @return The number of moves made since the board was created. */ public int getAmountOfMoves() { return this.amountOfMoves; } /** * Get the last move made on the board. * * @return The last move that was made on the board. */ private Move getPreviousMove() { return ( this.previousMove ); } /** * Which square is the white king located on? * * @return The square index of the white king position. */ public int getWhiteKingPosition() { return ( this.whiteKingPosition ); } /** * Which square is the black king located on? * * @return The square index of the black king position. */ public int getBlackKingPosition() { return ( this.blackKingPosition ); } /** * Which square is the current players king on? * * @return The square index of the current players king. */ public int getKingPosition() { if ( isWhiteTurn() == true){ return this.whiteKingPosition; }else{ return this.blackKingPosition; } } /** * Which square is the opponent of the current players king on? * * @return The square index of opponent of the current players king. */ private int getOpposingKingPosition() { if (isWhiteTurn() == true){ return this.blackKingPosition; }else{ return this.whiteKingPosition; } } /** * Is the square mapped to by the given index empty? * * @param position The square index. * * @return True if there are no pieces on the square, false otherwise. */ private boolean squareEmpty( int position ) { if ( pieceAt( position ) == EMPTY ){ return true; }else{ return false; } } /** * Get the piece located on the square mapped to by the given index. * * @param position The square index. * * @return A byte representation of the piece located at 'position'. */ private byte pieceAt( int position ) { if ( ( position & 0x88 ) == VALID ) { return ( this.squares[ position ] ); } return ( EMPTY ); } /** * What colour is the piece on the square mapped to by the given index? * * @param position The square index. * * @return The colour, as a byte, of the piece. */ public byte pieceColourAt( int position ) { return ( (byte)( pieceAt( position ) & COLOUR_MASK ) ); } /** * What is the type of the given piece? * * @param piece The piece to check. * * @return A byte representing the piece type. */ public static byte pieceType( byte piece ) { return ( (byte)( piece & PIECE_MASK ) ); } /** * What is the colour of the given piece? * * @param piece The piece to check. * * @return A byte representing the piece colour. */ public static byte pieceColour( byte piece ) { return ( (byte)( piece & COLOUR_MASK ) ); } /** * What is the type of the piece located at the given square index? * * @param position The square index. * * @return A byte representing the piece type. */ public byte pieceTypeAt( int position ) { return ( (byte)( pieceAt( position ) & PIECE_MASK ) ); } /** * Is the given square index within the playable game area? * * @param destination The square index to check. * * @return True if the destination square index is on the playable chess board, false otherwise. */ private boolean isValidDestination( int destination ) { if ( ( ( destination & 0x88 ) == VALID ) && ( squareEmpty( destination ) || ( pieceColourAt( destination ) != this.turnColour ) ) ) { return true; }else { return false; } } /** * Is the piece located at the given square index white? * * @param position The square index. * * @return True if the piece is white, false otherwise. */ private boolean isWhitePiece( int position ) { if ( pieceColourAt( position ) == WHITE ){ return true; }else{ return false; } } /** * Can the given move be played on the chess board? * * @param move The move to check the validity of. * * @return True if the move is valid, false otherwise. */ public boolean isValidMove( Move move ) { if ( this.validMoves.contains( move ) == true ){ return true; }else{ return false; } } /** * Set the bit that represents whether or not a piece has moved. * * @param position The square index at which to set the bit. */ private void setMovementBit( int position ) { this.squares[ position ] |= MOVED; } /** * Has a given piece made at least one move? * * @param piece The piece to check. * * @return True if the piece has moved, false otherwise. */ private static boolean hasPieceMoved( byte piece ) { if ( ( piece & MOVED_MASK ) == MOVED ){ return true; }else{ return false; } } /** * Does the current board state represent a checkmate situation? * * @return True if checkmate, false otherwise. */ public boolean isCheckmate() { if ( this.validMoves.size() == 0 && kingInCheck() ){ return true; }else{ return false; } } /** * Does the current board state represent a stalemate situation? * * @return True if stalemate, false otherwise. */ public boolean isStalemate() { if ( this.validMoves.size() == 0 && !kingInCheck() ){ return true; }else{ return false; } } /** * Is is the white players turn to move? * * @return True if it is the white players turn to move, false otherwise. */ private boolean isWhiteTurn() { if ( this.turnColour == WHITE ){ return true; }else{ return false; } } /** * Set the position of the current players king to a new square. * * @param position The new square index. */ private void setKingPosition( int position ) { if ( isWhiteTurn() ) { this.whiteKingPosition = position; } else { this.blackKingPosition = position; } } /** * Return the colour of the current players opponent. * * @return A byte representation of the opponents colour. */ private byte opponentColour() { if ( isWhiteTurn() ){ return BLACK; }else{ return WHITE; } } /** * Does the given move perform a king or queenside castle? * * @param move The move to check. * * @return True if the move performs a castling, false otherwise. */ private boolean isCastle( Move move ) { return ( isKingMove( move ) && Math.abs( move.to() - move.from() ) == 2 ); } /** * Perform the castling move contained in 'move'. * * @param move - The castling move to perform. */ private void performCastle( Move move ) { if ( move.to() > move.from() ) { performCastleKingSide( getKingPosition() ); } else { performCastleQueenSide( getKingPosition() ); } if ( isWhiteTurn() ) { score += 30; } else { score -= 30; } setKingPosition( move.to() ); } /** * Perform a kingside castling for the king located at 'kingPosition'. * * @param kingPosition - The position of the king to castle. */ private void performCastleKingSide( int kingPosition ) { this.squares[ kingPosition + 1 ] = this.squares[ kingPosition + 3 ]; this.squares[ kingPosition + 3 ] = EMPTY; this.squares[ kingPosition + 2 ] = this.squares[ kingPosition ]; this.squares[ kingPosition ] = EMPTY; } /** * Perform a queenside castling for the king located at 'kingPosition'. * * @param kingPosition - The position of the king to castle. */ private void performCastleQueenSide( int kingPosition ) { this.squares[ kingPosition - 1 ] = this.squares[ kingPosition - 4 ]; this.squares[ kingPosition - 4 ] = EMPTY; this.squares[ kingPosition - 2 ] = this.squares[ kingPosition ]; this.squares[ kingPosition ] = EMPTY; } /** * Is the given move an en passent move? * * @param move - The move to check. * * @return True if the move performs en passent, false otherwise. */ private boolean isEnPassant( Move move ) { return ( ( Math.abs( move.to() - move.from() ) == 17 || Math.abs( move.to() - move.from() ) == 15 ) && squareEmpty( move.to() ) && isPawnMove( move ) ); } /** * Is a pawn being moved? * * @param move - The move to check. * * @return True if a pawn is being moved. */ private boolean isPawnMove( Move move ) { if ( pieceTypeAt( move.from() ) == PAWN ) { return true; } else { return false; } } /** * Is a rook being moved? * * @param move - The move to check. * * @return True if a rook is being moved. */ private boolean isRookMove( Move move ) { if ( pieceTypeAt( move.from() ) == ROOK ) { return true; } else { return false; } } /** * Is a king being moved? * * @param move - The move to check. * * @return True if a king is being moved. */ private boolean isKingMove( Move move ) { if ( pieceTypeAt( move.from() ) == KING ) { return true; } else { return false; } } /** * Does the move result in a pawn promotion? * * @param move - The move to check. */ private boolean isPawnPromotion( Move move ) { if ( isPawnMove( move ) && ( ( move.to() >= A1 && move.to() <= H1 ) || ( move.to() >= A8 && move.to() <= H8 ) ) ) { return true; } else { return false; } } /** * Promote the pawn located on the given square. * * @param pawnPosition - The square index of the pawn to promote. */ private void promotePawn( int pawnPosition ) { this.squares[ pawnPosition ] = isWhiteTurn() ? QUEEN : BQUEEN; } /** * Perform the supplied move on the board. * * @param move - The move to make. */ public void makeMove( Move move ) { setMovementBit( move.from() ); if ( isPawnMove( move ) ) { setMovementBit( move.from() ); if ( isEnPassant( move ) ) { if ( isWhiteTurn() ) { updateScore( move.to() - 16 ); this.squares[ move.to() - 16 ] = EMPTY; this.squares[ move.to() ] = this.squares[ move.from() ]; this.squares[ move.from() ] = EMPTY; this.blackPiecesCaptured.add( PAWN ); } else { updateScore( move.to() + 16 ); this.squares[ move.to() + 16 ] = EMPTY; this.squares[ move.to() ] = this.squares[ move.from() ]; this.squares[ move.from() ] = EMPTY; this.whitePiecesCaptured.add( PAWN ); } this.turnColour = opponentColour(); this.previousMove = move; this.validMoves = generateValidMoves(); return; } else if ( isPawnPromotion( move ) ) { promotePawn( move.from() ); if ( isWhiteTurn() ) { score += 700; } else { score -= 700; } } } else if ( isKingMove( move ) ) { setMovementBit( move.from() ); if ( isCastle( move ) ) { performCastle( move ); setKingPosition( move.to() ); this.turnColour = opponentColour(); this.previousMove = move; this.validMoves = generateValidMoves(); return; } setKingPosition( move.to() ); } else if ( isRookMove( move ) ) { setMovementBit( move.from() ); } updateScore( move.to() ); if ( !squareEmpty( move.to() ) ) { if ( isWhiteTurn() ) { this.blackPiecesCaptured.add( this.squares[ move.to() ] ); } else { this.whitePiecesCaptured.add( this.squares[ move.to() ] ); } } else { //do nothing } this.squares[ move.to() ] = this.squares[ move.from() ]; this.squares[ move.from() ] = EMPTY; this.turnColour = opponentColour(); this.previousMove = move; this.validMoves = generateValidMoves(); this.amountOfMoves++; } /** * What is the value of the piece located on the given square index? * * @param position The index of the square the piece is on. * * @return A integer value of the piece worth. */ private int pieceValueAt( int position ) { switch ( pieceTypeAt( position ) ) { case PAWN: { return ( 100 ); } case KNIGHT: { return ( 325 ); } case BISHOP: { return ( 330 ); } case ROOK: { return ( 500 ); } case QUEEN: { return ( 900 ); } case KING: { return ( 20000 ); } default: { //do nothing } } return 0; } /** * Update the zero sum material balance score. * * @param position The index of the square at which a piece was captured. */ private void updateScore( int position ) { if ( this.turnColour == WHITE ) { score = score + pieceValueAt( position ); } else { score = score - pieceValueAt( position ); } } private boolean canMoveTo( int position, int destination ) { byte p = this.squares[ position ]; byte t = this.squares[ destination ]; if ( pieceType( p ) == KING ) { setKingPosition( destination ); } else { //do nothing } this.squares[ position ] = EMPTY; this.squares[ destination ] = p; boolean canMove = !kingInCheck(); if ( pieceType( p ) == KING ) { setKingPosition( position ); } else { //do nothing } this.squares[ position ] = p; this.squares[ destination ] = t; return ( canMove ); } /** * Is the current players king in check? * * @return True if the king is in check, false otherwise. */ public boolean kingInCheck() { return ( squareAttacked( getKingPosition() ) ); } /** * Is the square indexed by 'position' under attack from any opponent pieces? * * @param position The index of the square to check. * * @return True if at least one piece is attacking the square, false otherwise. */ private boolean squareAttacked( int position ) { int[] directions = new int[]{ 15, 17, -15, -17 }; for ( int direction : directions ) { for ( int i = 1; isValidDestination( position + i*direction ); i++ ) { if ( enemyPieceAt( position + i*direction ) ) { if ( pieceTypeAt( position + i*direction ) == QUEEN || pieceTypeAt( position + i*direction ) == BISHOP ) { return ( true ); } else if ( pieceTypeAt( position + i*direction ) == PAWN && i == 1 ) { if ( this.turnColour == WHITE ) { return ( direction == 15 || direction == 17 ); } else { //do nothing } return ( direction == -15 || direction == -17 ); } else { //do nothing } break; } else { //do nothing } } } for ( int direction : new int[]{ 1, -1, 16, -16 } ) { for ( int i = 1; isValidDestination( position + i*direction ); i++ ) { if ( enemyPieceAt( position + i*direction ) ) { if ( pieceTypeAt( position + i*direction ) == ROOK || pieceTypeAt( position + i*direction ) == QUEEN ) { return ( true ); } break; } else { //do nothing } } } directions = new int[]{ 18, 33, 31, 14, -18, -33, -31, -14 }; for ( int direction : directions ) { if ( isValidDestination( position + direction ) && enemyPieceAt( position + direction ) && pieceTypeAt( position + direction ) == KNIGHT ) { return ( true ); } else { //do nothing } } return ( false ); } /** * Obtain a list of all valid moves that can be played on the current board position. * * @return An ArrayList of all valid moves that can be played. */ public ArrayList<Move> getValidMoves() { return ( new ArrayList<Move>( this.validMoves ) ); } private ArrayList<Move> generateValidMoves() { ArrayList<Move> validMoves = new ArrayList<Move>(); for ( int rank = 0; rank < 8; rank++ ) { for ( int file = rank * 16 + 7; file >= rank * 16; file if ( !squareEmpty( file ) && pieceColourAt( file ) == this.turnColour ) { validMoves.addAll( generateValidMoves( pieceTypeAt( file ), file ) ); } else { //do nothing } } } return ( validMoves ); } /** * Generate all valid moves for the piece of type 'pieceType' located on square 'position'. * * @param pieceType The type of the piece to generate moves for. * @param position The index of the current square position of the piece. * * @return An ArrayList of all valid moves that the piece can make. */ public ArrayList<Move> generateValidMoves( byte pieceType, int position ) { ArrayList<Move> validMoves = new ArrayList<Move>(); ArrayList<Integer> destinations = generateDestinations( pieceType, position ); for ( int destination : destinations ) { if ( isValidDestination( destination ) && canMoveTo( position, destination ) ) { validMoves.add( new Move( position, destination ) ); } else { //do nothing } } return ( validMoves ); } /** * Generate all destinations for the piece of type 'pieceType' located on square 'position'. * * @param pieceType The type of the piece to generate moves for. * @param position The index of the current square position of the piece. * * @return An ArrayList of all destinations that the piece can move to. */ private ArrayList<Integer> generateDestinations( byte pieceType, int position ) { switch ( pieceType ) { case PAWN: { return ( generatePawnDestinations( position ) ); } case KNIGHT: { return ( generateKnightDestinations( position ) ); } case BISHOP: { return ( generateBishopDestinations( position ) ); } case ROOK: { return ( generateRookDestinations( position ) ); } case QUEEN: { return ( generateQueenDestinations( position ) ); } case KING: { return ( generateKingDestinations( position ) ); } default: { //do nothing } } return ( new ArrayList<Integer>() ); } /** * Generate the destinations for a pawn located at 'position'. * * @param position The index of the square the pawn is located. * * @return An ArrayList of all destinations that the pawn can move to. */ private ArrayList<Integer> generatePawnDestinations( int position ) { if ( isWhitePiece( position ) ) { return ( generateWhitePawnDestinations( position ) ); } else { //do nothing } return ( generateBlackPawnDestinations( position ) ); } /** * Generate the destinations for a white pawn located at 'position'. * * @param position The index of the square the white pawn is located. * * @return An ArrayList of all destinations that the white pawn can move to. */ public ArrayList<Integer> generateWhitePawnDestinations( int position ) { ArrayList<Integer> destinations = new ArrayList<Integer>(); if ( !hasPieceMoved( pieceAt( position ) ) && squareEmpty( position + 16 ) && squareEmpty( position + 32 ) ) { destinations.add( position + 32 ); } if ( !squareEmpty( position + 15 ) || whiteCanEnPassantLeft( position ) ) { destinations.add( position + 15 ); } if ( !squareEmpty( position + 17 ) || whiteCanEnPassantRight( position ) ) { destinations.add( position + 17 ); } if ( squareEmpty( position + 16 ) ) { destinations.add( position + 16 ); } return ( destinations ); } /** * Can the white pawn located at 'position' perform en passent to the left? * * @param position The index of the square the white pawn is located. * * @return True if the pawn can en passent left, false otherwise. */ private boolean whiteCanEnPassantLeft( int position ) { if ( this.previousMove != null && pieceTypeAt( position - 1 ) == PAWN && this.previousMove.from() == ( position + 31 ) && this.previousMove.to() == ( position - 1 )){ return true; } else { return false; } } /** * Can the white pawn located at 'position' perform en passent to the right? * * @param position The index of the square the white pawn is located. * * @return True if the pawn can en passent right, false otherwise. */ private boolean whiteCanEnPassantRight( int position ) { if ( this.previousMove != null && pieceTypeAt( position + 1 ) == PAWN && this.previousMove.from() == ( position + 33 ) && this.previousMove.to() == ( position + 1 ) ){ return true; } else { return false; } } /** * Generate the destinations for a black pawn located at 'position'. * * @param position The index of the square the black pawn is located. * * @return An ArrayList of all destinations that the black pawn can move to. */ public ArrayList<Integer> generateBlackPawnDestinations( int position ) { ArrayList<Integer> destinations = new ArrayList<Integer>(); if ( !hasPieceMoved( pieceAt( position ) ) && squareEmpty( position - 16 ) && squareEmpty( position - 32 ) ) { destinations.add( position - 32 ); } else { //do nothing } if ( !squareEmpty( position - 15 ) || blackCanEnPassantLeft( position ) ) { destinations.add( position - 15 ); } else { //do nothing } if ( !squareEmpty( position - 17 ) || blackCanEnPassantRight( position ) ) { destinations.add( position - 17 ); } else { //do nothing } if ( squareEmpty( position - 16 ) ) { destinations.add( position - 16 ); } else { //do nothing } return ( destinations ); } /** * Can the black pawn located at 'position' perform en passent to the left? * * @param position The index of the square the black pawn is located. * * @return True if the pawn can en passent left, false otherwise. */ private boolean blackCanEnPassantLeft( int position ) { if ( this.previousMove != null && pieceTypeAt( position + 1 ) == PAWN && this.previousMove.from() == ( position - 31 ) && this.previousMove.to() == ( position + 1 ) ){ return true; } else { return false; } } /** * Can the black pawn located at 'position' perform en passent to the right? * * @param position The index of the square the black pawn is located. * * @return True if the pawn can en passent right, false otherwise. */ private boolean blackCanEnPassantRight( int position ) { if ( this.previousMove != null && pieceTypeAt( position - 1 ) == PAWN && this.previousMove.from() == ( position - 33 ) && this.previousMove.to() == ( position -1 ) ){ return true; } else { return false; } } /** * Generate the destinations for a king located at 'position'. * * @param position The index of the square the king is located on. * * @return An ArrayList of all destinations that the king can move to. */ public ArrayList<Integer> generateKingDestinations( int position ) { ArrayList<Integer> destinations = new ArrayList<Integer>(); if ( canCastleKingSide( position ) ) { destinations.add( position + 2 ); } else { //do nothing } if ( canCastleQueenSide( position ) ) { destinations.add( position - 2 ); } else { //do nothing } for ( int i : new int[]{ 15, 16, 17, 1, -1, -17, -16, -15 } ) { if ( !nextToOpponentKing( position + i ) ) { destinations.add( position + i ); } else { //do nothing } } return ( destinations ); } /** * Can the king located at 'position' perform a king side castling move? * * @return True if the king can castle, false otherwise. */ private boolean canCastleKingSide( int position ) { return ( !hasPieceMoved( pieceAt( position ) ) && !kingInCheck() && pieceTypeAt( position + 3 ) == ROOK && !hasPieceMoved( pieceAt( position + 3 ) ) && squareEmpty( position + 1 ) && !squareAttacked( position + 1 ) && squareEmpty( position + 2 ) && !squareAttacked( position + 2 ) ); } /** * Can the king located at 'position' perform a queen side castling move? * * @return True if the king can castle, false otherwise. */ private boolean canCastleQueenSide( int position ) { return ( !hasPieceMoved( pieceAt( position ) ) && !kingInCheck() && pieceTypeAt( position + 3 ) == ROOK && !hasPieceMoved( pieceAt( position - 4 ) ) && squareEmpty( position - 1 ) && !squareAttacked( position - 1 ) && squareEmpty( position - 2 ) && !squareAttacked( position - 2 ) && squareEmpty( position - 3 ) && !squareAttacked( position - 3 ) ); } /** * Is the king located at 'position' adjacent to an opponents king? * * @param position The location of the king to check. */ private boolean nextToOpponentKing( int position ) { int[] offsets = new int[]{ 15, 16, 17, -1, 1, -15, -16, -17 }; for ( int i : offsets ) { if ( ( position + i ) == getOpposingKingPosition() ) { return ( true ); } } return ( false ); } /** * Generate the destinations for a knight located at 'position'. * * @param position The index of the square the knight is located on. * * @return An ArrayList of all destinations that the knight can move to. */ public ArrayList<Integer> generateKnightDestinations( int position ) { ArrayList<Integer> destinations = new ArrayList<Integer>(); for ( int d : new int[]{ 18, 33, 31, 14, -18, -33, -31, -14 } ) { destinations.add( position + d ); } return ( destinations ); } /** * Generate the destinations for a bishop located at 'position'. * * @param position The index of the square the bishop is located on. * * @return An ArrayList of all destinations that the bishop can move to. */ public ArrayList<Integer> generateBishopDestinations( int position ) { return ( generateUpDownDestinations( position, new int[]{ 15, 17, -15, -17 } ) ); } /** * Generate the destinations for a rook located at 'position'. * * @param position The index of the square the rook is located on. * * @return An ArrayList of all destinations that the rook can move to. */ public ArrayList<Integer> generateRookDestinations( int position ) { return ( generateUpDownDestinations( position, new int[]{ 1, -1, 16, -16 } ) ); } /** * Generate the destinations for a queen located at 'position'. * * @param position The index of the square the queen is located on. * * @return An ArrayList of all destinations that the queen can move to. */ public ArrayList<Integer> generateQueenDestinations( int position ) { return ( generateUpDownDestinations( position, new int[]{ 1, -1, 16, -16, 15, 17, -15, -17 } ) ); } /** * Is there an enemy piece located at the given square index? * * @param position The square index to check. * * @return True if an opponents piece is located at that position, false otherwise. */ public boolean enemyPieceAt( int position ) { if ( !squareEmpty( position ) && pieceColourAt( position ) != this.turnColour ) { return true; } else { return false; } } /** * Multipurpose method that can generate destinations for sliding pieces. * * @param position The square index of the locations of the piece. * @param directions The directions in which the piece should be moving. * * @return An ArrayList of all destinations that the piece can move to. */ private ArrayList<Integer> generateUpDownDestinations( int position, int[] directions ) { ArrayList<Integer> destinations = new ArrayList<Integer>(); for ( int direction : directions ) { for ( int i = 1; isValidDestination( position + i*direction ); i++ ) { if ( enemyPieceAt( position + i*direction ) ) { destinations.add( position + i*direction ); break; } else { //do nothing } destinations.add( position + i*direction ); } } return ( destinations ); } /** * Evaluate the material balance on the board. * * @return The zero sum material score. */ public int evaluateMaterial() { if ( isWhiteTurn() == true ) { return this.score; } else { return -this.score; } } /** * Evaluate the positional score of each piece on the board. * * @return The material score for the current player. */ public int evaluatePiecePositions() { int score = 0; for ( int rank = 0; rank < 8; rank++ ) { for ( int file = rank * 16 + 7; file >= rank * 16; file if ( !squareEmpty( file ) && pieceColourAt( file ) == this.turnColour ) { if ( isWhiteTurn() ) { score += piecePositionScore( pieceTypeAt( file ), file ); } else { score -= piecePositionScore( pieceTypeAt( file ), file ); } } else { //do nothing } } } if ( isWhiteTurn() == true ) { return score; } else { return -score; } } /** * Give a score to a piece based on its position on the board. * * @return A score representing how good/bad the position of the piece is. */ public int piecePositionScore( byte pieceType, int pos ) { switch ( pieceType ) { case PAWN: { return isWhiteTurn() ? WPAWN_POSITION_TABLE[ pos ] : BPAWN_POSITION_TABLE[ pos ]; } case KNIGHT: { return KNIGHT_POSITION_TABLE[ pos ]; } case BISHOP: { return isWhiteTurn() ? WBISHOP_POSITION_TABLE[ pos ] : BBISHOP_POSITION_TABLE[ pos ]; } case ROOK: { return isWhiteTurn() ? WROOK_POSITION_TABLE[ pos ] : BROOK_POSITION_TABLE[ pos ]; } case QUEEN: { return this.amountOfMoves < 15 ? OPENING_QUEEN_POSITION_TABLE[ pos ] : QUEEN_POSITION_TABLE[ pos ]; } case KING: { return isWhiteTurn() ? WKING_POSITION_TABLE[ pos ] : BKING_POSITION_TABLE[ pos ]; } default: { // do nothing } } return 0; } /** * Evaluate the development of knights and bishops. * * @return A score representing how good the piece development of the current player is. */ public int evaluatePieceDevelopment() { int score = 0; int[] minorPiecePositions = new int[]{ 1, 2, 5, 6 }; int turn = isWhiteTurn() ? 0 : 112; for ( int pos : minorPiecePositions ) { if ( !squareEmpty( pos + turn ) && !hasPieceMoved( pieceAt( pos + turn ) ) ) { if ( isWhiteTurn() ) { score -= 50; } else { score += 50; } } } if ( isWhiteTurn() == true ) { return score; } else { return -score; } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.badrobot.commands; import com.badrobot.OI; import edu.wpi.first.wpilibj.GenericHID; import edu.wpi.first.wpilibj.Joystick; import com.badrobot.commands.Shoot; import edu.wpi.first.wpilibj.command.Subsystem; /** *SAME CODE AS SHOOT WITH CONTROLLER, JUST THAT TRIGGER IS TESTED * @author Jon Buckley */ public class triggerToShoot extends CommandBase { boolean runShooter; double shooterSpeed; public triggerToShoot() { requires((Subsystem) shooter); } // Called just before this Command runs the first time protected void initialize() { shooterSpeed = .4; runShooter = false; } // Called repeatedly when this Command is scheduled to run protected void execute() { //TESTING THE TRIGGER //3 - Triggers (Each trigger = 0 to 1, axis value = right - left //if(OI.primaryXboxController.getRawAxis(3)>=0)//right trigger if (OI.primaryXboxController.getTrigger(GenericHID.Hand.kLeft)) { if (!runShooter) { shooter.runShooter(shooterSpeed); runShooter = true; } else { shooter.runShooter(0); runShooter = false; } } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
package model; import dataSet.*;//`ll be changed import view.UI.FileSaveUI; import view.UI.Position;//`ll be changed import java.io.File; import java.util.List; import java.util.ArrayList; public class Model implements ModelInterface{ private FileManager fm; private Document left; private Document right; private Document oleft; private Document oright; private Algorithm algo; private ArrayList<String> compResultLeft; private ArrayList<String> compResultRight; public Model(){ this.fm = new FileManager(null,null); this.left = null; this.right = null; this.oleft = null; this.oright = null; this.algo = null; this.compResultLeft = null; this.compResultRight = null; } public Model(File fl, File fr){ this.fm = new FileManager(fl,fr); if(this.fm.getPathLeft() != null){ this.left = new Document(this.fm.getBufLeft()); } else { this.left = null; } if(this.fm.getPathRight() != null){ this.right = new Document(this.fm.getBufRight()); } else { this.right = null; } this.algo = null; this.compResultLeft = null; this.compResultRight = null; } private ArrayList<String> parseData(String data){ if(data == null){ return null; } StringBuilder buf = new StringBuilder(data); ArrayList<String> listData = new ArrayList<String>(); int tmpIdx = 0; int newlineIdx = 0; if(data.length() > 0){ while((newlineIdx = buf.indexOf("\n",tmpIdx)) > 0){ listData.add(buf.substring(tmpIdx, newlineIdx)); tmpIdx = newlineIdx + 1; } if(tmpIdx < buf.length()){ listData.add(buf.substring(tmpIdx, buf.length())); } } return listData; } private String concatData(List<String> data){ if(data == null){ return ""; } String buf = new String(""); for(int i = 0; i < data.size();i++){ buf += data.get(i) +( (i != data.size() - 1) ? ("\n") : ("") ); } return buf; } @Override public Item load(File f, int lr){ if(f == null){ return null; } if(lr == Position.LEFT){ return this.loadLeft(f); } else if(lr == Position.RIGHT){ return this.loadRight(f); } else { //error return null; } } // load sub-methods private Item loadLeft(File f){ FileOpen rtn = new Item(); if(f != null && f.isFile()){ if(this.fm.loadLeft(f)){ this.left = new Document(this.fm.getBufLeft()); if(this.isCompared()){ this.algo = null; } rtn.setFileName(f.getName()); rtn.setTextData(this.concatData(this.left.getLines())); return (Item) rtn; } } return null; } private Item loadRight(File f){ FileOpen rtn = new Item(); if(f != null && f.isFile()){ if(this.fm.loadRight(f)){ this.right = new Document(this.fm.getBufRight()); if(this.isCompared()){ this.algo = null; } rtn.setFileName(f.getName()); rtn.setTextData(this.concatData(this.right.getLines())); return (Item) rtn; } } return null; } @Override public Item load(String path, int lr){ File f = new File(path); return this.load(f, lr); } public Item save(int lr){ if(lr == Position.LEFT || lr == Position.ALL){ while(!this.saveLeft()); } if(lr == Position.RIGHT || lr == Position.ALL){ while(!this.saveRight()); } return null; } @Override public Item save(String data, int lr){ return this.save(this.parseData(data), lr); } @Override public Item save(List<String> data, int lr){ FileEditSave rtn = new Item(); if(data == null){ return null; } if(lr == Position.LEFT || lr == Position.ALL){ // if(this.fm.getPathLeft() == null){ // return null; this.left = new Document(data, false); this.oleft = null; } if(lr == Position.RIGHT || lr == Position.ALL){ // if(this.fm.getPathRight() == null){ // return null; this.right = new Document(data, false); this.oright = null; } if(lr == Position.LEFT || lr == Position.ALL){ while(!this.saveLeft()); rtn.setFileName(fm.getNameLeft()); return (Item)rtn; } if(lr == Position.RIGHT || lr == Position.ALL){ while(!this.saveRight()); rtn.setFileName(fm.getNameRight()); return (Item)rtn; } return null; } // save sub-methods private boolean saveLeft(){ return this.fm.saveLeft(this.left.getLines()); } private boolean saveRight(){ return this.fm.saveRight(this.right.getLines()); } public Item edit(String data, int lr){ return this.edit(this.parseData(data), lr); } public Item edit(List<String> data, int lr){ String name = ""; boolean isEdited = false; FileEditSave rtn = new Item(); if(lr == Position.LEFT){ name = this.fm.getNameLeft(); if(isEdited = this.editLeft(data)){ name = "*" + name; } } else if(lr == Position.RIGHT){ name = this.fm.getNameRight(); if(isEdited = this.editRight(data)){ name = "*" + name; } } if(isEdited && this.isCompared()){ this.algo = null; } rtn.setFileName(name); return (Item) rtn; } private boolean editLeft(List<String> data){ boolean isEdited = false; if(!this.left.isEdited() && this.oleft == null){ this.oleft = new Document(this.left.getLines()); } if(data.size() == this.oleft.length()){ for(int i = 0; i < data.size(); i++){ if(!data.get(i).equals(this.oleft.getLine(i))){ isEdited = true; this.left.setLine(i,data.get(i)); } } } else { isEdited = true; this.left = new Document(data); } return isEdited; } private boolean editRight(List<String> data){ boolean isEdited = false; if(!this.right.isEdited() && this.oright == null){ this.oright = new Document(this.right.getLines()); } if(data.size() == this.oright.length()){ for(int i = 0; i < data.size(); i++){ if(!data.get(i).equals(this.oright.getLine(i))){ isEdited = true; this.right.setLine(i,data.get(i)); } } } else { isEdited = true; this.right = new Document(data); } return isEdited; } @Override public Item compare(){ MergeCompare rtn = new Item(); if(!this.isCompared()){ this.algo = new Algorithm(this.left.getLines(), this.right.getLines()); } String[][] ListData = { this.getResultLeft().toArray(new String[this.getResultLeft().size()]), this.getResultRight().toArray(new String[this.getResultRight().size()]) }; rtn.setListViewItem(ListData); rtn.setListActiveOrder(this.algo.isFirstAreSame()); return (Item) rtn; } // @Override // public Item getCompareResult(int lr){ // if(this.isCompared()){ // if(lr == Position.LEFT){ // return new Item(this.getResultLeft()); // else if(lr == Position.RIGHT){ // return new Item(this.getResultRight()); // else if(lr == Position.ALL){ // return new Item(this.getResultLeft(), this.getResultRight()); // else { // return null; private ArrayList<String> getResultLeft(){ if(!this.isCompared()){ return new ArrayList<String>(); } if(this.compResultLeft != null){ return this.compResultLeft; } //StringBuilder data = new StringBuilder(concatData(this.left.getLines())); ArrayList<String> result = new ArrayList<String>(); StringBuilder buf = new StringBuilder(); ArrayList<IdxPair> diff = this.algo.getResultLeft(); ArrayList<Integer> same = this.algo.getLcsIdxLeft(); int cntDiff = 0, cntSame = 0, cntResultLen = 0; for(int i = 0; i < this.left.length();){ int chki = i; if(!this.algo.isIdentical() && i == diff.get(cntDiff).begin){ if(i < diff.get(cntDiff).end){ for(int j = diff.get(cntDiff).begin; j < diff.get(cntDiff).end; j++){ buf.append(this.left.getLines().get(j) + "\n"); cntResultLen++; } if(diff.get(cntDiff).distance < this.algo.getResultRight().get(cntDiff).distance){ for(int j = 0; j < this.algo.getResultRight().get(cntDiff).distance - diff.get(cntDiff).distance; j++){ buf.append("\u23CE\n"); cntResultLen++; } } if(cntResultLen >= this.algo.totalLength()){ buf.deleteCharAt(buf.length() - 1); } result.add(buf.toString()); buf = new StringBuilder(""); i += diff.get(cntDiff).distance; } else if(diff.get(cntDiff).begin == diff.get(cntDiff).end && this.algo.getResultRight().get(cntDiff).distance > 0){ for(int j = 0; j < this.algo.getResultRight().get(cntDiff).distance; j++){ buf.append("\u23CE\n"); cntResultLen++; } if(cntResultLen >= this.algo.totalLength()){ buf.deleteCharAt(buf.length() - 1); } result.add(buf.toString()); buf = new StringBuilder(""); } if(cntDiff < diff.size() - 1){ cntDiff++; } } if(this.algo.lenLcs() > 0 && i == same.get(cntSame)){ buf.append(this.left.getLines().get(same.get(cntSame)) + "\n"); cntResultLen++; if(i + 1 < this.left.length()){ if(cntSame < same.size() - 1){ cntSame++; } if((!this.algo.isIdentical() && i + 1 == diff.get(cntDiff).begin)){ if(cntResultLen >= this.algo.totalLength()){ buf.deleteCharAt(buf.length() - 1); } result.add(buf.toString()); buf = new StringBuilder(""); } } else { if(cntResultLen >= this.algo.totalLength()){ buf.deleteCharAt(buf.length() - 1); } result.add(buf.toString()); } i++; } if(i == chki){ // unexpected condition return new ArrayList<String>(); } } if(!this.algo.isIdentical() && this.left.length() < this.right.length()){ buf = new StringBuilder(); for(int i = 0; i < this.algo.getResultRight().get(this.algo.getResultRight().size() - 1).distance;i++){ buf.append("\u23CE\n"); cntResultLen++; } if(cntResultLen >= this.algo.totalLength()){ buf.deleteCharAt(buf.length() - 1); } result.add(buf.toString()); } return result; } private ArrayList<String> getResultRight(){ if(!this.isCompared()){ return new ArrayList<String>(); } if(this.compResultRight != null){ return this.compResultRight; } //StringBuilder data = new StringBuilder(concatData(this.left.getLines())); ArrayList<String> result = new ArrayList<String>(); StringBuilder buf = new StringBuilder(); ArrayList<IdxPair> diff = this.algo.getResultRight(); ArrayList<Integer> same = this.algo.getLcsIdxRight(); int cntDiff = 0, cntSame = 0, cntResultLen = 0; for(int i = 0; i < this.right.length();){ int chki = i; if(!this.algo.isIdentical() && i == diff.get(cntDiff).begin){ if(i < diff.get(cntDiff).end){ for(int j = diff.get(cntDiff).begin; j < diff.get(cntDiff).end; j++){ buf.append(this.right.getLines().get(j) + "\n"); cntResultLen++; } if(diff.get(cntDiff).distance < this.algo.getResultLeft().get(cntDiff).distance){ for(int j = 0; j < this.algo.getResultLeft().get(cntDiff).distance - diff.get(cntDiff).distance; j++){ buf.append("\u23CE\n"); cntResultLen++; } } if(cntResultLen >= this.algo.totalLength()){ buf.deleteCharAt(buf.length() - 1); } result.add(buf.toString()); buf = new StringBuilder(""); i += diff.get(cntDiff).distance; } else if(diff.get(cntDiff).begin == diff.get(cntDiff).end && this.algo.getResultLeft().get(cntDiff).distance > 0){ for(int j = 0; j < this.algo.getResultLeft().get(cntDiff).distance; j++){ buf.append("\u23CE\n"); cntResultLen++; } if(cntResultLen >= this.algo.totalLength()){ buf.deleteCharAt(buf.length() - 1); } result.add(buf.toString()); buf = new StringBuilder(""); } if(cntDiff < diff.size() - 1){ cntDiff++; } } if(this.algo.lenLcs() > 0 && i == same.get(cntSame)){ buf.append(this.right.getLines().get(same.get(cntSame)) + "\n"); cntResultLen++; if(i + 1 < this.right.length()){ if(cntSame < same.size() - 1){ cntSame++; } if((!this.algo.isIdentical() && i + 1 == diff.get(cntDiff).begin)){ if(cntResultLen >= this.algo.totalLength()){ buf.deleteCharAt(buf.length() - 1); } result.add(buf.toString()); buf = new StringBuilder(""); } } else { if(cntResultLen >= this.algo.totalLength()){ buf.deleteCharAt(buf.length() - 1); } result.add(buf.toString()); } i++; } if(i == chki){ // unexpected condition return new ArrayList<String>(); } } if(!this.algo.isIdentical() && this.right.length() < this.left.length()){ buf = new StringBuilder(); for(int i = 0; i < this.algo.getResultLeft().get(this.algo.getResultLeft().size() - 1).distance;i++){ buf.append("\u23CE\n"); cntResultLen++; } if(cntResultLen >= this.algo.totalLength()){ buf.deleteCharAt(buf.length() - 1); } result.add(buf.toString()); } return result; } public boolean isCompared(){ return this.algo != null; } @Override public Item merge(List<Integer> idxList, int lr){ if(this.isCompared()){ if(!this.algo.isIdentical()){ if(lr == Position.LEFT){ for(int i = 0; i < idxList.size();i++){ this.copyToRight(idxList.get(i).intValue()); } } else if(lr == Position.RIGHT){ for(int i = 0; i < idxList.size();i++){ this.copyToLeft(idxList.get(i).intValue()); } } else { return null; } // if(this.isCompared()){ // this.algo = null; // return this.compare(); this.algo = null; return this.compare(); } return null; } else { return null; } } @Override public Item merge(int idx, int lr){ if(this.isCompared()){ if(!this.algo.isIdentical()){ if(lr == Position.LEFT){ this.copyToRight(idx); } else if(lr == Position.RIGHT){ this.copyToLeft(idx); } else { return null; } // if(this.isCompared()){ // this.algo = null; // return this.compare(); this.algo = null; return this.compare(); } return null; } else { return null; } } // @Override // public Item merge(int lr){ // if(this.isCompared()){ // if(this.algo.isIdentical()){ // return new Item(); // return new Item(); // else { // return null; private void copyToRight(int idx){ ArrayList<String> compResult = this.getResultLeft(); ArrayList<String> dataToCp = this.parseData(compResult.get(idx)); int diffIdx = (idx - (this.algo.isFirstAreSame() ? 1 : 0) )/ 2; this.right.deleteLine(this.algo.getResultRight().get(diffIdx).begin, this.algo.getResultRight().get(diffIdx).end); this.right.insertLine(this.algo.getResultRight().get(diffIdx).begin, dataToCp); } private void copyToLeft(int idx){ ArrayList<String> compResult = this.getResultRight(); ArrayList<String> dataToCp = this.parseData(compResult.get(idx)); int diffIdx = (idx - (this.algo.isFirstAreSame() ? 1 : 0) )/ 2; this.left.deleteLine(this.algo.getResultLeft().get(diffIdx).begin, this.algo.getResultLeft().get(diffIdx).end); this.left.insertLine(this.algo.getResultLeft().get(diffIdx).begin, dataToCp); } }
package com.bkahlert.nebula.views; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.apache.log4j.Logger; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import com.bkahlert.nebula.utils.ExecUtils; import com.bkahlert.nebula.utils.NamedJob; import com.bkahlert.nebula.widgets.composer.Composer.ToolbarSet; import com.bkahlert.nebula.widgets.editor.AutosaveEditor; import com.bkahlert.nebula.widgets.editor.Editor; /** * Instances of this class are {@link ViewPart}s that wrap a {@link Editor}. * * @param <T> * type of the objects that can be loaded in the wrapped * {@link Editor} * * @author bkahlert */ public abstract class EditorView<T> extends ViewPart { private static final Logger LOGGER = Logger.getLogger(EditorView.class); public static class PartInfo { private final String title; private final Image image; public PartInfo(String title, Image image) { super(); this.title = title; this.image = image; } /** * @return the part's title */ public String getTitle() { return this.title; } /** * @return the part's image */ public Image getImage() { return this.image; } } private final long delayChangeEventUpTo; private final ToolbarSet toolbarSet; private final boolean autosave; private Composite parent; private final List<Editor<T>> editors; /** * Creates a new instance using a classic {@link Editor} or a * {@link AutosaveEditor}. * * @param delayChangeEventUpTo * is the delay that must have been passed in order save the * currently loaded object. If 0 no delay will be applied. The * minimal delay however defined by the wrapped {@link Image}. * @param autosave */ public EditorView(long delayChangeEventUpTo, ToolbarSet toolbarSet, boolean autosave) { this.delayChangeEventUpTo = delayChangeEventUpTo; this.toolbarSet = toolbarSet; this.autosave = autosave; this.parent = null; this.editors = new ArrayList<Editor<T>>(2); } public List<Editor<T>> getEditors() { return new ArrayList<Editor<T>>(this.editors); } protected void refreshHeader() { final AtomicReference<PartInfo> partInfo = new AtomicReference<PartInfo>(); List<T> loadedObjects = this.getLoadedObjects(); if (loadedObjects.size() > 0) { try { partInfo.set(this.getPartInfo(loadedObjects)); } catch (Exception e) { LOGGER.error("Error while refreshing header", e); partInfo.set(new PartInfo("ERROR", PlatformUI.getWorkbench() .getSharedImages() .getImage(ISharedImages.IMG_OBJS_ERROR_TSK))); } } else { partInfo.set(this.getDefaultPartInfo()); } ExecUtils.asyncExec(new Runnable() { @Override public void run() { EditorView.this.setPartName(partInfo != null && partInfo.get().getTitle() != null ? partInfo.get() .getTitle() : "Editor"); EditorView.this.setTitleImage(partInfo != null && partInfo.get().getImage() != null ? partInfo.get() .getImage() : null); } }); } /** * Returns the {@link PartInfo} to be used when no object is loaded. * * @return */ public abstract PartInfo getDefaultPartInfo(); /** * Returns the {@link PartInfo} is the given object is loaded. * * @param loadedObject * @return */ public abstract PartInfo getPartInfo(List<T> loadedObjects) throws Exception; @Override public final void createPartControl(Composite parent) { this.parent = parent; this.parent.setLayout(new FillLayout()); MenuManager menuManager = new MenuManager("#PopupMenu"); menuManager.setRemoveAllWhenShown(true); menuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { manager.add(new Separator( IWorkbenchActionConstants.MB_ADDITIONS)); } }); this.postInit(); } /** * This method is called after this {@link EditorView} has been initialized. */ public void postInit() { return; } /** * * @param objectsToLoad * @see Editor#load(Object) */ public final void load(final Runnable callback, T... objectsToLoad) { this.createEditors(objectsToLoad.length); Assert.isTrue(objectsToLoad.length == this.editors.size()); if (objectsToLoad.length == 0) { EditorView.this.refreshHeader(); if (callback != null) { callback.run(); } return; } final AtomicReference<Integer> jobCount = new AtomicReference<Integer>( 0); for (int i = 0; i < objectsToLoad.length; i++) { NamedJob loadJob = this.editors.get(i).load(objectsToLoad[i]); if (loadJob != null) { jobCount.set(jobCount.get() + 1); loadJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { jobCount.set(jobCount.get() - 1); if (jobCount.get() == 0) { EditorView.this.refreshHeader(); if (callback != null) { callback.run(); } } } }); } } } private void createEditors(int length) { List<Editor<T>> disposed = new ArrayList<Editor<T>>(); List<Editor<T>> created = new ArrayList<Editor<T>>(); while (length < this.editors.size()) { this.editors.get(length).dispose(); disposed.add(this.editors.remove(length)); } while (length > this.editors.size()) { Editor<T> editor; if (this.autosave) { editor = new AutosaveEditor<T>(this.parent, SWT.NONE, this.delayChangeEventUpTo, this.toolbarSet) { @Override public String getHtml(T loadedObject, IProgressMonitor monitor) throws Exception { return EditorView.this.getHtml(loadedObject, monitor); } @Override public void setHtml(T loadedObject, String html, IProgressMonitor monitor) throws Exception { EditorView.this.setHtml(loadedObject, html, monitor); } }; } else { editor = new Editor<T>(this.parent, SWT.NONE, this.delayChangeEventUpTo, this.toolbarSet) { @Override public String getHtml(T loadedObject, IProgressMonitor monitor) throws Exception { return EditorView.this.getHtml(loadedObject, monitor); } @Override public void setHtml(T loadedObject, String html, IProgressMonitor monitor) throws Exception { EditorView.this.setHtml(loadedObject, html, monitor); } }; } this.editors.add(editor); created.add(editor); } this.parent.layout(); if (disposed.size() > 0) { this.disposed(created); } if (created.size() > 0) { this.created(created); } } public abstract void created(List<Editor<T>> editors); public abstract void disposed(List<Editor<T>> editors); /** * @throws Exception * @see {@link Editor#save()} */ public final void save() throws Exception { for (Editor<T> editor : this.editors) { if (!editor.isDisposed()) { editor.save(); } } } /** * @return * @see {@link Editor#getLoadedObject()} */ public List<T> getLoadedObjects() { List<T> loadedObjects = new ArrayList<T>(); for (int i = 0; i < this.editors.size(); i++) { loadedObjects.add(this.editors.get(i).getLoadedObject()); } return loadedObjects; } /** * Returns the html for the given object. * * @param objectToLoad * @param monitor * @return * @throws Exception */ public abstract String getHtml(T objectToLoad, IProgressMonitor monitor) throws Exception; /** * Sets the given html to the loaded object. * * @param loadedObject * @param html * @param monitor */ public abstract void setHtml(T loadedObject, String html, IProgressMonitor monitor) throws Exception; @Override public void setFocus() { if (this.editors.size() > 0 && this.editors.get(0) != null && !this.editors.get(0).isDisposed()) { this.editors.get(0).setFocus(); } } }
package com.blarg.gdx.graphics; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.utils.Disposable; public class RenderContext implements Disposable { public final SpriteBatch spriteBatch; public final DelayedSpriteBatch delayedSpriteBatch; public final ShapeRenderer debugGeometryRenderer; public final ModelBatch modelBatch; public final ScreenPixelScaler pixelScaler; public final SolidColorTextureCache solidColorTextures; Camera perspectiveCamera; OrthographicCamera orthographicCamera; public RenderContext(boolean use2dPixelScaling) { Gdx.app.debug("RenderContext", "ctor"); spriteBatch = new SpriteBatch(); delayedSpriteBatch = new DelayedSpriteBatch(); debugGeometryRenderer = new ShapeRenderer(); modelBatch = new ModelBatch(); solidColorTextures = new SolidColorTextureCache(); if (use2dPixelScaling) pixelScaler = new DefaultScreenPixelScaler(); else pixelScaler = new NoScaleScreenPixelScaler(); pixelScaler.calculateScale(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); orthographicCamera = new OrthographicCamera(pixelScaler.getScaledWidth(), pixelScaler.getScaledHeight()); setDefaultPerspectiveCamera(); } public Camera getPerspectiveCamera() { return perspectiveCamera; } public OrthographicCamera getOrthographicCamera() { return orthographicCamera; } public void setPerspectiveCamera(Camera camera) { perspectiveCamera = camera; } public void setDefaultPerspectiveCamera() { perspectiveCamera = new PerspectiveCamera(60.0f, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); perspectiveCamera.position.set(0.0f, 0.0f, 0.0f); perspectiveCamera.lookAt(0.0f, 0.0f, 1.0f); perspectiveCamera.near = 0.1f; perspectiveCamera.far = 100.0f; perspectiveCamera.update(); } public void clear() { clear(0.0f, 0.0f, 0.0f, 1.0f); } public void clear(float red, float green, float blue, float alpha) { Gdx.graphics.getGL20().glClearColor(red, green, blue, alpha); Gdx.graphics.getGL20().glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); } public void onPreRender() { spriteBatch.setProjectionMatrix(orthographicCamera.combined); debugGeometryRenderer.begin(ShapeRenderer.ShapeType.Line); delayedSpriteBatch.begin(spriteBatch); modelBatch.begin(perspectiveCamera); } public void onPostRender() { modelBatch.end(); delayedSpriteBatch.end(); debugGeometryRenderer.end(); } public void onUpdate(float delta) { perspectiveCamera.update(); orthographicCamera.update(); } public void onResize(int width, int height) { Gdx.app.debug("RenderContext", String.format("onResize(%d, %d)", width, height)); pixelScaler.calculateScale(width, height); orthographicCamera.setToOrtho(false, pixelScaler.getScaledWidth(), pixelScaler.getScaledHeight()); } public void onPause() { Gdx.app.debug("RenderContext", String.format("onPause")); solidColorTextures.onPause(); } public void onResume() { Gdx.app.debug("RenderContext", String.format("onResume")); solidColorTextures.onResume(); } @Override public void dispose() { Gdx.app.debug("RenderContext", String.format("dispose")); solidColorTextures.dispose(); spriteBatch.dispose(); } }
package com.dmdirc.addons.ui_swing; import com.dmdirc.FrameContainer; import com.dmdirc.Main; import com.dmdirc.ServerManager; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.CoreActionType; import com.dmdirc.addons.ui_swing.components.LoggingSwingWorker; import com.dmdirc.addons.ui_swing.components.SplitPane; import com.dmdirc.addons.ui_swing.components.frames.TextFrame; import com.dmdirc.addons.ui_swing.components.menubar.MenuBar; import com.dmdirc.addons.ui_swing.components.statusbar.SwingStatusBar; import com.dmdirc.addons.ui_swing.dialogs.ConfirmQuitDialog; import com.dmdirc.addons.ui_swing.dialogs.StandardQuestionDialog; import com.dmdirc.addons.ui_swing.framemanager.FrameManager; import com.dmdirc.addons.ui_swing.framemanager.FramemanagerPosition; import com.dmdirc.addons.ui_swing.framemanager.ctrltab.CtrlTabWindowManager; import com.dmdirc.addons.ui_swing.framemanager.tree.TreeFrameManager; import com.dmdirc.config.IdentityManager; import com.dmdirc.interfaces.ConfigChangeListener; import com.dmdirc.interfaces.FrameInfoListener; import com.dmdirc.interfaces.NotificationListener; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.ui.CoreUIUtils; import com.dmdirc.ui.IconManager; import com.dmdirc.util.ListenerList; import com.dmdirc.util.QueuedLinkedHashSet; import com.dmdirc.util.ReturnableThread; import java.awt.Color; import java.awt.Dimension; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; import java.awt.event.WindowListener; import java.lang.reflect.InvocationTargetException; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.MenuSelectionManager; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import net.miginfocom.swing.MigLayout; /** * The main application frame. */ public final class MainFrame extends JFrame implements WindowListener, ConfigChangeListener, SwingWindowListener, FrameInfoListener, NotificationListener { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 9; /** Focus queue. */ private final QueuedLinkedHashSet<TextFrame> focusOrder; /** The main application icon. */ private ImageIcon imageIcon; /** The frame manager that's being used. */ private FrameManager mainFrameManager; /** Active frame. */ private TextFrame activeFrame; /** Panel holding frame. */ private JPanel framePanel; /** Main panel. */ private JPanel frameManagerPanel; /** Frame manager position. */ private FramemanagerPosition position; /** Show version? */ private boolean showVersion; /** Exit code. */ private int exitCode = 0; /** Swing Controller. */ private final SwingController controller; /** Status bar. */ private SwingStatusBar statusBar; /** Client Version. */ private final String version; /** Main split pane. */ private SplitPane mainSplitPane; /** Frame manager used for ctrl tab frame switching. */ private final CtrlTabWindowManager frameManager; /** The listeners registered with this class. */ private final ListenerList listeners = new ListenerList(); /** * Creates new form MainFrame. * * @param controller Swing controller */ public MainFrame(final SwingController controller) { super(); this.controller = controller; focusOrder = new QueuedLinkedHashSet<TextFrame>(); initComponents(); imageIcon = new ImageIcon(IconManager.getIconManager() .getImage("icon")); setIconImage(imageIcon.getImage()); CoreUIUtils.centreWindow(this); addWindowListener(this); showVersion = IdentityManager.getGlobalConfig().getOptionBool("ui", "showversion"); version = IdentityManager.getGlobalConfig().getOption("version", "version"); IdentityManager.getGlobalConfig().addChangeListener("ui", "lookandfeel", this); IdentityManager.getGlobalConfig().addChangeListener("ui", "showversion", this); IdentityManager.getGlobalConfig().addChangeListener("ui", "framemanager", this); IdentityManager.getGlobalConfig().addChangeListener("ui", "framemanagerPosition", this); IdentityManager.getGlobalConfig().addChangeListener("icon", "icon", this); addWindowFocusListener(new WindowFocusListener() { /** {@inheritDoc} */ @Override public void windowGainedFocus(final WindowEvent e) { ActionManager.getActionManager().triggerEvent( CoreActionType.CLIENT_FOCUS_GAINED, null); } /** {@inheritDoc} */ @Override public void windowLostFocus(final WindowEvent e) { ActionManager.getActionManager().triggerEvent( CoreActionType.CLIENT_FOCUS_LOST, null); //TODO: Remove me when we switch to java7 MenuSelectionManager.defaultManager().clearSelectedPath(); } }); controller.getWindowFactory().addWindowListener(this); setTitle(getTitlePrefix()); frameManager = new CtrlTabWindowManager(controller, this, rootPane); } /** * Returns the status bar for this frame. * * @return Status bar */ public SwingStatusBar getStatusBar() { return statusBar; } /** * Returns the size of the frame manager. * * @return Frame manager size. */ public int getFrameManagerSize() { return UIUtilities.invokeAndWait(new ReturnableThread<Integer>() { /** {@inheritDoc} */ @Override public void run() { if (position == FramemanagerPosition.LEFT || position == FramemanagerPosition.RIGHT) { setObject(frameManagerPanel.getWidth()); } else { setObject(frameManagerPanel.getHeight()); } } }); } /** * Returns the window that is currently active. * * @return The active window */ public TextFrame getActiveFrame() { return UIUtilities.invokeAndWait(new ReturnableThread<TextFrame>() { /** {@inheritDoc} */ @Override public void run() { setObject(activeFrame); } }); } /** {@inheritDoc} */ @Override public MenuBar getJMenuBar() { return (MenuBar) super.getJMenuBar(); } /** {@inheritDoc}. */ @Override public void setTitle(final String title) { if (title == null || getActiveFrame() == null) { super.setTitle(getTitlePrefix()); } else { super.setTitle(getTitlePrefix() + " - " + title); } } /** * Gets the string which should be prefixed to this frame's title. * * @return This frame's title prefix */ private String getTitlePrefix() { return "DMDirc" + (showVersion ? " " + version : ""); } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowOpened(final WindowEvent windowEvent) { //ignore } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowClosing(final WindowEvent windowEvent) { quit(exitCode); } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowClosed(final WindowEvent windowEvent) { new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { Main.quit(exitCode); } }, "Quit thread").start(); } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowIconified(final WindowEvent windowEvent) { ActionManager.getActionManager().triggerEvent( CoreActionType.CLIENT_MINIMISED, null); } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowDeiconified(final WindowEvent windowEvent) { ActionManager.getActionManager().triggerEvent( CoreActionType.CLIENT_UNMINIMISED, null); } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowActivated(final WindowEvent windowEvent) { //ignore } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowDeactivated(final WindowEvent windowEvent) { //ignore } /** Initialiases the frame managers. */ private void initFrameManagers() { UIUtilities.invokeAndWait(new Runnable() { /** {@inheritDoc} */ @Override public void run() { frameManagerPanel.removeAll(); if (mainFrameManager != null) { controller.getWindowFactory().removeWindowListener( mainFrameManager); } final String manager = IdentityManager.getGlobalConfig(). getOption("ui", "framemanager"); try { mainFrameManager = (FrameManager) Class.forName(manager). getConstructor().newInstance(); } catch (InvocationTargetException ex) { Logger.appError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (InstantiationException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (NoSuchMethodException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (SecurityException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (IllegalAccessException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (IllegalArgumentException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (ClassNotFoundException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (LinkageError ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } finally { if (mainFrameManager == null) { mainFrameManager = new TreeFrameManager(); } } mainFrameManager.setController(controller); mainFrameManager.setParent(frameManagerPanel); addSelectionListener(mainFrameManager); controller.getWindowFactory().addWindowListener( mainFrameManager); } }); } /** * Initialises the components for this frame. */ private void initComponents() { statusBar = new SwingStatusBar(controller, this); frameManagerPanel = new JPanel(); activeFrame = null; framePanel = new JPanel(new MigLayout("fill, ins 0")); initFrameManagers(); mainSplitPane = initSplitPane(); final MenuBar menu = new MenuBar(controller, this); Apple.getApple().setMenuBar(menu); setJMenuBar(menu); setPreferredSize(new Dimension(800, 600)); getContentPane().setLayout(new MigLayout( "fill, ins rel, wrap 1, hidemode 2")); layoutComponents(); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); pack(); } /** * Lays out the this component. */ private void layoutComponents() { getContentPane().add(mainSplitPane, "grow, push"); getContentPane().add(statusBar, "hmax 20, wmax 100%-2*rel, " + "wmin 100%-2*rel, south, gap rel rel 0 rel"); } /** * Initialises the split pane. * * @return Returns the initialised split pane */ private SplitPane initSplitPane() { final SplitPane splitPane = new SplitPane(SplitPane .Orientation.HORIZONTAL); position = FramemanagerPosition.getPosition(IdentityManager. getGlobalConfig().getOption("ui", "framemanagerPosition")); if (position == FramemanagerPosition.UNKNOWN) { position = FramemanagerPosition.LEFT; } if (!mainFrameManager.canPositionVertically() && (position == FramemanagerPosition.LEFT || position == FramemanagerPosition.RIGHT)) { position = FramemanagerPosition.BOTTOM; } if (!mainFrameManager.canPositionHorizontally() && (position == FramemanagerPosition.TOP || position == FramemanagerPosition.BOTTOM)) { position = FramemanagerPosition.LEFT; } switch (position) { case TOP: splitPane.setTopComponent(frameManagerPanel); splitPane.setBottomComponent(framePanel); splitPane.setResizeWeight(0.0); splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); frameManagerPanel.setPreferredSize(new Dimension( Integer.MAX_VALUE, IdentityManager.getGlobalConfig(). getOptionInt("ui", "frameManagerSize"))); break; case LEFT: splitPane.setLeftComponent(frameManagerPanel); splitPane.setRightComponent(framePanel); splitPane.setResizeWeight(0.0); splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); frameManagerPanel.setPreferredSize(new Dimension( IdentityManager.getGlobalConfig().getOptionInt("ui", "frameManagerSize"), Integer.MAX_VALUE)); break; case BOTTOM: splitPane.setTopComponent(framePanel); splitPane.setBottomComponent(frameManagerPanel); splitPane.setResizeWeight(1.0); splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); frameManagerPanel.setPreferredSize(new Dimension( Integer.MAX_VALUE, IdentityManager.getGlobalConfig(). getOptionInt("ui", "frameManagerSize"))); break; case RIGHT: splitPane.setLeftComponent(framePanel); splitPane.setRightComponent(frameManagerPanel); splitPane.setResizeWeight(1.0); splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); frameManagerPanel.setPreferredSize(new Dimension( IdentityManager.getGlobalConfig().getOptionInt("ui", "frameManagerSize"), Integer.MAX_VALUE)); break; default: break; } return splitPane; } /** * Exits with an "OK" status code. */ public void quit() { quit(0); } /** * Exit code call to quit. * * @param exitCode Exit code */ public void quit(final int exitCode) { if (exitCode == 0 && IdentityManager.getGlobalConfig().getOptionBool( "ui", "confirmQuit")) { final StandardQuestionDialog dialog = new ConfirmQuitDialog(this) { /** * A version number for this class. It should be changed * whenever the class structure is changed (or anything else * that would prevent serialized objects being unserialized * with the new class). */ private static final long serialVersionUID = 9; /** {@inheritDoc} */ @Override protected void handleQuit() { doQuit(exitCode); } }; dialog.display(); return; } doQuit(exitCode); } /** * Exit code call to quit. * * @param exitCode Exit code */ public void doQuit(final int exitCode) { this.exitCode = exitCode; new LoggingSwingWorker<Void, Void>() { /** {@inheritDoc} */ @Override protected Void doInBackground() { ActionManager.getActionManager().triggerEvent( CoreActionType.CLIENT_CLOSING, null); ServerManager.getServerManager().closeAll(IdentityManager. getGlobalConfig().getOption("general", "closemessage")); IdentityManager.getConfigIdentity().setOption("ui", "frameManagerSize", String.valueOf(getFrameManagerSize())); return null; } /** {@inheritDoc} */ @Override protected void done() { super.done(); dispose(); } }.executeInExecutor(); } /** {@inheritDoc} */ @Override public void configChanged(final String domain, final String key) { if ("ui".equals(domain)) { if ("lookandfeel".equals(key)) { controller.updateLookAndFeel(); } else if ("framemanager".equals(key) || "framemanagerPosition".equals(key)) { UIUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { setVisible(false); getContentPane().remove(mainSplitPane); initFrameManagers(); getContentPane().removeAll(); layoutComponents(); setVisible(true); } }); } else { showVersion = IdentityManager.getGlobalConfig().getOptionBool( "ui", "showversion"); } } else { imageIcon = new ImageIcon(IconManager.getIconManager().getImage( "icon")); UIUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { setIconImage(imageIcon.getImage()); } }); } } /** * Changes the visible frame. * * @param activeFrame The frame to be activated, or null to show none */ public void setActiveFrame(final TextFrame activeFrame) { UIUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { focusOrder.offerAndMove(activeFrame); framePanel.setVisible(false); framePanel.removeAll(); if (MainFrame.this.activeFrame != null) { MainFrame.this.activeFrame.getContainer() .removeNotificationListener(MainFrame.this); } MainFrame.this.activeFrame = activeFrame; if (activeFrame == null) { framePanel.add(new JPanel(), "grow"); setTitle(null); } else { framePanel.add(activeFrame, "grow"); setTitle(activeFrame.getContainer().getTitle()); activeFrame.getContainer().addNotificationListener( MainFrame.this); } framePanel.setVisible(true); if (activeFrame != null) { activeFrame.activateFrame(); } for (SelectionListener listener : listeners.get( SelectionListener.class)) { listener.selectionChanged(activeFrame); } ActionManager.getActionManager().triggerEvent( CoreActionType.CLIENT_FRAME_CHANGED, null, activeFrame == null ? null : activeFrame .getContainer()); } }); } /** * Registers a new selection listener with this frame. The listener will * be notified whenever the currently selected frame is changed. * * @param listener The listener to be added * @see #setActiveFrame(com.dmdirc.addons.ui_swing.components.frames.TextFrame) * @see #getActiveFrame() */ public void addSelectionListener(final SelectionListener listener) { listeners.add(SelectionListener.class, listener); } /** * Removes a previously registered selection listener. * * @param listener The listener to be removed * @see #addSelectionListener(com.dmdirc.addons.ui_swing.SelectionListener) */ public void removeSelectionListener(final SelectionListener listener) { listeners.remove(SelectionListener.class, listener); } /** {@inheritDoc} */ @Override public void windowAdded(final TextFrame parent, final TextFrame window) { if (activeFrame == null) { setActiveFrame(window); } window.getContainer().addFrameInfoListener(this); } /** {@inheritDoc} */ @Override public void windowDeleted(final TextFrame parent, final TextFrame window) { focusOrder.remove(window); if (activeFrame.equals(window)) { activeFrame = null; framePanel.setVisible(false); framePanel.removeAll(); framePanel.setVisible(true); if (focusOrder.peek() == null) { SwingUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { frameManager.scrollUp(); } }); } else { setActiveFrame(focusOrder.peek()); } } window.getContainer().removeFrameInfoListener(this); } /** {@inheritDoc} */ @Override public void iconChanged(final FrameContainer window, final String icon) { //Ignore } /** {@inheritDoc} */ @Override public void nameChanged(final FrameContainer window, final String name) { //Ignore } /** {@inheritDoc} */ @Override public void titleChanged(final FrameContainer window, final String title) { setTitle(title); } /** {@inheritDoc} */ @Override public void notificationSet(final FrameContainer window, final Color colour) { if (activeFrame.getContainer().equals(window)) { window.clearNotification(); } } /** {@inheritDoc} */ @Override public void notificationCleared(final FrameContainer window) { //Ignore } }
package model; import model.formulas.Formula; import model.rules.Premise; import model.rules.Rule; import start.Constants; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.prefs.Preferences; import static java.util.prefs.Preferences.userRoot; public class Proof implements Serializable{ private transient ArrayList<ProofListener> listeners = new ArrayList<ProofListener>(); private transient Parser parser = new Parser(); //this won't be serialized private Formula conclusion; private Box proofData = new Box(null, true); public boolean isLoaded = false; public Proof(){} public String getProofString() { return proofData.rowsToString(1); } /*** * Add a new row at the end of the proof. */ public void addRow() { proofData.addRow(); for (ProofListener listener : this.listeners) { listener.rowAdded(); } verifyProof(); //verifyRow(proofData.size() - 1); printProof("Row added"); } /** * delete the row at index rowNumber-1 * TODO: update indexes of rule objects in rows below? * TODO: verify rows below since they now might not be correct anymore * * @param rowNumber */ public int deleteRow(int rowNumber) { if (rowNumber < 1 || rowNumber > proofData.size() || proofData.size() == 1) { return -1; } boolean updatedPremises = false; if(proofData.getRow(rowNumber-1).getRule() instanceof Premise){ updatedPremises = true; } System.out.println(proofData.size()); int delDepth = (proofData.deleteRow(rowNumber - 1)); if (delDepth == -1) return -1; for (ProofListener listener : this.listeners) { listener.rowDeleted(rowNumber); } if(updatedPremises){ this.updatedPremises(); } verifyProof(); printProof("Row deleted"); return delDepth; } /** * Inserts a new row into the same box as the referenced row * TODO: update indexes of rule objects in rows below? * TODO: verify rows below since they now might not be correct anymore * * @param rowNumber: the number of the row used as reference * @param br: Indicates whether the new row should be added before or after the reference row */ public boolean insertNewRow(int rowNumber, BoxReference br, int depth) { if (rowNumber > proofData.size() + 1) { System.out.println("Proof.insertNewRow: incorrect rowNumber"); System.out.println("rows.size(): " + proofData.size() + ", rowNumber: " + rowNumber); return false; } proofData.insertRow(rowNumber - 1, br, depth); for (ProofListener pl : listeners) { pl.rowInserted(rowNumber, br, depth); } // verifyProof(rowNumber-1 + (br == BoxReference.BEFORE ? 0 : 1)); verifyProof(); printProof("Inserted new row"); return true; } public boolean deleteRowAfterBox(int rowNumber) { if (rowNumber < 1 || rowNumber > proofData.size() + 1) { return false; } proofData.deleteRowAfterBox(rowNumber - 1); for (ProofListener pl : listeners) { pl.deletedRowAfterBox(rowNumber); } verifyProof(); printProof("Deleted row"); return true; } //Will you ever update both the formula and rule fields at the same time? public void updateRow(String formula, String rule, int rowNumber) { } /** * Alert the listeners about the row. * * @param strFormula * @param rowNumber */ public void updateFormulaRow(String strFormula, int rowNumber) { //System.out.println("Proof.updateFormulaRow("+formula+", "+rowNumber+")"); int rowIndex = rowNumber - 1; ProofRow toBeUpdated = proofData.getRow(rowIndex); Formula parsedFormula = null; boolean wellFormed; try { parsedFormula = parser.parse(strFormula); wellFormed = true; } catch (ParseException e) { wellFormed = false; } String parsedString = parsedFormula == null ? "" : parsedFormula.parenthesize(); toBeUpdated.setFormula(parsedFormula); toBeUpdated.setUserInput((strFormula == null ? "" : strFormula)); toBeUpdated.setWellformed(wellFormed); for (ProofListener listener : this.listeners) { listener.updateParsingStatus(rowNumber, parsedString); listener.rowUpdated(null, wellFormed, rowNumber); } // verifyProof(rowIndex); //should use verifyProof later probably, to verify rows lower in the proof aswell verifyProof(); if(toBeUpdated.getRule() instanceof Premise){ this.updatedPremises(); } printProof("Updated formula in row"); } public void updateRuleRow(String ruleString, int rowNumber) throws IllegalAccessException, InstantiationException { //System.out.println("updateRuleRow: rule=" + ruleString + ", rowNr=" + rowNumber); int rowIndex = rowNumber - 1; boolean premiseUpdate = false; ProofRow pr = proofData.getRow(rowIndex); if(pr.getRule() instanceof Premise){ premiseUpdate = true; } Rule rule = RuleMapper.getRule(ruleString); if(ruleString.equals(Constants.premise)){ premiseUpdate = true; } pr.setRule(rule); // verifyProof(rowIndex); verifyProof(); if(premiseUpdate){ this.updatedPremises(); } printProof("Updated rule in row"); } //Adds a rule object to the given row public void addRule(int rowNr, Rule rule) { System.out.println("addRule: " + rowNr + ", Rule: " + rule); proofData.getRow(rowNr - 1).setRule(rule); // verifyRow(rowNr - 1); verifyProof(); } //should verify each line in the proof from line startIndex public boolean verifyProof() { return verifyProof(0); } public boolean verifyProof(int startIndex) { assert (startIndex < proofData.size()) : "Proof.verifyProof: index out of bounds"; boolean returnValue = true; for (int i = startIndex; i < proofData.size(); i++) { try { if (verifyRow(i) == false) returnValue = false; for (ProofListener listener : this.listeners) { listener.updateErrorStatus(i + 1, ""); } } catch (VerificationInputException e) { for (ProofListener listener : this.listeners) { listener.updateErrorStatus(i+1, e.getMessage()); } } //TODO: inform listeners about each row } for (ProofListener listener : this.listeners) { listener.updateStatus(); } return returnValue; } //should verify that the row is correct with regards to it's rule and //update the row object with this info public boolean verifyRow(int rowIndex) { assert (rowIndex < proofData.size()) : "Proof.verifyRow: index out of bounds"; ProofRow row = proofData.getRow(rowIndex); Rule rule = row.getRule(); boolean isVerified = false; VerificationInputException exceptionToThrow = null; if (rule == null) { exceptionToThrow = new VerificationInputException("Invalid rule syntax."); } else if (rule.hasCompleteInfo() == false) { exceptionToThrow = new VerificationInputException("A reference is empty."); } else if ( row.getFormula() == null ) { exceptionToThrow = new VerificationInputException("Invalid formula syntax."); } else { try { isVerified = rule.verify(proofData, rowIndex); } catch (VerificationInputException e) { exceptionToThrow = e; } } row.setVerified(isVerified); for (ProofListener listener : this.listeners) { listener.rowVerified(isVerified, rowIndex + 1); } verifyConclusion(rowIndex); if (exceptionToThrow != null) throw exceptionToThrow; return isVerified; } public boolean insertBox(int rowIndex) { ProofRow pr = proofData.getRow(rowIndex); if (pr.getParent() != null && !pr.getParent().isTopLevelBox()) { if (pr.getParent().getRow(0) == pr) { return false; // Don't insert box if it's the first row in a box. } } proofData.insertBox(rowIndex); for (ProofListener listener : this.listeners) { listener.boxInserted(rowIndex + 1); } // verifyProof(rowIndex); verifyProof(); printProof("inserted box"); return true; } public boolean removeBox(int rowIndex) { // We assume this is possible by precondition proofData.removeBox(rowIndex); for (ProofListener listener : this.listeners) { listener.boxRemoved(rowIndex + 1); } verifyProof(); return true; } /** * Updates the conclusion used as the 'goal' of the proof * * @param conclusion */ public void updateConclusion(String conclusion) { try { this.conclusion = parser.parse(conclusion); } catch (Exception ParseException) { this.conclusion = null; } for (int i = 0; i < proofData.size(); i++) { verifyConclusion(i); } } /** * Verifies if the row matches the conclusion * * @param rowIndex: index of the row to verify */ //TODO: check that the row has been verified, not just matches conclusion public void verifyConclusion(int rowIndex) { ProofRow row = proofData.getRow(rowIndex); /*if (false) { for (ProofListener listener : this.listeners) { listener.conclusionReached(false, rowIndex + 1); } }*/ if (this.conclusion != null && row.getFormula() != null && row.isVerified() && this.conclusion.equals(row.getFormula()) && row.getParent().isTopLevelBox()) { for (ProofListener listener : this.listeners) { listener.conclusionReached(true, rowIndex + 1); } } else { for (ProofListener listener : this.listeners) { listener.conclusionReached(false, rowIndex + 1); } } } /** * Needs to be called after a proof has been loaded/deserialized */ public void load() { parser = new Parser(); this.listeners = new ArrayList<ProofListener>(); isLoaded = true; } public void registerProofListener(ProofListener listener) { this.listeners.add(listener); } //Only for debugging, do not use this for actual implementation public Box getData() { return proofData; } public void printBoxes() { proofData.printBoxes(); } public void printProof(boolean zeroBasedNumbering) { int x = zeroBasedNumbering ? 0 : 1; proofData.printRows(1, x); } public void rulePromptUpdate(int rowNr, int promptNumber, String newValue) { //System.out.println("rulePromptUpdate rowNr:" + rowNr + " promptNumber:" + promptNumber + " newValue:" + newValue); int rowIndex = rowNr - 1; ProofRow row = proofData.getRow(rowNr - 1); Rule rule = row.getRule(); if (rule == null) return; //System.out.println(rowIndex); //System.out.println(rule.toString()); try { rule.updateReference(promptNumber, newValue); } //if the string is not of the correct format ie an integer or interval catch (NumberFormatException e) { System.out.println("Incorrect reference format"); } //if the promptNumber does not match the rule object, for example ConjunctionIntro has 2 references, //so promptNumber = 3 wouldn't make sense catch (IllegalArgumentException e) { System.out.println("Invalid argument for " + rule.getClass().getSimpleName()); } generateRow(rowIndex); // verifyProof(rowIndex); verifyProof(); printProof("rulePromptUpdate"); } private void generateRow(int rowIndex) { Preferences prefs = userRoot().node("General"); if (!prefs.getBoolean("generate", true)) return; assert (rowIndex < proofData.size()); ProofRow row = proofData.getRow(rowIndex); Rule rule = row.getRule(); if (rule == null || rule.hasCompleteInfo() == false || row.getFormula() != null) { return; } Formula generated = null; try { generated = rule.generateFormula(proofData, rowIndex); } catch (VerificationInputException e) { return; } if (generated == null) return; row.setFormula(generated); for (ProofListener listener : this.listeners) { listener.rowUpdated(generated.toString(), true, rowIndex + 1); } } public String getPremisesStr(){ StringBuilder strB = new StringBuilder(); String prefix = ""; for(int i = 0; i < proofData.size(); i++){ ProofRow row = proofData.getRow(i); if(row.getRule() == null) continue; else if(row.getRule() instanceof Premise){ strB.append( prefix +(row.getFormula() == null ? row.getUserInput() : row.getFormula()+"") ); prefix = ", "; } } return strB.toString(); } public String getConclusionStr(){ return conclusion == null ? "" : conclusion+""; } public void printRowScopes(boolean zeroBasedNumbering) { proofData.printRowScopes(zeroBasedNumbering); } public void printIntervalScopes(boolean zeroBasedNumbering) { proofData.printIntervalScopes(zeroBasedNumbering); } public List<ProofListener.RowInfo> getProofInfo(){ ArrayList<ProofListener.RowInfo> returnList = new ArrayList<ProofListener.RowInfo>(); proofData.fillList(returnList); return returnList; } public void printProof(String updateAction){ System.out.println(updateAction); System.out.println("Premises: "+getPremisesStr()+", Conclusion: "+conclusion); boolean zeroBasedNumbering = false; int x = zeroBasedNumbering ? 0 : 1; proofData.printRows(1, x); System.out.println("==========================================================="); } public void updatedPremises(){ for(ProofListener pl : this.listeners){ pl.premisesUpdated(this.getPremisesStr()); } } }
package verification.platu.project; import java.io.IOException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import lpn.parser.LhpnFile; import org.antlr.runtime.ANTLRFileStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.TokenStream; import verification.platu.lpn.DualHashMap; import verification.platu.lpn.io.Instance; import verification.platu.lpn.io.PlatuGrammarLexer; import verification.platu.lpn.io.PlatuInstLexer; import verification.platu.main.Options; import verification.platu.stategraph.*; import verification.platu.TimingAnalysis.*; import verification.platu.logicAnalysis.Analysis; import verification.platu.logicAnalysis.CompositionalAnalysis; import verification.platu.lpn.LPN; import verification.platu.lpn.LPNTranRelation; import verification.platu.lpn.io.PlatuGrammarParser; import verification.platu.lpn.io.PlatuInstParser; import verification.platu.stategraph.State; import verification.platu.stategraph.StateGraph; public class Project { protected String label; /* 1. Each design unit has an unique label index. * 2. The indices of all design units are sequential starting from 0. * */ protected List<StateGraph> designUnitSet; protected LPNTranRelation lpnTranRelation = null; protected CompositionalAnalysis analysis = null; public Project() { this.label = ""; this.designUnitSet = new ArrayList<StateGraph>(1); lpnTranRelation = new LPNTranRelation(this.designUnitSet); } public Project(LhpnFile lpn) { this.label = ""; this.designUnitSet = new ArrayList<StateGraph>(1); StateGraph stateGraph = new StateGraph(lpn); designUnitSet.add(stateGraph); //stateGraph.printStates(); } public Project(ArrayList<LhpnFile> lpns) { this.label = ""; this.designUnitSet = new ArrayList<StateGraph>(lpns.size()); for (int i=0; i<lpns.size(); i++) { LhpnFile lpn = lpns.get(i); StateGraph stateGraph = new StateGraph(lpn); designUnitSet.add(stateGraph); } } /** * Find the SG for the entire project where each project state is a tuple of * local states * */ public StateGraph[] search() { validateInputs(); // if(Options.getSearchType().equals("compositional")){ // this.analysis = new CompositionalAnalysis(); // if(Options.getParallelFlag()){ // this.analysis.parallelCompositionalFindSG(this.designUnitSet); // else{ // this.analysis.findReducedSG(this.designUnitSet); // return; long start = System.currentTimeMillis(); int lpnCnt = designUnitSet.size(); /* Prepare search by placing LPNs in an array in the order of their indices.*/ StateGraph[] sgArray = new StateGraph[lpnCnt]; int idx = 0; for (StateGraph du : designUnitSet) { LhpnFile lpn = du.getLpn(); lpn.setIndex(idx++); sgArray[lpn.getIndex()] = du; } // Initialize the project state HashMap<String, Integer> varValMap = new HashMap<String, Integer>(); State[] initStateArray = new State[lpnCnt]; for (int index = 0; index < lpnCnt; index++) { LhpnFile curLpn = sgArray[index].getLpn(); StateGraph curSg = sgArray[index]; initStateArray[index] = curSg.getInitState(); //curLpn.getInitState(); int[] curStateVector = initStateArray[index].getVector(); varValMap = curLpn.getAllVarsWithValues(curStateVector); // HashMap<String, String> vars = curLpn.getAllOutputs();//curLpn.getAllOutputs(); // DualHashMap<String, Integer> VarIndexMap = curLpn.getVarIndexMap(); // for(String var : vars.keySet()) { // varValMap.put(var, curStateVector[VarIndexMap.getValue(var)]); } // TODO: (future) Need to adjust the transition vector as well? // Adjust the value of the input variables in LPN in the initial state. // Add the initial states into their respective LPN. for (int index = 0; index < lpnCnt; index++) { StateGraph curSg = sgArray[index]; initStateArray[index].update(curSg, varValMap, curSg.getLpn().getVarIndexMap()); initStateArray[index] = curSg.addState(initStateArray[index]); } // if (Options.getTimingAnalysisFlag()) { // new TimingAnalysis(sgArray); // return; // else if(!Options.getTimingAnalysisFlag()) { // Analysis tmp = new Analysis(sgArray, initStateArray, lpnTranRelation, Options.getSearchType()); // // Analysis tmp = new Analysis(lpnList, curStateArray, // // lpnTranRelation, "dfs_por"); // //Analysis tmp = new Analysis(modArray, initStateArray, lpnTranRelation, "dfs"); // //Analysis tmp = new Analysis(modArray, initStateArray, lpnTranRelation, "dfs_noDisabling"); // else { // return; /* Entry point for the timed analysis. */ if(Options.getTimingAnalysisFlag()) { System.out.print("Wow, wow."); return new StateGraph[0]; } Analysis dfsStateExploration = new Analysis(sgArray); StateGraph[] stateGraphArray = dfsStateExploration.search_dfs(sgArray, initStateArray); long elapsedTimeMillis = System.currentTimeMillis() - start; float elapsedTimeSec = elapsedTimeMillis/1000F; System.out.println("---> total runtime: " + elapsedTimeSec + " sec\n"); return stateGraphArray; } public Set<LPN> readLpn(final String src_file) { Set<LPN> lpnSet = null; try { if (!src_file.endsWith(".lpn")) { System.err.println("Invalid file extention"); System.exit(1); } ANTLRFileStream input = new ANTLRFileStream(src_file); PlatuGrammarLexer lexer = new PlatuGrammarLexer(input); TokenStream tokenStream = new CommonTokenStream(lexer); PlatuGrammarParser parser = new PlatuGrammarParser(tokenStream); lpnSet = parser.lpn(this); } catch (Exception ex) { Logger.getLogger(Project.class.getName()).log(Level.SEVERE, null, ex); } return lpnSet; } /** * Find the SG for the entire project where each project state is a tuple of * local states. Use partial order reduction during dfs search. * @param outputDotFile * @return * */ public StateGraph searchWithPOR() { validateInputs(); // if(Options.getSearchType().equals("compositional")){ // this.analysis = new CompositionalAnalysis(); // if(Options.getParallelFlag()){ // this.analysis.parallelCompositionalFindSG(this.designUnitSet); // else{ // this.analysis.findReducedSG(this.designUnitSet); // return; long start = System.currentTimeMillis(); int lpnCnt = designUnitSet.size(); /* Prepare search by placing LPNs in an array in the order of their indices.*/ StateGraph[] sgArray = new StateGraph[lpnCnt]; int idx = 0; for (StateGraph du : designUnitSet) { LhpnFile lpn = du.getLpn(); lpn.setIndex(idx++); sgArray[lpn.getIndex()] = du; } // Initialize the project state HashMap<String, Integer> varValMap = new HashMap<String, Integer>(); State[] initStateArray = new State[lpnCnt]; for (int index = 0; index < lpnCnt; index++) { LhpnFile curLpn = sgArray[index].getLpn(); StateGraph curSg = sgArray[index]; initStateArray[index] = curSg.getInitState(); //curLpn.getInitState(); int[] curStateVector = initStateArray[index].getVector(); varValMap = curLpn.getAllVarsWithValues(curStateVector); // DualHashMap<String, Integer> VarIndexMap = curLpn.getVarIndexMap(); // HashMap<String, String> outVars = curLpn.getAllOutputs(); // for(String var : outVars.keySet()) { // varValMap.put(var, curStateVector[VarIndexMap.getValue(var)]); } // TODO: (future) Need to adjust the transition vector as well? // Adjust the value of the input variables in LPN in the initial state. // Add the initial states into their respective LPN. for (int index = 0; index < lpnCnt; index++) { StateGraph curLpn = sgArray[index]; initStateArray[index].update(curLpn, varValMap, curLpn.getLpn().getVarIndexMap()); initStateArray[index] = curLpn.addState(initStateArray[index]); } StateGraph stateGraph; Analysis dfsStateExplorationWithPOR = new Analysis(sgArray); stateGraph = dfsStateExplorationWithPOR.search_dfsPORSingleLpn(sgArray, initStateArray); long elapsedTimeMillis = System.currentTimeMillis() - start; float elapsedTimeSec = elapsedTimeMillis/1000F; System.out.println("---> total runtime: " + elapsedTimeSec + " sec\n"); return stateGraph; } public void readLpn(List<String> fileList) { for(String srcFile : fileList){ if (!srcFile.endsWith(".lpn")) { System.err.println("Invalid file extention"); System.exit(1); } ANTLRFileStream input = null; try { input = new ANTLRFileStream(srcFile); } catch (IOException e) { System.err.println("error: error reading " + srcFile); System.exit(1); } PlatuInstLexer lexer = new PlatuInstLexer(input); TokenStream tokenStream = new CommonTokenStream(lexer); PlatuInstParser parser = new PlatuInstParser(tokenStream); try { parser.parseLpnFile(this); } catch (RecognitionException e) { System.err.println("error: error parsing " + srcFile); System.exit(1); } } PlatuInstParser.includeSet.removeAll(fileList); for(String srcFile : PlatuInstParser.includeSet){ if (!srcFile.endsWith(".lpn")) { System.err.println("Invalid file extention"); System.exit(1); } ANTLRFileStream input = null; try { input = new ANTLRFileStream(srcFile); } catch (IOException e) { System.err.println("error: error reading " + srcFile); System.exit(1); } PlatuInstLexer lexer = new PlatuInstLexer(input); TokenStream tokenStream = new CommonTokenStream(lexer); PlatuInstParser parser = new PlatuInstParser(tokenStream); try { parser.parseLpnFile(this); } catch (RecognitionException e) { System.err.println("error: error parsing " + srcFile); System.exit(1); } } verification.platu.lpn.LPN.nextID = 1; HashMap<String, LPN> instanceMap = new HashMap<String, LPN>(); for(Instance inst : PlatuInstParser.InstanceList){ LPN lpn = PlatuInstParser.LpnMap.get(inst.getLpnLabel()); if(lpn == null){ System.err.println("error: class " + inst.getLpnLabel() + " does not exist"); System.exit(1); } LPN instLpn = lpn.instantiate(inst.getName()); instanceMap.put(instLpn.getLabel(), instLpn); this.designUnitSet.add(instLpn.getStateGraph()); } // TODO: (irrelevant) Is this really needed??? /* for(StateGraph sg : this.designUnitSet){ sg.getLpn().setGlobals(this.designUnitSet); } */ for(Instance inst : PlatuInstParser.InstanceList){ LPN dstLpn = instanceMap.get(inst.getName()); if(dstLpn == null){ System.err.println("error: instance " + inst.getName() + " does not exist"); System.exit(1); } List<String> argumentList = dstLpn.getArgumentList(); List<String> varList = inst.getVariableList(); List<String> modList = inst.getModuleList(); if(argumentList.size() != varList.size()){ System.err.println("error: incompatible number of arguments for instance " + inst.getName()); System.exit(1); } for(int i = 0; i < argumentList.size(); i++){ LPN srcLpn = instanceMap.get(modList.get(i)); if(srcLpn == null){ System.err.println("error: instance " + modList.get(i) + " does not exist"); System.exit(1); } String outputVar = varList.get(i); String inputVar = argumentList.get(i); srcLpn.connect(outputVar, dstLpn, inputVar); } } } /** * @return the designUnitSet */ public List<StateGraph> getDesignUnitSet() { return designUnitSet; } /** * Validates each lpn's input variables are driven by another lpn's output. */ private void validateInputs(){ boolean error = false; for(StateGraph sg : designUnitSet){ for(String input : sg.getLpn().getAllInputs().keySet()){ boolean connected = false; for(StateGraph sg2 : designUnitSet){ if(sg == sg2) continue; if(sg2.getLpn().getAllOutputs().keySet().contains(input)){ connected = true; break; } } if(!connected){ error = true; System.err.println("error in lpn " + sg.getLpn().getLabel() + ": input variable '" + input + "' is not dependent on an output"); } } } if(error){ System.exit(1); } } }
package ashley.core; import java.util.BitSet; import ashley.signals.Signal; import ashley.utils.Array; import ashley.utils.ImmutableArray; import ashley.utils.ObjectMap; import ashley.utils.ObjectMap.Keys; /** * Entities are simple containers. They can hold components that give them "data". The component's data * is then in return process by systems. * * An entity can only hold one instance of a component type. So you can't add two PositionComponents to the * same entity. Sorry. * * @author Stefan Bachmann */ public class Entity { private static int nextIndex; /** Unique entity index for fast retrieval */ private int index; /** The hashmap that holds all the components hashed via their class type */ private ObjectMap<Class<? extends Component>, Component> components; /** An auxiliary array for quick access to all the components of an entity */ private Array<Component> componentsArray; /** A bitset describing all the components in this entity. For quick matching. */ private BitSet componentBits; /** A bitset describing all the systems this entity was matched with. */ private BitSet familyBits; /** A flag that can be used to bit mask this entity. Up to the user to manage. */ public int flags; /** Will dispatch an event when a component is added. */ public Signal<Entity> componentAdded; /** Will dispatch an event when a component is removed. */ public Signal<Entity> componentRemoved; /** * Creates an empty Entity. */ public Entity(){ components = new ObjectMap<Class<? extends Component>, Component>(); componentsArray = new Array<Component>(); componentBits = new BitSet(); familyBits = new BitSet(); flags = 0; index = nextIndex++; componentAdded = new Signal<Entity>(); componentRemoved = new Signal<Entity>(); } /** * Add a component to this Entity. If a component of the same type already exists, it'll be replaced. * @param component The component to add * @return The entity for easy chaining */ public Entity add(Component component){ Class<? extends Component> componentClass = component.getClass(); for (int i = 0; i < componentsArray.size; ++i) { if (componentsArray.get(i).getClass() == componentClass) { componentsArray.removeIndex(i); break; } } components.put(component.getClass(), component); componentsArray.add(component); componentBits.set(ComponentType.getIndexFor(component.getClass())); componentAdded.dispatch(this); return this; } /** * Removes the component of the specified type. Since there is only ever one component of one type, we * don't need an instance reference. * @param componentType The Component to remove * @return The removed component, or null if the Entity did no contain such a component */ public Component remove(Class<? extends Component> componentType){ Component removeComponent = components.get(componentType, null); if(removeComponent != null){ components.remove(componentType); componentsArray.removeValue(removeComponent, true); componentBits.clear(ComponentType.getIndexFor(componentType)); componentRemoved.dispatch(this); components.remove(componentType); } return removeComponent; } /** * Removes all the entity components */ public void removeAll() { Keys<Class<? extends Component>> keys = components.keys(); while (keys.hasNext()) { remove(keys.next()); keys = components.keys(); } } /** * Quick and dirty component retrieval * @param componentType The Component class to retrieve * @return The Component */ public <T extends Component> T getComponent(Class<T> componentType){ return componentType.cast(components.get(componentType)); } /** * Quick way of checking whether an entity has a component or not * @param componentType The Component class to check * @return True if the entity has a Component of that class, False if it doesn't */ public boolean hasComponent(Class<? extends Component> componentType) { return componentBits.get(ComponentType.getIndexFor(componentType)); } /** * @return this Entity's component bits, describing all the components it contains */ public BitSet getComponentBits(){ return componentBits; } /** * @return immutable array with all the entity components */ public ImmutableArray<Component> getComponents() { return componentsArray; } /** * @return this Entity's family bits, describing all the systems it currently is being processed with */ public BitSet getFamilyBits(){ return familyBits; } /** * @return this entity's unique index */ public int getIndex(){ return index; } }