answer
stringlengths
17
10.2M
package org.hcjf.io.net.http; import org.hcjf.encoding.MimeType; import org.hcjf.errors.Errors; import org.hcjf.properties.SystemProperties; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.FileAttribute; import java.security.MessageDigest; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * This class publish some local folder in the web environment. * @author javaito */ public class FolderContext extends Context { private final Path baseFolder; private final String name; private final String defaultFile; private final String[] names; private final MessageDigest messageDigest; public FolderContext(String name, Path baseFolder, String defaultFile) { super(START_CONTEXT + URI_FOLDER_SEPARATOR + name + END_CONTEXT); if(baseFolder == null) { throw new NullPointerException(Errors.getMessage(Errors.ORG_HCJF_IO_NET_HTTP_1)); } if(!baseFolder.toFile().exists()) { throw new IllegalArgumentException(Errors.getMessage(Errors.ORG_HCJF_IO_NET_HTTP_2)); } if(verifyJatFormat(baseFolder)) { try { baseFolder = unzipJar(baseFolder); } catch (IOException e) { throw new IllegalArgumentException("Unable to unzip jar file", e); } } else if(verifyZipFormat(baseFolder)) { try { baseFolder = unzip(baseFolder); } catch (IOException e) { throw new IllegalArgumentException("Unable to unzip file", e); } } this.name = name; this.baseFolder = baseFolder; this.defaultFile = defaultFile; this.names = name.split(URI_FOLDER_SEPARATOR); try { this.messageDigest = MessageDigest.getInstance( SystemProperties.get(SystemProperties.Net.Http.DEFAULT_FILE_CHECKSUM_ALGORITHM)); } catch (Exception ex) { throw new IllegalArgumentException(Errors.getMessage(Errors.ORG_HCJF_IO_NET_HTTP_9), ex); } } public FolderContext(String name, Path baseFolder) { this(name, baseFolder, null); } /** * Verify if the specific path is a zip file or not. * @param path Specific path. * @return True if the path point to the zip file. */ private boolean verifyZipFormat(Path path) { boolean result = false; try { new ZipFile(path.toFile()).getName(); result = true; } catch (Exception ex){} return result; } /** * Verify if the specific path is a jar file or not. * @param path Specific path. * @return True if the path point to the jar file. */ private boolean verifyJatFormat(Path path) { boolean result = false; try { new JarFile(path.toFile()).getName(); result = true; } catch (Exception ex) {} return result; } /** * Unzip the specific file and create a temporal folder with all the content and returns * the new base folder for the context. * @param zipFilePath Specific file. * @return New base folder. */ private Path unzip(Path zipFilePath) throws IOException { ZipFile zipFile = new ZipFile(zipFilePath.toFile()); Path tempFolder = Files.createTempDirectory( SystemProperties.getPath(SystemProperties.Net.Http.Folder.ZIP_CONTAINER), SystemProperties.get(SystemProperties.Net.Http.Folder.ZIP_TEMP_PREFIX)); int errors; Set<String> processedNames = new TreeSet<>(); do { errors = 0; Enumeration<? extends ZipEntry> entryEnumeration = zipFile.entries(); while (entryEnumeration.hasMoreElements()) { ZipEntry zipEntry = entryEnumeration.nextElement(); if(!processedNames.contains(zipEntry.getName())) { try { if (zipEntry.isDirectory()) { Files.createDirectory(tempFolder.resolve(zipEntry.getName())); } else { Path file = Files.createFile(tempFolder.resolve(zipEntry.getName())); try (InputStream inputStream = zipFile.getInputStream(zipEntry); FileOutputStream fileOutputStream = new FileOutputStream(file.toFile())) { byte[] buffer = new byte[2048]; int readSize = inputStream.read(buffer); while (readSize >= 0) { fileOutputStream.write(buffer, 0, readSize); fileOutputStream.flush(); readSize = inputStream.read(buffer); } } } } catch (IOException ex) { errors++; } processedNames.add(zipEntry.getName()); } } } while(errors > 0); return tempFolder; } /** * Unzip the specific file and create a temporal folder with all the content and returns * the new base folder for the context. * @param jarFilePath Specific file. * @return New base folder. */ private Path unzipJar(Path jarFilePath) throws IOException { JarFile jarFile = new JarFile(jarFilePath.toFile()); Path tempFolder = Files.createTempDirectory( SystemProperties.getPath(SystemProperties.Net.Http.Folder.JAR_CONTAINER), SystemProperties.get(SystemProperties.Net.Http.Folder.JAR_TEMP_PREFIX)); int errors; Set<String> processedNames = new TreeSet<>(); do { errors = 0; Enumeration<? extends ZipEntry> entryEnumeration = jarFile.entries(); while (entryEnumeration.hasMoreElements()) { ZipEntry zipEntry = entryEnumeration.nextElement(); if(!processedNames.contains(zipEntry.getName())) { try { if (zipEntry.isDirectory()) { Files.createDirectory(tempFolder.resolve(zipEntry.getName())); } else { Path file = Files.createFile(tempFolder.resolve(zipEntry.getName())); try (InputStream inputStream = jarFile.getInputStream(zipEntry); FileOutputStream fileOutputStream = new FileOutputStream(file.toFile())) { byte[] buffer = new byte[2048]; int readSize = inputStream.read(buffer); while (readSize >= 0) { fileOutputStream.write(buffer, 0, readSize); fileOutputStream.flush(); readSize = inputStream.read(buffer); } } } } catch (IOException ex) { errors++; } processedNames.add(zipEntry.getName()); } } } while(errors > 0); return tempFolder; } /** * This method is called when there comes a http package addressed to this * context. * * @param request All the request information. * @return Return an object with all the response information. */ @Override public HttpResponse onContext(HttpRequest request) { List<String> elements = request.getPathParts(); for(String forbidden : SystemProperties.getList(SystemProperties.Net.Http.Folder.FORBIDDEN_CHARACTERS)) { for(String element : elements) { if (element.contains(forbidden)) { throw new IllegalArgumentException(Errors.getMessage(Errors.ORG_HCJF_IO_NET_HTTP_3, forbidden, request.getContext())); } } } //The first value is a empty value, and the second value is the base public context. Path path = baseFolder.toAbsolutePath(); boolean emptyElement = true; for(String element : elements) { if(!element.isEmpty() && Arrays.binarySearch(names, element) < 0) { path = path.resolve(element); emptyElement = false; } } if(emptyElement && defaultFile != null) { path = path.resolve(defaultFile); } HttpResponse response = new HttpResponse(); File file = path.toFile(); if(file.exists()) { if (file.isDirectory()) { StringBuilder list = new StringBuilder(); for(File subFile : file.listFiles()) { list.append(String.format(SystemProperties.get(SystemProperties.Net.Http.Folder.DEFAULT_HTML_ROW), path.relativize(baseFolder).resolve(request.getContext()).resolve(subFile.getName()).toString(), subFile.getName())); } String htmlBody = String.format(SystemProperties.get(SystemProperties.Net.Http.Folder.DEFAULT_HTML_BODY), list.toString()); String document = String.format(SystemProperties.get(SystemProperties.Net.Http.Folder.DEFAULT_HTML_DOCUMENT), file.getName(), htmlBody); byte[] body = document.getBytes(); response.addHeader(new HttpHeader(HttpHeader.CONTENT_LENGTH, Integer.toString(body.length))); response.addHeader(new HttpHeader(HttpHeader.CONTENT_TYPE, MimeType.HTML)); response.setResponseCode(HttpResponseCode.OK); response.setBody(body); } else { byte[] body; String checksum; try { body = Files.readAllBytes(file.toPath()); synchronized (this) { checksum = new String(Base64.getEncoder().encode(messageDigest.digest(body))); messageDigest.reset(); } } catch (IOException ex) { throw new RuntimeException(Errors.getMessage(Errors.ORG_HCJF_IO_NET_HTTP_4, Paths.get(request.getContext(), file.getName())), ex); } Integer responseCode = HttpResponseCode.OK; HttpHeader ifNonMatch = request.getHeader(HttpHeader.IF_NONE_MATCH); if(ifNonMatch != null) { if(checksum.equals(ifNonMatch.getHeaderValue())) { responseCode = HttpResponseCode.NOT_MODIFIED; } } String[] nameExtension = file.getName().split(SystemProperties.get(SystemProperties.Net.Http.Folder.FILE_EXTENSION_REGEX)); String extension = nameExtension.length == 2 ? nameExtension[1] : MimeType.BIN; response.setResponseCode(responseCode); MimeType mimeType = MimeType.fromSuffix(extension); response.addHeader(new HttpHeader(HttpHeader.CONTENT_TYPE, mimeType == null ? MimeType.BIN : mimeType.toString())); response.addHeader(new HttpHeader(HttpHeader.E_TAG, checksum)); response.addHeader(new HttpHeader(HttpHeader.LAST_MODIFIED, SystemProperties.getDateFormat(SystemProperties.Net.Http.RESPONSE_DATE_HEADER_FORMAT_VALUE). format(new Date(file.lastModified())))); if(responseCode.equals(HttpResponseCode.OK)) { HttpHeader acceptEncodingHeader = request.getHeader(HttpHeader.ACCEPT_ENCODING); if(acceptEncodingHeader != null) { boolean notAcceptable = true; for(String group : acceptEncodingHeader.getGroups()) { if (group.equalsIgnoreCase(HttpHeader.GZIP) || group.equalsIgnoreCase(HttpHeader.DEFLATE)) { try (ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(out)) { gzipOutputStream.write(body); gzipOutputStream.flush(); gzipOutputStream.finish(); body = out.toByteArray(); response.addHeader(new HttpHeader(HttpHeader.CONTENT_ENCODING, HttpHeader.GZIP)); notAcceptable = false; break; } catch (Exception ex) { //TODO: Log.w(); } } else if (group.equalsIgnoreCase(HttpHeader.IDENTITY)) { response.addHeader(new HttpHeader(HttpHeader.CONTENT_ENCODING, HttpHeader.IDENTITY)); notAcceptable = false; break; } } if (notAcceptable) { response.setResponseCode(HttpResponseCode.NOT_ACCEPTABLE); } } if(responseCode.equals(HttpResponseCode.OK)) { response.addHeader(new HttpHeader(HttpHeader.CONTENT_LENGTH, Integer.toString(body.length))); response.setBody(body); } } } } else { throw new IllegalArgumentException(Errors.getMessage(Errors.ORG_HCJF_IO_NET_HTTP_5, request.getContext())); } return response; } }
package org.jake.depmanagement.ivy; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.ivy.Ivy; import org.apache.ivy.core.IvyPatternHelper; import org.apache.ivy.core.cache.ResolutionCacheManager; import org.apache.ivy.core.deliver.DeliverOptions; import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.module.descriptor.Configuration; import org.apache.ivy.core.module.descriptor.DefaultArtifact; import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor; import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor; import org.apache.ivy.core.module.descriptor.MDArtifact; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.core.report.ArtifactDownloadReport; import org.apache.ivy.core.report.ResolveReport; import org.apache.ivy.core.resolve.ResolveOptions; import org.apache.ivy.core.settings.IvySettings; import org.apache.ivy.plugins.parser.m2.PomModuleDescriptorWriter; import org.apache.ivy.plugins.parser.m2.PomWriterOptions; import org.apache.ivy.plugins.resolver.DependencyResolver; import org.jake.JakeException; import org.jake.JakeLog; import org.jake.JakeOptions; import org.jake.depmanagement.JakeArtifact; import org.jake.depmanagement.JakeDependencies; import org.jake.depmanagement.JakeModuleId; import org.jake.depmanagement.JakeRepo; import org.jake.depmanagement.JakeRepos; import org.jake.depmanagement.JakeResolutionParameters; import org.jake.depmanagement.JakeScope; import org.jake.depmanagement.JakeScopeMapping; import org.jake.depmanagement.JakeVersion; import org.jake.depmanagement.JakeVersionedModule; import org.jake.publishing.JakeIvyPublication; import org.jake.publishing.JakeMavenPublication; import org.jake.utils.JakeUtilsString; public final class JakeIvy { private static final JakeVersionedModule ANONYMOUS_MODULE = JakeVersionedModule.of( JakeModuleId.of("anonymousGroup", "anonymousName"), JakeVersion.of("anonymousVersion")); private final Ivy ivy; private JakeIvy(Ivy ivy) { super(); this.ivy = ivy; ivy.getLoggerEngine().setDefaultLogger(new MessageLogger()); } public static JakeIvy of(IvySettings ivySettings) { final Ivy ivy = Ivy.newInstance(ivySettings); return new JakeIvy(ivy); } public static JakeIvy of(JakeRepo repo) { return JakeIvy.of(JakeRepos.of(repo)); } public static JakeIvy of(JakeRepos repos) { final IvySettings ivySettings = new IvySettings(); Translations.populateIvySettingsWithRepo(ivySettings, repos); return of(ivySettings); } public static JakeIvy of() { return of(JakeRepos.mavenCentral()); } public Set<JakeArtifact> resolve(JakeDependencies deps, JakeScope resolvedScope) { return resolve(ANONYMOUS_MODULE, deps, resolvedScope, JakeResolutionParameters.of()); } public Set<JakeArtifact> resolve(JakeDependencies deps, JakeScope resolvedScope, JakeResolutionParameters parameters) { return resolve(ANONYMOUS_MODULE, deps, resolvedScope, parameters); } public Set<JakeArtifact> resolve(JakeVersionedModule module, JakeDependencies deps, JakeScope resolvedScope, JakeResolutionParameters parameters) { final DefaultModuleDescriptor moduleDescriptor = Translations.toPublicationFreeModule(module, deps, parameters.defaultScope(), parameters.defaultMapping()); final ResolveOptions resolveOptions = new ResolveOptions(); resolveOptions.setConfs(new String[] {resolvedScope.name()}); resolveOptions.setTransitive(true); resolveOptions.setOutputReport(JakeOptions.isVerbose()); resolveOptions.setLog(logLevel()); resolveOptions.setRefresh(parameters.refreshed()); final ResolveReport report; try { report = ivy.resolve(moduleDescriptor, resolveOptions); } catch (final Exception e1) { throw new RuntimeException(e1); } final Set<JakeArtifact> result = new HashSet<JakeArtifact>(); final ArtifactDownloadReport[] artifactDownloadReports = report.getAllArtifactsReports(); for (final String conf : resolveOptions.getConfs()) { result.addAll(getArtifacts(conf, artifactDownloadReports)); } return result; } /** * Get artifacts of the given modules published for the specified scopes (no transitive resolution). */ public AttachedArtifacts getArtifacts(Iterable<JakeVersionedModule> modules, JakeScope ...scopes) { //final String defaultConf = "default"; final DefaultModuleDescriptor moduleDescriptor = Translations.toUnpublished(ANONYMOUS_MODULE); for (final JakeScope jakeScope : scopes) { moduleDescriptor.addConfiguration(new Configuration(jakeScope.name())); } for (final JakeVersionedModule module : modules) { final ModuleRevisionId moduleRevisionId = Translations.from(module); final DefaultDependencyDescriptor dependency = new DefaultDependencyDescriptor(moduleRevisionId, true, false); for (final JakeScope scope : scopes) { dependency.addDependencyConfiguration(scope.name(), scope.name()); } moduleDescriptor.addDependency(dependency); } final AttachedArtifacts result = new AttachedArtifacts(); final ResolveOptions resolveOptions = new ResolveOptions() .setTransitive(false) .setOutputReport(JakeOptions.isVerbose()) .setRefresh(false); resolveOptions.setLog(logLevel()); for (final JakeScope scope : scopes ) { resolveOptions.setConfs(Translations.toConfNames(scope)); final ResolveReport report; try { report = ivy.resolve(moduleDescriptor, resolveOptions); } catch (final Exception e1) { throw new RuntimeException(e1); } final ArtifactDownloadReport[] artifactDownloadReports = report.getAllArtifactsReports(); for (final ArtifactDownloadReport artifactDownloadReport : artifactDownloadReports) { final JakeArtifact artifact = Translations.to(artifactDownloadReport.getArtifact(), artifactDownloadReport.getLocalFile()); result.add(scope, artifact); } } return result; } /** * Publish the specified module. Dependencies, default scopes and mapping are necessary * in order to generate the ivy.xml file. * * @param versionedModule The module/version to publish. * @param publication The artifacts to publish. * @param dependencies The dependencies of the published module. * @param defaultScope The default scope of the published module * @param defaultMapping The default scope mapping of the published module * @param deliveryDate The delivery date. */ public void publish(JakeVersionedModule versionedModule, JakeIvyPublication publication, JakeDependencies dependencies, JakeScope defaultScope, JakeScopeMapping defaultMapping, Date deliveryDate) { final JakeDependencies publishedDependencies = resolveDependencies(versionedModule, dependencies); final ModuleDescriptor moduleDescriptor = createModuleDescriptor(versionedModule, publication, publishedDependencies, defaultScope, defaultMapping, deliveryDate); publishIvyArtifacts(publication, deliveryDate, moduleDescriptor); } public void publish(JakeVersionedModule versionedModule, JakeMavenPublication publication, JakeDependencies dependencies, Date deliveryDate) { final JakeDependencies publishedDependencies = resolveDependencies(versionedModule, dependencies); final ModuleDescriptor moduleDescriptor = createModuleDescriptor(versionedModule, publication, publishedDependencies,deliveryDate); publishMavenArtifacts(publication, deliveryDate, moduleDescriptor); } @SuppressWarnings("unchecked") private JakeDependencies resolveDependencies(JakeVersionedModule module, JakeDependencies dependencies) { if (!dependencies.hasDynamicAndResovableVersions()) { return dependencies; } final ModuleRevisionId moduleRevisionId = Translations.from(module); final ResolutionCacheManager cacheManager = this.ivy.getSettings().getResolutionCacheManager(); final File cachedIvyFile = cacheManager.getResolvedIvyFileInCache(moduleRevisionId); if (!cachedIvyFile.exists()) { JakeLog.start("Cached resolved ivy file not found for " + module + ". Performing a fresh resolve"); final ModuleDescriptor moduleDescriptor = Translations.toPublicationFreeModule(module, dependencies, null, null); final ResolveOptions resolveOptions = new ResolveOptions(); resolveOptions.setConfs(new String[] {"*"}); resolveOptions.setTransitive(false); resolveOptions.setOutputReport(JakeOptions.isVerbose()); resolveOptions.setLog(logLevel()); resolveOptions.setRefresh(true); final ResolveReport report; try { report = ivy.resolve(moduleDescriptor, resolveOptions); } catch (final Exception e1) { throw new IllegalStateException(e1); } finally { JakeLog.done(); } if (report.hasError()) { JakeLog.error(report.getAllProblemMessages()); cachedIvyFile.delete(); throw new JakeException("Error while reloving dependencies : " + JakeUtilsString.join(report.getAllProblemMessages(), ", ")); } } try { cacheManager.getResolvedModuleDescriptor(moduleRevisionId); } catch (final ParseException e) { throw new IllegalStateException(e); } catch (final IOException e) { throw new IllegalStateException(e); } return dependencies; } private void publishIvyArtifacts(JakeIvyPublication publication, Date date, ModuleDescriptor moduleDescriptor) { final DependencyResolver resolver = this.ivy.getSettings().getDefaultResolver(); final ModuleRevisionId ivyModuleRevisionId = moduleDescriptor.getModuleRevisionId(); try { resolver.beginPublishTransaction(ivyModuleRevisionId, true); } catch (final IOException e) { throw new IllegalStateException(e); } for (final JakeIvyPublication.Artifact artifact : publication) { final Artifact ivyArtifact = Translations.toPublishedArtifact(artifact, ivyModuleRevisionId, date); try { resolver.publish(ivyArtifact, artifact.file, true); } catch (final IOException e) { throw new IllegalStateException(e); } } // Publish Ivy file final File publishedIvy = this.ivy.getSettings().resolveFile(IvyPatternHelper.substitute(ivyPatternForIvyFiles(), moduleDescriptor.getResolvedModuleRevisionId())); try { final Artifact artifact = MDArtifact.newIvyArtifact(moduleDescriptor); resolver.publish(artifact, publishedIvy, true); } catch (final IOException e) { throw new RuntimeException(e); } try { commitOrAbortPublication(resolver); } finally { publishedIvy.delete(); } } private void publishMavenArtifacts(JakeMavenPublication publication, Date date, ModuleDescriptor moduleDescriptor) { final DependencyResolver resolver = this.ivy.getSettings().getDefaultResolver(); final ModuleRevisionId ivyModuleRevisionId = moduleDescriptor.getModuleRevisionId(); try { resolver.beginPublishTransaction(ivyModuleRevisionId, true); } catch (final IOException e) { throw new RuntimeException(e); } for (final JakeMavenPublication.Artifact artifact : publication) { final Artifact mavenArtifact = Translations.toPublishedArtifact(artifact, ivyModuleRevisionId, date); try { resolver.publish(mavenArtifact, artifact.file(), true); } catch (final IOException e) { throw new RuntimeException(e); } } // // Create ivy file // final File ivyXml = this.ivy.getSettings().resolveFile(IvyPatternHelper.substitute(ivyPatternForIvyFiles(), // moduleDescriptor.getResolvedModuleRevisionId())); try { final File pomXml = new File(targetDir(), "pom.xml"); final Artifact artifact = new DefaultArtifact(ivyModuleRevisionId, date, ivyModuleRevisionId.getName(), "xml", "pom", true); PomModuleDescriptorWriter.write(moduleDescriptor, pomXml, new PomWriterOptions()); resolver.publish(artifact, pomXml, true); } catch (final IOException e) { throw new IllegalStateException(e); } try { commitOrAbortPublication(resolver); } finally { // po.delete(); } } private ModuleDescriptor createModuleDescriptor(JakeVersionedModule jakeVersionedModule, JakeIvyPublication publication, JakeDependencies resolvedDependencies, JakeScope defaultScope, JakeScopeMapping defaultMapping, Date deliveryDate) { final ModuleRevisionId moduleRevisionId = Translations.from(jakeVersionedModule); final ResolutionCacheManager cacheManager = this.ivy.getSettings().getResolutionCacheManager(); final File cachedIvyFile = cacheManager.getResolvedIvyFileInCache(moduleRevisionId); final File propsFile = cacheManager.getResolvedIvyPropertiesInCache(moduleRevisionId); final DefaultModuleDescriptor moduleDescriptor = Translations.toPublicationFreeModule(jakeVersionedModule, resolvedDependencies, defaultScope, defaultMapping); Translations.populateModuleDescriptorWithPublication(moduleDescriptor, publication, deliveryDate); try { cacheManager.saveResolvedModuleDescriptor(moduleDescriptor); } catch (final Exception e) { cachedIvyFile.delete(); propsFile.delete(); throw new RuntimeException("Error while creating cache file for " + moduleRevisionId + ". Deleting potentially corrupted cache files.", e); } final DeliverOptions deliverOptions = new DeliverOptions(); if (publication.status != null) { deliverOptions.setStatus(publication.status.name()); } deliverOptions.setPubBranch(publication.branch); deliverOptions.setPubdate(deliveryDate); try { this.ivy.getDeliverEngine().deliver(moduleRevisionId, moduleRevisionId.getRevision(), ivyPatternForIvyFiles(), deliverOptions); } catch (final Exception e) { throw new RuntimeException(e); } return moduleDescriptor; } private ModuleDescriptor createModuleDescriptor(JakeVersionedModule jakeVersionedModule, JakeMavenPublication publication, JakeDependencies resolvedDependencies, Date deliveryDate) { final ModuleRevisionId moduleRevisionId = Translations.from(jakeVersionedModule); final ResolutionCacheManager cacheManager = this.ivy.getSettings().getResolutionCacheManager(); final File cachedIvyFile = cacheManager.getResolvedIvyFileInCache(moduleRevisionId); final File propsFile = cacheManager.getResolvedIvyPropertiesInCache(moduleRevisionId); final DefaultModuleDescriptor moduleDescriptor = Translations.toPublicationFreeModule(jakeVersionedModule, resolvedDependencies, null, null); Translations.populateModuleDescriptorWithPublication(moduleDescriptor, publication, deliveryDate); try { cacheManager.saveResolvedModuleDescriptor(moduleDescriptor); } catch (final Exception e) { cachedIvyFile.delete(); propsFile.delete(); throw new RuntimeException("Error while creating cache file for " + moduleRevisionId + ". Deleting potentially corrupted cache files.", e); } return moduleDescriptor; } private String ivyPatternForIvyFiles() { return targetDir() + "/jake/[organisation]-[module]-[revision]-ivy.xml"; } private String targetDir() { return System.getProperty("java.io.tmpdir"); } private static String logLevel() { if (JakeOptions.isSilent()) { return "quiet"; } if (JakeOptions.isVerbose()) { return "default"; } return "download-only"; } private static Set<JakeArtifact> getArtifacts(String config, ArtifactDownloadReport[] artifactDownloadReports) { final Set<JakeArtifact> result = new HashSet<JakeArtifact>(); for (final ArtifactDownloadReport artifactDownloadReport : artifactDownloadReports) { result.add(Translations.to(artifactDownloadReport.getArtifact(), artifactDownloadReport.getLocalFile())); } return result; } public final class AttachedArtifacts { private final Map<JakeModuleId, Map<JakeScope, Set<JakeArtifact>>> map= new HashMap<JakeModuleId, Map<JakeScope,Set<JakeArtifact>>>(); public AttachedArtifacts() { super(); } public Set<JakeArtifact> getArtifacts(JakeModuleId moduleId, JakeScope jakeScope) { final Map<JakeScope, Set<JakeArtifact>> subMap = map.get(moduleId); if (subMap == null) { return Collections.emptySet(); } final Set<JakeArtifact> artifacts = subMap.get(jakeScope); if (artifacts == null) { return Collections.emptySet(); } return artifacts; } public void add(JakeScope scope, JakeArtifact artifact) { Map<JakeScope, Set<JakeArtifact>> subMap = map.get(artifact.versionedModule().moduleId()); if (subMap == null) { subMap = new HashMap<JakeScope, Set<JakeArtifact>>(); map.put(artifact.versionedModule().moduleId(), subMap); } Set<JakeArtifact> subArtifacts = subMap.get(scope); if (subArtifacts == null) { subArtifacts = new HashSet<JakeArtifact>(); subMap.put(scope, subArtifacts); } subArtifacts.add(artifact); } @Override public String toString() { return this.map.toString(); } } private static void createPomFile(ModuleDescriptor descriptor, File file) { final PomWriterOptions options = new PomWriterOptions(); try { PomModuleDescriptorWriter.write(descriptor, file, options); } catch (final IOException e) { throw new RuntimeException(e); } } private static void commitOrAbortPublication(DependencyResolver resolver) { try { resolver.commitPublishTransaction(); } catch (final Exception e) { try { resolver.abortPublishTransaction(); } catch (final IOException e1) { throw new RuntimeException(e); } } } }
package org.javabits.maven.md; import com.google.common.io.Files; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.codehaus.plexus.archiver.zip.ZipArchiver; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.logging.console.ConsoleLogger; import org.codehaus.plexus.util.DirectoryScanner; import org.pegdown.Extensions; import org.pegdown.PegDownProcessor; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import static com.google.common.io.Files.createParentDirs; import static com.google.common.io.Files.getFileExtension; import static org.javabits.maven.md.Resources.copyToDir; /** * This plugin is responsible to generate Html files from Markdown input files. * The output file is the result of the merge of a template http file and the * output of the parsing of the input file. You may want to change the html template file. * Or you may simply change the css used in the original template. * TODO provide a way to change the template or the css. * * @author Romain Gilles */ @Mojo(name = "generate") public class MarkdownMojo extends AbstractMojo { private static final String DEFAULT_FILE_EXTENSION = "md"; private static final String FILE_FILTER = "**/*"; private static final String[] DEFAULT_INCLUDES = new String[]{FILE_FILTER}; private static final String DEFAULT_CHARSET = "UTF-8"; private static final String DEFAULT_OUTPUT_DIRECTORY = "${project.build.directory}/docs"; private static final String DEFAULT_TARGET_FILE_NAME = "${project.build.finalName}-docs"; private static final String TARGET_FILE_EXTENSION = "zip"; // private static final String DEFAULT_TARGET_FILE_NAME = "${project.artifactId}-${project.version}-docs.zip"; /** * The input directory from where the input files will be looked for generation. * By default it points to {@code ${basedir}/src/main/md} */ @Parameter(property = "md.sources", defaultValue = "${basedir}/src/main/md") private File sources; /** * The default charset to use when read the source files. * By default it uses {@code UTF-8} charset. */ @Parameter(property = "md.charset", defaultValue = DEFAULT_CHARSET) private String charset; /** * The output directory where the generated files will be written. * By default it's {@code ${project.build.directory}/site} */ @Parameter(property = "md.output.dir", defaultValue = DEFAULT_OUTPUT_DIRECTORY) private File outputDir; /** * List of include patterns to use to discover * the files that need to be parsed. * By default it includes all the '.md' files. */ @Parameter private String[] includes; @Parameter private String[] options; /** * You can provide an optional css that will be applied to the generated documentation. */ @Parameter(property = "md.css") private File css; /** * The Markdown file extension without the dote '.'. By default is set to {@code 'md'} */ @Parameter(property = "md.file.extension", defaultValue = DEFAULT_FILE_EXTENSION) private String fileExtension; /** * The target archive file path. */ @Parameter(property = "md.target.name", defaultValue = DEFAULT_TARGET_FILE_NAME) private String targetName; /** * Project build directory. */ @Parameter(defaultValue = "${project.build.directory}", readonly = true) private File projectBuildDirectory; /** * Artifact final name. */ @Parameter(defaultValue = "${project.build.finalName}", readonly = true) private String finalName; /** * add the artifact final name as root directory into the archive before * the {@link #outputDir} name its default value is {@code "docs"}. */ @Parameter(property = "md.add.final.name", defaultValue = "false") private boolean addFinalName; @Component private MavenProject project; @Component private MavenProjectHelper projectHelper; @Override public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("Markdown"); PegDownProcessor pegDownProcessor = new PegDownProcessor(getOptions()); DirectoryScanner markDownScanner = new DirectoryScanner(); if (!sources.exists()) { getLog().info("Skip project no documentation found at: " + sources); return; } getLog().debug("Scan files " + Arrays.toString(getIncludes()) + ", from: " + sources); markDownScanner.setIncludes(getIncludes()); markDownScanner.setBasedir(sources); markDownScanner.scan(); String[] includedFiles = markDownScanner.getIncludedFiles(); getLog().debug("Included files: " + Arrays.toString(includedFiles)); final String templateFile = getTemplate(); Path targetCss = prepareCss().getAbsoluteFile().toPath(); for (String includedFile : includedFiles) { try { if (fileExtension.equals(getFileExtension(includedFile))) { Charset charset = Charset.forName(this.charset); String file = Files.toString(getInputFile(includedFile), charset); getLog().debug("Transform file: " + includedFile); String html = pegDownProcessor.markdownToHtml(file); File destinationFile = getDestinationFileForTransformation(includedFile); createParentDirs(destinationFile); String title = Markdowns.getTitle(file); getLog().debug("Document title: " + title); String templateFileWithTile = templateFile.replace("${title}", title).replace("${css}", getCssRelativePath(targetCss, destinationFile)); html = templateFileWithTile.replace("${content}", html); Files.write(html, destinationFile, charset); } else { //just copy static resource. File destinationFileForCopy = getDestinationFileForCopy(includedFile); createParentDirs(destinationFileForCopy); Files.copy(getInputFile(includedFile), destinationFileForCopy); } } catch (IOException e) { throw new MojoExecutionException("IO exception when generated from: " + includedFile, e); } } packageDoc(); } private int getLogLevel() { if (getLog().isDebugEnabled()) { return Logger.LEVEL_DEBUG; } if (getLog().isInfoEnabled()) { return Logger.LEVEL_INFO; } if (getLog().isWarnEnabled()) { return Logger.LEVEL_WARN; } if (getLog().isErrorEnabled()) { return Logger.LEVEL_ERROR; } return Logger.LEVEL_DISABLED; } private String getCssRelativePath(Path targetCss, File destinationFile) { return destinationFile.getAbsoluteFile().toPath().getParent().relativize(targetCss).toString().replace("\\", "/"); } private File prepareCss() throws MojoExecutionException { if (outputDir.mkdirs()) { getLog().debug("Create the root directory: " + outputDir); } File targetCss = null; try { if (css != null) { targetCss = new File(outputDir, css.toPath().getFileName().toString()); Files.copy(css, targetCss); } else { targetCss = copyToDir("/base.css", outputDir); } return targetCss; } catch (IOException e) { throw new MojoExecutionException("Cannot copy css file: " + targetCss, e); } } private String getTemplate() throws MojoExecutionException { String templateFile; try { templateFile = Resources.toString("/file-template.html"); } catch (IOException e) { throw new MojoExecutionException("Cannot read the template-file", e); } return templateFile; } private File getInputFile(String includedFile) { return new File(sources, includedFile); } private File getDestinationFile(String includedFile, String extension) { String nameWithoutExtension = getDestinationFilePath(includedFile, extension); return new File(outputDir, nameWithoutExtension); } private File getDestinationFileForTransformation(String includedFile) { return getDestinationFile(includedFile, "html"); } private File getDestinationFileForCopy(String includedFile) { return getDestinationFile(includedFile, getFileExtension(includedFile)); } static String getDestinationFilePath(String includedFile) { return getDestinationFilePath(includedFile, "html"); } static String getDestinationFilePath(String includedFile, String extension) { Path path = Paths.get(includedFile); String fileName = Files.getNameWithoutExtension(includedFile) + '.' + extension; Path parent = path.getParent(); if (parent != null) { return parent.resolve(fileName).toString(); } return fileName; } private String[] getIncludes() { if (includes != null && includes.length > 0) { return includes; } return DEFAULT_INCLUDES; } public int getOptions() throws MojoExecutionException { int result = Extensions.NONE; Extensions extensions = new Extensions() { }; if (options != null && options.length > 0) { for (String option : options) { getLog().debug("Lookup option value for: " + option); try { Field field = Extensions.class.getField(option); result |= (int) field.get(extensions); } catch (NoSuchFieldException e) { throw new MojoExecutionException("Cannot find the corresponding extension: " + option, e); } catch (IllegalAccessException e) { throw new MojoExecutionException("Cannot get the value for extension: " + option, e); } } } return result; } private void packageDoc() throws MojoExecutionException { //prepare docs structure AbstractBuildDir buildDirectory = createBuildDir(); File buildDocsDirectory = buildDirectory.docsDir(); Path buildDocsDirPath = buildDocsDirectory.toPath(); Path outputDirPath = outputDir.toPath(); try { java.nio.file.Files.move(outputDirPath, buildDocsDirPath); } catch (IOException e) { throw new MojoExecutionException("Cannot move the docs dir into the build directory.", e); } //create the zip archive ZipArchiver archive = new ZipArchiver(); ConsoleLogger plexusLogger = new ConsoleLogger(getLogLevel(), "md-maven-plugin:archive"); archive.enableLogging(plexusLogger); archive.addDirectory(buildDirectory.dir()); archive.setDestFile(getTargetFile()); try { archive.createArchive(); } catch (IOException e) { throw new MojoExecutionException("Cannot produce the documentation archive.", e); } projectHelper.attachArtifact(this.project, TARGET_FILE_EXTENSION, "docs", getTargetFile()); // clean up try { java.nio.file.Files.move(buildDocsDirPath, outputDirPath); } catch (IOException e) { throw new MojoExecutionException("Cannot move the docs dir into the build directory.", e); } buildDirectory.clean(); } private File getBuildDirectory() { return new File(projectBuildDirectory, "md-build"); } private File getTargetFile() { return new File(projectBuildDirectory, targetName + '.' + TARGET_FILE_EXTENSION); } private AbstractBuildDir createBuildDir() { AbstractBuildDir buildDir; if (addFinalName) { buildDir = new FinalNameBuildDir(); } else { buildDir = new DefaultBuildDir(); } buildDir.init(); return buildDir; } private abstract class AbstractBuildDir { File buildDirectory = getBuildDirectory(); abstract void init(); File dir() { return buildDirectory; } abstract void clean(); File docsDir() { File parent = dir(); return getDocsDir(parent); } File getDocsDir(File parent) { return new File(parent, outputDir.getName()); } } private class DefaultBuildDir extends AbstractBuildDir { void init() { buildDirectory.mkdir(); } void clean() { if (buildDirectory.exists()) buildDirectory.delete(); } } private class FinalNameBuildDir extends AbstractBuildDir { File finalNameBuildDirectory = new File(buildDirectory, finalName); void init() { buildDirectory.mkdir(); finalNameBuildDirectory.mkdir(); } @Override File docsDir() { return getDocsDir(finalNameBuildDirectory); } void clean() { if (finalNameBuildDirectory.exists()) finalNameBuildDirectory.delete(); if (buildDirectory.exists()) buildDirectory.delete(); } } }
package org.javacs; import com.google.common.base.Joiner; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.LineMap; import com.sun.source.util.SourcePositions; import com.sun.source.util.TreePath; import com.sun.source.util.Trees; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; import org.eclipse.lsp4j.*; import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.eclipse.lsp4j.services.TextDocumentService; class JavaTextDocumentService implements TextDocumentService { private final JavaLanguageServer server; private final Map<URI, VersionedContent> activeDocuments = new HashMap<>(); JavaTextDocumentService(JavaLanguageServer server) { this.server = server; } void doLint(Collection<URI> paths) { LOG.info("Lint " + Joiner.on(", ").join(paths)); // TODO } @Override public CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion( TextDocumentPositionParams position) { URI uri = URI.create(position.getTextDocument().getUri()); String content = contents(uri).content; int line = position.getPosition().getLine() + 1; int column = position.getPosition().getCharacter(); List<CompletionItem> result = new ArrayList<>(); for (Completion c : server.compiler.completions(uri, content, line, column)) { CompletionItem i = new CompletionItem(); if (c.element != null) { i.setLabel(c.element.getSimpleName().toString()); // TODO details } else if (c.packagePart != null) { i.setLabel(c.packagePart.name); // TODO details } result.add(i); } return CompletableFuture.completedFuture(Either.forRight(new CompletionList(false, result))); } @Override public CompletableFuture<CompletionItem> resolveCompletionItem(CompletionItem unresolved) { return CompletableFuture.completedFuture(unresolved); // TODO } @Override public CompletableFuture<Hover> hover(TextDocumentPositionParams position) { URI uri = URI.create(position.getTextDocument().getUri()); String content = contents(uri).content; int line = position.getPosition().getLine() + 1; int column = position.getPosition().getCharacter(); Element e = server.compiler.element(uri, content, line, column); if (e != null && e.asType() != null) { MarkedString hover = new MarkedString("java", e.asType().toString()); Hover result = new Hover(Collections.singletonList(Either.forRight(hover))); return CompletableFuture.completedFuture(result); } else return CompletableFuture.completedFuture(new Hover(Collections.emptyList())); } @Override public CompletableFuture<SignatureHelp> signatureHelp(TextDocumentPositionParams position) { URI uri = URI.create(position.getTextDocument().getUri()); String content = contents(uri).content; int line = position.getPosition().getLine() + 1; int column = position.getPosition().getCharacter(); List<SignatureInformation> result = new ArrayList<>(); for (ExecutableElement e : server.compiler.overloads(uri, content, line, column)) { SignatureInformation i = new SignatureInformation(); i.setLabel(e.getSimpleName().toString()); List<ParameterInformation> ps = new ArrayList<>(); for (VariableElement v : e.getParameters()) { ParameterInformation p = new ParameterInformation(); p.setLabel(v.getSimpleName().toString()); // TODO use type when name is not available } i.setParameters(ps); result.add(i); } int activeSig = 0; // TODO int activeParam = 0; // TODO return CompletableFuture.completedFuture(new SignatureHelp(result, activeSig, activeParam)); } private Location location(TreePath p) { Trees trees = server.compiler.trees(); SourcePositions pos = trees.getSourcePositions(); CompilationUnitTree cu = p.getCompilationUnit(); LineMap lines = cu.getLineMap(); long start = pos.getStartPosition(cu, p.getLeaf()), end = pos.getEndPosition(cu, p.getLeaf()); int startLine = (int) lines.getLineNumber(start) - 1, startCol = (int) lines.getColumnNumber(start); int endLine = (int) lines.getLineNumber(end) - 1, endCol = (int) lines.getColumnNumber(end); URI dUri = cu.getSourceFile().toUri(); return new Location( dUri.toString(), new Range(new Position(startLine, startCol), new Position(endLine, endCol))); } @Override public CompletableFuture<List<? extends Location>> definition(TextDocumentPositionParams position) { URI uri = URI.create(position.getTextDocument().getUri()); String content = contents(uri).content; int line = position.getPosition().getLine() + 1; int column = position.getPosition().getCharacter(); List<Location> result = new ArrayList<>(); server.compiler .definition(uri, content, line, column) .ifPresent( d -> { result.add(location(d)); }); return CompletableFuture.completedFuture(result); } @Override public CompletableFuture<List<? extends Location>> references(ReferenceParams position) { URI uri = URI.create(position.getTextDocument().getUri()); String content = contents(uri).content; int line = position.getPosition().getLine() + 1; int column = position.getPosition().getCharacter(); List<Location> result = new ArrayList<>(); for (TreePath r : server.compiler.references(uri, content, line, column)) { result.add(location(r)); } return CompletableFuture.completedFuture(result); } @Override public CompletableFuture<List<? extends DocumentHighlight>> documentHighlight(TextDocumentPositionParams position) { return null; } @Override public CompletableFuture<List<? extends SymbolInformation>> documentSymbol(DocumentSymbolParams params) { return null; // TODO } @Override public CompletableFuture<List<? extends Command>> codeAction(CodeActionParams params) { return null; } @Override public CompletableFuture<List<? extends CodeLens>> codeLens(CodeLensParams params) { return null; } @Override public CompletableFuture<CodeLens> resolveCodeLens(CodeLens unresolved) { return null; } @Override public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) { return null; } @Override public CompletableFuture<List<? extends TextEdit>> rangeFormatting(DocumentRangeFormattingParams params) { return null; } @Override public CompletableFuture<List<? extends TextEdit>> onTypeFormatting(DocumentOnTypeFormattingParams params) { return null; } @Override public CompletableFuture<WorkspaceEdit> rename(RenameParams params) { return null; } @Override public void didOpen(DidOpenTextDocumentParams params) { TextDocumentItem document = params.getTextDocument(); URI uri = URI.create(document.getUri()); activeDocuments.put(uri, new VersionedContent(document.getText(), document.getVersion())); doLint(Collections.singleton(uri)); } @Override public void didChange(DidChangeTextDocumentParams params) { VersionedTextDocumentIdentifier document = params.getTextDocument(); URI uri = URI.create(document.getUri()); VersionedContent existing = activeDocuments.get(uri); String newText = existing.content; if (document.getVersion() > existing.version) { for (TextDocumentContentChangeEvent change : params.getContentChanges()) { if (change.getRange() == null) activeDocuments.put(uri, new VersionedContent(change.getText(), document.getVersion())); else newText = patch(newText, change); } activeDocuments.put(uri, new VersionedContent(newText, document.getVersion())); } else LOG.warning("Ignored change with version " + document.getVersion() + " <= " + existing.version); } private String patch(String sourceText, TextDocumentContentChangeEvent change) { try { Range range = change.getRange(); BufferedReader reader = new BufferedReader(new StringReader(sourceText)); StringWriter writer = new StringWriter(); // Skip unchanged lines int line = 0; while (line < range.getStart().getLine()) { writer.write(reader.readLine() + '\n'); line++; } // Skip unchanged chars for (int character = 0; character < range.getStart().getCharacter(); character++) writer.write(reader.read()); // Write replacement text writer.write(change.getText()); // Skip replaced text reader.skip(change.getRangeLength()); // Write remaining text while (true) { int next = reader.read(); if (next == -1) return writer.toString(); else writer.write(next); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public void didClose(DidCloseTextDocumentParams params) { TextDocumentIdentifier document = params.getTextDocument(); URI uri = URI.create(document.getUri()); // Remove from source cache activeDocuments.remove(uri); // Clear diagnostics server.publishDiagnostics(uri, Collections.emptyList()); } @Override public void didSave(DidSaveTextDocumentParams params) { // Re-lint all active documents doLint(activeDocuments.keySet()); } VersionedContent contents(URI openFile) { if (activeDocuments.containsKey(openFile)) { return activeDocuments.get(openFile); } else try { String content = Files.readAllLines(Paths.get(openFile)).stream().collect(Collectors.joining("\n")); return new VersionedContent(content, -1); } catch (IOException e) { throw new RuntimeException(e); } } private static final Logger LOG = Logger.getLogger("main"); }
package org.jcodec.containers.mps; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import org.jcodec.common.IntArrayList; import org.jcodec.common.io.NIOUtils; import org.jcodec.common.model.Rational; import org.jcodec.containers.mps.MPSDemuxer.PESPacket; public class MPSUtils { public static final int VIDEO_MIN = 0x1E0; public static final int VIDEO_MAX = 0x1EF; public static final int AUDIO_MIN = 0x1C0; public static final int AUDIO_MAX = 0x1DF; public static final int PACK = 0x1ba; public static final int SYSTEM = 0x1bb; public static final int PSM = 0x1bc; public static final int PRIVATE_1 = 0x1bd; public static final int PRIVATE_2 = 0x1bf; public static final boolean mediaStream(int streamId) { return (streamId >= $(AUDIO_MIN) && streamId <= $(VIDEO_MAX) || streamId == $(PRIVATE_1) || streamId == $(PRIVATE_2)); } public static final boolean mediaMarker(int marker) { return (marker >= AUDIO_MIN && marker <= VIDEO_MAX || marker == PRIVATE_1 || marker == PRIVATE_2); } public static final boolean psMarker(int marker) { return marker >= PRIVATE_1 && marker <= VIDEO_MAX; } public static boolean videoMarker(int marker) { return marker >= VIDEO_MIN && marker <= VIDEO_MAX; } public static final boolean videoStream(int streamId) { return streamId >= $(VIDEO_MIN) && streamId <= $(VIDEO_MAX); } public static boolean audioStream(int streamId) { return streamId >= $(AUDIO_MIN) && streamId <= $(AUDIO_MAX) || streamId == $(PRIVATE_1) || streamId == $(PRIVATE_2); } static int $(int marker) { return marker & 0xff; } public static abstract class PESReader { private int marker = -1; private int lenFieldLeft; private int pesLen; private long pesFileStart = -1; private int stream; private boolean _pes; private int pesLeft; private ByteBuffer pesBuffer; public PESReader() { this.pesBuffer = ByteBuffer.allocate(1 << 21); } protected abstract void pes(ByteBuffer pesBuffer, long start, int pesLen, int stream); public void analyseBuffer(ByteBuffer buf, long pos) { int init = buf.position(); while (buf.hasRemaining()) { if (pesLeft > 0) { int toRead = Math.min(buf.remaining(), pesLeft); pesBuffer.put(NIOUtils.read(buf, toRead)); pesLeft -= toRead; if (pesLeft == 0) { long filePos = pos + buf.position() - init; pes1(pesBuffer, pesFileStart, (int) (filePos - pesFileStart), stream); pesFileStart = -1; _pes = false; stream = -1; } continue; } int bt = buf.get() & 0xff; if (_pes) pesBuffer.put((byte) (marker >>> 24)); marker = (marker << 8) | bt; if (marker >= SYSTEM && marker <= VIDEO_MAX) { long filePos = pos + buf.position() - init - 4; if (_pes) pes1(pesBuffer, pesFileStart, (int) (filePos - pesFileStart), stream); pesFileStart = filePos; _pes = true; stream = marker & 0xff; lenFieldLeft = 2; pesLen = 0; } else if (marker >= 0x1b9 && marker <= 0x1ff) { if (_pes) { long filePos = pos + buf.position() - init - 4; pes1(pesBuffer, pesFileStart, (int) (filePos - pesFileStart), stream); } pesFileStart = -1; _pes = false; stream = -1; } else if (lenFieldLeft > 0) { pesLen = (pesLen << 8) | bt; lenFieldLeft if (lenFieldLeft == 0) { pesLeft = pesLen; if (pesLen != 0) { flushMarker(); marker = -1; } } } } } private void flushMarker() { pesBuffer.put((byte) (marker >>> 24)); pesBuffer.put((byte) ((marker >>> 16) & 0xff)); pesBuffer.put((byte) ((marker >>> 8) & 0xff)); pesBuffer.put((byte) (marker & 0xff)); } private void pes1(ByteBuffer pesBuffer, long start, int pesLen, int stream) { pesBuffer.flip(); pes(pesBuffer, start, pesLen, stream); pesBuffer.clear(); } public void finishRead() { if (pesLeft <= 4) { flushMarker(); pes1(pesBuffer, pesFileStart, pesBuffer.position(), stream); } } } public static PESPacket readPESHeader(ByteBuffer iss, long pos) { int streamId = iss.getInt() & 0xff; int len = iss.getShort() & 0xffff; if (streamId != 0xbf) { int b0 = iss.get() & 0xff; if ((b0 & 0xc0) == 0x80) return mpeg2Pes(b0, len, streamId, iss, pos); else return mpeg1Pes(b0, len, streamId, iss, pos); } return new PESPacket(null, -1, streamId, len, pos, -1); } public static PESPacket mpeg1Pes(int b0, int len, int streamId, ByteBuffer is, long pos) { int c = b0; while (c == 0xff) { c = is.get() & 0xff; } if ((c & 0xc0) == 0x40) { is.get(); c = is.get() & 0xff; } long pts = -1, dts = -1; if ((c & 0xf0) == 0x20) { pts = _readTs(is, c); } else if ((c & 0xf0) == 0x30) { pts = _readTs(is, c); dts = readTs(is); } else { if (c != 0x0f) throw new RuntimeException("Invalid data"); } return new PESPacket(null, pts, streamId, len, pos, dts); } public static long _readTs(ByteBuffer is, int c) { return (((long) c & 0x0e) << 29) | ((is.get() & 0xff) << 22) | (((is.get() & 0xff) >> 1) << 15) | ((is.get() & 0xff) << 7) | ((is.get() & 0xff) >> 1); } public static PESPacket mpeg2Pes(int b0, int len, int streamId, ByteBuffer is, long pos) { int flags1 = b0; int flags2 = is.get() & 0xff; int header_len = is.get() & 0xff; long pts = -1, dts = -1; if ((flags2 & 0xc0) == 0x80) { pts = readTs(is); NIOUtils.skip(is, header_len - 5); } else if ((flags2 & 0xc0) == 0xc0) { pts = readTs(is); dts = readTs(is); NIOUtils.skip(is, header_len - 10); } else NIOUtils.skip(is, header_len); return new PESPacket(null, pts, streamId, len, pos, dts); } public static long readTs(ByteBuffer is) { return (((long) is.get() & 0x0e) << 29) | ((is.get() & 0xff) << 22) | (((is.get() & 0xff) >> 1) << 15) | ((is.get() & 0xff) << 7) | ((is.get() & 0xff) >> 1); } public static void writeTs(ByteBuffer is, long ts) { is.put((byte) ((ts >> 29) << 1)); is.put((byte) (ts >> 22)); is.put((byte) ((ts >> 15) << 1)); is.put((byte) (ts >> 7)); is.put((byte) (ts >> 1)); } public static class MPEGMediaDescriptor { private int tag; private int len; public void parse(ByteBuffer buf) { tag = buf.get() & 0xff; len = buf.get() & 0xff; } public int getTag() { return tag; } public int getLen() { return len; } } public static class VideoStreamDescriptor extends MPEGMediaDescriptor { private int multipleFrameRate; private int frameRateCode; private boolean mpeg1Only; private int constrainedParameter; private int stillPicture; private int profileAndLevel; private int chromaFormat; private int frameRateExtension; Rational[] frameRates; public VideoStreamDescriptor() { this.frameRates = new Rational[] { null, new Rational(24000, 1001), new Rational(24, 1), new Rational(25, 1), new Rational(30000, 1001), new Rational(30, 1), new Rational(50, 1), new Rational(60000, 1001), new Rational(60, 1), null, null, null, null, null, null, null}; } @Override public void parse(ByteBuffer buf) { super.parse(buf); int b0 = buf.get() & 0xff; multipleFrameRate = (b0 >> 7) & 1; frameRateCode = (b0 >> 3) & 0xf; mpeg1Only = ((b0 >> 2) & 1) == 0; constrainedParameter = (b0 >> 1) & 1; stillPicture = b0 & 1; if (!mpeg1Only) { profileAndLevel = buf.get() & 0xff; int b1 = buf.get() & 0xff; chromaFormat = b1 >> 6; frameRateExtension = (b1 >> 5) & 1; } } public Rational getFrameRate() { return frameRates[frameRateCode]; } public int getMultipleFrameRate() { return multipleFrameRate; } public int getFrameRateCode() { return frameRateCode; } public boolean isMpeg1Only() { return mpeg1Only; } public int getConstrainedParameter() { return constrainedParameter; } public int getStillPicture() { return stillPicture; } public int getProfileAndLevel() { return profileAndLevel; } public int getChromaFormat() { return chromaFormat; } public int getFrameRateExtension() { return frameRateExtension; } } public static class AudioStreamDescriptor extends MPEGMediaDescriptor { private int variableRateAudioIndicator; private int freeFormatFlag; private int id; private int layer; @Override public void parse(ByteBuffer buf) { super.parse(buf); int b0 = buf.get() & 0xff; freeFormatFlag = (b0 >> 7) & 1; id = (b0 >> 6) & 1; layer = (b0 >> 5) & 3; variableRateAudioIndicator = (b0 >> 3) & 1; } public int getVariableRateAudioIndicator() { return variableRateAudioIndicator; } public int getFreeFormatFlag() { return freeFormatFlag; } public int getId() { return id; } public int getLayer() { return layer; } } public static class ISO639LanguageDescriptor extends MPEGMediaDescriptor { private IntArrayList languageCodes; public ISO639LanguageDescriptor() { super(); this.languageCodes = IntArrayList.createIntArrayList(); } @Override public void parse(ByteBuffer buf) { super.parse(buf); while (buf.remaining() >= 4) { languageCodes.add(buf.getInt()); } } public IntArrayList getLanguageCodes() { return languageCodes; } } public static class Mpeg4VideoDescriptor extends MPEGMediaDescriptor { private int profileLevel; @Override public void parse(ByteBuffer buf) { super.parse(buf); profileLevel = buf.get() & 0xff; } } public static class Mpeg4AudioDescriptor extends MPEGMediaDescriptor { private int profileLevel; @Override public void parse(ByteBuffer buf) { super.parse(buf); profileLevel = buf.get() & 0xff; } public int getProfileLevel() { return profileLevel; } } public static class AVCVideoDescriptor extends MPEGMediaDescriptor { private int profileIdc; private int flags; private int level; @Override public void parse(ByteBuffer buf) { super.parse(buf); profileIdc = buf.get() & 0xff; flags = buf.get() & 0xff; level = buf.get() & 0xff; } public int getProfileIdc() { return profileIdc; } public int getFlags() { return flags; } public int getLevel() { return level; } } public static class AACAudioDescriptor extends MPEGMediaDescriptor { private int profile; private int channel; private int flags; @Override public void parse(ByteBuffer buf) { super.parse(buf); profile = buf.get() & 0xff; channel = buf.get() & 0xff; flags = buf.get() & 0xff; } public int getProfile() { return profile; } public int getChannel() { return channel; } public int getFlags() { return flags; } } public static class DataStreamAlignmentDescriptor extends MPEGMediaDescriptor { private int alignmentType; @Override public void parse(ByteBuffer buf) { super.parse(buf); alignmentType = buf.get() & 0xff; } public int getAlignmentType() { return alignmentType; } } public static class RegistrationDescriptor extends MPEGMediaDescriptor { private int formatIdentifier; private IntArrayList additionalFormatIdentifiers; public RegistrationDescriptor() { super(); this.additionalFormatIdentifiers = IntArrayList.createIntArrayList(); } @Override public void parse(ByteBuffer buf) { super.parse(buf); formatIdentifier = buf.getInt(); while(buf.hasRemaining()) { additionalFormatIdentifiers.add(buf.get() & 0xff); } } public int getFormatIdentifier() { return formatIdentifier; } public IntArrayList getAdditionalFormatIdentifiers() { return additionalFormatIdentifiers; } } public static Class<? extends MPEGMediaDescriptor>[] dMapping = new Class[256]; static { dMapping[2] = VideoStreamDescriptor.class; dMapping[3] = AudioStreamDescriptor.class; dMapping[6] = DataStreamAlignmentDescriptor.class; dMapping[5] = RegistrationDescriptor.class; dMapping[10] = ISO639LanguageDescriptor.class; dMapping[27] = Mpeg4VideoDescriptor.class; dMapping[28] = Mpeg4AudioDescriptor.class; dMapping[40] = AVCVideoDescriptor.class; dMapping[43] = AACAudioDescriptor.class; } public static List<MPEGMediaDescriptor> parseDescriptors(ByteBuffer bb) { List<MPEGMediaDescriptor> result = new ArrayList<MPEGMediaDescriptor>(); while (bb.remaining() >= 2) { ByteBuffer dup = bb.duplicate(); int tag = dup.get() & 0xff; int len = dup.get() & 0xff; ByteBuffer descriptorBuffer = NIOUtils.read(bb, len + 2); if (dMapping[tag] != null) try { MPEGMediaDescriptor descriptor = dMapping[tag].newInstance(); descriptor.parse(descriptorBuffer); result.add(descriptor); } catch (Exception e) { throw new RuntimeException(e); } } return result; } }
package org.jruby.rack.util; import java.io.IOException; import org.jruby.NativeException; import org.jruby.Ruby; import org.jruby.RubyClass; import org.jruby.exceptions.RaiseException; /** * * @author kares */ public abstract class ExceptionUtils { public static RaiseException wrapException(final Ruby runtime, final Exception cause) { if ( cause instanceof RaiseException ) return (RaiseException) cause; NativeException nativeException = new NativeException(runtime, runtime.getNativeException(), cause); return new RaiseException(cause, nativeException); // getCause() != null } public static RaiseException newRuntimeError(final Ruby runtime, final Throwable cause) { return newRaiseException(runtime, runtime.getRuntimeError(), cause); } public static RaiseException newArgumentError(final Ruby runtime, final RuntimeException cause) { return newRaiseException(runtime, runtime.getArgumentError(), cause); } public static RaiseException newIOError(final Ruby runtime, final IOException cause) { RaiseException raise = runtime.newIOErrorFromException(cause); raise.initCause(cause); return raise; } static RaiseException newRaiseException(final Ruby runtime, final RubyClass errorClass, final String message) { return new RaiseException(runtime, errorClass, message, true); } private static RaiseException newRaiseException(final Ruby runtime, final RubyClass errorClass, final Throwable cause) { final String message = cause.getMessage(); RaiseException raise = new RaiseException(runtime, errorClass, message, true); raise.initCause(cause); return raise; } }
package org.jtrfp.trcl.snd; import java.nio.FloatBuffer; import org.jtrfp.trcl.math.Misc; public final class AudioCompressor implements AudioProcessor { private FloatBuffer source; private double release = .01f; private double scalar = 1f; @Override public float get(){ scalar += release; scalar = Misc.clamp(scalar, 0, 1); double val = source.get(); final double aVal = Math.abs(val*scalar); if(aVal>1) scalar /=aVal; return (float)(val*scalar); }//end get() /** * @param source the source to set */ public void setSource(FloatBuffer source) { this.source = source; } /** * @param release the release to set */ public void setRelease(double changePerSample) { this.release = changePerSample; } }//end AudioCompressor
package org.lantern; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import javax.net.ssl.TrustManager; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.littleshoot.proxy.KeyStoreManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LanternKeyStoreManager implements KeyStoreManager { private final Logger log = LoggerFactory.getLogger(getClass()); private final File CONFIG_DIR; public final File KEYSTORE_FILE; private final File TRUSTSTORE_FILE; private final File CERT_FILE; private static final String PASS = String.valueOf(LanternHub.secureRandom().nextLong()); private static final String KEYSIZE = "2048"; private static final String ALG = "RSA"; private String localCert; private final TrustManager[] trustManagers; private final LanternTrustManager lanternTrustManager; public LanternKeyStoreManager() { this(null); } public LanternKeyStoreManager(final File rootDir) { CONFIG_DIR = rootDir != null ? rootDir : LanternConstants.CONFIG_DIR; KEYSTORE_FILE = new File(CONFIG_DIR, "lantern_keystore.jks"); TRUSTSTORE_FILE = new File(CONFIG_DIR, "lantern_truststore.jks"); CERT_FILE = new File(CONFIG_DIR, "local_lantern_cert"); fullDelete(KEYSTORE_FILE); fullDelete(TRUSTSTORE_FILE); if (!CONFIG_DIR.isDirectory()) { if (!CONFIG_DIR.mkdir()) { log.error("Could not create config dir!! "+CONFIG_DIR); } } reset(LanternUtils.getMacAddress()); createTrustStore(); this.lanternTrustManager = new LanternTrustManager(this, TRUSTSTORE_FILE, PASS); trustManagers = new TrustManager[] { lanternTrustManager }; Runtime.getRuntime().addShutdownHook(new Thread (new Runnable() { @Override public void run() { fullDelete(KEYSTORE_FILE); fullDelete(TRUSTSTORE_FILE); } }, "Keystore-Delete-Thread")); } private void fullDelete(final File file) { file.deleteOnExit(); if (file.isFile() && !file.delete()) { log.error("Could not delete file {}!!", file); } } private void createTrustStore() { if (TRUSTSTORE_FILE.isFile()) { log.info("Trust store already exists"); return; } final String result = LanternUtils.runKeytool("-genkey", "-alias", "foo", "-keysize", KEYSIZE, "-validity", "365", "-keyalg", ALG, "-dname", "CN="+LanternUtils.getMacAddress(), "-keystore", TRUSTSTORE_FILE.getAbsolutePath(), "-keypass", PASS, "-storepass", PASS); log.info("Got result of creating trust store: {}", result); } private void reset(final String macAddress) { log.info("RESETTING KEYSTORE AND TRUSTSTORE!!"); if (KEYSTORE_FILE.isFile()) { log.info("Deleting existing keystore file at: " + KEYSTORE_FILE.getAbsolutePath()); KEYSTORE_FILE.delete(); } if (TRUSTSTORE_FILE.isFile()) { log.info("Deleting existing truststore file at: " + TRUSTSTORE_FILE.getAbsolutePath()); TRUSTSTORE_FILE.delete(); } final String genKeyResult = LanternUtils.runKeytool("-genkey", "-alias", macAddress, "-keysize", KEYSIZE, "-validity", "365", "-keyalg", ALG, "-dname", "CN="+macAddress, "-keypass", PASS, "-storepass", PASS, "-keystore", KEYSTORE_FILE.getAbsolutePath()); log.info("Result of keytool -genkey call: {}", genKeyResult); waitForFile(KEYSTORE_FILE); // Now grab our newly-generated cert. All of our trusted peers will // use this to connect. final String exportCertResult = LanternUtils.runKeytool("-exportcert", "-alias", macAddress, "-keystore", KEYSTORE_FILE.getAbsolutePath(), "-storepass", PASS, "-file", CERT_FILE.getAbsolutePath()); log.info("Result of keytool -exportcert call: {}", exportCertResult); waitForFile(CERT_FILE); try { final InputStream is = new FileInputStream(CERT_FILE); localCert = Base64.encodeBase64String(IOUtils.toByteArray(is)); } catch (final FileNotFoundException e) { log.error("Cert file not found at "+CERT_FILE, e); throw new Error("Cert file not found", e); } catch (final IOException e) { log.error("Could not base 64 encode cert?", e); throw new Error("Could not base 64 encode cert?", e); } /* log.info("Importing cert"); nativeCall("keytool", "-import", "-noprompt", "-file", CERT_FILE.getName(), "-alias", AL, "-keystore", TRUSTSTORE_FILE.getName(), "-storepass", PASS); */ } /** * The completion of the native calls is dependent on OS process * scheduling, so we need to wait until files actually exist. * * @param file The file to wait for. */ private void waitForFile(final File file) { int i = 0; while (!file.isFile() && i < 100) { try { Thread.sleep(80); i++; } catch (final InterruptedException e) { log.error("Interrupted?", e); } } } public String getBase64Cert() { return localCert; } @Override public InputStream keyStoreAsInputStream() { try { return new FileInputStream(KEYSTORE_FILE); } catch (final FileNotFoundException e) { log.error("Key store file not found", e); throw new Error("Could not find keystore file!!"); } } @Override public InputStream trustStoreAsInputStream() { try { return new FileInputStream(TRUSTSTORE_FILE); } catch (final FileNotFoundException e) { log.error("Trust store file not found", e); throw new Error("Could not find truststore file!!"); } } @Override public char[] getCertificatePassword() { return PASS.toCharArray(); } @Override public char[] getKeyStorePassword() { return PASS.toCharArray(); } @Override public void addBase64Cert(final String macAddress, final String base64Cert) throws IOException { this.lanternTrustManager.addBase64Cert(macAddress, base64Cert); } @Override public TrustManager[] getTrustManagers() { return Arrays.copyOf(trustManagers, trustManagers.length); } public LanternTrustManager getTrustManager() { return this.lanternTrustManager; } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable { // Cache for all configuration passed from API or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); // Resource path (META-INF) private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } Map<K, V> value = ObjectUtils.cast(CollectionUtils.getAsMap(key, from)); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (CollectionUtils.available(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = CollectionUtils.available(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(ConfigKeys.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuraion * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES.key); if (CollectionUtils.available(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(ConfigKeys.POOL_PROVIDER_TYPE.key); if (CollectionUtils.available(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES_PATH.key); if (CollectionUtils.available(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties and default values */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(ConfigKeys.IP_ADDRESS.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.IP_ADDRESS.key, ConfigKeys.IP_ADDRESS.value); } contains = containsConfigKey(ConfigKeys.PORT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.PORT.key, ConfigKeys.PORT.value); } contains = containsConfigKey(ConfigKeys.BOSS_POOL.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.BOSS_POOL.key, ConfigKeys.BOSS_POOL.value); } contains = containsConfigKey(ConfigKeys.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int defaultWorkers = ConfigKeys.WORKER_POOL.getValue(); int workers = RUNTIME.availableProcessors() * defaultWorkers; String workerProperty = String.valueOf(workers); setConfigValue(ConfigKeys.WORKER_POOL.key, workerProperty); } contains = containsConfigKey(ConfigKeys.CONNECTION_TIMEOUT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.CONNECTION_TIMEOUT.key, ConfigKeys.CONNECTION_TIMEOUT.value); } } /** * Merges configuration with default properties */ public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = ConfigKeys.DEMPLOYMENT_PATH.getValue(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Map<Object, Object> mapValue2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = ObjectUtils.getAsMap(key, map1); mapValue2 = ObjectUtils.cast(value2); mergedValue = deepMerge(value1, mapValue2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { Map<Object, Object> innerConfig = ObjectUtils .cast(configuration); configure(innerConfig); } } finally { ObjectUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { Object value = config.get(key); String textValue; if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { ObjectUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { InputStream propertiesStream = null; String configFilePath = ConfigKeys.CONFIG_FILE.getValue(); try { File configFile = new File(configFilePath); if (configFile.exists()) { propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { InputStream propertiesStream = null; try { propertiesStream = new FileInputStream(new File(configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return ConfigKeys.ADMIN_USER_PATH.getValue(); } public static void setAdminUsersPath(String adminUserPath) { ConfigKeys.ADMIN_USERS_PATH.value = adminUserPath; } public boolean isRemote() { return ConfigKeys.REMOTE.getValue(); } public void setRemote(boolean remote) { ConfigKeys.REMOTE.value = remote; } public static boolean isServer() { return ConfigKeys.SERVER.getValue(); } public static void setServer(boolean server) { ConfigKeys.SERVER.value = server; } public boolean isClient() { return getConfigValue(ConfigKeys.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(ConfigKeys.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(ConfigKeys.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(ConfigKeys.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(ConfigKeys.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(ConfigKeys.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue( ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key, persistenceProperties); } /** * Property for connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable { // Cache for all configuration passed from API or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); // Resource path (META-INF) private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } Map<K, V> value = ObjectUtils.cast(CollectionUtils.getAsMap(key, from)); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (CollectionUtils.valid(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = CollectionUtils.valid(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(ConfigKeys.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuration * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES.key); if (CollectionUtils.valid(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(ConfigKeys.POOL_PROVIDER_TYPE.key); if (StringUtils.valid(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES_PATH.key); if (StringUtils.valid(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties and default values */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(ConfigKeys.IP_ADDRESS.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.IP_ADDRESS.key, ConfigKeys.IP_ADDRESS.value); } contains = containsConfigKey(ConfigKeys.PORT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.PORT.key, ConfigKeys.PORT.value); } contains = containsConfigKey(ConfigKeys.BOSS_POOL.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.BOSS_POOL.key, ConfigKeys.BOSS_POOL.value); } contains = containsConfigKey(ConfigKeys.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int defaultWorkers = ConfigKeys.WORKER_POOL.getValue(); int workers = RUNTIME.availableProcessors() * defaultWorkers; String workerProperty = String.valueOf(workers); setConfigValue(ConfigKeys.WORKER_POOL.key, workerProperty); } contains = containsConfigKey(ConfigKeys.CONNECTION_TIMEOUT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.CONNECTION_TIMEOUT.key, ConfigKeys.CONNECTION_TIMEOUT.value); } } /** * Merges configuration with default properties */ public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = ConfigKeys.DEMPLOYMENT_PATH.getValue(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Map<Object, Object> mapValue2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = CollectionUtils.getAsMap(key, map1); mapValue2 = ObjectUtils.cast(value2); mergedValue = deepMerge(value1, mapValue2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { Map<Object, Object> innerConfig = ObjectUtils .cast(configuration); configure(innerConfig); } } finally { ObjectUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { Object value = config.get(key); String textValue; if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { ObjectUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { InputStream propertiesStream = null; String configFilePath = ConfigKeys.CONFIG_FILE.getValue(); try { File configFile = new File(configFilePath); if (configFile.exists()) { propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { InputStream propertiesStream = null; try { propertiesStream = new FileInputStream(new File(configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return ConfigKeys.ADMIN_USER_PATH.getValue(); } public static void setAdminUsersPath(String adminUserPath) { ConfigKeys.ADMIN_USERS_PATH.value = adminUserPath; } public boolean isRemote() { return ConfigKeys.REMOTE.getValue(); } public void setRemote(boolean remote) { ConfigKeys.REMOTE.value = remote; } public static boolean isServer() { return ConfigKeys.SERVER.getValue(); } public static void setServer(boolean server) { ConfigKeys.SERVER.value = server; } public boolean isClient() { return getConfigValue(ConfigKeys.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(ConfigKeys.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(ConfigKeys.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(ConfigKeys.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(ConfigKeys.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(ConfigKeys.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue( ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key, persistenceProperties); } /** * Gets cached {@link PoolConfig} instance a connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { // Deep clone for configuration Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package org.minimalj.model.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation for String, Long, Integer, BigDecimal. * * <UL> * <LI>For String its mandatory. * <LI>For Integer or Long the default size is defined by the size of the java * values * <LI>For BigDecimal the default size is 10 (with scale of 0) as in MySql DB. * The size means the total count of digits including the decimals. * <LI>For Time the defined constants must be used * </UL> * */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface Size { int value(); /** * Constant to annotate the precision of LocalDate fields to minutes */ public static final int TIME_HH_MM = 5; /** * Constant to annotate the precision of LocalDate fields to seconds */ public static final int TIME_WITH_SECONDS = 8; /** * Constant to annotate the precision of LocalDate fields to milliseconds */ public static final int TIME_WITH_MILLIS = 12; /** * Maximum size of an Integer (unsigned) */ public static final int INTEGER = String.valueOf(Integer.MAX_VALUE).length(); /** * Maximum size of a Long (unsigned) */ public static final int LONG = String.valueOf(Long.MAX_VALUE).length(); /** * The default size (number of digits) for BigDecimals. * Note: 10 is als the default used in MariaDB. */ public static final int BIG_DECIMAL_DEFAULT = 10; }
package org.mycat.web.util; import java.sql.Connection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.dbcp.BasicDataSource; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.hx.rainbow.common.context.RainbowContext; import org.hx.rainbow.common.core.SpringApplicationContext; import org.hx.rainbow.common.core.service.SoaManager; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mycat.web.task.common.TaskManger; import org.mycat.web.task.server.CheckMycatSuspend; import org.mycat.web.task.server.CheckServerDown; import org.mycat.web.task.server.SyncClearData; import org.mycat.web.task.server.SyncSysSql; import org.mycat.web.task.server.SyncSysSqlhigh; import org.mycat.web.task.server.SyncSysSqlslow; import org.mycat.web.task.server.SyncSysSqlsum; import org.mycat.web.task.server.SyncSysSqtable; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.context.ConfigurableApplicationContext; public class DataSourceUtils { private static final Logger logger = LogManager .getLogger(DataSourceUtils.class); public enum MycatPortType{ MYCAT_MANGER, MYCAT_SERVER } public static final String DEFAULT_MYSQL_DRIVER_CLASS = "com.mysql.jdbc.Driver"; private volatile static DataSourceUtils dataSourceUtils = null; private DataSourceUtils(){}; public static DataSourceUtils getInstance(){ if(dataSourceUtils == null){ synchronized (DataSourceUtils.class) { if(dataSourceUtils == null){ dataSourceUtils = new DataSourceUtils(); } } } return dataSourceUtils; } private static final String NAME_SUFFIX = "dataSource"; public boolean register(Map<String, Object> jdbc, String dbName, MycatPortType portType) throws Exception { Connection conn = null; dbName = dbName + portType; String beanName = dbName + NAME_SUFFIX; try { logger.info("dbname:" + dbName + " is initializing!!"); remove(beanName); switch (portType) { case MYCAT_MANGER: jdbc.put("port", jdbc.get("mangerPort")); break; case MYCAT_SERVER: jdbc.put("port", jdbc.get("serverPort")); break; default: break; }; ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) SpringApplicationContext.getApplicationContext(); DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getBeanFactory(); beanFactory.registerBeanDefinition(beanName, getDefinition(jdbc)); BasicDataSource dbSource = (BasicDataSource)SpringApplicationContext.getBean(beanName); conn = dbSource.getConnection(); beanFactory.registerBeanDefinition(dbName + "sqlSessionFactory", getSqlSessionFactoryDef(dbSource)); Object sqlSessionFactory = SpringApplicationContext.getBean(dbName + "sqlSessionFactory"); beanFactory.registerBeanDefinition(dbName + "sqlSessionTemplate", getSqlSessionTemplateDef(sqlSessionFactory)); if(MycatPortType.MYCAT_MANGER == portType){ updateTask(dbName); } return true; } catch (Exception e) { logger.error(e.getMessage(), e.getCause()); remove(dbName); return false; }finally{ if(conn != null){ conn.close(); } } } private void updateTask(String dbName){ TaskManger taskManger = TaskManger.getInstance(); taskManger.addDBName(dbName); taskManger.cancelTask("SyncSysSql", "SyncSysSqlhigh", "SyncSysSqlslow", "SyncSysSqtable", "SyncSysSqlsum"); taskManger.addTask(new SyncSysSql(), 60 * 1000, "SyncSysSql"); taskManger.addTask(new SyncSysSqlhigh(), 60 * 1000*2, "SyncSysSqlhigh"); taskManger.addTask(new SyncSysSqlslow(), 60 * 1000*2, "SyncSysSqlslow"); taskManger.addTask(new SyncSysSqtable(), 60 * 1000*3, "SyncSysSqtable"); taskManger.addTask(new SyncSysSqlsum(), 60 * 1000*3, "SyncSysSqlsum"); taskManger.addTask(new SyncClearData(),60 *1000*60*10, "SyncClearData"); taskManger.addTask(new CheckMycatSuspend(), 60 * 1000*5, "CheckMycatSuspend",10);//510 taskManger.addTask(new CheckServerDown(), 60 * 1000*5, "CheckServerDown"); } public boolean register(String dbName, MycatPortType portType) throws Exception { String beanId = dbName + portType + NAME_SUFFIX; if(!SpringApplicationContext.getApplicationContext().containsBean(beanId)){ RainbowContext context = new RainbowContext("mycatService", "query"); context.addAttr("mycatName", dbName); context = SoaManager.getInstance().invokeNoTx(context); if (context.getRows() == null || context.getRows().size() == 0) { return false; } Map<String, Object> row = context.getRow(0); switch (portType) { case MYCAT_MANGER: row.put("port", row.get("mangerPort")); break; case MYCAT_SERVER: row.put("port", row.get("serverPort")); break; default: break; }; return register(row, dbName, portType); }else{ Connection conn = null; try{ BasicDataSource dbSource = (BasicDataSource)SpringApplicationContext.getBean(beanId); conn = dbSource.getConnection(); }catch(Exception ex){ logger.warn(",!"); remove(dbName + portType); return register(dbName, portType); }finally{ if(conn != null){ conn.close(); } } } return true; } public boolean register(Map<String, Object> jdbc, String dbName) throws Exception { if(!register(jdbc, dbName, MycatPortType.MYCAT_MANGER)){ return false; } if(! register(jdbc, dbName, MycatPortType.MYCAT_SERVER)){ return false; } return true; } public boolean register(String dbName) throws Exception { if(!register(dbName, MycatPortType.MYCAT_MANGER)){ return false; } if(! register(dbName, MycatPortType.MYCAT_SERVER)){ return false; } return true; } public String getDbName(String dbName) { int n_pos = dbName.indexOf(MycatPortType.MYCAT_MANGER+""); if (n_pos>0) { return dbName.substring(0,n_pos); } else { return dbName; } } public String getDbName(String dbName, MycatPortType portType ) { int n_pos = dbName.indexOf(portType+""); if (n_pos>0) { return dbName.substring(0,n_pos); } else { return dbName; } } public void remove(String dbName) { SpringApplicationContext.removeBeans(dbName + NAME_SUFFIX, dbName + "sqlSessionFactory", dbName + "sqlSessionTemplate", dbName + "transactionManager"); } private GenericBeanDefinition getDefinition(Map<String, Object> jdbc) { GenericBeanDefinition messageSourceDefinition = new GenericBeanDefinition(); Map<String, Object> original = new HashMap<String, Object>(); original.put("driverClassName", DEFAULT_MYSQL_DRIVER_CLASS); original.put("url", getMySQLURL((String)jdbc.get("ip"), (String)jdbc.get("port"), (String)jdbc.get("dbName"))); original.put("username", jdbc.get("username")); original.put("password", jdbc.get("password")); original.put("maxActive", 20); original.put("initialSize", 5); original.put("maxWait", 60000); original.put("minIdle", 5); messageSourceDefinition.setBeanClass(BasicDataSource.class); messageSourceDefinition.setDestroyMethodName("close"); messageSourceDefinition.setPropertyValues(new MutablePropertyValues(original)); return messageSourceDefinition; } private String getMySQLURL(String ip, String port, String server) { return "jdbc:mysql://" + ip + ":" + port + "/" + server + "?characterEncoding=utf8"; } private GenericBeanDefinition getSqlSessionFactoryDef(Object dbSource) { GenericBeanDefinition sessionFactoryDef = new GenericBeanDefinition(); Map<String, Object> paramData = new HashMap<String, Object>(); paramData.put("dataSource", dbSource); List<String> list = new ArrayList<String>(); list.add("classpath:mybatis*Mapper.xml"); paramData.put("mapperLocations", list); paramData.put("typeAliasesPackage", "org.hx.rainbow.common.dao.handler"); sessionFactoryDef.setBeanClass(SqlSessionFactoryBean.class); sessionFactoryDef.setPropertyValues(new MutablePropertyValues(paramData)); return sessionFactoryDef; } private GenericBeanDefinition getSqlSessionTemplateDef(Object sqlSessionFacotry) { GenericBeanDefinition sqlSessionTemplateDef = new GenericBeanDefinition(); ConstructorArgumentValues values = new ConstructorArgumentValues(); values.addIndexedArgumentValue(0, sqlSessionFacotry); sqlSessionTemplateDef.setConstructorArgumentValues(values); sqlSessionTemplateDef.setBeanClass(SqlSessionTemplate.class); return sqlSessionTemplateDef; } }
package org.netlight.client; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.ssl.SslContext; import org.netlight.channel.ChannelState; import org.netlight.channel.ChannelStateListener; import org.netlight.encoding.EncodingProtocol; import org.netlight.messaging.MessageQueueLoopGroup; import org.netlight.util.EventNotifier; import org.netlight.util.EventNotifierHandler; import org.netlight.util.OSValidator; import org.netlight.util.concurrent.AtomicBooleanField; import org.netlight.util.concurrent.AtomicReferenceField; import java.net.SocketAddress; import java.util.Objects; /** * @author ahmad */ public final class NetLightClient implements Client { private final SocketAddress remoteAddress; private final SslContext sslCtx; private final ClientChannelInitializer channelInitializer; private final AtomicReferenceField<Channel> channel = new AtomicReferenceField<>(); private final AtomicBooleanField connected = new AtomicBooleanField(false); private final AtomicReferenceField<ChannelState> state = new AtomicReferenceField<>(ChannelState.DISCONNECTED); private final EventNotifier<ChannelState, ChannelStateListener> channelStateNotifier; public NetLightClient(SocketAddress remoteAddress, SslContext sslCtx, EncodingProtocol protocol, MessageQueueLoopGroup loopGroup) { Objects.requireNonNull(remoteAddress); this.remoteAddress = remoteAddress; this.sslCtx = sslCtx; this.channelInitializer = new ClientChannelInitializer(remoteAddress, sslCtx, protocol, loopGroup); channelStateNotifier = new EventNotifier<>(new EventNotifierHandler<ChannelState, ChannelStateListener>() { @Override public void handle(ChannelState event, ChannelStateListener listener) { listener.stateChanged(event); } @Override public void exceptionCaught(Throwable cause) { channelStateNotifier.start(); } }, ChannelState.class); } @Override public boolean connect() { if (connected.get()) { return true; } channelStateNotifier.start(); final Bootstrap b = configureBootstrap(new Bootstrap()); try { final Channel ch = b.connect().sync().channel(); connected.set(true); channel.set(ch); ch.closeFuture().addListener(f -> closed(b.group())); fireChannelStateChanged(ChannelState.CONNECTED); return true; } catch (Exception e) { connected.set(false); fireChannelStateChanged(ChannelState.CONNECTION_FAILED); channelStateNotifier.stopLater(); } return false; } private void closed(EventLoopGroup g) { connected.set(false); channel.set(null); if (g != null) { g.shutdownGracefully(); } fireChannelStateChanged(ChannelState.DISCONNECTED); channelStateNotifier.stopLater(); } private Bootstrap configureBootstrap(Bootstrap b) { return configureBootstrap(b, OSValidator.isUnix() ? new EpollEventLoopGroup() : new NioEventLoopGroup()); } private Bootstrap configureBootstrap(Bootstrap b, EventLoopGroup g) { b.group(g) .channel(OSValidator.isUnix() ? EpollSocketChannel.class : NioSocketChannel.class) .remoteAddress(remoteAddress) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .handler(channelInitializer); return b; } @Override public boolean isConnected() { return connected.get(); } @Override public ChannelFuture closeFuture() { Channel ch = channel.get(); return ch == null ? null : ch.closeFuture(); } @Override public SocketAddress remoteAddress() { return remoteAddress; } @Override public SslContext getSslContext() { return sslCtx; } @Override public ClientChannelInitializer getChannelInitializer() { return channelInitializer; } @Override public ChannelState getChannelState() { return state.get(); } @Override public void addChannelStateListener(ChannelStateListener channelStateListener) { channelStateNotifier.addListener(channelStateListener); } @Override public void removeChannelStateListener(ChannelStateListener channelStateListener) { channelStateNotifier.removeListener(channelStateListener); } @Override public void fireChannelStateChanged(ChannelState state) { this.state.set(state); channelStateNotifier.notify(state); } @Override public void close() { final Channel ch = channel.getAndSet(null); if (ch != null) { ch.close().awaitUninterruptibly(); } } }
package org.openremote.security; import org.openremote.exception.OpenRemoteException; import org.openremote.logging.Logger; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; import java.security.cert.CertificateException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Abstract superclass with a shared implementation to handle keystore based operations. * * @author <a href="mailto:juha@openremote.org">Juha Lindfors</a> */ public abstract class KeyManager { /** * This is the default key storage type used if nothing else is specified. Note that PKCS12 * is used for asymmetric PKI keys but not for storing symmetric secret keys. For the latter, * other provider-specific storage types must be used. <p> * * Default: {@value} */ public final static StorageType DEFAULT_KEYSTORE_STORAGE_TYPE = StorageType.PKCS12; /** * The default security provider used by this instance. Note that can contain a null value * if loading of the security provider fails. A null value should indicate using the system * installed security providers in their preferred order rather than this explicit security * provider. <p> * * Default: {@value} */ private final static SecurityProvider DEFAULT_SECURITY_PROVIDER = SecurityProvider.BC; /** * Manages the dynamic loading of a security provider implementations. */ protected enum SecurityProvider { /** * BouncyCastle provider. */ BC("org.bouncycastle.jce.provider.BouncyCastleProvider"); private String className; private SecurityProvider(String className) { this.className = className; } /** * Manages the dynamic loading of a security provider. * * @return A provider instance <b>or null</b> if the instance could not be loaded */ protected Provider getProviderInstance() { try { Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(className); Class<? extends Provider> cp = c.asSubclass(Provider.class); return cp.newInstance(); } catch (ClassCastException e) { securityLog.error( "The security provider implementation ''{0}'' does not extend Provider class." + "Defaulting to system installed security providers: {1}", e, className, Arrays.toString(Security.getProviders()) ); return null; } catch (ClassNotFoundException e) { securityLog.error( "The security provider implementation ''{0}'' was not found in classpath. " + "Defaulting to system installed security providers: {1}", e, className, Arrays.toString(Security.getProviders()) ); return null; } catch (InstantiationException e) { securityLog.error( "The configured security provider ''{0}'' cannot be instantiated: {1}. " + "Defaulting to system installed security providers: {2} ", e, className, e.getMessage(), Arrays.toString(Security.getProviders()) ); return null; } catch (IllegalAccessException e) { securityLog.error( "The configured security provider ''{0}'' cannot be accessed: {1]." + "Defaulting to system installed security providers: {2} ", e, className, e.getMessage(), Arrays.toString(Security.getProviders()) ); return null; } catch (ExceptionInInitializerError e) { securityLog.error( "Error initializing security provider class ''{0}'': {1}. " + "Defaulting to system installed security providers: {2}", e, className, e.getMessage(), Arrays.toString(Security.getProviders()) ); return null; } catch (SecurityException e) { securityLog.error( "Security manager prevented instantiating security provider class ''{0}'': {1}. " + "Defaulting to system installed security providers: {2} " + e, className, e.getMessage(), Arrays.toString(Security.getProviders()) ); return null; } } } public enum StorageType { /** * PKCS #12 format */ PKCS12, JKS, JCEKS, /** * BouncyCastle keystore format roughly equivalent to Sun JKS implementation. */ BKS; // TODO : add the rest of BC keystore options @Override public String toString() { return getStorageTypeName(); } public String getStorageTypeName() { return name(); } } /** * Default logger for the security package. */ protected final static Logger securityLog = Logger.getInstance(SecurityLog.DEFAULT); /** * Stores key store entries which are used when the contents of this key manager is * turned into a keystore implementation (in-memory, file-persisted, or otherwise). */ private Map<String, KeyStoreEntry> keyEntries = new HashMap<String, KeyStoreEntry>(); /** * The storage type used by this instance. */ private StorageType storage = DEFAULT_KEYSTORE_STORAGE_TYPE; /** * The security provider used by this instance. */ private Provider provider = DEFAULT_SECURITY_PROVIDER.getProviderInstance(); /** * Empty implementation, no-args constructor limited for subclass use only. */ protected KeyManager() { } /** * This constructor allows the subclasses to specify both the storage type and explicit * security provider to use with this instance. The storage type and provider will be used * instead of the default values. <p> * * Note that the provider parameter allows a null value. This indicates that the appropriate * security provider should be searched from the JVM installed security providers in their * preferred order. * * @param storage * The storage type to use with this instance. * * @param provider * The explicit security provider to use with the storage of this instance. If a * null value is specified, the implementations should opt to delegate the selection * of a security provider to the JVMs installed security provider implementations. */ protected KeyManager(StorageType storage, Provider provider) { if (storage == null) { throw new IllegalArgumentException("Implementation Error: null storage type"); } this.provider = provider; this.storage = storage; } /** * Stores the keys in this key manager in a secure keystore format. This implementation generates * an in-memory keystore that is not backed by a persistent storage. The format used for * storing the key entries is PKCS #12. * * @param password * A secret password used to access the keystore contents. Note that the character * array will be set to zero bytes when this method completes. * * @return An in-memory keystore instance. * * @throws KeyManagerException * if the keystore creation fails for any reason */ public KeyStore save(char[] password) throws KeyManagerException { try { KeyStore keystore = instantiateKeyStore(password); return save(keystore, new ByteArrayOutputStream(), password); } finally { if (password != null) { for (int i = 0; i < password.length; ++i) { password[i] = 0; } } } } /** * Stores the keys in this key manager in a secure keystore format. This implementation generates * a file-based, persistent keystore which can be shared with other applications and processes. * The format used for storing the key entries is PKCS #12. * * @param file * the file where the keystore should be saved * * @param password * A secret password used to access the keystore contents. Note that the character * array will be set to zero values after this method call completes. * * @return an in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ public KeyStore save(File file, char[] password) throws KeyManagerException { if (file == null) { throw new KeyManagerException("Save failed due to null file descriptor."); } try { KeyStore keystore; if (exists(file)) { keystore = instantiateKeyStore(file, password); } else { keystore = instantiateKeyStore(password); } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); return save(keystore, out, password); } catch (FileNotFoundException e) { throw new KeyManagerException( "File ''{0}'' cannot be created or opened : {1}", e, resolveFilePath(file), e.getMessage() ); } catch (SecurityException e) { throw new KeyManagerException( "Security manager has denied access to file ''{0}'' : {1}", e, resolveFilePath(file), e.getMessage() ); } finally { if (password != null) { for (int i = 0; i < password.length; ++i) { password[i] = 0; } } } } protected void add(String keyAlias, KeyStore.Entry entry, KeyStore.ProtectionParameter param) { if (keyAlias == null || keyAlias.equals("")) { throw new IllegalArgumentException( "Implementation Error: null or empty key alias is not allowed." ); } if (entry == null) { throw new IllegalArgumentException( "Implementation Error: null keystore entry is not allowed." ); } // TODO check if null protection param is ok? // TODO boolean to save/not save immediately. keyEntries.put(keyAlias, new KeyStoreEntry(entry, param)); } protected boolean remove(String keyAlias) { KeyStoreEntry entry = keyEntries.remove(keyAlias); // TODO : remove from associated storage? return entry != null; } protected Provider getSecurityProvider() { return provider; } /** * Adds the key entries of this key manager into a keystore. The keystore is saved to the given * output stream. The keystore can be an existing, loaded keystore or a new, empty one. * * @param keystore * keystore to add keys from this key manager to * * @param out * the output stream for the keystore (can be used for persisting the keystore to disk) * * @param password * password to access the keystore * * @return an in-memory keystore instance * * @throws KeyManagerException * if the save operation fails */ private KeyStore save(KeyStore keystore, OutputStream out, char[] password) throws KeyManagerException { if (password == null || password.length == 0) { throw new KeyManagerException( "Null or empty password. Keystore must be protected with a password." ); } BufferedOutputStream bout = new BufferedOutputStream(out); try { for (String keyAlias : keyEntries.keySet()) { KeyStoreEntry entry = keyEntries.get(keyAlias); keystore.setEntry(keyAlias, entry.entry, entry.protectionParameter); } keystore.store(bout, password); return keystore; } catch (KeyStoreException e) { throw new KeyManagerException("Storing the key pair failed : {0}", e, e.getMessage()); } catch (IOException e) { throw new KeyManagerException( "Unable to write key to keystore : {1}", e, e.getMessage() ); } catch (NoSuchAlgorithmException e) { throw new KeyManagerException( "Security provider does not support required key store algorithm: {0}", e, e.getMessage() ); } catch (CertificateException e) { throw new KeyManagerException("Cannot store certificate: {0}", e, e.getMessage()); } finally { if (bout != null) { try { bout.flush(); bout.close(); } catch (IOException e) { securityLog.warn("Failed to close file output stream to keystore : {0}", e, e.getMessage()); } } } } /** * Instantiante an in-memory, non-persistent PKCS #12 keystore. * * @param password * password to access the keystore * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore instantiateKeyStore(char[] password) throws ConfigurationException, KeyManagerException { return instantiateKeyStore(password, storage); } /** * Instantiate an in-memory, non-persistent keystore with a given algorithm for the storage * format. * * @param password * password to access the keystore * * @param type * the algorithm used to store the keystore data * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore instantiateKeyStore(char[] password, StorageType type) throws ConfigurationException, KeyManagerException { return getKeyStore(null, password, type); } /** * Loads a PKCS #12 keystore instance from an existing file. * * @param file * file to load the keystore from * * @param password * password to access the keystore * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore instantiateKeyStore(File file, char[] password) throws ConfigurationException, KeyManagerException { return instantiateKeyStore(file, password, storage); } /** * Loads a keystore instance from an existing file. * * @param file * file to load the keystore from * * @param password * password to access the keystore * * @param type * the algorithm used to store the keystore data * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore instantiateKeyStore(File file, char[] password, StorageType type) throws ConfigurationException, KeyManagerException { try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); return getKeyStore(in, password, type); } catch (FileNotFoundException e) { throw new KeyManagerException( "Keystore file ''{0}'' could not be created or opened : {1}", e, resolveFilePath(file), e.getMessage() ); } catch (SecurityException e) { throw new KeyManagerException( "Security manager has denied access to keystore file ''{0}'' : {1}", e, resolveFilePath(file), e.getMessage() ); } } /** * Loads a key store from input stream (or creates a new, empty one). The keystore storage * format can be provided as a parameter. * * @param in * input stream to keystore file (or null to create a new one) * * @param password * shared secret (a password) used for protecting access to the keystore * * @param type * the algorithm used to securely store the keystore data * * @return an in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore getKeyStore(InputStream in, char[] password, StorageType type) throws ConfigurationException, KeyManagerException { if (password == null || password.length == 0) { throw new KeyManagerException( "Null or empty password. Keystore must be protected with a password." ); } try { KeyStore keystore; if (provider == null) { keystore = KeyStore.getInstance(type.name()); } else { keystore = KeyStore.getInstance(type.name(), provider); } keystore.load(in, password); return keystore; } catch (KeyStoreException e) { // NOTE: If the algorithm is not recognized by a provider, it is indicated by a nested // NoSuchAlgorithmException. This is the behavior for both SUN default provider // in Java 6 and BouncyCastle. if (e.getCause() != null && e.getCause() instanceof NoSuchAlgorithmException) { String usedProviders; if (provider == null) { usedProviders = Arrays.toString(Security.getProviders()); } else { usedProviders = provider.getName(); } throw new ConfigurationException( "The security provider(s) ''{0}'' do not support keystore type ''{1}'' : {2}", e, usedProviders, type.name(), e.getMessage() ); } throw new KeyManagerException("Cannot load keystore: {0}", e, e.getMessage()); } catch (NoSuchAlgorithmException e) { // If part of the keystore load() the algorithm to verify the keystore contents cannot // be found... throw new KeyManagerException( "Required keystore verification algorithm not found: {0}", e, e.getMessage() ); } catch (CertificateException e) { // Can happen if any of the certificates in the store cannot be loaded... throw new KeyManagerException("Can't load keystore: {0}", e, e.getMessage()); } catch (IOException e) { // If there's an I/O problem, or if keystore has been corrupted, or if password is missing // if (e.getCause() != null && e.getCause() instanceof UnrecoverableKeyException) // // The Java 6 javadoc claims that an incorrect password can be detected by having // // a nested UnrecoverableKeyException in the wrapping IOException -- this doesn't // // seem to be the case or is not working... incorrect password is reported as an // // IOException just like other I/O errors with no root causes as far as I'm able to // // tell. So leaving this out for now // // [JPL] // throw new PasswordException( // "Cannot recover keys from keystore (was the provided password correct?) : {0}", // e.getMessage(), e throw new KeyManagerException("Cannot load keystore: {0}", e, e.getMessage()); } } /** * File utility to print file path. * * @param file * file path to print * * @return resolves to an absolute file path if allowed by the security manager, if not * returns the file path as defined in the file object parameter */ private String resolveFilePath(File file) { try { return file.getAbsolutePath(); } catch (SecurityException e) { return file.getPath(); } } /** * Checks if given file exists. * * @param file * file to check * * @return true if file exists, false otherwise * * @throws KeyManagerException * if security manager has denied access to file information */ private boolean exists(final File file) throws KeyManagerException { try { return file.exists(); } catch (SecurityException e) { String path = resolveFilePath(file); throw new KeyManagerException( "Security manager has prevented access to file ''{0}'' : {1}", e, path, e.getMessage() ); } } /** * Convenience class to hold keystore entry and its protection parameter as single entity in * collections. */ private static class KeyStoreEntry { private KeyStore.Entry entry; private KeyStore.ProtectionParameter protectionParameter; private KeyStoreEntry(KeyStore.Entry entry, KeyStore.ProtectionParameter param) { this.entry = entry; this.protectionParameter = param; } } /** * Exception type for the public API of this class to indicate errors. */ public static class KeyManagerException extends OpenRemoteException { protected KeyManagerException(String msg) { super(msg); } protected KeyManagerException(String msg, Throwable cause, Object... params) { super(msg, cause, params); } } /** * Specific subclass of KeyManagerException that indicates a security configuration issue. */ public static class ConfigurationException extends KeyManagerException { protected ConfigurationException(String msg, Throwable cause, Object... params) { super(msg, cause, params); } } }
package org.xbill.DNS; import java.io.*; import java.util.*; import org.xbill.DNS.utils.*; /** * Transaction signature handling. This class generates and verifies * TSIG records on messages, which provide transaction security. * @see TSIGRecord * * @author Brian Wellington */ public class TSIG { private static final String HMAC_MD5_STR = "HMAC-MD5.SIG-ALG.REG.INT."; private static final String HMAC_SHA1_STR = "hmac-sha1."; private static final String HMAC_SHA256_STR = "hmac-sha256."; /** The domain name representing the HMAC-MD5 algorithm. */ public static final Name HMAC_MD5 = Name.fromConstantString(HMAC_MD5_STR); /** The domain name representing the HMAC-MD5 algorithm (deprecated). */ public static final Name HMAC = HMAC_MD5; /** The domain name representing the HMAC-SHA1 algorithm. */ public static final Name HMAC_SHA1 = Name.fromConstantString(HMAC_SHA1_STR); /** The domain name representing the HMAC-SHA256 algorithm. */ public static final Name HMAC_SHA256 = Name.fromConstantString(HMAC_SHA256_STR); /** * The default fudge value for outgoing packets. Can be overriden by the * tsigfudge option. */ public static final short FUDGE = 300; private Name name, alg; private String digest; private byte [] key; private void getDigest() { if (alg.equals(HMAC_MD5)) digest = "md5"; else if (alg.equals(HMAC_SHA1)) digest = "sha-1"; else if (alg.equals(HMAC_SHA256)) digest = "sha-256"; else throw new IllegalArgumentException("Invalid algorithm"); } /** * Creates a new TSIG key, which can be used to sign or verify a message. * @param algorithm The algorithm of the shared key. * @param name The name of the shared key. * @param key The shared key's data. */ public TSIG(Name algorithm, Name name, byte [] key) { this.name = name; this.alg = algorithm; this.key = key; getDigest(); } /** * Creates a new TSIG key with the hmac-md5 algorithm, which can be used to * sign or verify a message. * @param name The name of the shared key. * @param key The shared key's data. */ public TSIG(Name name, byte [] key) { this(HMAC_MD5, name, key); } public TSIG(Name algorithm, String name, String key) { if (key.length() > 1 && key.charAt(0) == ':') this.key = base16.fromString(key.substring(1)); else this.key = base64.fromString(key); if (this.key == null) throw new IllegalArgumentException("Invalid TSIG key string"); try { this.name = Name.fromString(name, Name.root); } catch (TextParseException e) { throw new IllegalArgumentException("Invalid TSIG key name"); } this.alg = algorithm; getDigest(); } public TSIG(String name, String key) { this(HMAC_MD5, name, key); } /** * Generates a TSIG record with a specific error for a message that has * been rendered. * @param m The message * @param b The rendered message * @param error The error * @param old If this message is a response, the TSIG from the request * @return The TSIG record to be added to the message */ public TSIGRecord generate(Message m, byte [] b, int error, TSIGRecord old) { Date timeSigned; if (error != Rcode.BADTIME) timeSigned = new Date(); else timeSigned = old.getTimeSigned(); int fudge; HMAC hmac = null; if (error == Rcode.NOERROR || error == Rcode.BADTIME) hmac = new HMAC(digest, key); fudge = Options.intValue("tsigfudge"); if (fudge < 0 || fudge > 0x7FFF) fudge = FUDGE; if (old != null) { DNSOutput out = new DNSOutput(); out.writeU16(old.getSignature().length); if (hmac != null) { hmac.update(out.toByteArray()); hmac.update(old.getSignature()); } } /* Digest the message */ if (hmac != null) hmac.update(b); DNSOutput out = new DNSOutput(); name.toWireCanonical(out); out.writeU16(DClass.ANY); /* class */ out.writeU32(0); /* ttl */ alg.toWireCanonical(out); long time = timeSigned.getTime() / 1000; int timeHigh = (int) (time >> 32); long timeLow = (time & 0xFFFFFFFFL); out.writeU16(timeHigh); out.writeU32(timeLow); out.writeU16(fudge); out.writeU16(error); out.writeU16(0); /* No other data */ if (hmac != null) hmac.update(out.toByteArray()); byte [] signature; if (hmac != null) signature = hmac.sign(); else signature = new byte[0]; byte [] other = null; if (error == Rcode.BADTIME) { out = new DNSOutput(); time = new Date().getTime() / 1000; timeHigh = (int) (time >> 32); timeLow = (time & 0xFFFFFFFFL); out.writeU16(timeHigh); out.writeU32(timeLow); other = out.toByteArray(); } return (new TSIGRecord(name, DClass.ANY, 0, alg, timeSigned, fudge, signature, m.getHeader().getID(), error, other)); } /** * Generates a TSIG record with a specific error for a message and adds it * to the message. * @param m The message * @param error The error * @param old If this message is a response, the TSIG from the request */ public void apply(Message m, int error, TSIGRecord old) { Record r = generate(m, m.toWire(), error, old); m.addRecord(r, Section.ADDITIONAL); m.tsigState = Message.TSIG_SIGNED; } /** * Generates a TSIG record for a message and adds it to the message * @param m The message * @param old If this message is a response, the TSIG from the request */ public void apply(Message m, TSIGRecord old) { apply(m, Rcode.NOERROR, old); } /** * Generates a TSIG record for a message and adds it to the message * @param m The message * @param old If this message is a response, the TSIG from the request */ public void applyStream(Message m, TSIGRecord old, boolean first) { if (first) { apply(m, old); return; } Date timeSigned = new Date(); int fudge; HMAC hmac = new HMAC(digest, key); fudge = Options.intValue("tsigfudge"); if (fudge < 0 || fudge > 0x7FFF) fudge = FUDGE; DNSOutput out = new DNSOutput(); out.writeU16(old.getSignature().length); hmac.update(out.toByteArray()); hmac.update(old.getSignature()); /* Digest the message */ hmac.update(m.toWire()); out = new DNSOutput(); long time = timeSigned.getTime() / 1000; int timeHigh = (int) (time >> 32); long timeLow = (time & 0xFFFFFFFFL); out.writeU16(timeHigh); out.writeU32(timeLow); out.writeU16(fudge); hmac.update(out.toByteArray()); byte [] signature = hmac.sign(); byte [] other = null; Record r = new TSIGRecord(name, DClass.ANY, 0, alg, timeSigned, fudge, signature, m.getHeader().getID(), Rcode.NOERROR, other); m.addRecord(r, Section.ADDITIONAL); m.tsigState = Message.TSIG_SIGNED; } /** * Verifies a TSIG record on an incoming message. Since this is only called * in the context where a TSIG is expected to be present, it is an error * if one is not present. * @param m The message * @param b An array containing the message in unparsed form. This is * necessary since TSIG signs the message in wire format, and we can't * recreate the exact wire format (with the same name compression). * @param length The length of the message in the array. * @param old If this message is a response, the TSIG from the request * @return The result of the verification (as an Rcode) * @see Rcode */ public byte verify(Message m, byte [] b, int length, TSIGRecord old) { TSIGRecord tsig = m.getTSIG(); HMAC hmac = new HMAC(digest, key); if (tsig == null) return Rcode.FORMERR; if (!tsig.getName().equals(name) || !tsig.getAlgorithm().equals(alg)) { if (Options.check("verbose")) System.err.println("BADKEY failure"); return Rcode.BADKEY; } long now = System.currentTimeMillis(); long then = tsig.getTimeSigned().getTime(); long fudge = tsig.getFudge(); if (Math.abs(now - then) > fudge * 1000) { if (Options.check("verbose")) System.err.println("BADTIME failure"); return Rcode.BADTIME; } if (old != null && tsig.getError() != Rcode.BADKEY && tsig.getError() != Rcode.BADSIG) { DNSOutput out = new DNSOutput(); out.writeU16(old.getSignature().length); hmac.update(out.toByteArray()); hmac.update(old.getSignature()); } m.getHeader().decCount(Section.ADDITIONAL); byte [] header = m.getHeader().toWire(); m.getHeader().incCount(Section.ADDITIONAL); hmac.update(header); int len = m.tsigstart - header.length; hmac.update(b, header.length, len); DNSOutput out = new DNSOutput(); tsig.getName().toWireCanonical(out); out.writeU16(tsig.dclass); out.writeU32(tsig.ttl); tsig.getAlgorithm().toWireCanonical(out); long time = tsig.getTimeSigned().getTime() / 1000; int timeHigh = (int) (time >> 32); long timeLow = (time & 0xFFFFFFFFL); out.writeU16(timeHigh); out.writeU32(timeLow); out.writeU16(tsig.getFudge()); out.writeU16(tsig.getError()); if (tsig.getOther() != null) { out.writeU16(tsig.getOther().length); out.writeByteArray(tsig.getOther()); } else { out.writeU16(0); } hmac.update(out.toByteArray()); if (hmac.verify(tsig.getSignature())) return Rcode.NOERROR; else { if (Options.check("verbose")) System.err.println("BADSIG failure"); return Rcode.BADSIG; } } /** * Verifies a TSIG record on an incoming message. Since this is only called * in the context where a TSIG is expected to be present, it is an error * if one is not present. * @param m The message * @param b The message in unparsed form. This is necessary since TSIG * signs the message in wire format, and we can't recreate the exact wire * format (with the same name compression). * @param old If this message is a response, the TSIG from the request * @return The result of the verification (as an Rcode) * @see Rcode */ public int verify(Message m, byte [] b, TSIGRecord old) { return verify(m, b, b.length, old); } /** * Returns the maximum length of a TSIG record generated by this key. * @see TSIGRecord */ public int recordLength() { return (name.length() + 10 + alg.length() + 8 + // time signed, fudge 18 + // 2 byte MAC length, 16 byte MAC 4 + // original id, error 8); // 2 byte error length, 6 byte max error field. } public static class StreamVerifier { /** * A helper class for verifying multiple message responses. */ private TSIG key; private HMAC verifier; private int nresponses; private int lastsigned; private TSIGRecord lastTSIG; /** Creates an object to verify a multiple message response */ public StreamVerifier(TSIG tsig, TSIGRecord old) { key = tsig; verifier = new HMAC(key.digest, key.key); nresponses = 0; lastTSIG = old; } /** * Verifies a TSIG record on an incoming message that is part of a * multiple message response. * TSIG records must be present on the first and last messages, and * at least every 100 records in between. * @param m The message * @param b The message in unparsed form * @return The result of the verification (as an Rcode) * @see Rcode */ public int verify(Message m, byte [] b) { TSIGRecord tsig = m.getTSIG(); nresponses++; if (nresponses == 1) { int result = key.verify(m, b, lastTSIG); if (result == Rcode.NOERROR) { byte [] signature = tsig.getSignature(); DNSOutput out = new DNSOutput(); out.writeU16(signature.length); verifier.update(out.toByteArray()); verifier.update(signature); } lastTSIG = tsig; return result; } if (tsig != null) m.getHeader().decCount(Section.ADDITIONAL); byte [] header = m.getHeader().toWire(); if (tsig != null) m.getHeader().incCount(Section.ADDITIONAL); verifier.update(header); int len; if (tsig == null) len = b.length - header.length; else len = m.tsigstart - header.length; verifier.update(b, header.length, len); if (tsig != null) { lastsigned = nresponses; lastTSIG = tsig; } else { boolean required = (nresponses - lastsigned >= 100); if (required) return Rcode.FORMERR; else return Rcode.NOERROR; } if (!tsig.getName().equals(key.name) || !tsig.getAlgorithm().equals(key.alg)) { if (Options.check("verbose")) System.err.println("BADKEY failure"); return Rcode.BADKEY; } DNSOutput out = new DNSOutput(); long time = tsig.getTimeSigned().getTime() / 1000; int timeHigh = (int) (time >> 32); long timeLow = (time & 0xFFFFFFFFL); out.writeU16(timeHigh); out.writeU32(timeLow); out.writeU16(tsig.getFudge()); verifier.update(out.toByteArray()); if (verifier.verify(tsig.getSignature()) == false) { if (Options.check("verbose")) System.err.println("BADSIG failure"); return Rcode.BADSIG; } verifier.clear(); out = new DNSOutput(); out.writeU16(tsig.getSignature().length); verifier.update(out.toByteArray()); verifier.update(tsig.getSignature()); return Rcode.NOERROR; } } }
package org.shopkeeper.preloader; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.control.ProgressBar; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import org.shopkeeper.database.DatabaseHandler; import org.shopkeeper.database.modules.DatabaseChooser; import org.shopkeeper.database.modules.DatabaseTypes; import org.shopkeeper.preferences.PreferenceHandler; import org.shopkeeper.subjects.SubjectHandler; import java.util.ArrayList; import java.util.List; public class Preloader extends Application { public static Boolean ready = false; private static List<Runnable> MODULES = new ArrayList<>(); // The list with all the runnables: private static Integer JOBCOUNTER = 0; private static ProgressBar PROGRESSBAR = null; public static void startPreloader() throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { initPreloader(); for (Runnable tasks : MODULES) { Thread thread = new Thread(tasks); thread.start(); synchronized (Preloader.ready) { try { ready.wait(); JOBCOUNTER++; updateProgressBar(JOBCOUNTER,JOBCOUNTER + " out of " + MODULES.size() + " jobs done..."); } catch (InterruptedException e) { e.printStackTrace(); } } } } }); thread.start(); } public static void initPreloader() { MODULES.add(new DatabaseHandler(DatabaseChooser.getDatabase(DatabaseTypes.DATABASETYPE_SQLLITE))); MODULES.add(new SubjectHandler()); MODULES.add(new PreferenceHandler()); } @Override public void start(Stage primaryStage) throws Exception { // GUI: primaryStage.setTitle("Shopkeeper"); BorderPane root = new BorderPane(); PROGRESSBAR = new ProgressBar(); root.setBottom(PROGRESSBAR); PROGRESSBAR.setMinWidth(600); primaryStage.setScene(new Scene(root, 600, 250)); primaryStage.show(); // STARTING THE PRELOADER: Preloader.startPreloader(); } public static void updateProgressBar(Integer procentage, String message) { Platform.runLater(new Runnable() { @Override public void run() { System.out.println(message); double p = new Float(procentage)/new Float(MODULES.size()); PROGRESSBAR.setProgress(p); } }); } public static void main(String[] args) throws InterruptedException { launch(args); } }
package org.smartwallet.stratum; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import org.jboss.aesh.cl.Arguments; import org.jboss.aesh.cl.CommandDefinition; import org.jboss.aesh.console.AeshConsole; import org.jboss.aesh.console.AeshConsoleBuilder; import org.jboss.aesh.console.Console; import org.jboss.aesh.console.Prompt; import org.jboss.aesh.console.command.Command; import org.jboss.aesh.console.command.CommandResult; import org.jboss.aesh.console.command.invocation.CommandInvocation; import org.jboss.aesh.console.command.registry.AeshCommandRegistryBuilder; import org.jboss.aesh.console.command.registry.CommandRegistry; import org.jboss.aesh.console.helper.InterruptHook; import org.jboss.aesh.console.settings.Settings; import org.jboss.aesh.console.settings.SettingsBuilder; import org.jboss.aesh.edit.actions.Action; import org.jboss.aesh.terminal.Color; import org.jboss.aesh.terminal.TerminalColor; import org.jboss.aesh.terminal.TerminalString; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.util.List; import java.util.concurrent.*; public class StratumCli { public static final int CALL_TIMEOUT = 5000; private StratumClient client; private AeshConsole console; private ObjectMapper mapper; private BlockingQueue<StratumMessage> addressChangeQueue; private ExecutorService addressChangeService; private BlockingQueue<StratumMessage> headersChangeQueue; private ExecutorService headersChangeService; public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Usage: StratumCli HOST:PORT"); System.exit(1); } String[] hostPort = args[0].split(":"); if (hostPort.length != 2) { System.err.println("Usage: StratumCli HOST:PORT"); System.exit(1); } String host = hostPort[0]; int port = Integer.parseInt(hostPort[1]); new StratumCli().run(host, port); } private void run(String host, int port) { mapper = new ObjectMapper(); client = new StratumClient(new InetSocketAddress(host, port), true); client.startAsync(); CommandRegistry registry = new AeshCommandRegistryBuilder() .command(new ExitCommand()) .command(new VersionCommand()) .command(new BannerCommand()) .command(new HelpCommand()) .command(new SubscribeAddressCommand()) .command(new SubscribeHeadersCommand()) .create(); Settings settings = new SettingsBuilder() .logging(true) .persistHistory(true) .historyFile(new File(System.getProperty("user.home"), ".cache/stratum-cli.hist")) .interruptHook(new InterruptHook() { @Override public void handleInterrupt(Console console, Action action) { if (action == Action.EOF) { console.stop(); } } }) .create(); console = new AeshConsoleBuilder() .commandRegistry(registry) .settings(settings) .prompt(new Prompt(new TerminalString("[aesh@rules]$ ", new TerminalColor(Color.GREEN, Color.DEFAULT, Color.Intensity.BRIGHT)))) .create(); console.start(); } @CommandDefinition(name="exit", description = "exit the program") public class ExitCommand implements Command { @Override public CommandResult execute(CommandInvocation commandInvocation) throws IOException, InterruptedException { commandInvocation.stop(); return CommandResult.SUCCESS; } } @CommandDefinition(name="version", description = "get server version") public class VersionCommand implements Command { @Override public CommandResult execute(CommandInvocation commandInvocation) throws IOException, InterruptedException { simpleCall("server.version"); return CommandResult.SUCCESS; } } @CommandDefinition(name="banner", description = "get server banner") public class BannerCommand implements Command { @Override public CommandResult execute(CommandInvocation commandInvocation) throws IOException, InterruptedException { simpleCall("server.banner"); return CommandResult.SUCCESS; } } private void simpleCall(String method) throws IOException { ListenableFuture<StratumMessage> future = client.call(method, Lists.newArrayList()); Futures.addCallback(future, new FutureCallback<StratumMessage>() { @Override public void onSuccess(StratumMessage result) { } @Override public void onFailure(Throwable t) { System.out.println("failed."); } }); try { StratumMessage result = future.get(CALL_TIMEOUT, TimeUnit.MILLISECONDS); System.out.print("result: "); System.out.println(result.result); } catch (InterruptedException | ExecutionException e) { // ignore, handled by callback } catch (TimeoutException e) { System.out.println("timeout"); } } private String formatResult(StratumMessage result) { try { return mapper.writeValueAsString(result.result); } catch (JsonProcessingException e) { throw Throwables.propagate(e); } } @CommandDefinition(name="help", description = "show this message") public class HelpCommand implements Command { @Override public CommandResult execute(CommandInvocation commandInvocation) throws IOException, InterruptedException { for (String cmd : console.getCommandRegistry().getAllCommandNames()) { System.out.println(cmd); System.out.print(console.getHelpInfo(cmd)); System.out.println(" } return CommandResult.SUCCESS; } } @CommandDefinition(name="subscribe_headers", description = "subscribe to headers") public class SubscribeHeadersCommand implements Command { @Override public CommandResult execute(CommandInvocation commandInvocation) throws IOException, InterruptedException { StratumSubscription subscription = client.subscribe("blockchain.headers.subscribe", Lists.newArrayList()); headersChangeQueue = subscription.queue; if (headersChangeService == null) { headersChangeService = Executors.newSingleThreadExecutor(); headersChangeService.submit(new Runnable() { @Override public void run() { while (true) { try { StratumMessage item = headersChangeQueue.take(); if (item.isSentinel()) break; System.out.println(mapper.writeValueAsString(item)); } catch (InterruptedException | JsonProcessingException e) { throw Throwables.propagate(e); } } } }); } handleSubscriptionResult(subscription); return CommandResult.SUCCESS; } } @CommandDefinition(name="subscribe_address", description = "subscribe to headers") public class SubscribeAddressCommand implements Command { @Arguments(description = "addresses") List<String> addresses; @Override public CommandResult execute(CommandInvocation commandInvocation) throws IOException, InterruptedException { List<Object> params = Lists.newArrayList(); params.addAll(addresses); StratumSubscription subscription = client.subscribe("blockchain.address.subscribe", params); addressChangeQueue = subscription.queue; if (addressChangeService == null) { addressChangeService = Executors.newSingleThreadExecutor(); addressChangeService.submit(new Runnable() { @Override public void run() { while (true) { try { StratumMessage item = addressChangeQueue.take(); if (item.isSentinel()) break; System.out.println(mapper.writeValueAsString(item)); } catch (InterruptedException | JsonProcessingException e) { throw Throwables.propagate(e); } } } }); } handleSubscriptionResult(subscription); return CommandResult.SUCCESS; } } private void handleSubscriptionResult(StratumSubscription subscription) { Futures.addCallback(subscription.future, new FutureCallback<StratumMessage>() { @Override public void onSuccess(StratumMessage result) { } @Override public void onFailure(Throwable t) { System.out.println("failed."); } }); try { StratumMessage result = subscription.future.get(CALL_TIMEOUT, TimeUnit.MILLISECONDS); System.out.print("initial state: "); System.out.println(formatResult(result)); } catch (InterruptedException | ExecutionException e) { // ignore, handled by callback } catch (TimeoutException e) { System.out.println("timeout"); } } }
package org.threadly.litesockets; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.SocketChannel; import java.util.ArrayDeque; import java.util.Deque; import java.util.concurrent.atomic.AtomicBoolean; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; import org.threadly.concurrent.future.FutureUtils; import org.threadly.concurrent.future.ListenableFuture; import org.threadly.concurrent.future.SettableListenableFuture; import org.threadly.litesockets.utils.IOUtils; import org.threadly.litesockets.utils.MergedByteBuffers; import org.threadly.litesockets.utils.SSLProcessor; import org.threadly.util.ArgumentVerifier; import org.threadly.util.Clock; import org.threadly.util.ExceptionUtils; import org.threadly.util.Pair; /** * A Simple TCP client. * */ public class TCPClient extends Client { protected static final int DEFAULT_SOCKET_TIMEOUT = 10000; protected static final int MIN_WRITE_BUFFER_SIZE = 8192; protected static final int MAX_COMBINED_WRITE_BUFFER_SIZE = 65536; private static final ListenableFuture<Long> closedFuture = FutureUtils.immediateFailureFuture(new IllegalStateException("Connection is Closed")); private final MergedByteBuffers writeBuffers = new MergedByteBuffers(); private final Deque<Pair<Long, SettableListenableFuture<Long>>> writeFutures = new ArrayDeque<>(8); private final TCPSocketOptions tso = new TCPSocketOptions(); protected final AtomicBoolean startedConnection = new AtomicBoolean(false); protected final SettableListenableFuture<Boolean> connectionFuture = new SettableListenableFuture<>(false); protected final SocketChannel channel; protected final InetSocketAddress remoteAddress; private volatile ListenableFuture<Long> lastWriteFuture = IOUtils.FINISHED_LONG_FUTURE; private volatile ByteBuffer currentWriteBuffer = IOUtils.EMPTY_BYTEBUFFER; private volatile SSLProcessor sslProcessor; protected volatile int maxConnectionTime = DEFAULT_SOCKET_TIMEOUT; protected volatile long connectExpiresAt = -1; /** * This creates TCPClient with a connection to the specified port and IP. This connection is not is not * yet made {@link #connect()} must be called which will do the actual connect. * * @param sei The {@link SocketExecuter} implementation this client will use. * @param host The hostname or IP address to connect this client too. * @param port The port to connect this client too. * @throws IOException - This is thrown if there are any problems making the socket. */ protected TCPClient(final SocketExecuterCommonBase sei, final String host, final int port) throws IOException { super(sei); remoteAddress = new InetSocketAddress(host, port); channel = SocketChannel.open(); channel.configureBlocking(false); } /** * <p>This creates a TCPClient based off an already existing {@link SocketChannel}. * This {@link SocketChannel} must already be connected.</p> * * @param sei the {@link SocketExecuter} to use for this client. * @param channel the {@link SocketChannel} to use for this client. * @throws IOException if there is anything wrong with the {@link SocketChannel} this will be thrown. */ protected TCPClient(final SocketExecuterCommonBase sei, final SocketChannel channel) throws IOException { super(sei); if(! channel.isOpen()) { throw new ClosedChannelException(); } connectionFuture.setResult(true); if(channel.isBlocking()) { channel.configureBlocking(false); } this.channel = channel; remoteAddress = (InetSocketAddress) channel.socket().getRemoteSocketAddress(); startedConnection.set(true); } @Override public void setConnectionTimeout(final int timeout) { ArgumentVerifier.assertGreaterThanZero(timeout, "Timeout"); this.maxConnectionTime = timeout; } @Override public ListenableFuture<Boolean> connect(){ if(startedConnection.compareAndSet(false, true)) { try { channel.connect(remoteAddress); connectExpiresAt = maxConnectionTime + Clock.accurateForwardProgressingMillis(); se.setClientOperations(this); se.watchFuture(connectionFuture, maxConnectionTime); } catch (Exception e) { connectionFuture.setFailure(e); close(); } } return connectionFuture; } @Override protected void setConnectionStatus(final Throwable t) { if(t == null) { connectionFuture.setResult(true); } else { if(connectionFuture.setFailure(t)) { close(); } } } @Override public boolean hasConnectionTimedOut() { if(! startedConnection.get() || channel.isConnected()) { return false; } return Clock.lastKnownForwardProgressingMillis() > connectExpiresAt || Clock.accurateForwardProgressingMillis() > connectExpiresAt; } @Override public int getTimeout() { return maxConnectionTime; } @Override protected SocketChannel getChannel() { return channel; } @Override public void close() { if(setClose()) { se.setClientOperations(this); this.getClientsThreadExecutor().execute(new Runnable() { @Override public void run() { synchronized(writerLock) { if(writeFutures.size() > 0) { final ClosedChannelException cce = new ClosedChannelException(); for(final Pair<Long, SettableListenableFuture<Long>> p: writeFutures) { p.getRight().setFailure(cce); } } writeFutures.clear(); writeBuffers.discard(writeBuffers.remaining()); } }}); this.callClosers(); } } @Override public WireProtocol getProtocol() { return WireProtocol.TCP; } @Override public boolean canWrite() { return writeBuffers.remaining() > 0 ; } @Override public int getWriteBufferSize() { return this.writeBuffers.remaining() + this.currentWriteBuffer.remaining(); } @Override public MergedByteBuffers getRead() { MergedByteBuffers mbb = super.getRead(); if(sslProcessor != null && sslProcessor.handShakeStarted() && mbb.remaining() > 0) { mbb = sslProcessor.decrypt(mbb); } return mbb; } @Override protected void doSocketRead(boolean doLocal) { if(doLocal) { doClientRead(doLocal); } else { this.getClientsThreadExecutor().execute(()->doClientRead(doLocal)); } } @Override protected void doSocketWrite(boolean doLocal) { if(doLocal) { doClientWrite(doLocal); } else { this.getClientsThreadExecutor().execute(()->doClientWrite(doLocal)); } } @Override public ListenableFuture<?> write(final ByteBuffer bb) { return write(new MergedByteBuffers(false, bb)); } @Override public ListenableFuture<?> write(final MergedByteBuffers mbb) { if(isClosed()) { return closedFuture; } synchronized(writerLock) { final SettableListenableFuture<Long> slf = new SettableListenableFuture<>(false); lastWriteFuture = slf; final boolean needNotify = !canWrite(); if(sslProcessor != null && sslProcessor.handShakeStarted()) { writeBuffers.add(sslProcessor.encrypt(mbb)); } else { writeBuffers.add(mbb); } writeFutures.add(new Pair<>(writeBuffers.getTotalConsumedBytes()+writeBuffers.remaining(), slf)); if(needNotify && se != null && channel.isConnected()) { se.setClientOperations(this); } return lastWriteFuture; } } public ListenableFuture<?> lastWriteFuture() { return lastWriteFuture; } @Override protected ByteBuffer getWriteBuffer() { if(currentWriteBuffer.remaining() != 0) { return currentWriteBuffer; } synchronized(writerLock) { //This is to keep from doing a ton of little writes if we can. We will try to //do at least 8k at a time, and up to 65k if we are already having to combine buffers if(writeBuffers.nextPopSize() < MIN_WRITE_BUFFER_SIZE && writeBuffers.remaining() > writeBuffers.nextPopSize()) { if(writeBuffers.remaining() < MAX_COMBINED_WRITE_BUFFER_SIZE) { currentWriteBuffer = writeBuffers.pull(writeBuffers.remaining()); } else { currentWriteBuffer = writeBuffers.pull(MAX_COMBINED_WRITE_BUFFER_SIZE); } } else { currentWriteBuffer = writeBuffers.pop(); } } return currentWriteBuffer; } @Override protected void reduceWrite(final int size) { synchronized(writerLock) { addWriteStats(size); if(currentWriteBuffer.remaining() == 0) { while(this.writeFutures.peekFirst() != null && writeFutures.peekFirst().getLeft() <= writeBuffers.getTotalConsumedBytes()) { final Pair<Long, SettableListenableFuture<Long>> p = writeFutures.pollFirst(); p.getRight().setResult(p.getLeft()); } } } } @Override public InetSocketAddress getRemoteSocketAddress() { return remoteAddress; } @Override public InetSocketAddress getLocalSocketAddress() { return (InetSocketAddress) channel.socket().getLocalSocketAddress(); } @Override public String toString() { return "TCPClient:FROM:"+getLocalSocketAddress()+":TO:"+getRemoteSocketAddress(); } @Override public ClientOptions clientOptions() { return tso; } public void setSSLEngine(final SSLEngine ssle) { sslProcessor = new SSLProcessor(this, ssle); } public boolean isEncrypted() { if(sslProcessor == null) { return false; } return sslProcessor.isEncrypted(); } public ListenableFuture<SSLSession> startSSL() { if(sslProcessor != null) { return sslProcessor.doHandShake(); } throw new IllegalStateException("Must Set the SSLEngine before starting Encryption!"); } private void doClientWrite(boolean doLocal) { if(isClosed()) { return; } int wrote = 0; try { wrote = channel.write(getWriteBuffer()); if(wrote > 0) { reduceWrite(wrote); se.addWriteAmount(wrote); } if(!doLocal) { se.setClientOperations(TCPClient.this); } } catch(Exception e) { ExceptionUtils.handleException(e); close(); } } private void doClientRead(boolean doLocal) { if(isClosed()) { return; } ByteBuffer readByteBuffer = provideReadByteBuffer(); final int origPos = readByteBuffer.position(); int size = 0; try { size = channel.read(readByteBuffer); if(size > 0) { readByteBuffer.position(origPos); final ByteBuffer resultBuffer = readByteBuffer.slice(); readByteBuffer.position(origPos+size); resultBuffer.limit(size); addReadBuffer(resultBuffer); if(!doLocal) { se.setClientOperations(TCPClient.this); } } else if(size < 0) { close(); return; } } catch (IOException e) { ExceptionUtils.handleException(e); close(); } } /** * * @author lwahlmeier * */ private class TCPSocketOptions extends BaseClientOptions { @Override public boolean setTcpNoDelay(boolean enabled) { try { channel.socket().setTcpNoDelay(enabled); return true; } catch (SocketException e) { return false; } } @Override public boolean getTcpNoDelay() { try { return channel.socket().getTcpNoDelay(); } catch (SocketException e) { return false; } } @Override public boolean setSocketSendBuffer(int size) { try { ArgumentVerifier.assertGreaterThanZero(size, "size"); int prev = channel.socket().getSendBufferSize(); channel.socket().setSendBufferSize(size); if(channel.socket().getSendBufferSize() != size) { channel.socket().setSendBufferSize(prev); return false; } return true; } catch (Exception e) { return false; } } @Override public int getSocketSendBuffer() { try { return channel.socket().getSendBufferSize(); } catch (SocketException e) { return -1; } } @Override public boolean setSocketRecvBuffer(int size) { try { ArgumentVerifier.assertGreaterThanZero(size, "size"); int prev = channel.socket().getReceiveBufferSize(); channel.socket().setReceiveBufferSize(size); if(channel.socket().getReceiveBufferSize() != size) { channel.socket().setReceiveBufferSize(prev); return false; } return true; } catch (Exception e) { return false; } } @Override public int getSocketRecvBuffer() { try { return channel.socket().getReceiveBufferSize(); } catch (SocketException e) { return -1; } } } }
package permafrost.tundra.lang; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * A collection of convenience methods for working with arrays. */ public class ArrayHelper { /** * Disallow instantiation of this class. */ private ArrayHelper() { } /** * Returns a new array, with the given element inserted at the end. * * @param array The array to append the item to. * @param item The item to be appended. * @param klass The class of the item being appended. * @param <T> The class of the item being appended. * @return A copy of the given array with the given item appended to the end. */ public static <T> T[] append(T[] array, T item, Class<T> klass) { return insert(array, item, -1, klass); } /** * Returns a new array with all null elements removed. * * @param array The array to be compacted. * @param <T> The class of the items in the array. * @return A copy of the given array with all null items removed. */ public static <T> T[] compact(T[] array) { if (array == null) return null; List<T> list = new ArrayList<T>(array.length); for (T item : array) { if (item != null) list.add(item); } return list.toArray(Arrays.copyOf(array, list.size())); } /** * Returns a new table with all null elements removed. * * @param table The two dimensional array to be compacted. * @param <T> The class of the items in the array. * @return A copy of the given array with all null items removed. */ public static <T> T[][] compact(T[][] table) { if (table == null) return null; List<T[]> list = new ArrayList<T[]>(table.length); for (int i = 0; i < table.length; i++) { T[] row = compact(table[i]); if (row != null) list.add(row); } return list.toArray(Arrays.copyOf(table, 0)); } /** * Returns a new array which contains all the elements from the given arrays. * * @param arrays One or more arrays to be concatenated together. * @param <T> The class of item stored in the array. * @return A new array which contains all the elements from the given arrays. */ public static <T> T[] concatenate(T[]... arrays) { if (arrays == null || arrays.length == 0) return null; if (arrays.length == 1) return Arrays.copyOf(arrays[0], arrays[0].length); int length = 0; for (T[] array : arrays) { if (array != null) length += array.length; } List<T> list = new ArrayList<T>(length); for (T[] array : arrays) { if (array != null) Collections.addAll(list, array); } return list.toArray(Arrays.copyOf(arrays[0], length)); } /** * Removes the element at the given index from the given list. * * @param array An array to remove an element from. * @param index The zero-based index of the element to be removed. * @param <T> The class of the items stored in the array. * @return A new array whose length is one item less than the given array, and which includes all elements from the * given array except for the element at the given index. */ @SuppressWarnings("unchecked") public static <T> T[] drop(T[] array, int index) { if (array != null) { // support reverse/tail indexing if (index < 0) index += array.length; if (index < 0 || array.length <= index) throw new ArrayIndexOutOfBoundsException(index); T[] head = slice(array, 0, index); T[] tail = slice(array, index + 1, array.length - index); array = concatenate(head, tail); } return array; } /** * Returns true if the given arrays are equal. * * @param arrays One or more arrays to be compared for equality. * @param <T> The class of item stored in the array. * @return True if the given arrays are all considered equivalent, otherwise false. */ public static <T> boolean equal(T[]... arrays) { if (arrays == null) return false; if (arrays.length < 2) return false; boolean result = true; for (int i = 0; i < arrays.length - 1; i++) { for (int j = i + 1; j < arrays.length; j++) { if (arrays[i] != null && arrays[j] != null) { result = (arrays[i].length == arrays[j].length); if (result) { for (int k = 0; k < arrays[i].length; k++) { result = ObjectHelper.equal(arrays[i][k], arrays[j][k]); if (!result) break; } } } else { result = arrays[i] == null && arrays[j] == null; } if (!result) break; } } return result; } /** * Returns the element from the given array at the given index (supports ruby-style reverse indexing). * * @param array An array to retrieve an item from. * @param index The zero-based index of the item to be retrieved; supports ruby-style reverse indexing where, for * example, -1 is the last item and -2 is the second last item in the array. * @param <T> The class of the items stored in the array. * @return The item stored in the array at the given index. */ public static <T> T get(T[] array, int index) { T item = null; if (array != null) { // support reverse/tail indexing if (index < 0) index += array.length; item = array[index]; } return item; } /** * Resizes the given array to the desired length, and pads with nulls. * * @param array The array to be resized, must not be null. * @param newLength The new length of returned array, which can be less than the given array's length in which case * it will be truncated, or more than the given array's length in which case it will be padded to * the new size with the given item (or null if no item is specified). * @param <T> The class of the items stored in the array. * @return A new array with the items from the given array but with the new desired length. */ public static <T> T[] resize(T[] array, int newLength) { return resize(array, newLength, null); } /** * Resizes the given array (or instantiates a new array, if null) to the desired length, and pads with the given * item. * * @param array The array to be resized. If null, a new array will be instantiated. * @param newLength The new length of returned array, which can be less than the given array's length in which case * it will be truncated, or more than the given array's length in which case it will be padded to * the new size with the given item (or null if no item is specified). * @param item The item to use when padding the array to a larger size. * @param klass The class of the items stored in the array. * @param <T> The class of the items stored in the array. * @return A new array with the items from the given array but with the new desired length. */ public static <T> T[] resize(T[] array, int newLength, T item, Class<T> klass) { if (array == null) { array = instantiate(klass, newLength); if (item != null) fill(array, item, 0, newLength); } else { array = resize(array, newLength, item); } return array; } /** * Resizes the given array to the desired length, and pads with the given item. * * @param array The array to be resized, must not be null. * @param newLength The new length of returned array, which can be less than the given array's length in which case * it will be truncated, or more than the given array's length in which case it will be padded to * the new size with the given item (or null if no item is specified). * @param item The item to use when padding the array to a larger size. * @param <T> The class of the items stored in the array. * @return A new array with the items from the given array but with the new desired length. */ public static <T> T[] resize(T[] array, int newLength, T item) { if (array == null) throw new IllegalArgumentException("array must not be null"); if (newLength < 0) newLength = array.length + newLength; if (newLength < 0) newLength = 0; int originalLength = array.length; if (newLength == originalLength) return array; array = Arrays.copyOf(array, newLength); if (item != null) { fill(array, item, originalLength, newLength - originalLength); } return array; } /** * Fills the given array with the given item for the given range. * * @param array The array to be filled. * @param item The item to fill the array with. * @param index The zero-based index from which the fill should start; supports ruby-style reverse indexing where, * for example, -1 is the last item and -2 is the second last item in the array. * @param length The number of items from the given index to be filled. * @param <T> The class of item stored in the array. * @return The given array filled with the given item for the given range. */ public static <T> T[] fill(T[] array, T item, int index, int length) { if (array == null) return null; if (length <= 0) return array; if (index > array.length - 1) return array; if (index < 0) index += array.length; for (int i = index; i < array.length; i++) { array[i] = item; if ((i - index) >= (length - 1)) break; } return array; } /** * Grows the size of the given array by the given count, and pads with the given item. * * @param array The array to be resized, must not be null. * @param count The number of additional items to be appended to the end of the array. * @param item The item to use to pad the array. * @param klass The class of the items stored in the array. * @param <T> The class of the items stored in the array. * @return A new array with the items from the given array but with a new length equal to the old length + count. */ public static <T> T[] grow(T[] array, int count, T item, Class<T> klass) { return resize(array, array == null ? count : array.length + count, item, klass); } /** * Shrinks the size of the given array by the given count. * * @param array The array to be shrunk. * @param count The number of items to shrink the array by. * @param <T> The class of the items stored in the array. * @return A new array with the items from the given array but with a new length equal to the old length - count. */ public static <T> T[] shrink(T[] array, int count) { if (array == null) return null; return resize(array, array.length - count); } /** * Returns true if the given item is found in the given array. * * @param array The array to be searched for the given item. * @param item The item to be searched for in the given array. * @param <T> The class of the items stored in the array. * @return True if the given item was found in the given array, otherwise false. */ public static <T> boolean include(T[] array, T item) { boolean found = false; // TODO: change this to Arrays.binarySearch with a custom comparator that supports IData etc. if (array != null) { for (T value : array) { found = ObjectHelper.equal(value, item); if (found) break; } } return found; } /** * Returns a new array with the given item inserted at the given index. * * @param array The array which is to be copied to a new array. * @param item The item to be inserted. * @param index The zero-based index at which the item is to be inserted; supports ruby-style reverse indexing * where, for example, -1 is the last item and -2 is the second last item in the array. * @param klass The class of the items stored in the array. * @param <T> The class of the items stored in the array. * @return A new array which includes all the items from the given array, with the given item inserted at the given * index, and existing items at and after the given index shifted to the right (by adding one to their indices). */ public static <T> T[] insert(T[] array, T item, int index, Class<T> klass) { if (array == null) array = instantiate(klass); ArrayList<T> list = new ArrayList<T>(Arrays.asList(array)); int capacity; if (index < 0) index += list.size() + 1; if (index < 0) { capacity = (index * -1) + list.size(); index = 0; } else { capacity = index; } list.ensureCapacity(capacity); if (capacity >= list.size()) { // fill the list with nulls if it needs to be extended for (int i = list.size(); i < capacity; i++) { list.add(i, null); } } list.add(index, item); return list.toArray(array); } /** * Returns a new array that contains only the items present in all the given arrays. * * @param arrays One or more arrays to be intersected. * @param <T> The class of the items stored in the arrays. * @return A new array which is a set intersection of the given arrays. */ @SuppressWarnings("unchecked") public static <T> T[] intersect(T[]... arrays) { if (arrays == null || arrays.length == 0) return null; List<T> intersection = new ArrayList<T>(arrays[0].length); intersection.addAll(Arrays.asList(arrays[0])); for (int i = 1; i < arrays.length; i++) { intersection.retainAll(Arrays.asList(arrays[i])); } return intersection.toArray(Arrays.copyOf(arrays[0], intersection.size())); } public static <T> String join(T[] array, String separator) { if (array == null) return ""; StringBuilder builder = new StringBuilder(); for (int i = 0; i < array.length; i++) { builder.append(ObjectHelper.stringify(array[i])); if (separator != null && i < array.length - 1) builder.append(separator); } return builder.toString(); } public static <T> String join(T[][] table, String separator) { if (table == null) return ""; StringBuilder builder = new StringBuilder(); for (int i = 0; i < table.length; i++) { builder.append("["); builder.append(join(table[i], separator)); builder.append("]"); if (separator != null && i < table.length - 1) builder.append(separator); } return builder.toString(); } /** * Returns a string representation of the given array. * * @param array The array to be stringified. * @param <T> The class of items stored in the array. * @return A string representation of the given array. */ public static <T> String stringify(T[] array) { return array == null ? null : "[" + join(array, ", ") + "]"; } /** * Returns a string representation of the given table. * * @param table The table to be stringified. * @param <T> The class of items stored in the array. * @return A string representation of the given array. */ public static <T> String stringify(T[][] table) { if (table == null) return null; String[] rows = new String[table.length]; for (int i = 0; i < table.length; i++) { StringBuilder builder = new StringBuilder(); builder.append("["); builder.append(join(table[i], ", ")); builder.append("]"); rows[i] = builder.toString(); } StringBuilder builder = new StringBuilder(); builder.append("["); builder.append(join(rows, ", ")); builder.append("]"); return builder.toString(); } /** * Returns a new array with a new element inserted at the beginning. * * @param array The array to be prepended. * @param item The item to prepend to the array. * @param klass The class of the items stored in the array. * @param <T> The class of the items stored in the array. * @return A new copy of the given array with the given item prepended to the start of the array. */ public static <T> T[] prepend(T[] array, T item, Class<T> klass) { return insert(array, item, 0, klass); } /** * Sets the element from the given array at the given index (supports ruby-style reverse indexing). * * @param array The array in which to set the item at the given index. * @param item The item to be set at the given index in the array. * @param index The zero-based index of the array item whose value is to be set; supports ruby-style reverse * indexing where, for example, -1 is the last item and -2 is the second last item in the array. * @param klass The class of the items stored in the array. * @param <T> The class of the items stored in the array. * @return The given array with the item at the given index set to the given value. */ public static <T> T[] put(T[] array, T item, int index, Class<T> klass) { if (array == null) array = instantiate(klass); // support reverse/tail indexing if (index < 0) index += array.length; int capacity; if (index < 0) { capacity = (index * -1) + array.length; index = 0; } else { capacity = index + 1; } if (capacity > array.length) array = Arrays.copyOf(array, capacity); array[index] = item; return array; } /** * Returns a new array with all elements from the given array but in reverse order. * * @param array The array to be reversed. * @param <T> The class of the items stored in the array. * @return A copy of the given array but with all item orders reversed. */ public static <T> T[] reverse(T[] array) { if (array == null) return null; List<T> list = Arrays.asList(Arrays.copyOf(array, array.length)); Collections.reverse(list); return list.toArray(Arrays.copyOf(array, list.size())); } /** * Returns a new array which is a subset of elements from the given array. * * @param array The array to be sliced. * @param index The zero-based start index of the subset; supports ruby-style reverse indexing where, for example, * -1 is the last item and -2 is the second last item in the array. * @param length The desired length of the slice; supports negative lengths for slicing backwards from the end of * the array. * @param <T> The class of the items stored in the array. * @return A new array which is a subset of the given array taken at the desired index for the desired length. */ public static <T> T[] slice(T[] array, int index, int length) { if (array == null || array.length == 0) return array; // support reverse/tail length if (length < 0) length = array.length + length; // support reverse/tail indexing if (index < 0) index += array.length; // don't slice past the end of the array if ((length += index) > array.length) length = array.length; return Arrays.copyOfRange(array, index, length); } /** * Returns a new array with all elements sorted. * * @param array The array to be sorted. * @param <T> The class of items stored in the array. * @return A new copy of the given array but with the items sorted in their natural order. */ public static <T> T[] sort(T[] array) { return sort(array, null); } /** * Returns a new array with all elements sorted according to the given comparator. * * @param array The array to be sorted. * @param comparator The comparator used to determine element ordering. * @param <T> The class of items stored in the array. * @return A new copy of the given array but with the items sorted. */ public static <T> T[] sort(T[] array, Comparator<T> comparator) { return sort(array, comparator, false); } /** * Returns a new array with all elements sorted in natural ascending or descending order. * * @param array The array to be sorted. * @param descending Whether to sort in descending or ascending order. * @param <T> The class of items stored in the array. * @return A new copy of the given array but with the items sorted in their natural order. */ public static <T> T[] sort(T[] array, boolean descending) { return sort(array, null, descending); } /** * Returns a new array with all elements sorted according to the given comparator. * * @param array The array to be sorted. * @param comparator The comparator used to determine element ordering. * @param descending Whether to sort in descending or ascending order. * @param <T> The class of items stored in the array. * @return A new copy of the given array but with the items sorted. */ public static <T> T[] sort(T[] array, Comparator<T> comparator, boolean descending) { if (array == null) return null; T[] copy = Arrays.copyOf(array, array.length); Arrays.sort(copy, comparator); if (descending) copy = reverse(copy); return copy; } /** * Returns a new array with all duplicate elements removed. * * @param array The array to remove duplicates from. * @param <T> The class of items stored in the array. * @return A new copy of the given array with all duplicate elements removed. */ public static <T> T[] unique(T[] array) { if (array == null) return null; java.util.Set<T> set = new java.util.TreeSet<T>(Arrays.asList(array)); return set.toArray(Arrays.copyOf(array, set.size())); } /** * Dynamically instantiates a new zero-length array of the given class. * * @param klass The class of items to be stored in the array. * @param <T> The class of items to be stored in the array. * @return A new zero-length array of the given class. */ @SuppressWarnings("unchecked") public static <T> T[] instantiate(Class<T> klass) { return instantiate(klass, 0); } /** * Dynamically instantiates a new array of the given class with the given length. * * @param klass The class of items to be stored in the array. * @param length The desired length of the returned array. * @param <T> The class of items to be stored in the array. * @return A new array of the given class with the given length. */ @SuppressWarnings("unchecked") public static <T> T[] instantiate(Class<T> klass, int length) { return (T[])java.lang.reflect.Array.newInstance(klass, length); } /** * Converts a Collection to an Object[]. * * @param input A Collection to be converted to an Object[]. * @return An Object[] representation of the given Collection. */ public static Object[] toArray(Collection input) { if (input == null) return null; return normalize(input.toArray()); } /** * Converts an Object[] to a Collection. * * @param input An Object[] to be converted to a Collection. * @return An Collection representation of the given Object[]. */ public static List toList(Object[] input) { if (input == null) return null; return Arrays.asList(input); } /** * Returns a new array whose class is the nearest ancestor class of all contained items. * * @param input The array to be normalized. * @return A new copy of the given array whose class is the nearest ancestor of all contained items. */ public static Object[] normalize(Object[] input) { if (input == null) return null; return toList(input).toArray(instantiate(ObjectHelper.getNearestAncestor(input), input.length)); } /** * Returns a new array with all string items trimmed, all empty string items removed, and all null items removed. * * @param array An array to be squeezed. * @param <T> The type of item in the array. * @return A new array that is the given array squeezed. */ @SuppressWarnings("unchecked") public static <T> T[] squeeze(T[] array) { if (array == null || array.length == 0) return null; List<T> list = new ArrayList<T>(array.length); for (T item : array) { if (item instanceof String) item = (T)StringHelper.squeeze((String)item, false); if (item != null) list.add(item); } array = list.toArray(Arrays.copyOf(array, list.size())); return array.length == 0 ? null : array; } /** * Returns a new table with all empty or null elements removed. * * @param table A table to be squeezed. * @param <T> The type of item in the table. * @return A new table that is the given table squeezed. */ private static <T> T[][] squeeze(T[][] table) { if (table == null || table.length == 0) return null; List<T[]> list = new ArrayList<T[]>(table.length); for (T[] row : table) { row = squeeze(row); if (row != null) list.add(row); } table = list.toArray(Arrays.copyOf(table, list.size())); return table.length == 0 ? null : table; } /** * Converts the given two dimensional array of objects to a string table. * * @param table The two dimensional array to be converted. * @param <T> The type of item in the given array. * @return The converted string table. */ public static <T> String[][] toStringTable(T[][] table) { if (table == null) return null; String[][] stringTable = new String[table.length][]; for (int i = 0; i < table.length; i++) { stringTable[i] = toStringArray(table[i]); } return stringTable; } /** * Converts the given array to a string array. * * @param array The array to be converted * @param <T> The type of item in the array. * @return The converted string array. */ public static <T> String[] toStringArray(T[] array) { if (array == null) return null; String[] stringArray = new String[array.length]; for (int i = 0; i < array.length; i++) { if (array[i] != null) stringArray[i] = array[i].toString(); } return stringArray; } /** * Converts varargs to an array. * * @param args A varargs list of arguments. * @param <T> The type of arguments. * @return An array representation of the given varargs argument. */ public static <T> T[] arrayify(T... args) { return args; } }
package sb.tasks.jobs.dailypress; import com.mongodb.client.model.Updates; import org.apache.commons.lang3.exception.ExceptionUtils; import org.bson.conversions.Bson; import org.jtwig.JtwigModel; import org.jtwig.JtwigTemplate; import sb.tasks.jobs.NotifObj; import java.io.File; import java.util.Date; import java.util.HashMap; import java.util.Map; public final class MagResult implements NotifObj { private final File file; private final String url; private final String text; public MagResult(File file, String url, String text) { this.file = file; this.url = url; this.text = text; } @Override public String telegramText() { return ""; } @Override public File file() { return file; } @Override public String mailText() { Map<String, Object> model = new HashMap<>(); model.put("text", text); return JtwigTemplate .classpathTemplate("templates/mail/magazine.twig") .render( JtwigModel.newModel(model) ); } @Override public String mailFailText(Throwable th) { Map<String, Object> model = new HashMap<>(); model.put("url", url); model.put("tech", ExceptionUtils.getStackTrace(th)); return JtwigTemplate .classpathTemplate("templates/mail/magazine_fail.twig") .render( JtwigModel.newModel(model) ); } @Override public Bson updateSets() { Bson updates = Updates.combine( Updates.set("vars.download_url", url), Updates.set("vars.checked", new Date()) ); return file.lastModified() == 0L ? updates : Updates.combine( updates, Updates.set("vars.download_date", new Date(file.lastModified())) ); } @Override public String toString() { return String.format("MagResult {file=%s, url='%s', text='%s'}", file, url, text); } }
package scrum.client.project; import ilarkesto.gwt.client.Gwt; import java.util.List; public class EstimationBar { private int sprintOffset; private List<Integer> workPerSprint; public EstimationBar(int sprintOffset, List<Integer> workPerSprint) { super(); this.sprintOffset = sprintOffset; this.workPerSprint = workPerSprint; } public int getSprintOffset() { return sprintOffset; } public int getEndSprintOffset() { return sprintOffset + workPerSprint.size() - 1; } public List<Integer> getWorkPerSprint() { return workPerSprint; } public boolean isCompetedOnSameSprint(EstimationBar previous) { return getEndSprintOffset() == previous.getEndSprintOffset(); } @Override public String toString() { return "EstimationBar(" + sprintOffset + ", " + Gwt.toString(workPerSprint) + ")"; } }
package sds.decompile.cond_expr; import java.util.Arrays; import java.util.StringJoiner; import sds.assemble.controlflow.CFEdge; import sds.assemble.controlflow.CFNode; import sds.classfile.bytecode.BranchOpcode; import sds.classfile.bytecode.OpcodeInfo; import static sds.assemble.controlflow.CFNodeType.Entry; import static sds.assemble.controlflow.CFEdgeType.FalseBranch; import static sds.assemble.controlflow.CFEdgeType.TrueBranch; import static sds.assemble.controlflow.NodeTypeChecker.check; import static java.util.Objects.isNull; import static sds.util.Printer.println; /** * This class is for conditional expression. * @author inagaki */ public class Expression { String[] exprs; String logical; int jumpPoint; Expression trueExpr; Expression falseExpr; Child child; private int[] range; private int[] ownDest; public enum Child { TRUE, FALSE, OWN; public boolean is(Child child) { return ordinal() == child.ordinal(); } public boolean isNot(Child child) { return (! is(child)); } } public Expression(int number, String expr, CFNode node) { this.range = new int[]{ -1, 0 }; setRange(number, node); this.exprs = new String[]{expr}; if(check(node, Entry)) { setChild(node); } else { setOneLineChild(node); } } private void setRange(int number, CFNode node) { int ifCount = 0; for(OpcodeInfo op : node.getOpcodes().getAll()) { if((ifCount == number)) { if(range[0] == -1) { range[0] = op.getPc(); } else if(isIf(op)) { BranchOpcode branch = (BranchOpcode)op; range[1] = branch.getPc(); this.jumpPoint = branch.getBranch() + range[1]; break; } } if(isIf(op)) { ifCount++; if(ifCount > number) { break; } } } } private boolean isIf(OpcodeInfo opcode) { return (opcode instanceof BranchOpcode) && ((BranchOpcode)opcode).isIf(); } private void setChild(CFNode node) { for(CFEdge edge : node.getChildren()) { if(edge.getDest().isInPcRange(jumpPoint)) { if(edge.getType() == TrueBranch) { this.child = Child.TRUE; } else if(edge.getType() == FalseBranch) { reverse(); this.child = Child.FALSE; } break; } } if(isNull(child)) { this.child = Child.OWN; this.ownDest = new int[]{ jumpPoint }; } } private void setOneLineChild(CFNode node) { OpcodeInfo[] opcodes = node.getOpcodes().getAll(); int[] trueRange = new int[2]; for(int i = opcodes.length - 1; i >= 0; i if(isIf(opcodes[i])) { BranchOpcode branch = (BranchOpcode)opcodes[i]; trueRange[0] = branch.getPc(); trueRange[1] = opcodes[opcodes.length - 1].getPc(); break; } } if(node.isInPcRange(jumpPoint)) { if((trueRange[0] < jumpPoint) && (jumpPoint <= trueRange[1])) { this.child = Child.TRUE; } else { this.child = Child.OWN; this.ownDest = new int[]{ jumpPoint }; } } else { this.child = Child.FALSE; reverse(); } } /** * combines specified expression and this.<br> * @param newExpr conditional expression * @param logical logical operator */ public void combine(Expression newExpr, String logical) { println("\t" + toString()); this.exprs = new String[]{ getExpr(), newExpr.getExpr() }; this.logical = logical; this.trueExpr = newExpr.trueExpr; this.falseExpr = newExpr.falseExpr; this.child = newExpr.child; if(equalsChild(Child.OWN)) { int[] replaced = new int[ownDest.length + 1]; System.arraycopy(ownDest, 0, replaced, 0, ownDest.length); replaced[replaced.length - 1] = newExpr.jumpPoint; this.ownDest = replaced; } range[1] = newExpr.range[1]; this.jumpPoint = newExpr.jumpPoint; println("\t" + toString()); } /** * returns this conditional expression. * @return conditional expression */ public String getExpr() { if(exprs.length < 2) { return exprs[0]; } String result = exprs[0] + logical + exprs[1]; return logical.contains("&&") ? result : "(" + result + ")"; } /** * returns other jump points to own.<br> * this method is able to call only this expression child is OWN. * @return jump points */ public int[] getOwnDest() { if(child.isNot(Child.OWN)) { throw new IllegalStateException(child + " type expression must not call this method."); } return ownDest; } /** * returns whether destination is this expression. * @param pc index of code array. * @return * if destination is this expression, this method returns true.<br> * otherwise, it returns false. */ public boolean isDestination(int pc) { return (range[0] <= pc) && (pc <= range[1]); } /** * returns whether destination of this expression is equal to specified expression's. * @param expr target expression * @return if the destination is equal to specified, this method returns true.<br> * otherwise, it returns false. */ public boolean equalsDest(Expression expr) { return jumpPoint == expr.jumpPoint; } /** * returns whether this expression child type is equal to specified expression's. * @param expr target expression * @return if the type is equal to specified, this method returns true.<br> * otherwise, it returns false. */ public boolean equalsChild(Expression expr) { return equalsChild(expr.child); } /** * returns whether this expression child type is equal to specified that. * @param expr target expression * @return if the type is equal to specified, this method returns true.<br> * otherwise, it returns false. */ public boolean equalsChild(Expression.Child child) { return this.child.is(child); } /** * reverses comparing operator of this expression. */ public void reverse() { for(int i = 0; i < exprs.length; i++) { String expr = exprs[i]; if(expr.contains("||")) { exprs[i] = changeOperator(expr, " || "); } else if(expr.contains("&&")) { exprs[i] = changeOperator(expr, " && "); } else { exprs[i] = changeOperator(expr); } } } private String changeOperator(String target, String separator) { StringJoiner sj = new StringJoiner(separator); for(String boolExpr : target.split(separator.replace("|", "\\|"))) { if(boolExpr.contains("||")) { sj.add(changeOperator(boolExpr, " && ")); } else if(boolExpr.contains("&&")) { sj.add(changeOperator(boolExpr, " || ")); } else { sj.add(changeOperator(boolExpr)); } } return sj.toString(); } private String changeOperator(String target) { if(target.contains("==")) return target.replace("==", "!="); if(target.contains("!=")) return target.replace("!=", "=="); if(target.contains(">=")) return target.replace(">=", "<"); if(target.contains("<=")) return target.replace("<=", ">"); if(target.contains(">")) return target.replace(">" , "<="); if(target.contains("<")) return target.replace("<" , ">="); if(target.startsWith("(!")) return target.replace("(!", "("); return "(! " + target + ")"; } @Override public boolean equals(Object obj) { if(isNull(obj) || (! (obj instanceof Expression))) { return false; } Expression target = (Expression)obj; boolean equal = true; equal &= Arrays.equals(exprs, target.exprs); equal &= Arrays.equals(range, target.range); equal &= (jumpPoint == target.jumpPoint); equal &= (child == target.child); return equal; } @Override public String toString() { StringBuilder sb = new StringBuilder(getExpr()); return sb.append("{").append(child).append(",").append(jumpPoint) .append(",[").append(range[0]).append("-").append(range[1]).append("]}") .toString(); } }
package tamaized.aov.client.gui; import com.mojang.authlib.GameProfile; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.MainWindow; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.AbstractGui; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.screen.inventory.InventoryScreen; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.resources.I18n; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.EntityViewRenderEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import org.lwjgl.opengl.GL11; import tamaized.aov.AoV; import tamaized.aov.client.ClientHelpers; import tamaized.aov.client.SizedFontHelper; import tamaized.aov.client.handler.ClientTicker; import tamaized.aov.common.capabilities.CapabilityList; import tamaized.aov.common.capabilities.aov.IAoVCapability; import tamaized.aov.common.capabilities.astro.IAstroCapability; import tamaized.aov.common.capabilities.polymorph.IPolymorphCapability; import tamaized.aov.common.core.abilities.Ability; import tamaized.aov.common.core.skills.AoVSkills; import tamaized.aov.common.entity.EntityEarthquake; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Random; @Mod.EventBusSubscriber(modid = AoV.MODID, value = Dist.CLIENT) public class AoVOverlay { public static final ResourceLocation TEXTURE_ASTRO = new ResourceLocation(AoV.MODID, "textures/gui/astro.png"); public static final ResourceLocation TEXTURE_FOCUS = new ResourceLocation(AoV.MODID, "textures/gui/focus.png"); public static final ResourceLocation TEXTURE_DOGGO = new ResourceLocation(AoV.MODID, "textures/gui/doggo.png"); private static final ResourceLocation TEXTURE_ELEMENTALS = new ResourceLocation(AoV.MODID, "textures/entity/fluid.png"); private static final ResourceLocation TEXTURE_DANGERBIOME = new ResourceLocation(AoV.MODID, "textures/gui/dangerbiome.png"); private static final Minecraft mc = Minecraft.getInstance(); private static final Random rand = new Random(); public static boolean hackyshit = false; public static float intensity = 0F; public static boolean NO_STENCIL = false; public static float zLevel; private static LivingEntity cacheEntity; private static int cacheEntityID = -1; public static void drawRect(float left, float top, float right, float bottom, int color) { if (left < right) { float i = left; left = right; right = i; } if (top < bottom) { float j = top; top = bottom; bottom = j; } float f3 = (float) (color >> 24 & 255) / 255.0F; float f = (float) (color >> 16 & 255) / 255.0F; float f1 = (float) (color >> 8 & 255) / 255.0F; float f2 = (float) (color & 255) / 255.0F; Tessellator tessellator = Tessellator.getInstance(); BufferBuilder bufferbuilder = tessellator.getBuffer(); GlStateManager.enableBlend(); GlStateManager.disableTexture(); GlStateManager.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); GlStateManager.color4f(f, f1, f2, f3); bufferbuilder.begin(7, DefaultVertexFormats.POSITION); bufferbuilder.pos((double) left, (double) bottom, 0.0D).endVertex(); bufferbuilder.pos((double) right, (double) bottom, 0.0D).endVertex(); bufferbuilder.pos((double) right, (double) top, 0.0D).endVertex(); bufferbuilder.pos((double) left, (double) top, 0.0D).endVertex(); tessellator.draw(); GlStateManager.enableTexture(); GlStateManager.disableBlend(); } @SubscribeEvent public static void renderOverlayPre(RenderGameOverlayEvent.Pre e) { if (e.getType() == RenderGameOverlayEvent.ElementType.HOTBAR) { IPolymorphCapability poly = CapabilityList.getCap(mc.player, CapabilityList.POLYMORPH); if (poly != null) { if (poly.getMorph() == IPolymorphCapability.Morph.Wolf) { e.setCanceled(true); float perc = poly.getAttackCooldown() / poly.getInitalAttackCooldown(); if (perc > 0F) { GlStateManager.pushMatrix(); { Tessellator tessellator = Tessellator.getInstance(); BufferBuilder buffer = tessellator.getBuffer(); buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); MainWindow resolution = Minecraft.getInstance().mainWindow; float scale = 3F; float w = 89F / scale; float h = 54F / scale; float x = (resolution.getScaledWidth() / 2F) - (w / 2F); float y = resolution.getScaledHeight() - 12F - (h / 2F); float alpha = 0.35F; float tone = 0.75F; float heightscale = perc * h; buffer.pos(x, y + heightscale, 0F).tex(0, perc).color(tone, tone, tone, alpha).endVertex(); buffer.pos(x, y + h, 0F).tex(0, 1).color(tone, tone, tone, alpha).endVertex(); buffer.pos(x + w, y + h, 0F).tex(1, 1).color(tone, tone, tone, alpha).endVertex(); buffer.pos(x + w, y + heightscale, 0F).tex(1, perc).color(tone, tone, tone, alpha).endVertex(); mc.textureManager.bindTexture(TEXTURE_DOGGO); tessellator.draw(); } GlStateManager.popMatrix(); } } } } else if (e.getType() == RenderGameOverlayEvent.ElementType.AIR) { IPolymorphCapability poly = CapabilityList.getCap(mc.player, CapabilityList.POLYMORPH); if (poly != null && poly.getMorph() == IPolymorphCapability.Morph.WaterElemental) e.setCanceled(true); } else if (e.getType() == RenderGameOverlayEvent.ElementType.ALL) { renderStencils(); hackyshit = true; IPolymorphCapability poly = CapabilityList.getCap(mc.player, CapabilityList.POLYMORPH); if (poly != null) { ClientTicker.dangerBiomeTicksFlag = (poly.getFlagBits() & 0b0001) == 0b0001; if (ClientTicker.dangerBiomeTicks > 0) { mc.textureManager.bindTexture(TEXTURE_DANGERBIOME); boolean isWater = (poly.getFlagBits() & 0b0010) == 0b0000; float r = isWater ? 1F : 0F; float g = isWater ? 0.15F : 0.6F; float b = isWater ? 0F : 1F; float a = MathHelper.clamp(((float) ClientTicker.dangerBiomeTicks + (mc.isGamePaused() ? 0 : e.getPartialTicks())) / (float) ClientTicker.dangerBiomeMaxTick, 0F, 1F); MainWindow resolution = mc.mainWindow; Tessellator tessellator = Tessellator.getInstance(); BufferBuilder buffer = tessellator.getBuffer(); buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); buffer.pos(0, resolution.getScaledHeight(), 0).tex(0, 1).color(r, g, b, a).endVertex(); buffer.pos(resolution.getScaledWidth(), resolution.getScaledHeight(), 0).tex(1, 1).color(r, g, b, a).endVertex(); buffer.pos(resolution.getScaledWidth(), 0, 0).tex(1, 0).color(r, g, b, a).endVertex(); buffer.pos(0, 0, 0).tex(0, 0).color(r, g, b, a).endVertex(); GlStateManager.enableBlend(); tessellator.draw(); GlStateManager.disableBlend(); } } } } @SubscribeEvent public static void renderOverlayPost(RenderGameOverlayEvent.Post e) { if (e.getType() != RenderGameOverlayEvent.ElementType.EXPERIENCE) // TODO: ??? shouldnt this be hotbar? recheck it later. return; IAoVCapability cap = CapabilityList.getCap(mc.player, CapabilityList.AOV); FontRenderer fontRender = mc.fontRenderer; MainWindow sr = mc.mainWindow; float sW = (float) sr.getScaledWidth() / 2F; if (cap != null && cap.hasCoreSkill()) { if (ClientHelpers.barToggle) { GlStateManager.pushMatrix(); { if (AoV.config.renderBarOverHotbar.get()) GlStateManager.translated(0, sr.getScaledHeight() - 23, 0); for (int i = 0; i < 9; i++) { float x = sW - 90F + (20F * (float) i); float y = ClientTicker.charges.getValue(i); float partialTicks = (mc.isGamePaused() ? 0 : e.getPartialTicks()) * AoVUIBar.slotLoc == i ? 1 : -1; if (AoV.config.renderBarOverHotbar.get() || AoV.config.renderChargesAboveSpellbar.get()) { y = 1F - y - partialTicks; y = MathHelper.clamp(y, -15F, 1F); } else { y = 1F + y + partialTicks; y = MathHelper.clamp(y, 1F, 15F); } renderCharges(x + (AoV.config.renderBarOverHotbar.get() ? 0 : AoV.config.ELEMENT_POSITIONS.spellbar_x.get()), y + (AoV.config.renderBarOverHotbar.get() ? 0 : AoV.config.ELEMENT_POSITIONS.spellbar_y.get()), fontRender, cap, i); } } GlStateManager.popMatrix(); } AoVUIBar.render(AoV.config.ELEMENT_POSITIONS.spellbar_x.get(), AoV.config.ELEMENT_POSITIONS.spellbar_y.get()); if (cap.getCoreSkill() == AoVSkills.astro_core_1) renderAstro(mc.player, sr); Entity target = ClientHelpers.getTarget() != null ? ClientHelpers.getTarget() : ClientHelpers.getTargetOverMouse(mc, 128); if (AoV.config.renderTarget.get() && target instanceof LivingEntity) renderTarget((LivingEntity) target); } } @SubscribeEvent public static void render(TickEvent.RenderTickEvent e) { if (AoV.config.EARTHQUAKE.shake.get() && e.phase == TickEvent.Phase.START && mc.world != null) { for (Entity entity : mc.world.getAllEntities()) { if (entity instanceof EntityEarthquake) { float intense = (float) (1F - entity.getDistanceSq(Minecraft.getInstance().player) / Math.pow(16, 2)); if (intense > AoVOverlay.intensity) AoVOverlay.intensity = intense; } } PlayerEntity player = Minecraft.getInstance().player; if (!mc.isGamePaused() && intensity > 0 && player != null) { player.setPositionAndRotation(player.posX, player.posY, player.posZ, player.rotationYaw + (rand.nextFloat() * 2F - 1F) * intensity, player.rotationPitch + (rand.nextFloat() * 2F - 1F) * intensity); intensity = 0F; } } if (e.phase == TickEvent.Phase.END && mc.currentScreen != null) { renderStencils(); } hackyshit = false; } @SubscribeEvent public static void camera(EntityViewRenderEvent.CameraSetup e) { if (!mc.isGamePaused() && AoV.config.EARTHQUAKE.shake.get() && intensity > 0) { e.setYaw(e.getYaw() + (rand.nextFloat() * 2F - 1F) * intensity); e.setPitch(e.getPitch() + (rand.nextFloat() * 2F - 1F) * intensity); e.setRoll(e.getRoll() + (rand.nextFloat() * 2F - 1F) * intensity); intensity = 0F; } } private static void renderStencils() { if (GL11.glGetInteger(GL11.GL_STENCIL_BITS) < 1) { NO_STENCIL = true; return; } NO_STENCIL = false; float frames = ClientTicker.frames + (mc.isGamePaused() ? 0 : mc.getRenderPartialTicks()); if (mc.world != null) { Minecraft.getInstance().textureManager.bindTexture(TEXTURE_ELEMENTALS); Tessellator tess = Tessellator.getInstance(); BufferBuilder buffer = tess.getBuffer(); MainWindow resolution = mc.mainWindow; float w = resolution.getScaledWidth(); float h = resolution.getScaledHeight(); float scale = (float) ((4F - resolution.getGuiScaleFactor() + 1F) * 32F); //TODO check float u = 1F / (scale / w); float v = 1F / (scale / h); resolution.loadGUIRenderMatrix(Minecraft.IS_RUNNING_ON_MAC); GlStateManager.enableBlend(); GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GlStateManager.shadeModel(GL11.GL_SMOOTH); GlStateManager.color4f(1F, 1F, 1F, 1F); GL11.glEnable(GL11.GL_STENCIL_TEST); int curStencil = AoV.config.stencil.get() + 8 + (hackyshit ? 3 : 0); GL11.glStencilFunc(GL11.GL_EQUAL, curStencil, 0xFF); // Water { buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); buffer.pos(0, h, 0).tex(0, v).color(0F, 0.5F, 0.75F, 0.75F).endVertex(); buffer.pos(w, h, 0).tex(u, v).color(0F, 0.5F, 0.5F, 0.75F).endVertex(); buffer.pos(w, 0, 0).tex(u, 0).color(0F, 0.5F, 1F, 0.75F).endVertex(); buffer.pos(0, 0, 0).tex(0, 0).color(0F, 0F, 1F, 1F).endVertex(); GlStateManager.pushMatrix(); GlStateManager.matrixMode(GL11.GL_TEXTURE); GlStateManager.loadIdentity(); GlStateManager.translated(frames * 0.001F, frames * -0.01F, 0.0F); GlStateManager.scalef(0.5F, 0.5F, 0.5F); GlStateManager.rotatef(frames * 0.1F, 0, 1, 0); GlStateManager.matrixMode(GL11.GL_MODELVIEW); tess.draw(); GlStateManager.matrixMode(GL11.GL_TEXTURE); GlStateManager.loadIdentity(); GlStateManager.matrixMode(GL11.GL_MODELVIEW); GlStateManager.popMatrix(); } GL11.glStencilFunc(GL11.GL_ALWAYS, curStencil, 0xFF); GL11.glStencilFunc(GL11.GL_EQUAL, curStencil = (AoV.config.stencil.get() + 9 + (hackyshit ? 3 : 0)), 0xFF); // Fire { buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); buffer.pos(0, h, 0).tex(0, v).color(0.75F, 0.25F, 0F, 0.75F).endVertex(); buffer.pos(w, h, 0).tex(u, v).color(1F, 0F, 0F, 0.75F).endVertex(); buffer.pos(w, 0, 0).tex(u, 0).color(1F, 0.5F, 0F, 0.75F).endVertex(); buffer.pos(0, 0, 0).tex(0, 0).color(0.5F, 0.5F, 0F, 1F).endVertex(); GlStateManager.pushMatrix(); GlStateManager.matrixMode(GL11.GL_TEXTURE); GlStateManager.loadIdentity(); GlStateManager.translated(frames * 0.01F, frames * 0.01F, 0.0F); GlStateManager.scalef(0.5F, 0.5F, 0.5F); GlStateManager.rotatef(frames, 0, 0, 1); GlStateManager.matrixMode(GL11.GL_MODELVIEW); tess.draw(); GlStateManager.matrixMode(GL11.GL_TEXTURE); GlStateManager.loadIdentity(); GlStateManager.matrixMode(GL11.GL_MODELVIEW); GlStateManager.popMatrix(); } GL11.glStencilFunc(GL11.GL_ALWAYS, curStencil, 0xFF); GL11.glStencilFunc(GL11.GL_EQUAL, curStencil = (AoV.config.stencil.get() + 10 + (hackyshit ? 3 : 0)), 0xFF); // Arch-Angel { buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); buffer.pos(0, h, 0).tex(0, v).color(1F, 0.85F, 0.2F, 0.75F).endVertex(); buffer.pos(w, h, 0).tex(u, v).color(1F, 0.85F, 0.2F, 0.75F).endVertex(); buffer.pos(w, 0, 0).tex(u, 0).color(1F, 0.85F, 0.2F, 0.75F).endVertex(); buffer.pos(0, 0, 0).tex(0, 0).color(1F, 0.85F, 0.2F, 0.75F).endVertex(); GlStateManager.pushMatrix(); GlStateManager.matrixMode(GL11.GL_TEXTURE); GlStateManager.loadIdentity(); GlStateManager.translated(0.0F, frames * 0.1F, 0.0F); GlStateManager.scalef(0.5F, 0.5F, 0.5F); // GlStateManager.rotatef(frames, 0, 0, 1); GlStateManager.matrixMode(GL11.GL_MODELVIEW); GlStateManager.blendFunc(GL11.GL_ONE, GL11.GL_ONE); tess.draw(); GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GlStateManager.matrixMode(GL11.GL_TEXTURE); GlStateManager.loadIdentity(); GlStateManager.matrixMode(GL11.GL_MODELVIEW); GlStateManager.popMatrix(); } GL11.glStencilFunc(GL11.GL_ALWAYS, curStencil, 0xFF); if (!hackyshit) GL11.glStencilMask(0xFF); GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT); GL11.glStencilMask(0x00); GL11.glDisable(GL11.GL_STENCIL_TEST); GlStateManager.shadeModel(GL11.GL_FLAT); GlStateManager.disableBlend(); GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); GlStateManager.disableBlend(); } } private static void renderCharges(float x, float y, FontRenderer fontRender, IAoVCapability cap, int index) { Ability ability = cap.getSlot(index); int val = ability == null ? -1 : ability.getCharges(); if (val < 0) return; int w = 20; int h = 20; drawRect(x, y, x + w, y + h, (!cap.canUseAbility(ability) || (ability.isOnCooldown(cap) && !ability.getAbility().canUseOnCooldown(cap, mc.player))) ? 0x77FF0000 : 0x7700BBFF); drawCenteredStringNoShadow(fontRender, String.valueOf(val), x + 10, y + (AoV.config.renderBarOverHotbar.get() || AoV.config.renderChargesAboveSpellbar.get() ? 3 : 10), 0x000000); } private static void drawCenteredStringNoShadow(FontRenderer fontRendererIn, String text, float x, float y, int color) { fontRendererIn.drawString(text, x - (float) fontRendererIn.getStringWidth(text) / 2F, y, color); } private static void renderAstro(PlayerEntity player, MainWindow sr) { IAstroCapability cap = CapabilityList.getCap(player, CapabilityList.ASTRO); if (cap == null) return; if (!AoV.config.renderAstro.get() && cap.getDraw() == null && cap.getBurn() == null && cap.getSpread() == null) return; GlStateManager.pushMatrix(); { GlStateManager.color4f(1F, 1F, 1F, 1F); mc.getTextureManager().bindTexture(TEXTURE_ASTRO); GlStateManager.enableAlphaTest(); GlStateManager.enableBlend(); Tessellator tess = Tessellator.getInstance(); BufferBuilder buffer = tess.getBuffer(); buffer.begin(7, DefaultVertexFormats.POSITION_TEX); float x = sr.getScaledWidth() * 2F / 3F; float y = sr.getScaledHeight() / 5F; x += AoV.config.ELEMENT_POSITIONS.astro_x.get(); y += AoV.config.ELEMENT_POSITIONS.astro_y.get(); float scale = 0.35F; buffer.pos(x, y + 143F * scale, 0).tex(0, 0.5F).endVertex(); buffer.pos(x + 235F * scale, y + 143F * scale, 0).tex(0.5F, 0.5F).endVertex(); buffer.pos(x + 235F * scale, y, 0).tex(0.5F, 0).endVertex(); buffer.pos(x, y, 0).tex(0, 0).endVertex(); if (cap.getDraw() != null) { renderAstroIcon(IAstroCapability.ICard.getCardID(cap.getDraw()), buffer, x + 33.5F, y + 17F, scale); tess.draw(); drawCenteredString(mc.fontRenderer, "" + cap.getDrawTime(), (int) (x + 43), (int) (y + 50), 0xbd7e10); buffer.begin(7, DefaultVertexFormats.POSITION_TEX); mc.getTextureManager().bindTexture(TEXTURE_ASTRO); GlStateManager.color4f(1, 1, 1, 1); } if (cap.getSpread() != null) renderAstroIcon(IAstroCapability.ICard.getCardID(cap.getSpread()), buffer, x + 14F, y + 20F, scale * 0.8F); if (cap.getBurn() != null) renderAstroRoyalRoadIcon((int) Math.floor(IAstroCapability.ICard.getCardID(cap.getBurn()) / 2F), buffer, x + 55F, y - 7.5F, scale); tess.draw(); } GlStateManager.popMatrix(); } private static void renderAstroIcon(int index, BufferBuilder buffer, float x, float y, float scale) { scale = scale / 4F; float xOffset = 0.25F * (index % 4); float yOffset = 0.25F * (float) Math.floor(index / 4F); buffer.pos(x, y + 286F * scale, 0).tex(0.5F * xOffset, 0.75F + yOffset).endVertex(); buffer.pos(x + 235F * scale, y + 286F * scale, 0).tex(0.5F * (0.25F + xOffset), 0.75F + yOffset).endVertex(); buffer.pos(x + 235F * scale, y, 0).tex(0.5F * (0.25F + xOffset), 0.5F + yOffset).endVertex(); buffer.pos(x, y, 0).tex(0.5F * xOffset, 0.5F + yOffset).endVertex(); } private static void renderAstroRoyalRoadIcon(int index, BufferBuilder buffer, float x, float y, float scale) { scale *= 0.60F; float xOffset = 0.15F + (0.084F * index); float yOffset = 0;//0.25F * (float) Math.floor(index / 4); buffer.pos(x + 80F * scale, y, 0).tex(0.5F + xOffset, 0 + yOffset).endVertex(); buffer.pos(x, y, 0).tex(0.5F + (0.08F + xOffset), 0 + yOffset).endVertex(); buffer.pos(x, y + 286F * scale, 0).tex(0.5F + (0.08F + xOffset), 0.5F + yOffset).endVertex(); buffer.pos(x + 80F * scale, y + 286F * scale, 0).tex(0.5F + xOffset, 0.5F + yOffset).endVertex(); if (AoV.config.renderRoyalRoad.get()) { Tessellator.getInstance().draw(); GlStateManager.pushMatrix(); drawCenteredString(mc.fontRenderer, I18n.format("aov.astro.burn." + index), (int) x - 16, (int) y, index == 0 ? 0x00AAFF : index == 1 ? 0x00FFAA : 0xFFDD88); GlStateManager.popMatrix(); buffer.begin(7, DefaultVertexFormats.POSITION_TEX); mc.getTextureManager().bindTexture(TEXTURE_ASTRO); } GlStateManager.color4f(1, 1, 1, 1); } private static void renderTarget(LivingEntity target) { GlStateManager.pushMatrix(); { double x = 10 + AoV.config.ELEMENT_POSITIONS.target_x.get(); double y = 150 + AoV.config.ELEMENT_POSITIONS.target_y.get(); double w = 100; double h = 41; Tessellator tess = Tessellator.getInstance(); BufferBuilder buffer = tess.getBuffer(); buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); GlStateManager.color4f(1F, 1F, 1F, 1F); GlStateManager.enableBlend(); GlStateManager.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); { float r = 1F; float g = 1F; float b = 1F; float a = AoV.config.targetOpacity.get().floatValue(); buffer.pos(x + w, y, 0).tex(1, 0).color(r, g, b, a).endVertex(); buffer.pos(x, y, 0).tex(0, 0).color(r, g, b, a).endVertex(); buffer.pos(x, y + h, 0).tex(0, 1).color(r, g, b, a).endVertex(); buffer.pos(x + w, y + h, 0).tex(1, 1).color(r, g, b, a).endVertex(); Minecraft.getInstance().textureManager.bindTexture(TEXTURE_FOCUS); tess.draw(); } GlStateManager.disableBlend(); { GlStateManager.pushMatrix(); { if (cacheEntityID != target.getEntityId()) { cacheEntityID = target.getEntityId(); try { if (target instanceof PlayerEntity) cacheEntity = target.getClass().getConstructor(World.class, GameProfile.class).newInstance(mc.world, ((PlayerEntity) target).getGameProfile()); else { for (Constructor<?> ctor : target.getClass().getConstructors()) { if (ctor.getParameterTypes().length == 2) { if (ctor.getParameterTypes()[0] == EntityType.class && ctor.getParameterTypes()[1] == World.class) cacheEntity = target.getClass().getConstructor(EntityType.class, World.class).newInstance(target.getType(), target.world); else if (ctor.getParameterTypes()[0] == World.class && ctor.getParameterTypes()[1] == EntityType.class) cacheEntity = target.getClass().getConstructor(World.class, EntityType.class).newInstance(target.world, target.getType()); } else if (ctor.getParameterTypes().length == 1 && ctor.getParameterTypes()[0] == World.class) cacheEntity = target.getClass().getConstructor(World.class).newInstance(target.world); else if (ctor.getParameterTypes().length == 0) cacheEntity = target.getClass().newInstance(); } } } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) { e1.printStackTrace(); } } if (cacheEntity != null && mc.renderViewEntity != null) InventoryScreen.drawEntityOnScreen((int) (x + 30), (int) (y + 36), 8, -40, 5, cacheEntity); } GlStateManager.popMatrix(); String name = target.getDisplayName().getFormattedText(); { FontRenderer font = Minecraft.getInstance().fontRenderer; List<String> list = font.listFormattedStringToWidth(name, 80); if (!list.isEmpty()) name = list.get(0); SizedFontHelper.render(font, name, (float) (x + w / 3) + 3, (float) (y + 28) - font.FONT_HEIGHT / 3F, 0.5F, 0xFFFFFF, true); SizedFontHelper.render(font, "x " + (int) target.getHealth() + "/" + (int) target.getMaxHealth(), (float) (x + w / 3) + 3, (float) (y + 16) - font.FONT_HEIGHT / 3F, 0.5F, 0xFFFFFF, true); } { Minecraft.getInstance().textureManager.bindTexture(AbstractGui.GUI_ICONS_LOCATION); int posx = (int) (x + 30); int posy = (int) (y + 13); int textureX = 52; int textureY = 0; int width = 9; int height = 9; int sizeX = 5; int sizeY = 5; Tessellator tessellator = Tessellator.getInstance(); BufferBuilder bufferbuilder = tessellator.getBuffer(); bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX); bufferbuilder.pos((double) (posx), (double) (posy + sizeY), (double) zLevel).tex((double) ((float) (textureX) * 0.00390625F), (double) ((float) (textureY + height) * 0.00390625F)).endVertex(); bufferbuilder.pos((double) (posx + sizeX), (double) (posy + sizeY), (double) zLevel).tex((double) ((float) (textureX + width) * 0.00390625F), (double) ((float) (textureY + height) * 0.00390625F)).endVertex(); bufferbuilder.pos((double) (posx + sizeX), (double) (posy), (double) zLevel).tex((double) ((float) (textureX + width) * 0.00390625F), (double) ((float) (textureY) * 0.00390625F)).endVertex(); bufferbuilder.pos((double) (posx), (double) (posy), (double) zLevel).tex((double) ((float) (textureX) * 0.00390625F), (double) ((float) (textureY) * 0.00390625F)).endVertex(); tessellator.draw(); } } } GlStateManager.popMatrix(); } public static void drawCenteredString(FontRenderer fontRendererIn, String text, int x, int y, int color) { fontRendererIn.drawStringWithShadow(text, (float) (x - fontRendererIn.getStringWidth(text) / 2), (float) y, color); } public static void drawString(FontRenderer fontRendererIn, String text, int x, int y, int color) { fontRendererIn.drawStringWithShadow(text, (float) x, (float) y, color); } public static void drawTexturedModalRect(int x, int y, int textureX, int textureY, int width, int height) { Tessellator tessellator = Tessellator.getInstance(); BufferBuilder bufferbuilder = tessellator.getBuffer(); bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX); bufferbuilder.pos((double) (x + 0), (double) (y + height), (double) zLevel).tex((double) ((float) (textureX + 0) * 0.00390625F), (double) ((float) (textureY + height) * 0.00390625F)).endVertex(); bufferbuilder.pos((double) (x + width), (double) (y + height), (double) zLevel).tex((double) ((float) (textureX + width) * 0.00390625F), (double) ((float) (textureY + height) * 0.00390625F)).endVertex(); bufferbuilder.pos((double) (x + width), (double) (y + 0), (double) zLevel).tex((double) ((float) (textureX + width) * 0.00390625F), (double) ((float) (textureY + 0) * 0.00390625F)).endVertex(); bufferbuilder.pos((double) (x + 0), (double) (y + 0), (double) zLevel).tex((double) ((float) (textureX + 0) * 0.00390625F), (double) ((float) (textureY + 0) * 0.00390625F)).endVertex(); tessellator.draw(); } }
package team.unstudio.udpl.util; import java.lang.reflect.InvocationTargetException; import org.bukkit.Location; import org.bukkit.entity.Player; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.wrappers.BlockPosition; import team.unstudio.udpl.core.UDPLib; public interface BlockUtils { boolean debug = UDPLib.isDebug(); ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager(); static boolean sendBlockBreakAnimation(Player player, Location location, byte state) { PacketContainer container = protocolManager.createPacket(PacketType.Play.Server.BLOCK_BREAK_ANIMATION); container.getIntegers().write(0, player.getEntityId()); container.getBlockPositionModifier().write(0, new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ())); container.getBytes().write(0, state); try { protocolManager.sendServerPacket(player, container); return true; } catch (InvocationTargetException e) { if (debug) e.printStackTrace(); } return false; } }
package throwing.function; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import javax.annotation.Nullable; import throwing.Nothing; import throwing.RethrowChain; @FunctionalInterface public interface ThrowingSupplier<R, X extends Throwable> { public R get() throws X; default public Supplier<R> fallbackTo(Supplier<? extends R> supplier) { ThrowingSupplier<R, Nothing> t = supplier::get; return orTry(t)::get; } default public <Y extends Throwable> ThrowingSupplier<R, Y> orTry( ThrowingSupplier<? extends R, ? extends Y> supplier) { return orTry(supplier, null); } default public <Y extends Throwable> ThrowingSupplier<R, Y> orTry( ThrowingSupplier<? extends R, ? extends Y> supplier, @Nullable Consumer<? super Throwable> thrown) { Objects.requireNonNull(supplier, "supplier"); return () -> { try { return get(); } catch (Throwable x) { try { R ret = supplier.get(); if (thrown != null) { thrown.accept(x); } return ret; } catch (Throwable y) { y.addSuppressed(x); throw y; } } }; } default public <Y extends Throwable> ThrowingSupplier<R, Y> rethrow(Class<X> x, Function<? super X, ? extends Y> mapper) { Function<Throwable, ? extends Y> rethrower = RethrowChain.rethrowAs(x) .rethrow(mapper) .finish(); return () -> { try { return get(); } catch (Throwable t) { throw rethrower.apply(t); } }; } }
package org.epics.util.time; /** * A period of time where each end can either be an absolute moment in time * (e.g. 5/16/2012 11:30 AM) or a relative moment from a reference (e.g. 30 seconds before) * which typically is going to be "now". * <p> * This class stores a reference for start and a reference for end. Each reference * can either be absolute, in which case it's a TimeStamp, or relative, in * which case it's a TimeDuration. The {@link #toAbsoluteInterval(org.epics.util.time.TimeStamp) } * can be used to transform the relative interval into an absolute one * calculated from the reference. This allows to keep the relative interval, * and then to convert multiple time to an absolute interval every time * that one needs to calculate. For example, one can keep the range of a plot * from 1 minute ago to now, and then get a specific moment the absolute range * of that plot. * * @author carcassi */ public class TimeRelativeInterval { private final Object start; private final Object end; private TimeRelativeInterval(Object start, Object end) { this.start = start; this.end = end; } public static TimeRelativeInterval of(Timestamp start, Timestamp end) { return new TimeRelativeInterval(start, end); } public boolean isIntervalAbsolute() { return isStartAbsolute() && isEndAbsolute(); } public boolean isStartAbsolute() { return start instanceof Timestamp || start == null; } public boolean isEndAbsolute() { return end instanceof Timestamp || end == null; } public Object getStart() { return start; } public Object getEnd() { return end; } public Timestamp getAbsoluteStart() { return (Timestamp) start; } public Timestamp getAbsoluteEnd() { return (Timestamp) end; } public TimeDuration getRelativeStart() { return (TimeDuration) start; } public TimeDuration getRelativeEnd() { return (TimeDuration) end; } public TimeInterval toAbsoluteInterval(Timestamp reference) { Timestamp absoluteStart; if (isStartAbsolute()) { absoluteStart = getAbsoluteStart(); } else { absoluteStart = reference.plus(getRelativeStart()); } Timestamp absoluteEnd; if (isEndAbsolute()) { absoluteEnd = getAbsoluteEnd(); } else { absoluteEnd = reference.plus(getRelativeEnd()); } return TimeInterval.between(absoluteStart, absoluteEnd); } }
package vaeke.countrydata.rest; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.Provider; import vaeke.countrydata.domain.Country; import com.google.gson.Gson; import com.google.gson.stream.JsonReader; @Provider @Path("rest") @Produces(MediaType.APPLICATION_JSON) public class CountryRest { @GET public Object getCountries() { try { return getAll(); } catch (IOException e) { return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } @GET @Path("alpha2/{alpha2code}") public Object getByAlpha2(@PathParam("alpha2code") String alpha2) { try { List<Country> countries = getAll(); for(Country country : countries) { if (country.getCca2().toLowerCase().equals(alpha2.toLowerCase())) { return country; } } } catch (IOException e) { return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } return Response.status(Status.NOT_FOUND).build(); } @GET @Path("alpha3/{alpha3code}") public Object getByAlpha3(@PathParam("alpha3code") String alpha3) { try { List<Country> countries = getAll(); for(Country country : countries) { if (country.getCca3().toLowerCase().equals(alpha3.toLowerCase())) { return country; } } } catch (IOException e) { return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } return Response.status(Status.NOT_FOUND).build(); } @GET @Path("currency/{currency}") public Object getByCurrency(@PathParam("currency") String currency) { try { List<Country> countries = getAll(); List<Country> result = new ArrayList<Country>(); for(Country country : countries) { if(country.getCurrency().toLowerCase().contains(currency.toLowerCase())) { result.add(country); } } return result; } catch (IOException e) { return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } @GET @Path("callingcode/{callingcode}") public Object getByCallingCode(@PathParam("callingcode") String callingcode) { try { List<Country> countries = getAll(); for(Country country : countries) { if(country.getCallingcode().equals(callingcode)) return country; } } catch (IOException e) { return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } return Response.status(Status.NOT_FOUND).build(); } private List<Country> getAll() throws IOException { InputStream is = this.getClass().getClassLoader().getResourceAsStream("countries.json"); Gson gson = new Gson(); JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8")); List<Country> list = new ArrayList<Country>(); reader.beginArray(); while(reader.hasNext()) { Country country = gson.fromJson(reader, Country.class); list.add(country); } reader.endArray(); reader.close(); return list; } }
package wasdev.sample.servlet; //package com.mcademo; import okhttp3.*; import org.json.JSONObject; import net.iharder.Base64; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; //import java.util.Base64; import java.util.logging.Logger; public class OAuthServlet extends HttpServlet { private static final long serialVersionUID = 1L; // Define properties required for OAuth flows private static final Logger logger = Logger.getLogger(OAuthServlet.class.getName()); private static final OkHttpClient client = new OkHttpClient(); private static final String clientId = "4b07cfe1-3875-419c-a0a2-8fb0a7b43dff"; private static final String clientSecret = "MDlkYjZkYjAtOGVkOS00MjcxLWE5ZTMtMWNlODVhMDQ0MDUy"; private static final String callbackUri = "http://mca-java.mybluemix.net/oauth/callback"; private static final String authzEndpoint = "https://mobileclientaccess.ng.bluemix.net/oauth/v2/authorization"; private static final String tokenEndpoint = "https://mobileclientaccess.ng.bluemix.net/oauth/v2/token"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("Incoming request :: " + request.getRequestURL() + "/" + request.getQueryString()); logger.info("Redirecting to MCA for authorization"); if (request.getRequestURI().contains("/login")){ onLogin(request, response); } else if (request.getRequestURI().contains("/callback")){ onCallback(request, response); } else if (request.getRequestURI().contains("/logout")){ onLogout(request, response); } else { response.sendError(404, "Not Found"); } } private void onLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("onLogin"); String authzUrl = authzEndpoint + "?response_type=code"; authzUrl += "&client_id=" + clientId; authzUrl += "&redirect_uri=" + callbackUri; response.sendRedirect(authzUrl); } private void onCallback(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("onCallback"); String grantCode = request.getQueryString().split("=")[1]; JSONObject body = new JSONObject(); try { body.put("grant_type", "authorization_code"); body.put("client_id", clientId); body.put("redirect_uri", callbackUri); body.put("code", grantCode); } catch (Throwable t){} String credentials = Credentials.basic(clientId, clientSecret); Request req = new Request.Builder() .url(tokenEndpoint) .header("Authorization", credentials) .post(RequestBody.create(MediaType.parse("application/json"), body.toString())) .build(); Response res = client.newCall(req).execute(); JSONObject parsedBody = new JSONObject(res.body().string()); String accessToken = parsedBody.getString("access_token"); String idToken = parsedBody.getString("id_token"); //byte[] decodedIdTokenPayload = Base64.getUrlDecoder().decode(idToken.split("\\.")[1]); byte[] decodedIdTokenPayload = Base64.decode(idToken.split("\\.")[1], Base64.URL_SAFE); JSONObject decodedIdentityToken = new JSONObject(new String(decodedIdTokenPayload)); JSONObject userIdentity = decodedIdentityToken.getJSONObject("imf.user"); JSONObject authData = new JSONObject(); authData.put("accessToken", accessToken); authData.put("idToken", idToken); authData.put("userIdentity", userIdentity); request.getSession().setAttribute("mca", authData); response.sendRedirect("/"); } private void onLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("onLogout"); request.getSession().setAttribute("mca", null); response.sendRedirect("/"); } }
package org.openintents.filemanager.util; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.openintents.filemanager.R; import org.openintents.filemanager.files.FileHolder; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; public class CompressManager { /** * TAG for log messages. */ static final String TAG = "CompressManager"; private static final int BUFFER_SIZE = 1024; private Context mContext; private ProgressDialog progressDialog; private int fileCount; private String fileOut; private OnCompressFinishedListener onCompressFinishedListener = null; public CompressManager(Context context) { mContext = context; } public void compress(FileHolder f, String out) { List<FileHolder> list = new ArrayList<FileHolder>(1); list.add(f); compress(list, out); } public void compress(List<FileHolder> list, String out) { if (list.isEmpty()){ Log.v(TAG, "couldn't compress empty file list"); return; } this.fileOut = list.get(0).getFile().getParent() + File.separator + out; fileCount = 0; for (FileHolder f: list){ fileCount += FileUtils.getFileCount(f.getFile()); } new CompressTask().execute(list); } private class CompressTask extends AsyncTask<List<FileHolder>, Void, Integer> { private static final int success = 0; private static final int error = 1; private ZipOutputStream zos; private File zipDirectory; private boolean cancelCompression=false; /** * count of compressed file to update the progress bar */ private int isCompressed = 0; /** * Recursively compress file or directory * @returns 0 if successful, error value otherwise. */ private void compressFile(File file, String path) throws IOException { progressDialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface progressDialog) { if(cancelCompression==false) { Log.e(TAG, "Dialog Dismissed"); Log.e(TAG, "Compression Cancel Attempted"); cancelCompression=true; cancel(true); } } }); if (!file.isDirectory()){ byte[] buf = new byte[BUFFER_SIZE]; int len; FileInputStream in = new FileInputStream(file); if(path.length() > 0) zos.putNextEntry(new ZipEntry(path + "/" + file.getName())); else zos.putNextEntry(new ZipEntry(file.getName())); while ((len = in.read(buf)) > 0) { zos.write(buf, 0, len); } in.close(); return; } if (file.list() == null || cancelCompression==true){ return; } for (String fileName: file.list()){ if(cancelCompression==true) { return; } File f = new File(file.getAbsolutePath()+File.separator+fileName); compressFile(f, path + File.separator + file.getName()); isCompressed++; progressDialog.setProgress((isCompressed * 100)/ fileCount); } } @Override protected void onPreExecute() { FileOutputStream out = null; zipDirectory=new File(fileOut); progressDialog = new ProgressDialog(mContext); progressDialog.setCancelable(false); progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface progressDialog, int which) { progressDialog.dismiss(); Log.e(TAG, "Dialog Dismiss Detected"); } }); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage(mContext.getString(R.string.compressing)); progressDialog.show(); progressDialog.setProgress(0); try { out = new FileOutputStream(zipDirectory); zos = new ZipOutputStream(new BufferedOutputStream(out)); } catch (FileNotFoundException e) { Log.e(TAG, "error while creating ZipOutputStream"); } } @Override protected Integer doInBackground(List<FileHolder>... params) { if (zos == null){ return error; } List<FileHolder> list = params[0]; for (FileHolder file : list){ if(cancelCompression==true){ return error; } try { compressFile(file.getFile(), ""); } catch (IOException e) { Log.e(TAG, "Error while compressing", e); return error; } } return success; } @Override protected void onCancelled (Integer result) { Log.e(TAG,"onCancelled Initialised"); try { zos.flush(); zos.close(); } catch (IOException e) { Log.e(TAG, "error while closing zos", e); } if(zipDirectory.delete()){ Log.e(TAG, "test deleted successfully"); } else { Log.e(TAG, "error while deleting test"); } Toast.makeText(mContext, "Compression Canceled", Toast.LENGTH_SHORT).show(); if(onCompressFinishedListener != null) onCompressFinishedListener.compressFinished(); } @Override protected void onPostExecute(Integer result) { try { zos.flush(); zos.close(); } catch (IOException e) { Log.e(TAG, "error while closing zos", e); } cancelCompression=true; progressDialog.cancel(); if (result == error){ Toast.makeText(mContext, R.string.compressing_error, Toast.LENGTH_SHORT).show(); } else if (result == success){ Toast.makeText(mContext, R.string.compressing_success, Toast.LENGTH_SHORT).show(); } if(onCompressFinishedListener != null) onCompressFinishedListener.compressFinished(); } } public interface OnCompressFinishedListener{ public abstract void compressFinished(); } public CompressManager setOnCompressFinishedListener(OnCompressFinishedListener listener) { this.onCompressFinishedListener = listener; return this; } }
package org.openintents.filemanager.util; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.openintents.filemanager.R; import org.openintents.filemanager.files.FileHolder; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; public class CompressManager { /** * TAG for log messages. */ static final String TAG = "CompressManager"; private static final int BUFFER_SIZE = 1024; private Context mContext; private ProgressDialog progressDialog; private int fileCount; private String fileOut; private OnCompressFinishedListener onCompressFinishedListener = null; public CompressManager(Context context) { mContext = context; } public void compress(FileHolder f, String out) { List<FileHolder> list = new ArrayList<FileHolder>(1); list.add(f); compress(list, out); } public void compress(List<FileHolder> list, String out) { if (list.isEmpty()){ Log.v(TAG, "couldn't compress empty file list"); return; } this.fileOut = list.get(0).getFile().getParent() + File.separator + out; fileCount = 0; for (FileHolder f: list){ fileCount += FileUtils.getFileCount(f.getFile()); } new CompressTask().execute(list); } private class CompressTask extends AsyncTask<List<FileHolder>, Void, Integer> { private static final int success = 0; private static final int error = 1; private ZipOutputStream zos; private File zipDirectory; private boolean cancelCompression=false; /** * count of compressed file to update the progress bar */ private int isCompressed = 0; /** * Recursively compress file or directory * @returns 0 if successful, error value otherwise. */ private void compressFile(File file, String path) throws IOException { progressDialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface progressDialog) { if(cancelCompression==false) { Log.e(TAG, "Dialog Dismissed"); Log.e(TAG, "Compression Cancel Attempted"); cancelCompression=true; cancel(true); } } }); if (!file.isDirectory()){ byte[] buf = new byte[BUFFER_SIZE]; int len; FileInputStream in = new FileInputStream(file); if(path.length() > 0) zos.putNextEntry(new ZipEntry(path + "/" + file.getName())); else zos.putNextEntry(new ZipEntry(file.getName())); while ((len = in.read(buf)) > 0) { zos.write(buf, 0, len); } in.close(); return; } if (file.list() == null || cancelCompression==true){ return; } for (String fileName: file.list()){ if(cancelCompression==true) { return; } File f = new File(file.getAbsolutePath()+File.separator+fileName); compressFile(f, path + File.separator + file.getName()); isCompressed++; progressDialog.setProgress((isCompressed * 100)/ fileCount); } } @Override protected void onPreExecute() { FileOutputStream out = null; zipDirectory=new File(fileOut); progressDialog = new ProgressDialog(mContext); progressDialog.setCancelable(false); progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface progressDialog, int which) { progressDialog.dismiss(); Log.e(TAG, "Dialog Dismiss Detected"); } }); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage(mContext.getString(R.string.compressing)); progressDialog.show(); progressDialog.setProgress(0); try { out = new FileOutputStream(zipDirectory); zos = new ZipOutputStream(new BufferedOutputStream(out)); } catch (FileNotFoundException e) { Log.e(TAG, "error while creating ZipOutputStream"); } } @Override protected Integer doInBackground(List<FileHolder>... params) { if (zos == null){ return error; } List<FileHolder> list = params[0]; for (FileHolder file : list){ if(cancelCompression==true) { return error; } try { compressFile(file.getFile(), ""); } catch (IOException e) { Log.e(TAG, "Error while compressing", e); return error; } } return success; } @Override protected void onCancelled (Integer result) { Log.e(TAG,"onCancelled Initialised"); try { zos.flush(); zos.close(); } catch (IOException e) { Log.e(TAG, "error while closing zos", e); } if(zipDirectory.delete()) { Log.e(TAG, "test deleted successfully"); } else { Log.e(TAG, "error while deleting test"); } Toast.makeText(mContext, "Compression Canceled", Toast.LENGTH_SHORT).show(); if(onCompressFinishedListener != null) onCompressFinishedListener.compressFinished(); } @Override protected void onPostExecute(Integer result) { cancelCompression=true; try { zos.flush(); zos.close(); } catch (IOException e) { Log.e(TAG, "error while closing zos", e); } progressDialog.cancel(); if (result == error){ Toast.makeText(mContext, R.string.compressing_error, Toast.LENGTH_SHORT).show(); } else if (result == success){ Toast.makeText(mContext, R.string.compressing_success, Toast.LENGTH_SHORT).show(); } if(onCompressFinishedListener != null) onCompressFinishedListener.compressFinished(); } } public interface OnCompressFinishedListener{ public abstract void compressFinished(); } public CompressManager setOnCompressFinishedListener(OnCompressFinishedListener listener) { this.onCompressFinishedListener = listener; return this; } }
package org.waterforpeople.mapping.app.web; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.JAXBException; import org.apache.commons.lang.StringEscapeUtils; import org.apache.log4j.Logger; import org.waterforpeople.mapping.app.web.dto.SurveyAssemblyRequest; import org.waterforpeople.mapping.dao.SurveyContainerDao; import com.gallatinsystems.common.domain.UploadStatusContainer; import com.gallatinsystems.common.util.PropertyUtil; import com.gallatinsystems.common.util.S3Util; import com.gallatinsystems.common.util.ZipUtil; import com.gallatinsystems.framework.rest.AbstractRestApiServlet; import com.gallatinsystems.framework.rest.RestRequest; import com.gallatinsystems.framework.rest.RestResponse; import com.gallatinsystems.messaging.dao.MessageDao; import com.gallatinsystems.messaging.domain.Message; import com.gallatinsystems.survey.dao.CascadeResourceDao; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.dao.QuestionGroupDao; import com.gallatinsystems.survey.dao.SurveyDAO; import com.gallatinsystems.survey.dao.SurveyGroupDAO; import com.gallatinsystems.survey.dao.SurveyUtils; import com.gallatinsystems.survey.dao.SurveyXMLFragmentDao; import com.gallatinsystems.survey.dao.TranslationDao; import com.gallatinsystems.survey.domain.CascadeResource; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.QuestionGroup; import com.gallatinsystems.survey.domain.QuestionHelpMedia; import com.gallatinsystems.survey.domain.QuestionOption; import com.gallatinsystems.survey.domain.ScoringRule; import com.gallatinsystems.survey.domain.Survey; import com.gallatinsystems.survey.domain.SurveyContainer; import com.gallatinsystems.survey.domain.SurveyGroup; import com.gallatinsystems.survey.domain.SurveyXMLFragment; import com.gallatinsystems.survey.domain.SurveyXMLFragment.FRAGMENT_TYPE; import com.gallatinsystems.survey.domain.Translation; import com.gallatinsystems.survey.domain.xml.AltText; import com.gallatinsystems.survey.domain.xml.Dependency; import com.gallatinsystems.survey.domain.xml.Help; import com.gallatinsystems.survey.domain.xml.Level; import com.gallatinsystems.survey.domain.xml.Levels; import com.gallatinsystems.survey.domain.xml.ObjectFactory; import com.gallatinsystems.survey.domain.xml.Option; import com.gallatinsystems.survey.domain.xml.Options; import com.gallatinsystems.survey.domain.xml.Score; import com.gallatinsystems.survey.domain.xml.Scoring; import com.gallatinsystems.survey.domain.xml.ValidationRule; import com.gallatinsystems.survey.xml.SurveyXMLAdapter; import com.google.appengine.api.backends.BackendServiceFactory; import com.google.appengine.api.datastore.Text; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.utils.SystemProperty; public class SurveyAssemblyServlet extends AbstractRestApiServlet { private static final Logger log = Logger .getLogger(SurveyAssemblyServlet.class.getName()); private static final int BACKEND_QUESTION_THRESHOLD = 80; private static final String BACKEND_PUBLISH_PROP = "backendpublish"; private static final long serialVersionUID = -6044156962558183224L; private static final String OPTION_RENDER_MODE_PROP = "optionRenderMode"; public static final String FREE_QUESTION_TYPE = "free"; public static final String OPTION_QUESTION_TYPE = "option"; public static final String GEO_QUESTION_TYPE = "geo"; public static final String VIDEO_QUESTION_TYPE = "video"; public static final String PHOTO_QUESTION_TYPE = "photo"; public static final String SCAN_QUESTION_TYPE = "scan"; public static final String STRENGTH_QUESTION_TYPE = "strength"; public static final String DATE_QUESTION_TYPE = "date"; public static final String CASCADE_QUESTION_TYPE = "cascade"; public static final String GEOSHAPE_QUESTION_TYPE = "geoshape"; public static final String SIGNATURE_QUESTION_TYPE = "signature"; private static final String SURVEY_UPLOAD_URL = "surveyuploadurl"; private static final String SURVEY_UPLOAD_DIR = "surveyuploaddir"; private Random randomNumber = new Random(); @Override protected RestRequest convertRequest() throws Exception { HttpServletRequest req = getRequest(); RestRequest restRequest = new SurveyAssemblyRequest(); restRequest.populateFromHttpRequest(req); return restRequest; } @Override protected RestResponse handleRequest(RestRequest req) throws Exception { RestResponse response = new RestResponse(); SurveyAssemblyRequest importReq = (SurveyAssemblyRequest) req; if (SurveyAssemblyRequest.ASSEMBLE_SURVEY.equalsIgnoreCase(importReq .getAction())) { QuestionDao questionDao = new QuestionDao(); boolean useBackend = false; // make sure we're not already running on a backend and that we are // allowed to use one if (!importReq.getIsForwarded() && "true".equalsIgnoreCase(PropertyUtil .getProperty(BACKEND_PUBLISH_PROP))) { // if we're allowed to use a backend, then check to see if we // need to (based on survey size) List<Question> questionList = questionDao .listQuestionsBySurvey(importReq.getSurveyId()); if (questionList != null && questionList.size() > BACKEND_QUESTION_THRESHOLD) { useBackend = true; } } if (useBackend) { com.google.appengine.api.taskqueue.TaskOptions options = com.google.appengine.api.taskqueue.TaskOptions.Builder .withUrl("/app_worker/surveyassembly") .param(SurveyAssemblyRequest.ACTION_PARAM, SurveyAssemblyRequest.ASSEMBLE_SURVEY) .param(SurveyAssemblyRequest.IS_FWD_PARAM, "true") .param(SurveyAssemblyRequest.SURVEY_ID_PARAM, importReq.getSurveyId().toString()); // change the host so the queue invokes the backend options = options .header("Host", BackendServiceFactory.getBackendService() .getBackendAddress("dataprocessor")); com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory .getQueue("surveyAssembly"); queue.add(options); } else { // assembleSurvey(importReq.getSurveyId()); assembleSurveyOnePass(importReq.getSurveyId()); } List<Long> ids = new ArrayList<Long>(); ids.add(importReq.getSurveyId()); SurveyUtils.notifyReportService(ids, "invalidate"); } else if (SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP .equalsIgnoreCase(importReq.getAction())) { this.dispatchAssembleQuestionGroup(importReq.getSurveyId(), importReq.getQuestionGroupId(), importReq.getTransactionId()); } else if (SurveyAssemblyRequest.ASSEMBLE_QUESTION_GROUP .equalsIgnoreCase(importReq.getAction())) { assembleQuestionGroups(importReq.getSurveyId(), importReq.getTransactionId()); } else if (SurveyAssemblyRequest.DISTRIBUTE_SURVEY .equalsIgnoreCase(importReq.getAction())) { uploadSurvey(importReq.getSurveyId(), importReq.getTransactionId()); } else if (SurveyAssemblyRequest.CLEANUP.equalsIgnoreCase(importReq .getAction())) { cleanupFragments(importReq.getSurveyId(), importReq.getTransactionId()); } return response; } /** * uploads full survey XML to S3 * * @param surveyId */ private void uploadSurvey(Long surveyId, Long transactionId) { SurveyContainerDao scDao = new SurveyContainerDao(); SurveyContainer sc = scDao.findBySurveyId(surveyId); Properties props = System.getProperties(); String document = sc.getSurveyDocument().getValue(); String bucketName = props.getProperty("s3bucket"); boolean uploadedFile = false; boolean uploadedZip = false; try { uploadedFile = S3Util.put(bucketName, props.getProperty(SURVEY_UPLOAD_DIR) + "/" + sc.getSurveyId() + ".xml", document.getBytes("UTF-8"), "text/xml", true); } catch (IOException e) { log.error("Error uploading file " + e.getMessage(), e); } ByteArrayOutputStream os = ZipUtil.generateZip(document, sc.getSurveyId() + ".xml"); try { uploadedZip = S3Util.put(bucketName, props.getProperty(SURVEY_UPLOAD_DIR) + "/" + sc.getSurveyId() + ".zip", os.toByteArray(), "application/zip", true); } catch (Exception e) { log.error("Error uploading zip file: " + e.getMessage(), e); } sendQueueMessage(SurveyAssemblyRequest.CLEANUP, surveyId, null, transactionId); Message message = new Message(); message.setActionAbout("surveyAssembly"); message.setObjectId(surveyId); if (uploadedFile && uploadedZip) { // increment the version so devices know to pick up the changes SurveyDAO surveyDao = new SurveyDAO(); String messageText = "Published. Please check: " + props.getProperty(SURVEY_UPLOAD_URL) + props.getProperty(SURVEY_UPLOAD_DIR) + "/" + surveyId + ".xml"; message.setShortMessage(messageText); Survey s = surveyDao.getById(surveyId); if (s != null) { message.setObjectTitle(s.getPath() + "/" + s.getName()); } message.setTransactionUUID(transactionId.toString()); MessageDao messageDao = new MessageDao(); messageDao.save(message); } else { String messageText = "Failed to publish: " + surveyId + "\n"; message.setTransactionUUID(transactionId.toString()); message.setShortMessage(messageText); MessageDao messageDao = new MessageDao(); messageDao.save(message); } } /** * deletes fragments for the survey * * @param surveyId */ private void cleanupFragments(Long surveyId, Long transactionId) { SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao(); sxmlfDao.deleteFragmentsForSurvey(surveyId, transactionId); } @Override protected void writeOkResponse(RestResponse resp) throws Exception { HttpServletResponse httpResp = getResponse(); httpResp.setStatus(HttpServletResponse.SC_OK); // httpResp.setContentType("text/plain"); httpResp.getWriter().print("OK"); httpResp.flushBuffer(); } private void assembleSurveyOnePass(Long surveyId) { /************** * 1, Select survey based on surveyId 2. Retrieve all question groups fire off queue tasks */ log.warn("Starting assembly of " + surveyId); // Swap with proper UUID SurveyDAO surveyDao = new SurveyDAO(); Survey s = surveyDao.getById(surveyId); SurveyGroupDAO surveyGroupDao = new SurveyGroupDAO(); SurveyGroup sg = surveyGroupDao.getByKey(s.getSurveyGroupId()); Long transactionId = randomNumber.nextLong(); String lang = "en"; if (s != null && s.getDefaultLanguageCode() != null) { lang = s.getDefaultLanguageCode(); } final String versionAttribute = s.getVersion() == null ? "" : "version='" + s.getVersion() + "'"; final String app = String.format("app=\"%s\"", StringEscapeUtils.escapeXml(SystemProperty.applicationId.get())); String name = s.getName(); String surveyGroupId = ""; String surveyGroupName = ""; String registrationForm = ""; if (sg != null) { surveyGroupId = "surveyGroupId=\"" + sg.getKey().getId() + "\""; surveyGroupName = "surveyGroupName=\"" + StringEscapeUtils.escapeXml(sg.getCode()) + "\""; if (Boolean.TRUE.equals(sg.getMonitoringGroup())) { registrationForm = " registrationSurvey=\"" + sg.getNewLocaleSurveyId() + "\""; } } String surveyHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><survey" + " name=\"" + StringEscapeUtils.escapeXml(name) + "\"" + " defaultLanguageCode=\"" + lang + "\" " + versionAttribute + " " + app + registrationForm + " " + surveyGroupId + " " + surveyGroupName + ">"; String surveyFooter = "</survey>"; QuestionGroupDao qgDao = new QuestionGroupDao(); TreeMap<Integer, QuestionGroup> qgList = qgDao .listQuestionGroupsBySurvey(surveyId); if (qgList != null) { StringBuilder surveyXML = new StringBuilder(); surveyXML.append(surveyHeader); for (QuestionGroup item : qgList.values()) { log.warn("Assembling group " + item.getKey().getId() + " for survey " + surveyId); surveyXML.append(buildQuestionGroupXML(item)); } surveyXML.append(surveyFooter); log.warn("Uploading " + surveyId); UploadStatusContainer uc = uploadSurveyXML(surveyId, surveyXML.toString()); Message message = new Message(); message.setActionAbout("surveyAssembly"); message.setObjectId(surveyId); message.setObjectTitle(sg.getCode() + " / " + s.getName()); // String messageText = CONSTANTS.surveyPublishOkMessage() + " " // + url; if (uc.getUploadedFile() && uc.getUploadedZip()) { // increment the version so devices know to pick up the changes log.warn("Finishing assembly of " + surveyId); s.setStatus(Survey.Status.PUBLISHED); surveyDao.save(s); String messageText = "Published. Please check: " + uc.getUrl(); message.setShortMessage(messageText); message.setTransactionUUID(transactionId.toString()); MessageDao messageDao = new MessageDao(); messageDao.save(message); } else { // String messageText = // CONSTANTS.surveyPublishErrorMessage(); String messageText = "Failed to publish: " + surveyId + "\n" + uc.getMessage(); message.setTransactionUUID(transactionId.toString()); message.setShortMessage(messageText); MessageDao messageDao = new MessageDao(); messageDao.save(message); } log.warn("Completed onepass assembly method for " + surveyId); } } public UploadStatusContainer uploadSurveyXML(Long surveyId, String surveyXML) { Properties props = System.getProperties(); String bucketName = props.getProperty("s3bucket"); String document = surveyXML; boolean uploadedFile = false; boolean uploadedZip = false; try { uploadedFile = S3Util.put(bucketName, props.getProperty(SURVEY_UPLOAD_DIR) + "/" + surveyId + ".xml", document.getBytes("UTF-8"), "text/xml", true); } catch (IOException e) { log.error("Error uploading file: " + e.getMessage(), e); } ByteArrayOutputStream os = ZipUtil.generateZip(document, surveyId + ".xml"); UploadStatusContainer uc = new UploadStatusContainer(); try { uploadedZip = S3Util.put(bucketName, props.getProperty(SURVEY_UPLOAD_DIR) + "/" + surveyId + ".zip", os.toByteArray(), "application/zip", true); } catch (IOException e) { log.error("Error uploading file: " + e.getMessage(), e); } uc.setUploadedFile(uploadedFile); uc.setUploadedZip(uploadedZip); uc.setUrl(props.getProperty(SURVEY_UPLOAD_URL) + props.getProperty(SURVEY_UPLOAD_DIR) + "/" + surveyId + ".xml"); return uc; } public String buildQuestionGroupXML(QuestionGroup item) { QuestionDao questionDao = new QuestionDao(); QuestionGroupDao questionGroupDao = new QuestionGroupDao(); QuestionGroup group = questionGroupDao.getByKey(item.getKey().getId()); TreeMap<Integer, Question> questionList = questionDao .listQuestionsByQuestionGroup(item.getKey().getId(), true); StringBuilder sb = new StringBuilder("<questionGroup") .append(Boolean.TRUE.equals(group.getRepeatable()) ? " repeatable=\"true\"" : "") .append("><heading>").append(StringEscapeUtils.escapeXml(group.getCode())) .append("</heading>"); if (questionList != null) { for (Question q : questionList.values()) { sb.append(marshallQuestion(q)); } } return sb.toString() + "</questionGroup>"; } /** * sends a message to the task queue for survey assembly * * @param action * @param surveyId * @param questionGroups */ private void sendQueueMessage(String action, Long surveyId, String questionGroups, Long transactionId) { Queue surveyAssemblyQueue = QueueFactory.getQueue("surveyAssembly"); TaskOptions task = TaskOptions.Builder.withUrl("/app_worker/surveyassembly") .param("action", action).param("surveyId", surveyId.toString()); if (questionGroups != null) { task.param("questionGroupId", questionGroups); } if (transactionId != null) { task.param("transactionId", transactionId.toString()); } surveyAssemblyQueue.add(task); } private void dispatchAssembleQuestionGroup(Long surveyId, String questionGroupIds, Long transactionId) { boolean isLast = true; String currentId = questionGroupIds; String remainingIds = null; if (questionGroupIds.contains(",")) { isLast = false; currentId = questionGroupIds.substring(0, questionGroupIds.indexOf(",")); remainingIds = questionGroupIds.substring(questionGroupIds .indexOf(",") + 1); } QuestionDao questionDao = new QuestionDao(); QuestionGroupDao questionGroupDao = new QuestionGroupDao(); QuestionGroup group = questionGroupDao.getByKey(Long .parseLong(currentId)); TreeMap<Integer, Question> questionList = questionDao .listQuestionsByQuestionGroup(Long.parseLong(currentId), true); StringBuilder sb = new StringBuilder("<questionGroup") .append(Boolean.TRUE.equals(group.getRepeatable()) ? " repeatable=\"true\"" : "") .append("><heading>").append(group.getCode()).append("</heading>"); if (questionList != null) { for (Question q : questionList.values()) { sb.append(marshallQuestion(q)); } } SurveyXMLFragment sxf = new SurveyXMLFragment(); sxf.setSurveyId(surveyId); sxf.setQuestionGroupId(Long.parseLong(currentId)); sxf.setFragmentOrder(group.getOrder()); sxf.setFragment(new Text(sb.append("</questionGroup>").toString())); sxf.setTransactionId(transactionId); sxf.setFragmentType(FRAGMENT_TYPE.QUESTION_GROUP); SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao(); sxmlfDao.save(sxf); if (isLast) { // Assemble the fragments sendQueueMessage(SurveyAssemblyRequest.ASSEMBLE_QUESTION_GROUP, surveyId, null, transactionId); } else { sendQueueMessage( SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP, surveyId, remainingIds, transactionId); } } private String marshallQuestion(Question q) { SurveyXMLAdapter sax = new SurveyXMLAdapter(); ObjectFactory objFactory = new ObjectFactory(); com.gallatinsystems.survey.domain.xml.Question qXML = objFactory .createQuestion(); qXML.setId(new String("" + q.getKey().getId() + "")); // ToDo fix qXML.setMandatory("false"); if (q.getText() != null) { com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text(); t.setContent(q.getText()); qXML.setText(t); } List<Help> helpList = new ArrayList<Help>(); // this is here for backward compatibility // however, we don't use the helpMedia at the moment if (q.getTip() != null) { Help tip = new Help(); com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text(); t.setContent(q.getTip()); tip.setText(t); tip.setType("tip"); if (q.getTip() != null && q.getTip().trim().length() > 0 && !"null".equalsIgnoreCase(q.getTip().trim())) { TranslationDao tDao = new TranslationDao(); Map<String, Translation> tipTrans = tDao.findTranslations( Translation.ParentType.QUESTION_TIP, q.getKey().getId()); // any translations for question tooltip? List<AltText> translationList = new ArrayList<AltText>(); for (Translation trans : tipTrans .values()) { AltText aText = new AltText(); aText.setContent(trans.getText()); aText.setLanguage(trans.getLanguageCode()); aText.setType("translation"); translationList.add(aText); } if (translationList.size() > 0) { tip.setAltText(translationList); } helpList.add(tip); } } if (q.getQuestionHelpMediaMap() != null) { for (QuestionHelpMedia helpItem : q.getQuestionHelpMediaMap() .values()) { Help tip = new Help(); com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text(); t.setContent(helpItem.getText()); if (helpItem.getType() == QuestionHelpMedia.Type.TEXT) { tip.setType("tip"); } else { tip.setType(helpItem.getType().toString().toLowerCase()); tip.setValue(helpItem.getResourceUrl()); } if (helpItem.getTranslationMap() != null) { List<AltText> translationList = new ArrayList<AltText>(); for (Translation trans : helpItem.getTranslationMap() .values()) { AltText aText = new AltText(); aText.setContent(trans.getText()); aText.setLanguage(trans.getLanguageCode()); aText.setType("translation"); translationList.add(aText); } if (translationList.size() > 0) { tip.setAltText(translationList); } } helpList.add(tip); } } if (helpList.size() > 0) { qXML.setHelp(helpList); } boolean hasValidation = false; if (q.getIsName() != null && q.getIsName()) { ValidationRule validationRule = objFactory.createValidationRule(); validationRule.setValidationType("name"); qXML.setValidationRule(validationRule); hasValidation = true; } else if (q.getType() == Question.Type.NUMBER && (q.getAllowDecimal() != null || q.getAllowSign() != null || q.getMinVal() != null || q.getMaxVal() != null)) { ValidationRule validationRule = objFactory.createValidationRule(); validationRule.setValidationType("numeric"); validationRule.setAllowDecimal(q.getAllowDecimal() != null ? q .getAllowDecimal().toString().toLowerCase() : "false"); validationRule.setSigned(q.getAllowSign() != null ? q .getAllowSign().toString().toLowerCase() : "false"); if (q.getMinVal() != null) { validationRule.setMinVal(q.getMinVal().toString()); } if (q.getMaxVal() != null) { validationRule.setMaxVal(q.getMaxVal().toString()); } qXML.setValidationRule(validationRule); hasValidation = true; } qXML.setAltText(formAltText(q.getTranslationMap())); if (q.getType().equals(Question.Type.FREE_TEXT)) { qXML.setType(FREE_QUESTION_TYPE); // add requireDoubleEntry flag if the field is true in the question if (q.getRequireDoubleEntry() != null && q.getRequireDoubleEntry()) { qXML.setRequireDoubleEntry(q.getRequireDoubleEntry().toString()); } } else if (q.getType().equals(Question.Type.GEO)) { qXML.setType(GEO_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.NUMBER)) { qXML.setType(FREE_QUESTION_TYPE); if (!hasValidation) { ValidationRule vrule = new ValidationRule(); vrule.setValidationType("numeric"); vrule.setSigned("false"); qXML.setValidationRule(vrule); } // add requireDoubleEntry flag if the field is true in the question if (q.getRequireDoubleEntry() != null && q.getRequireDoubleEntry()) { qXML.setRequireDoubleEntry(q.getRequireDoubleEntry().toString()); } } else if (q.getType().equals(Question.Type.OPTION)) { qXML.setType(OPTION_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.PHOTO)) { qXML.setType(PHOTO_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.VIDEO)) { qXML.setType(VIDEO_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.SCAN)) { qXML.setType(SCAN_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.NAME)) { qXML.setType(FREE_QUESTION_TYPE); ValidationRule vrule = new ValidationRule(); vrule.setValidationType("name"); qXML.setValidationRule(vrule); } else if (q.getType().equals(Question.Type.STRENGTH)) { qXML.setType(STRENGTH_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.DATE)) { qXML.setType(DATE_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.CASCADE)) { qXML.setType(CASCADE_QUESTION_TYPE); } else if (q.getType().equals(Question.Type.GEOSHAPE)) { qXML.setType(GEOSHAPE_QUESTION_TYPE); qXML.setAllowPoints(Boolean.toString(q.getAllowPoints())); qXML.setAllowLine(Boolean.toString(q.getAllowLine())); qXML.setAllowPolygon(Boolean.toString(q.getAllowPolygon())); } else if (q.getType().equals(Question.Type.SIGNATURE)) { qXML.setType(SIGNATURE_QUESTION_TYPE); } if (q.getType().equals(Question.Type.CASCADE) && q.getCascadeResourceId() != null) { CascadeResourceDao crDao = new CascadeResourceDao(); CascadeResource cr = crDao.getByKey(q.getCascadeResourceId()); if (cr != null) { qXML.setCascadeResource(cr.getResourceId()); List<String> levelNames = cr.getLevelNames(); if (levelNames != null && levelNames.size() > 0) { Levels levels = objFactory.createLevels(); ArrayList<Level> levelList = new ArrayList<Level>(); for (int i = 0; i < cr.getNumLevels(); i++) { Level levelItem = objFactory.createLevel(); com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text(); t.setContent(levelNames.get(i)); levelItem.addContent(t); levelList.add(levelItem); // TODO sort out translations } levels.setLevel(levelList); qXML.setLevels(levels); } } } if (q.getOrder() != null) { qXML.setOrder(q.getOrder().toString()); } if (q.getMandatoryFlag() != null) { qXML.setMandatory(q.getMandatoryFlag().toString()); } qXML.setLocaleNameFlag("false"); if (q.getLocaleNameFlag() != null) { qXML.setLocaleNameFlag(q.getLocaleNameFlag().toString()); } if (q.getLocaleLocationFlag() != null) { if (q.getLocaleLocationFlag()) { qXML.setLocaleLocationFlag("true"); } } if (Boolean.TRUE.equals(q.getAllowMultipleFlag())) { qXML.setAllowMultiple("true"); } // Both GEO and GEOSHAPE question types can block manual input if (Boolean.TRUE.equals(q.getGeoLocked())) { qXML.setLocked("true"); } Dependency dependency = objFactory.createDependency(); if (q.getDependentQuestionId() != null) { dependency.setQuestion(q.getDependentQuestionId().toString()); dependency.setAnswerValue(q.getDependentQuestionAnswer()); qXML.setDependency(dependency); } if (q.getQuestionOptionMap() != null && q.getQuestionOptionMap().size() > 0) { Options options = objFactory.createOptions(); if (q.getAllowOtherFlag() != null) { options.setAllowOther(q.getAllowOtherFlag().toString()); } if (q.getAllowMultipleFlag() != null) { options.setAllowMultiple(q.getAllowMultipleFlag().toString()); } if (options.getAllowMultiple() == null || "false".equals(options.getAllowMultiple())) { options.setRenderType(PropertyUtil .getProperty(OPTION_RENDER_MODE_PROP)); } ArrayList<Option> optionList = new ArrayList<Option>(); for (QuestionOption qo : q.getQuestionOptionMap().values()) { Option option = objFactory.createOption(); com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text(); t.setContent(qo.getText()); option.addContent(t); option.setCode(qo.getCode()); // to maintain backwards compatibility with older app versions, we set the value // attribute and text to the same option.setValue(qo.getText()); List<AltText> altTextList = formAltText(qo.getTranslationMap()); if (altTextList != null) { for (AltText alt : altTextList) { option.addContent(alt); } } optionList.add(option); } options.setOption(optionList); qXML.setOptions(options); } if (q.getScoringRules() != null) { Scoring scoring = new Scoring(); for (ScoringRule rule : q.getScoringRules()) { Score score = new Score(); if (scoring.getType() == null) { scoring.setType(rule.getType().toLowerCase()); } score.setRangeHigh(rule.getRangeMax()); score.setRangeLow(rule.getRangeMin()); score.setValue(rule.getValue()); scoring.addScore(score); } if (scoring.getScore() != null && scoring.getScore().size() > 0) { qXML.setScoring(scoring); } } if ("true".equalsIgnoreCase(String.valueOf(q.getAllowExternalSources()))) { qXML.setAllowExternalSources(String.valueOf(q.getAllowExternalSources())); } String questionDocument = null; try { questionDocument = sax.marshal(qXML); } catch (JAXBException e) { log.warn("Could not marshal question: " + qXML, e); } questionDocument = questionDocument .replace( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", ""); return questionDocument; } private List<AltText> formAltText(Map<String, Translation> translationMap) { List<AltText> altTextList = new ArrayList<AltText>(); if (translationMap != null) { for (Translation lang : translationMap.values()) { AltText alt = new AltText(); alt.setContent(lang.getText()); alt.setType("translation"); alt.setLanguage(lang.getLanguageCode()); altTextList.add(alt); } } return altTextList; } private void assembleQuestionGroups(Long surveyId, Long transactionId) { SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao(); List<SurveyXMLFragment> sxmlfList = sxmlfDao.listSurveyFragments( surveyId, SurveyXMLFragment.FRAGMENT_TYPE.QUESTION_GROUP, transactionId); StringBuilder sbQG = new StringBuilder(); for (SurveyXMLFragment item : sxmlfList) { sbQG.append(item.getFragment().getValue()); } StringBuilder completeSurvey = new StringBuilder(); String surveyHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><survey>"; String surveyFooter = "</survey>"; completeSurvey.append(surveyHeader); completeSurvey.append(sbQG.toString()); sbQG = null; completeSurvey.append(surveyFooter); SurveyContainerDao scDao = new SurveyContainerDao(); SurveyContainer sc = scDao.findBySurveyId(surveyId); if (sc == null) { sc = new SurveyContainer(); } sc.setSurveyDocument(new Text(completeSurvey.toString())); sc.setSurveyId(surveyId); scDao.save(sc); sendQueueMessage(SurveyAssemblyRequest.DISTRIBUTE_SURVEY, surveyId, null, transactionId); } }
/* * $Log: TransactionalStorage.java,v $ * Revision 1.5 2004-08-18 09:20:14 a1909356#db2admin * Add some logging * * Revision 1.4 2004/03/31 12:04:21 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * fixed javadoc * * Revision 1.3 2004/03/26 10:43:03 Johan Verrips <johan.verrips@ibissource.org> * added @version tag in javadoc * * Revision 1.2 2004/03/26 09:50:52 Johan Verrips <johan.verrips@ibissource.org> * Updated javadoc * * Revision 1.1 2004/03/23 17:26:40 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * initial version * */ package nl.nn.adapterframework.receivers; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.INamedObject; import nl.nn.adapterframework.core.ITransactionalStorage; import nl.nn.adapterframework.core.ICorrelatedPullingListener; import nl.nn.adapterframework.core.ISender; import nl.nn.adapterframework.core.IXAEnabled; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.core.TimeOutException; import org.apache.log4j.Logger; /** * Stores a message using a {@link ISender} and retrieves is back from a {@link ICorrelatedPullingListener listener}. * * <p><b>Configuration:</b> * <table border="1"> * <tr><th>attributes</th><th>description</th><th>default</th></tr> * <tr><td>{@link #setName(String) name}</td><td>name of the Pipe</td><td>&nbsp;</td></tr> * <tr><td><code>sender.*</td><td>any attribute of the sender instantiated by descendant classes</td><td>&nbsp;</td></tr> * <tr><td><code>listener.*</td><td>any attribute of the listener instantiated by descendant classes</td><td>&nbsp;</td></tr> * </table> * <table border="1"> * <tr><th>nested elements</th><th>description</th></tr> * <tr><td>{@link ISender sender}</td><td>specification of sender to send messages with</td></tr> * <tr><td>{@link ICorrelatedPullingListener listener}</td><td>specification of listener to listen to for replies</td></tr> * </table> * </p> * @version Id * @author Gerrit van Brakel * @since 4.1 */ public class TransactionalStorage implements ITransactionalStorage { public static final String version="$Id: TransactionalStorage.java,v 1.5 2004-08-18 09:20:14 a1909356#db2admin Exp $"; protected Logger log = Logger.getLogger(this.getClass()); private ISender sender=null; private ICorrelatedPullingListener listener=null; private String name; protected String getLogPrefix() { return "TransactionalStorage ["+getName()+"] "; } /** * Checks whether a sender is defined for this pipe. */ public void configure() throws ConfigurationException{ if (getSender()==null){ throw new ConfigurationException(getLogPrefix()+"has no sender defined"); } if (getListener()==null){ throw new ConfigurationException(getLogPrefix()+"has no listener defined"); } if (getSender().isSynchronous()) { throw new ConfigurationException(getLogPrefix()+"cannot have synchronous sender in TransactionalStorage"); } String senderName = getSender().getName(); if (senderName == null || senderName.equals("")) { getSender().setName(getName()+"-sender"); } getSender().configure(); getListener().configure(); } public boolean isTransacted() { return getSender()!=null && getSender() instanceof IXAEnabled && ((IXAEnabled)getSender()).isTransacted() && getListener()!=null && getListener() instanceof IXAEnabled && ((IXAEnabled)getListener()).isTransacted(); } public ICorrelatedPullingListener getListener() { return listener; } public ISender getSender() { return sender; } protected void setListener(ICorrelatedPullingListener listener) { this.listener = listener; log.debug("pipe ["+getName()+" registered listener ["+ listener.toString()+ "]"); } protected void setSender(ISender sender) { this.sender = sender; log.debug( "pipe [" + getName() + " registered sender [" + sender.getName() + "] with properties [" + sender.toString() + "]"); } public String getName() { return name; } public void setName(String name) { this.name = name; getSender().setName("sender of ["+name+"]"); if (getListener() instanceof INamedObject) { ((INamedObject) getListener()).setName("listener of ["+getName()+"]"); } } public void close() throws SenderException { log.info(getLogPrefix()+"is closing"); try { getSender().close(); } catch (SenderException e) { log.warn(getLogPrefix()+"exception closing sender", e); } if (getListener() != null) { try { log.info(getLogPrefix()+"is closing; closing listener"); getListener().close(); } catch (ListenerException e) { log.warn(getLogPrefix()+"Exception closing listener", e); } } } public void open() throws SenderException, ListenerException { log.debug(getLogPrefix()+"is opening"); getSender().open(); getListener().open(); } public void deleteMessage(String messageId) throws ListenerException { ICorrelatedPullingListener l = getListener(); Object rawmsg = null; try { rawmsg = l.getRawMessage(messageId, null); } catch (TimeOutException e) { } if (rawmsg ==null) { throw new ListenerException("["+getName()+"] timeout deleting message with handle ["+messageId+"] from storage"); } } public void storeMessage(String messageId, String message) throws SenderException { try { getSender().sendMessage(messageId, message); } catch (TimeOutException e) { throw new SenderException(e); } } }
package org.unitime.timetable.server.rooms; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import org.hibernate.Transaction; import org.springframework.stereotype.Service; import org.unitime.localization.impl.Localization; import org.unitime.timetable.ApplicationProperties; import org.unitime.timetable.defaults.CommonValues; import org.unitime.timetable.defaults.UserProperty; import org.unitime.timetable.gwt.command.client.GwtRpcException; import org.unitime.timetable.gwt.command.server.GwtRpcImplementation; import org.unitime.timetable.gwt.resources.GwtConstants; import org.unitime.timetable.gwt.resources.GwtMessages; import org.unitime.timetable.gwt.shared.RoomInterface; import org.unitime.timetable.gwt.shared.RoomInterface.RoomSharingModel; import org.unitime.timetable.gwt.shared.RoomInterface.RoomSharingOption; import org.unitime.timetable.gwt.shared.RoomInterface.RoomSharingRequest; import org.unitime.timetable.model.ChangeLog; import org.unitime.timetable.model.Department; import org.unitime.timetable.model.Location; import org.unitime.timetable.model.RoomDept; import org.unitime.timetable.model.dao.DepartmentDAO; import org.unitime.timetable.model.dao.LocationDAO; import org.unitime.timetable.security.SessionContext; import org.unitime.timetable.security.qualifiers.SimpleQualifier; import org.unitime.timetable.security.rights.Right; import org.unitime.timetable.util.Constants; import org.unitime.timetable.webutil.RequiredTimeTable; @Service("org.unitime.timetable.gwt.shared.RoomInterface$RoomSharingRequest") public class RoomSharingBackend implements GwtRpcImplementation<RoomSharingRequest, RoomSharingModel> { protected static final GwtConstants CONSTANTS = Localization.create(GwtConstants.class); protected static final GwtMessages MESSAGES = Localization.create(GwtMessages.class); @Override public RoomSharingModel execute(RoomSharingRequest request, SessionContext context) { switch (request.getOperation()) { case LOAD: return (request.isEventAvailability() ? loadEventAvailability(request, context) : loadRoomSharing(request, context)); case SAVE: return (request.isEventAvailability() ? saveEventAvailability(request, context) : saveRoomSharing(request, context)); default: return null; } } public RoomSharingModel loadRoomSharing(RoomSharingRequest request, SessionContext context) { context.checkPermission(request.getLocationId(), "Location", Right.RoomDetailAvailability); Location location = LocationDAO.getInstance().get(request.getLocationId()); RoomSharingModel model = new RoomSharingModel(); model.setId(location.getUniqueId()); model.setName(location.getLabel()); for (int i = 0; true; i++) { String mode = ApplicationProperties.getProperty("unitime.room.sharingMode" + (1 + i), i < CONSTANTS.roomSharingModes().length ? CONSTANTS.roomSharingModes()[i] : null); if (mode == null || mode.isEmpty()) break; model.addMode(new RoomInterface.RoomSharingDisplayMode(mode)); } boolean editable = context.hasPermission(location, Right.RoomEditAvailability); model.setDefaultEditable(editable); model.addOption(new RoomSharingOption(-1l, "#FFFFFF", MESSAGES.codeFreeForAll(), MESSAGES.legendFreeForAll(), editable)); model.addOption(new RoomSharingOption(-2l, "#696969", MESSAGES.codeNotAvailable(), MESSAGES.legendNotAvailable(), editable)); String defaultGridSize = RequiredTimeTable.getTimeGridSize(context.getUser()); if (defaultGridSize != null) for (int i = 0; i < model.getModes().size(); i++) { if (model.getModes().get(i).getName().equals(defaultGridSize)) { model.setDefaultMode(i); break; } } model.setDefaultHorizontal(CommonValues.HorizontalGrid.eq(context.getUser().getProperty(UserProperty.GridOrientation))); model.setDefaultOption(model.getOptions().get(0)); Set<Department> current = new TreeSet<Department>(); for (RoomDept rd: location.getRoomDepts()) current.add(rd.getDepartment()); for (Department d: current) model.addOption(new RoomSharingOption(d.getUniqueId(), "#" + d.getRoomSharingColor(current), d.getDeptCode(), d.getName() + (d.isExternalManager() ? " (EXT: " + d.getExternalMgrLabel() + ")" : ""), editable)); for (Department d: Department.findAllBeingUsed(context.getUser().getCurrentAcademicSessionId())) model.addOther(new RoomSharingOption(d.getUniqueId(), "#" + d.getRoomSharingColor(current), d.getDeptCode(), d.getName() + (d.isExternalManager() ? " (EXT: " + d.getExternalMgrLabel() + ")" : ""), editable)); Map<Character, Long> char2dept = new HashMap<Character, Long>(); char pref = '0'; if (location.getManagerIds() != null) { for (StringTokenizer stk = new StringTokenizer(location.getManagerIds(), ","); stk.hasMoreTokens();) { Long id = Long.valueOf(stk.nextToken()); char2dept.put(new Character(pref++), id); } } try { int idx = 0; for (int d = 0; d < Constants.NR_DAYS; d++) for (int t = 0; t < Constants.SLOTS_PER_DAY; t++) { pref = (location.getPattern() != null && idx < location.getPattern().length() ? location.getPattern().charAt(idx) : net.sf.cpsolver.coursett.model.RoomSharingModel.sFreeForAllPrefChar); idx++; if (pref == net.sf.cpsolver.coursett.model.RoomSharingModel.sNotAvailablePrefChar) { model.setOption(d, t, -2l); } else if (pref == net.sf.cpsolver.coursett.model.RoomSharingModel.sFreeForAllPrefChar) { model.setOption(d, t, -1l); } else { Long deptId = (char2dept == null ? null : char2dept.get(pref)); if (deptId == null) { try { deptId = new ArrayList<Department>(current).get(pref - '0').getUniqueId(); } catch (IndexOutOfBoundsException e) {} } model.setOption(d, t, deptId); } } } catch (NullPointerException e) { } catch (IndexOutOfBoundsException e) { } if (editable && !context.getUser().getCurrentAuthority().hasRight(Right.DepartmentIndependent)) { boolean control = false, allDept = true; for (RoomDept rd: location.getRoomDepts()) { if (rd.isControl()) control = context.getUser().getCurrentAuthority().hasQualifier(rd.getDepartment()); if (allDept && !context.getUser().getCurrentAuthority().hasQualifier(rd.getDepartment())) allDept = false; } model.setDefaultEditable(control || allDept); if (!control && !allDept) { for (int d = 0; d < 7; d++) for (int s = 0; s < 288; s ++) { RoomSharingOption option = model.getOption(d, s); model.setEditable(d, s, option != null && context.getUser().getCurrentAuthority().hasQualifier(new SimpleQualifier("Department", option.getId()))); } } } return model; } public RoomSharingModel saveRoomSharing(RoomSharingRequest request, SessionContext context) { context.checkPermission(request.getLocationId(), "Location", Right.RoomEditAvailability); Map<Long, Character> dept2char = new HashMap<Long, Character>(); dept2char.put(-1l, net.sf.cpsolver.coursett.model.RoomSharingModel.sFreeForAllPrefChar); dept2char.put(-2l, net.sf.cpsolver.coursett.model.RoomSharingModel.sNotAvailablePrefChar); String managerIds = ""; char pref = '0'; Set<Long> add = new HashSet<Long>(); for (RoomSharingOption option: request.getModel().getOptions()) { if (option.getId() >= 0) { managerIds += (managerIds.isEmpty() ? "" : ",") + option.getId(); dept2char.put(option.getId(), new Character(pref++)); add.add(option.getId()); } } String pattern = ""; for (int d = 0; d < 7; d++) for (int s = 0; s < 288; s ++) { RoomSharingOption option = request.getModel().getOption(d, s); pattern += dept2char.get(option.getId()); } org.hibernate.Session hibSession = LocationDAO.getInstance().getSession(); Transaction tx = hibSession.beginTransaction(); try { Location location = LocationDAO.getInstance().get(request.getLocationId(), hibSession); location.setManagerIds(managerIds); location.setPattern(pattern); for (Iterator<RoomDept> i = location.getRoomDepts().iterator(); i.hasNext(); ) { RoomDept rd = (RoomDept)i.next(); if (!add.remove(rd.getDepartment().getUniqueId())) { rd.getDepartment().getRoomDepts().remove(rd); i.remove(); hibSession.delete(rd); } } for (Long id: add) { RoomDept rd = new RoomDept(); rd.setControl(false); rd.setDepartment(DepartmentDAO.getInstance().get(id, hibSession)); rd.getDepartment().getRoomDepts().add(rd); rd.setRoom(location); location.getRoomDepts().add(rd); hibSession.saveOrUpdate(rd); } hibSession.saveOrUpdate(location); ChangeLog.addChange(hibSession, context, location, ChangeLog.Source.ROOM_DEPT_EDIT, ChangeLog.Operation.UPDATE, null, location.getControllingDepartment()); tx.commit(); return null; } catch (Exception ex) { tx.rollback(); if (ex instanceof GwtRpcException) throw (GwtRpcException)ex; throw new GwtRpcException(ex.getMessage(), ex); } } public RoomSharingModel loadEventAvailability(RoomSharingRequest request, SessionContext context) { context.checkPermission(request.getLocationId(), "Location", Right.RoomDetailEventAvailability); Location location = LocationDAO.getInstance().get(request.getLocationId()); RoomSharingModel model = new RoomSharingModel(); model.setId(location.getUniqueId()); model.setName(location.getLabel()); for (int i = 0; true; i++) { String mode = ApplicationProperties.getProperty("unitime.room.sharingMode" + (1 + i), i < CONSTANTS.roomSharingModes().length ? CONSTANTS.roomSharingModes()[i] : null); if (mode == null || mode.isEmpty()) break; model.addMode(new RoomInterface.RoomSharingDisplayMode(mode)); } boolean editable = context.hasPermission(location, Right.RoomEditEventAvailability); model.setDefaultEditable(editable); model.addOption(new RoomSharingOption(-1l, "#FFFFFF", MESSAGES.codeAvailable(), MESSAGES.legendAvailable(), editable)); model.addOption(new RoomSharingOption(-2l, "#696969", MESSAGES.codeNotAvailable(), MESSAGES.legendNotAvailable(), editable)); String defaultGridSize = RequiredTimeTable.getTimeGridSize(context.getUser()); if (defaultGridSize != null) for (int i = 0; i < model.getModes().size(); i++) { if (model.getModes().get(i).getName().equals(defaultGridSize)) { model.setDefaultMode(i); break; } } model.setDefaultHorizontal(CommonValues.HorizontalGrid.eq(context.getUser().getProperty(UserProperty.GridOrientation))); model.setDefaultOption(model.getOptions().get(0)); int idx = 0; for (int d = 0; d < Constants.NR_DAYS; d++) for (int t = 0; t < Constants.SLOTS_PER_DAY; t++) { char pref = (location.getEventAvailability() != null && idx < location.getEventAvailability().length() ? location.getEventAvailability().charAt(idx) : '0'); idx++; model.setOption(d, t, pref == '0' ? -1l : -2l); } return model; } public RoomSharingModel saveEventAvailability(RoomSharingRequest request, SessionContext context) { context.checkPermission(request.getLocationId(), "Location", Right.RoomEditEventAvailability); String availability = ""; for (int d = 0; d < 7; d++) for (int s = 0; s < 288; s ++) { RoomSharingOption option = request.getModel().getOption(d, s); availability += (option.getId() == -1l ? '0' : '1'); } org.hibernate.Session hibSession = LocationDAO.getInstance().getSession(); Transaction tx = hibSession.beginTransaction(); try { Location location = LocationDAO.getInstance().get(request.getLocationId(), hibSession); location.setEventAvailability(availability); hibSession.save(location); ChangeLog.addChange(hibSession, context, location, ChangeLog.Source.ROOM_DEPT_EDIT, ChangeLog.Operation.UPDATE, null, location.getControllingDepartment()); tx.commit(); return null; } catch (Exception ex) { tx.rollback(); if (ex instanceof GwtRpcException) throw (GwtRpcException)ex; throw new GwtRpcException(ex.getMessage(), ex); } } }
package org.bonej.ops.ellipsoid; import static java.util.stream.Collectors.toList; import static java.util.stream.Stream.generate; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.DoubleStream; import net.imagej.ops.Contingent; import net.imagej.ops.Op; import net.imagej.ops.special.function.AbstractBinaryFunctionOp; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.random.UnitSphereRandomVectorGenerator; import org.scijava.plugin.Plugin; import org.scijava.vecmath.Vector3d; /** * Generates isotropically located random points on an ellipsoid surface. * * @author Richard Domander */ @Plugin(type = Op.class) public class EllipsoidPoints extends AbstractBinaryFunctionOp<double[], Long, List<Vector3d>> implements Contingent { /** Smallest radius of the ellipsoid (x) */ private double a; /** Second radius of the ellipsoid (y) */ private double b; /** Largest radius of the ellipsoid (z) */ private double c; private static final Random rng = new Random(); private static UnitSphereRandomVectorGenerator sphereRng = new UnitSphereRandomVectorGenerator(3); /** * Creates random points on an ellipsoid surface. * * @param radii the radii of the ellipsoid. They'll be sorted in ascending * order. * @param n number of points to be created. * @return ellipsoid points. */ @Override public List<Vector3d> calculate(final double[] radii, final Long n) { Arrays.sort(radii); a = radii[0]; b = radii[1]; c = radii[2]; return sampleEllipsoidPoints(n); } /** * Sets the seed of the random generators used in point creation. * <p> * Setting a constant seed makes testing easier. * </p> * * @param seed the seed number. * @see Random#setSeed(long) * @see MersenneTwister#MersenneTwister(long) */ static void setSeed(final long seed) { rng.setSeed(seed); sphereRng = new UnitSphereRandomVectorGenerator(3, new MersenneTwister( seed)); } private List<Vector3d> sampleEllipsoidPoints(final long n) { final Supplier<Vector3d> spherePoint = () -> new Vector3d(sphereRng .nextVector()); // Probability function to keep a sphere point final double muMax = b * c; final Predicate<Vector3d> p = v -> rng.nextDouble() <= mu(v) / muMax; // Mapping function from sphere to ellipsoid final Function<Vector3d, Vector3d> toEllipsoid = v -> new Vector3d(a * v.x, b * v.y, c * v.z); return generate(spherePoint).filter(p).limit(n).map(toEllipsoid).collect( toList()); } /** * Calculates the &mu;-factor of a point. * * @param v a point on a unit sphere surface. * @return inverse ratio of ellipsoid surface area around given point. */ private double mu(final Vector3d v) { final DoubleStream terms = DoubleStream.of(a * c * v.y, a * b * v.z, b * c * v.x); final double sqSum = terms.map(x -> x * x).sum(); return Math.sqrt(sqSum); } @Override public boolean conforms() { final double[] radii = in1(); final Long n = in2(); return n >= 0 && radii.length == 3 && Arrays.stream(radii).allMatch( r -> r > 0 && Double.isFinite(r)); } }
package com.arnowouter.javaodoo; import com.arnowouter.javaodoo.defaults.OdooDefaults; import com.arnowouter.javaodoo.supportClasses.OdooDatabaseParams; import de.timroes.axmlrpc.XMLRPCException; import java.net.MalformedURLException; import static java.util.Collections.emptyList; /** * * @author Arno */ public class OdooCommonClient { OdooClient client; public OdooCommonClient(String protocol, String hostName) throws MalformedURLException { client = OdooClientFactory.createClient(protocol, hostName, OdooDefaults.DEFAULT_ODOO_PORT, OdooDefaults.COMMON_ENDPOINT); } public OdooCommonClient(String protocol, String hostName, int connectionPort) throws MalformedURLException{ client = OdooClientFactory.createClient(protocol,hostName,connectionPort,OdooDefaults.COMMON_ENDPOINT); } public OdooCommonClient(String protocol, String hostName, int connectionPort, boolean ignoreInvalidSSL) throws MalformedURLException { if(ignoreInvalidSSL) { client = OdooClientFactory.createUnsecureClient(protocol, hostName, connectionPort, OdooDefaults.COMMON_ENDPOINT); } else { client = OdooClientFactory.createClient(protocol, hostName, connectionPort, OdooDefaults.COMMON_ENDPOINT); } } private int authenticate(OdooDatabaseParams dbParams) throws XMLRPCException { return (int) client.call( OdooDefaults.ACTION_AUTHENTICATE, dbParams.getDatabaseName(), dbParams.getDatabaseLogin(), dbParams.getDatabasePassword(), emptyList() ); } private int getVersion() { return 0; } }
package model.supervised.neuralnetwork; import algorithms.gradient.Decent; import algorithms.gradient.GradientDecent; import com.google.common.util.concurrent.AtomicDouble; import data.DataSet; import gnu.trove.list.array.TIntArrayList; import gnu.trove.set.hash.TIntHashSet; import model.Predictable; import model.Trainable; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import utils.NumericalComputation; import utils.array.ArraySumUtil; import utils.random.RandomUtils; import utils.sort.SortIntDoubleUtils; import java.util.Arrays; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; public class NeuralNetwork implements Trainable, Predictable, GradientDecent, Decent { private static final Logger log = LogManager.getLogger(NeuralNetwork.class); public static double COST_DECENT_THRESHOLD = 0.00000001; public static double COST_COEF = 1; public static int MAX_THREADS = 4; public static int THREAD_WORK_LOAD = 200; // every thread should work at least 1 second public static int BATCH_WORK_LOAD = 500; public static int MAX_ROUND = 5000; public static int PRINT_GAP = 100; public static boolean PRINT_HIDDEN = false; public static double EPSILON = 1; public static double ALPHA = 0.01; // learning rate public static double LAMBDA = 0.0; // punish rate public static int BUCKET_COUNT = 1; // mini batch private double[][][] theta = null; private int[] structure = null; private int layerCount = 0; private boolean biased = true; private DataSet data = null; private ExecutorService service = null; private CountDownLatch countDownLatch = null; public NeuralNetwork(int[] structure, boolean bias) { this.structure = structure; this.biased = bias; } @Override public void initialize(DataSet d) { this.data = d; layerCount = structure.length; theta = new double[layerCount - 1][][]; for (int i = 1; i < layerCount; i++) { int layerIn = structure[i - 1]; int layerOut = structure[i]; if (i < layerCount - 1) { layerOut -= (biased ? 1 : 0); // output layer no bias other layer consider bias. } double[][] w = new double[layerOut][]; double epsilonInit = EPSILON * Math.sqrt(6 / (double)(layerIn + layerOut)); int randMin = Math.min(layerIn, layerOut); int randMax = Math.max(layerIn, layerOut) + 1; for (int j = 0; j < layerOut; j++) { w[j] = Arrays.stream(RandomUtils.randomIntRangeArray(randMin, randMax, layerIn)). mapToDouble(x -> epsilonInit * (x * 2.0 - 1)).toArray(); } theta[i - 1] = w; } log.debug("Initial theta: {}", Arrays.deepToString(theta)); log.info("Neural Network initialized, structure: {}, bias = {}", structure, biased); } @Override public double predict(double[] feature) { double[] labels = Arrays.stream(feedForward(feature, theta)).map(x -> x * 1000000).toArray(); int[] index = RandomUtils.getIndexes(labels.length); SortIntDoubleUtils.sort(index, labels); return index[index.length - 1]; } @Override public double score(double[] feature) { double[] labels = Arrays.stream(feedForward(feature, theta)).map(x -> x * 1000000).toArray(); int[] index = RandomUtils.getIndexes(labels.length); SortIntDoubleUtils.sort(index, labels); return index[index.length - 1] == 1 ? labels[index.length - 1] / (double) 1000000 : 1 - labels[index.length - 1] / (double) 1000000; } @Override public double[] probs(double[] feature) { return ArraySumUtil.normalize(feedForward(feature, theta)); } @Override public void train() { log.info("Training started .."); loop(data.getInstanceLength(), BUCKET_COUNT, theta, COST_DECENT_THRESHOLD, MAX_ROUND, PRINT_GAP); log.info("Training finished ..."); } @Override public <T> double cost(T params) { double[][][] theta = (double[][][]) params; AtomicDouble cost = new AtomicDouble(0); int costCalcLength = (int) (data.getInstanceLength() * COST_COEF); service = Executors.newFixedThreadPool(MAX_THREADS); int packageCount = (int) Math.ceil(costCalcLength / (double) THREAD_WORK_LOAD); countDownLatch = new CountDownLatch(packageCount); TIntArrayList indices = new TIntArrayList(RandomUtils.getIndexes(data.getInstanceLength())); indices.shuffle(new Random()); int[] indicesArray = indices.toArray(); TIntHashSet tasks = new TIntHashSet(); IntStream.range(0, costCalcLength).forEach(i -> { tasks.add(indicesArray[i]); if (tasks.size() == THREAD_WORK_LOAD || i == costCalcLength - 1) { TIntHashSet tasks2 = new TIntHashSet(tasks); service.submit(() -> { try { for (int taskId : tasks2.toArray()) { double[] X = data.getInstance(taskId); double y = data.getLabel(taskId); double[] labels = feedForward(X, theta); cost.getAndAdd(- Math.log(labels[(int) y])); } } catch (Throwable t) { log.error(t.getMessage(), t); } countDownLatch.countDown(); }); tasks.clear(); } } ); try { TimeUnit.MILLISECONDS.sleep(10); countDownLatch.await(); } catch (InterruptedException e) { log.error(e.getMessage(), e); } service.shutdown(); double punish = 0; for (int i = 0; i < theta.length; i++) for (int j = 0; j < theta[i].length; j++) for (int k = 1; k < theta[i][j].length; k++) punish += Math.pow(theta[i][j][k], 2); return (cost.get() + punish * LAMBDA) / costCalcLength; } @Override public <T> void gGradient(int start, int end, T params) { double[][][] theta = (double[][][]) params; service = Executors.newFixedThreadPool(MAX_THREADS); int packageCount = (int) Math.ceil((end - start) / (double) THREAD_WORK_LOAD); countDownLatch = new CountDownLatch(packageCount); TIntArrayList indices = new TIntArrayList(IntStream.range(start, end).toArray()); indices.shuffle(new Random()); int[] indicesArray = indices.toArray(); TIntHashSet tasks = new TIntHashSet(); IntStream.range(0, indicesArray.length).forEach(i ->{ tasks.add(indicesArray[i]); if (tasks.size() == THREAD_WORK_LOAD || i == indicesArray.length - 1) { TIntArrayList tasks2 = new TIntArrayList(tasks); service.submit(() -> { try{ TIntHashSet batchTasks = new TIntHashSet(BATCH_WORK_LOAD); for (int batchTaskIdIdx = 0; batchTaskIdIdx < tasks2.size(); batchTaskIdIdx++) { batchTasks.add(tasks2.get(batchTaskIdIdx)); if(batchTasks.size() == BATCH_WORK_LOAD || batchTaskIdIdx == tasks2.size() - 1) { double[][][] gradient = new double[theta.length][][]; for (int j = 0; j < theta.length; j++) { gradient[j] = new double[theta[j].length][theta[j][0].length]; } Arrays.stream(batchTasks.toArray()).forEach(taskId -> backPropagation(taskId, gradient)); for (int j = 0; j < gradient.length; j++) for (int k = 0; k < gradient[j].length; k++) for (int l = 0; l < gradient[j][k].length; l++) gradient[j][k][l] = ALPHA * gradient[j][k][l] / (double) batchTasks.size() + (l > 0 ? LAMBDA * theta[j][k][l] : 0); synchronized (theta) { for (int j = 0; j < gradient.length; j++) for (int k = 0; k < gradient[j].length; k++) for (int l = 0; l < gradient[j][k].length; l++) theta[j][k][l] -= gradient[j][k][l]; } batchTasks.clear(); } } }catch (Throwable t){ log.error(t.getMessage(), t); } countDownLatch.countDown(); }); tasks.clear(); } } ); try { TimeUnit.MILLISECONDS.sleep(10); countDownLatch.await(); } catch (InterruptedException e) { log.error(e.getMessage(), e); } service.shutdown(); } private static final double sigmG1 = NumericalComputation.sigmoidGradient(1.0); private void backPropagation(int i, double[][][] tempGradient) { double[] X = data.getInstance(i); double[] yVector = yVector(i); double[][] Z = new double[layerCount][]; double[][] A = new double[layerCount][]; A[0] = X; for (int j = 1; j < layerCount; j++) { double[][] currentLayerTheta = theta[j - 1]; Z[j] = new double[currentLayerTheta.length]; for (int k = 0; k < currentLayerTheta.length; k++) { double[] w = currentLayerTheta[k]; Z[j][k] = z(A[j - 1], w); } double[] AZ = a(Z[j]); if (j < layerCount - 1 && biased) { int activeNodeLength = Z[j].length + 1; A[j] = new double[activeNodeLength]; A[j][0] = 1; System.arraycopy(AZ, 0, A[j], 1, AZ.length); } else { A[j] = AZ; } } double[][] DELTA = new double[layerCount][]; DELTA[layerCount - 1] = IntStream.range(0, yVector.length).mapToDouble(idx -> A[layerCount - 1][idx] - yVector[idx]).toArray(); for (int j = layerCount - 2; j >= 1; --j) { double[][] currentLayerTheta = theta[j]; double[] currentZ = Z[j]; double[] sigmG; if (biased) { sigmG = new double[currentZ.length + 1]; IntStream.range(1, sigmG.length).forEach(k -> sigmG[k] = NumericalComputation.sigmoidGradient(currentZ[k - 1])); sigmG[0] = sigmG1; DELTA[j] = new double[currentLayerTheta[0].length - 1]; for (int k = 0; k < DELTA[j].length; k++) { DELTA[j][k] = z(DELTA[j + 1], currentLayerTheta, k + 1) * sigmG[k + 1]; } }else { sigmG = new double[currentZ.length]; IntStream.range(0, currentZ.length).forEach(k -> sigmG[k] = NumericalComputation.sigmoidGradient(currentZ[k])); DELTA[j] = new double[currentLayerTheta[0].length]; for (int k = 0; k < DELTA[j].length; k++) { DELTA[j][k] = z(DELTA[j + 1], currentLayerTheta, k) * sigmG[k]; } } } for (int j = 0; j < tempGradient.length; j++) for (int k = 0; k < tempGradient[j].length; k++) for (int l = 0; l < tempGradient[j][k].length; l++) tempGradient[j][k][l] += DELTA[j + 1][k] * A[j][l]; } public double[] feedForward(double[] feature, double[][][] theta) { double[] X = feature; double[][] Z = new double[layerCount][]; double[][] A = new double[layerCount][]; A[0] = X; for (int j = 1; j < layerCount; j++) { double[][] currentLayerTheta = theta[j - 1]; Z[j] = new double[currentLayerTheta.length]; for (int k = 0; k < currentLayerTheta.length; k++) { double[] w = currentLayerTheta[k]; Z[j][k] = z(A[j - 1], w); } double[] AZ = a(Z[j]); log.debug("HIDDEN Z: {}-{}", j, Z[j]); log.debug("HIDDEN A: {}-{}", j, AZ); if (j < layerCount - 1 && biased) { int activeNodeLength = Z[j].length + 1; A[j] = new double[activeNodeLength]; A[j][0] = 1; System.arraycopy(AZ, 0, A[j], 1, AZ.length); } else { A[j] = AZ; } } if (PRINT_HIDDEN) { for (int i = 1; i < A.length - 1; i++) { System.out.println("HIDDEN " + i + " : " + Arrays.toString(A[i])); } } return A[A.length - 1]; } private double[] a(double[] Z) { return Arrays.stream(Z).map(x -> NumericalComputation.sigmoid(x)).toArray(); } private double z(double[] A, double[] theta){ return IntStream.range(0, A.length).mapToDouble(i -> A[i] * theta[i]).sum(); } private double z(double[] A, double[][] theta, int col){ return IntStream.range(0, A.length).mapToDouble(i -> A[i] * theta[i][col]).sum(); } @Override public <T> void parameterGradient(int start, int end, T params) { gGradient(start, end, params); } public double[] yVector(int idx) { double y = data.getLabel(idx); double[] yVector = new double[structure[structure.length - 1]]; yVector[(int) y] = 1; return yVector; } public static void main(String[] args) { int[] struct = new int[]{6, 4, 2, 1}; NeuralNetwork mp = new NeuralNetwork(struct, false); mp.initialize(null); log.info(Arrays.deepToString(mp.theta)); } }
package net.mitchtech.xposed; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.Preference.OnPreferenceClickListener; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.ipaulpro.afilechooser.utils.FileUtils; import net.mitchtech.xposed.macroexpand.R; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.OutputStreamWriter; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; public class MacroPreferenceActivity extends PreferenceActivity { private static final String TAG = MacroPreferenceActivity.class.getSimpleName(); private static final String PKG_NAME = "net.mitchtech.xposed.macroexpand"; private static final int FORMAT_JSON = 0; private static final int FORMAT_AHK = 1; private static final int REQUEST_CODE = 6384; // onActivityResult request @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getPreferenceManager().setSharedPreferencesMode(Context.MODE_WORLD_READABLE); addPreferencesFromResource(R.xml.settings); getActionBar().setDisplayHomeAsUpEnabled(true); findPreference("prefImportMacros").setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { importFileChooser(); return false; } }); findPreference("prefExportMacros").setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { // exportMacros(FORMAT_JSON); exportMacros(FORMAT_AHK); return false; } }); } private void exportMacros(int format) { String json = getPreferenceScreen().getSharedPreferences().getString("json", ""); String path = Environment.getExternalStorageDirectory() + "/macros.txt"; List<MacroEntry> replacements = null; if (format == FORMAT_AHK) { Type type = new TypeToken<List<MacroEntry>>() { }.getType(); replacements = new Gson().fromJson(json, type); if (replacements == null || replacements.isEmpty()) { Toast.makeText(this, "Macro list empty, file not exported", Toast.LENGTH_SHORT).show(); return; } } try { FileOutputStream fileOutputStream = new FileOutputStream(path); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); if (format == FORMAT_AHK) { for (MacroEntry macro : replacements) { outputStreamWriter.append("::" + macro.actual + "::" + macro.replacement + "\n"); } } else if (format == FORMAT_JSON) { outputStreamWriter.append(json); } outputStreamWriter.close(); fileOutputStream.close(); Toast.makeText(this, "Macro list exported: " + path, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Log.e(TAG, "File export error:", e); } } private void importFileChooser() { // Use the GET_CONTENT intent from the utility class Intent target = FileUtils.createGetContentIntent(); // Create the chooser Intent target.setType(FileUtils.MIME_TYPE_TEXT); Intent intent = Intent.createChooser(target, getString(R.string.chooser_title)); try { startActivityForResult(intent, REQUEST_CODE); } catch (ActivityNotFoundException e) { // The reason for the existence of aFileChooser } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_CODE: // If the file selection was successful if (resultCode == RESULT_OK) { if (data != null) { // Get the URI of the selected file final Uri uri = data.getData(); Log.i(TAG, "Uri = " + uri.toString()); try { // Get the file path from the URI final String path = FileUtils.getPath(this, uri); Log.i(TAG, "path = " + path); // SharedPreferences.Editor editor = getPreferenceScreen() // .getSharedPreferences().edit(); // editor.putString("prefSoundFile", path); // editor.commit(); importConfirmDialog(); } catch (Exception e) { Log.e("FileSelectorTestActivity", "File select error", e); } } } break; } super.onActivityResult(requestCode, resultCode, data); } private void importConfirmDialog() { final AlertDialog.Builder alert = new AlertDialog.Builder(MacroPreferenceActivity.this); alert.setIcon(R.drawable.ic_launcher).setTitle("Append or Overwrite?") .setMessage("Do you want to overwrite your macro list or append imported entries? This operation cannot be undone!") .setPositiveButton("Overwrite", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // mList.remove(mListview.getItemAtPosition(position)); // if (mList.isEmpty()) { // mListEmptyTextView.setVisibility(View.VISIBLE); // mAdapter.notifyDataSetChanged(); // saveMacroList(); } }).setNeutralButton("Append", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); } }
package org.TexasTorque.TorqueLib.util; import com.sun.squawk.io.BufferedWriter; import com.sun.squawk.microedition.io.*; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Watchdog; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Hashtable; import javax.microedition.io.*; public class TorqueLogging extends Thread { private static TorqueLogging instance; private Watchdog watchdog; private FileConnection fileConnection = null; private BufferedWriter fileIO = null; private static String fileName = "TorqueLog.csv"; private String filePath = "file:///ni-rt/startup/"; private static boolean logToDashboard = false; private static long threadLoopTime = 2; private Hashtable table; private String keys; private String values; private int numLines; private boolean logData; public static void setFileName(String fileNm) { fileName = fileNm; } public static void setDashboardLogging(boolean log) { logToDashboard = log; } public static void setLoopTime(int loopTime) { threadLoopTime = loopTime; } public synchronized static TorqueLogging getInstance() { return (instance == null) ? instance = new TorqueLogging() : instance; } public TorqueLogging() { watchdog = Watchdog.getInstance(); try { fileConnection = (FileConnection) Connector.open(filePath + fileName); if(!fileConnection.exists()) { fileConnection.create(); fileIO = new BufferedWriter(new OutputStreamWriter(fileConnection.openOutputStream())); } else { fileIO = new BufferedWriter(new OutputStreamWriter(fileConnection.openOutputStream())); } } catch(IOException e) { System.err.println("Error creating file in TorqueLogging."); } table = new Hashtable(); keys = "FrameNumber,"; values = ""; numLines = 1; table.put("FrameNumber", "" + numLines); } public void setLogging(boolean log) { logData = log; } public void startLogging() { this.start(); } public void init() { if(logToDashboard) { SmartDashboard.putString("TorqueLog", keys); } else { writeKeysToFile(); } } public void run() { init(); DriverStation ds = DriverStation.getInstance(); while(true) { watchdog.feed(); while(ds.isDisabled() || !logData) { watchdog.feed(); } calculateValueString(); if(logToDashboard) { SmartDashboard.putString("TorqueLog", values); } else { writeValuesToFile(); } this.logValue("FrameNumber", numLines++); try { Thread.sleep(threadLoopTime); try { fileIO.flush(); } catch (IOException ex){} } catch (InterruptedException ex){} } } public synchronized void setKeyMapping(String mapping) { table.clear(); if(mapping.charAt(mapping.length() - 1) != ',') { mapping += ","; } keys = mapping; int start = 0; int index = 0; while(index != -1) { watchdog.feed(); index = keys.indexOf(",", start); if(index != -1) { String keyName = keys.substring(start, index); table.put(keyName, "0"); start = index + 1; } } } public synchronized void logValue(String name, int value) { if(table.get(name) == null) { keys += name + ","; } table.put(name, "" + value); SmartDashboard.putNumber(name, value); } public synchronized void logValue(String name, boolean value) { if(table.get(name) == null) { keys += name + ","; } table.put(name, "" + value); SmartDashboard.putBoolean(name, value); } public synchronized void logValue(String name, double value) { if(table.get(name) == null) { keys += name + ","; } table.put(name, "" + value); SmartDashboard.putNumber(name, value); } public synchronized void logValue(String name, String value) { if(table.get(name) == null) { keys += name + ","; } table.put(name, value); SmartDashboard.putString(name, value); } private void writeKeysToFile() { try { fileIO.write(keys.substring(0, keys.length() - 1)); } catch(IOException e){} } private void calculateValueString() { values = ""; int start = 0; int index = 0; boolean first = true; while(index != -1) { watchdog.feed(); index = keys.indexOf(",", start); if(index != -1) { String keyName = keys.substring(start, index); if(first) { values += table.get(keyName); first = false; } else { values += "," + table.get(keyName); } start = index + 1; } } } private void writeValuesToFile() { try { fileIO.newLine(); fileIO.write(values); } catch(IOException e){} } }
package org.appwork.utils.logging2; import java.util.HashSet; import java.util.Locale; import java.util.logging.ConsoleHandler; import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogRecord; import org.appwork.utils.logging.LogFormatter; /** * @author daniel * */ public class LogConsoleHandler extends ConsoleHandler { private HashSet<String> allowedLoggerNames = new HashSet<String>(); public LogConsoleHandler() { setLevel(Level.ALL); setFormatter(new LogFormatter()); } public HashSet<String> getAllowedLoggerNames() { return allowedLoggerNames; } @Override public boolean isLoggable(final LogRecord record) { final HashSet<String> lallowedLoggerNames = allowedLoggerNames; if (lallowedLoggerNames == null) { return false; } if (lallowedLoggerNames.size() == 0) { return true; } if (allowedLoggerNames.contains(record.getLoggerName().toLowerCase(Locale.ENGLISH))) { return true; } return false; } public void setAllowedLoggerNames(final String... strings) { if (strings == null) { allowedLoggerNames = null; return; } else { final HashSet<String> tmp = new HashSet<String>(); for (final String s : strings) { tmp.add(s.toLowerCase(Locale.ENGLISH)); } allowedLoggerNames = tmp; } } @Override public void setFilter(final Filter newFilter) throws SecurityException { } }
package org.codefx.lab.optional; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.Objects; import java.util.Optional; /** * Convenience class to wrap an {@link Optional} for serialization. * <p> * Note that it does not provide any of the methods {@code Optional} has as its only goal is to enable serialization. * But it holds a reference to the {@code Optional} which was used to create it (can be accessed with * {@link #asOptional()}). Instances of this class are immutable. * <p> * There are two ways to use this class to serialize instances which have an optional attribute. * <p> * <h2>Transform For (De)Serialization</h2> The attribute can be declared as * {@code transient Optional<T> optionalAttribute}, which will exclude it from serialization. * <p> * The class then needs to implement custom (de)serialization methods {@code writeObject} and {@code readObject}. They * must transform the {@code optionalAttribute} to a {@code SerializableOptional} when writing the object and after * reading such an instance transform it back to an {@code Optional}. * <p> * <h3>Code Example</h3> * * <pre> * private void writeObject(ObjectOutputStream out) throws IOException { * out.defaultWriteObject(); * out.writeObject( * SerializableOptional.fromOptional(optionalAttribute)); * } * * private void readObject(ObjectInputStream in) * throws IOException, ClassNotFoundException { * * in.defaultReadObject(); * optionalAttribute = * ((SerializableOptional<T>) in.readObject()).toOptional(); * } * </pre> * <h2>Transform For Access</h2> The attribute can be declared as {@code SerializableOptional<T> optionalAttribute}. * This will include it in the (de)serialization process so it does not need to be customized. * <p> * But methods interacting with the attribute need to get an {@code Optional} instead. This can easily be done by * writing the accessor methods such that they transform the attribute on each access. * <p> * Note that {@link #asOptional()} simply returns the {@code Optional} which with this instance was created so no * constructor needs to be invoked. * <p> * <h3>Code Example</h3> * * <pre> * public Optional<T> getOptionalAttribute() { * return optionalAttribute.asOptional(); * } * * private void setOptionalAttribute(Optional<T> optionalAttribute) { * this.optionalAttribute = SerializableOptional.fromOptional(optionalAttribute); * } * </pre> * * @param <T> * the type of the wrapped value */ public final class SerializableOptional<T extends Serializable> implements Serializable { // ATTRIBUTES private static final long serialVersionUID = -652697447004597911L; /** * The wrapped {@link Optional}. Note that this attribute is transient so it will not be (de)serializd * automatically. */ private final Optional<T> optional; // CONSTRUCTION AND TRANSFORMATION private SerializableOptional(Optional<T> optional) { Objects.requireNonNull(optional, "The argument 'optional' must not be null."); this.optional = optional; } /** * Creates a serializable optional from the specified optional. * * @param optional * the {@link Optional} from which the serializable wrapper will be created * @return a {@link SerializableOptional} which wraps the specified optional */ public static <T extends Serializable> SerializableOptional<T> fromOptional(Optional<T> optional) { return new SerializableOptional<>(optional); } /** * Creates a serializable optional for the specified value by wrapping it in an {@link Optional} * * @param value * the value which will be contained in the wrapped {@link Optional}; may be null * @return a {@link SerializableOptional} which wraps the an optional for the specified value */ public static <T extends Serializable> SerializableOptional<T> ofNullable(T value) { return new SerializableOptional<>(Optional.ofNullable(value)); } /** * Returns the {@code Optional} instance which with this instance was created. * * @return this instance as an {@link Optional} */ public Optional<T> asOptional() { return optional; } // SERIALIZATION private Object writeReplace() { return new SerializationProxy<>(this); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { throw new InvalidObjectException("Serialization proxy expected."); } private static class SerializationProxy<T extends Serializable> implements Serializable { private static final long serialVersionUID = -1326520485869949065L; private final T value; public SerializationProxy(SerializableOptional<T> serializableOptional) { value = serializableOptional.asOptional().orElse(null); } private Object readResolve() { return SerializableOptional.ofNullable(value); } } }
package org.concord.framework.otrunk; import java.util.Vector; /** * This class can be used to create more complex OTObjects. * The OTObject interface can be used for simple interfaces * that adhere to the current conventions of the OTrunk. * If there is an interface that doesn't follow these conventions * you can extend this class and make an OTResourceSchema * interface to store the state. The OTrunk will create a * proxy class that implements this OTResourceSchema. * * TODO provide some pointers to examples. * * @author scott * */ public class DefaultOTObject implements OTObject, OTChangeNotifying { private OTResourceSchema resources; private Vector changeListeners = new Vector(); private OTChangeEvent changeEvent = new OTChangeEvent(this); public DefaultOTObject(OTResourceSchema resources) { this.resources = resources; } //public DefaultOTObject(Vector userList) { // this.userList = userList; public OTID getGlobalId() { return resources.getGlobalId(); } public String getName() { return resources.getName(); } public void setName(String name) { resources.setName(name); } /** * This method can be used by an object to get the object service * associated with this object. This service can be used for creating * new objects, and getting objects from ids. * @return */ public OTObjectService getOTObjectService() { return resources.getOTObjectService(); } public void init() { } public OTObject getReferencedObject(String id) { OTObjectService objService = resources.getOTObjectService(); OTID linkId = objService.getOTID(id); if(linkId == null) { return null; } return getReferencedObject(linkId); } public OTID getReferencedId(String id) { OTObjectService objService = resources.getOTObjectService(); return objService.getOTID(id); } public OTObject getReferencedObject(OTID id) { try { OTObjectService objService = resources.getOTObjectService(); return objService.getOTObject(id); } catch (Exception e) { e.printStackTrace(); return null; } } public int hashCode() { String str = getClass().getName() + "@" + getGlobalId(); return str.hashCode(); } public boolean equals(Object other) { if(!(other instanceof OTObject)){ return false; } if(this == other) { return true; } if(((OTObject)other).getGlobalId().equals(getGlobalId())) { System.err.println("compared two ot objects with the same ID but different instances"); return true; } return false; } /* (non-Javadoc) * @see org.concord.framework.otrunk.OTChangeNotifying#addOTChangeListener(org.concord.framework.otrunk.OTChangeListener) */ public void addOTChangeListener(OTChangeListener listener) { if(changeListeners.contains(listener)) return; changeListeners.add(listener); } /* (non-Javadoc) * @see org.concord.framework.otrunk.OTChangeNotifying#removeOTChangeListener(org.concord.framework.otrunk.OTChangeListener) */ public void removeOTChangeListener(OTChangeListener listener) { changeListeners.remove(listener); } protected void notifyOTChange() { for(int i=0;i<changeListeners.size(); i++){ ((OTChangeListener)changeListeners.get(i)).stateChanged(changeEvent); } } }
package org.cytoscape.data.reader.kgml; import giny.view.NodeView; import java.awt.Color; import java.awt.Font; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.cytoscape.data.reader.kgml.generated.Entry; import org.cytoscape.data.reader.kgml.generated.Graphics; import org.cytoscape.data.reader.kgml.generated.Pathway; import org.cytoscape.data.reader.kgml.generated.Product; import org.cytoscape.data.reader.kgml.generated.Reaction; import org.cytoscape.data.reader.kgml.generated.Relation; import org.cytoscape.data.reader.kgml.generated.Substrate; import org.cytoscape.data.reader.kgml.generated.Subtype; import cytoscape.CyEdge; import cytoscape.CyNetwork; import cytoscape.CyNode; import cytoscape.Cytoscape; import cytoscape.data.CyAttributes; import cytoscape.data.Semantics; import cytoscape.view.CyNetworkView; import cytoscape.visual.ArrowShape; import cytoscape.visual.EdgeAppearanceCalculator; import cytoscape.visual.GlobalAppearanceCalculator; import cytoscape.visual.LineStyle; import cytoscape.visual.NodeAppearanceCalculator; import cytoscape.visual.NodeShape; import cytoscape.visual.VisualPropertyType; import cytoscape.visual.VisualStyle; import cytoscape.visual.calculators.BasicCalculator; import cytoscape.visual.calculators.Calculator; import cytoscape.visual.mappings.DiscreteMapping; import cytoscape.visual.mappings.ObjectMapping; import cytoscape.visual.mappings.PassThroughMapping; public class PathwayMapper { private final Pathway pathway; private final String pathwayName; private int[] nodeIdx; private int[] edgeIdx; private static final String KEGG_NAME = "KEGG.name"; private static final String KEGG_ENTRY_TYPE = "KEGG.entry"; private static final String KEGG_LABEL = "KEGG.label"; private static final String KEGG_RELATION_TYPE = "KEGG.relation"; private static final String KEGG_REACTION_TYPE = "KEGG.reaction"; private static final String KEGG_LINK = "KEGG.link"; public PathwayMapper(final Pathway pathway) { this.pathway = pathway; this.pathwayName = pathway.getName(); } public void doMapping() { mapNode(); final List<CyEdge> relationEdges = mapRelationEdge(); final List<CyEdge> reactionEdges = mapReactionEdge(); edgeIdx = new int[relationEdges.size() + reactionEdges.size()]; int idx = 0; for (CyEdge edge : reactionEdges) { edgeIdx[idx] = edge.getRootGraphIndex(); idx++; } for (CyEdge edge : relationEdges) { edgeIdx[idx] = edge.getRootGraphIndex(); idx++; } } private final Map<String, Entry> entryMap = new HashMap<String, Entry>(); final Map<String, CyNode> nodeMap = new HashMap<String, CyNode>(); // final Map<String, CyNode> cpdMap = new HashMap<String, CyNode>(); final Map<String, CyNode> id2cpdMap = new HashMap<String, CyNode>(); final Map<String, List<Entry>> cpdDataMap = new HashMap<String, List<Entry>>(); final Map<CyNode, Entry> geneDataMap = new HashMap<CyNode, Entry>(); private final Map<CyNode, String> entry2reaction = new HashMap<CyNode, String>(); private void mapNode() { final String pathwayID = pathway.getName(); final List<Entry> components = pathway.getEntry(); final CyAttributes nodeAttr = Cytoscape.getNodeAttributes(); for (final Entry comp : components) { for (Graphics grap : comp.getGraphics()) { if (!grap.getType().equals(KEGGShape.LINE.getTag())) { CyNode node = Cytoscape.getCyNode(pathwayID + "-" + comp.getId(), true); nodeAttr.setAttribute(node.getIdentifier(), KEGG_NAME, comp .getName()); if (comp.getLink() != null) nodeAttr.setAttribute(node.getIdentifier(), KEGG_LINK, comp.getLink()); nodeAttr.setAttribute(node.getIdentifier(), KEGG_ENTRY_TYPE, comp.getType()); final String reaction = comp.getReaction(); // Save reaction if (reaction != null) { entry2reaction.put(node, reaction); nodeAttr.setAttribute(node.getIdentifier(), "KEGG.reaction", reaction); } // final Graphics graphics = comp.getGraphics(); if (grap != null && grap.getName() != null) { nodeAttr.setAttribute(node.getIdentifier(), KEGG_LABEL, grap.getName()); } nodeMap.put(comp.getId(), node); entryMap.put(comp.getId(), comp); if (comp.getType().equals(KEGGEntryType.COMPOUND.getTag())) { id2cpdMap.put(comp.getId(), node); List<Entry> current = cpdDataMap.get(comp.getName()); if (current != null) { current.add(comp); } else { current = new ArrayList<Entry>(); current.add(comp); } cpdDataMap.put(comp.getName(), current); } else if (comp.getType().equals( KEGGEntryType.GENE.getTag()) || comp.getType().equals( KEGGEntryType.ORTHOLOG.getTag())) { geneDataMap.put(node, comp); } } } } nodeIdx = new int[nodeMap.values().size()]; int idx = 0; for (CyNode node : nodeMap.values()) { nodeIdx[idx] = node.getRootGraphIndex(); idx++; } } private List<CyEdge> mapRelationEdge() { final List<Relation> relations = pathway.getRelation(); final List<CyEdge> edges = new ArrayList<CyEdge>(); final CyAttributes edgeAttr = Cytoscape.getEdgeAttributes(); for (Relation rel : relations) { final String type = rel.getType(); if (rel.getType().equals(KEGGRelationType.MAPLINK.getTag())) { final List<Subtype> subs = rel.getSubtype(); if (entryMap.get(rel.getEntry1()).getType().equals( KEGGEntryType.MAP.getTag())) { CyNode maplinkNode = nodeMap.get(rel.getEntry1()); for (Subtype sub : subs) { CyNode cpdNode = nodeMap.get(sub.getValue()); System.out.println(maplinkNode.getIdentifier()); System.out.println(cpdNode.getIdentifier() + "\n\n"); CyEdge edge1 = Cytoscape.getCyEdge(cpdNode, maplinkNode, Semantics.INTERACTION, type, true, true); edges.add(edge1); edgeAttr.setAttribute(edge1.getIdentifier(), KEGG_RELATION_TYPE, type); CyEdge edge2 = Cytoscape.getCyEdge(maplinkNode, cpdNode, Semantics.INTERACTION, type, true, true); edges.add(edge2); // edgeAttr.setAttribute(edge2.getIdentifier(), // KEGG_RELATION_TYPE, type); } } else { CyNode maplinkNode = nodeMap.get(rel.getEntry2()); for (Subtype sub : subs) { CyNode cpdNode = nodeMap.get(sub.getValue()); System.out.println(maplinkNode.getIdentifier()); System.out.println(cpdNode.getIdentifier() + "\n\n"); CyEdge edge1 = Cytoscape.getCyEdge(cpdNode, maplinkNode, Semantics.INTERACTION, type, true, true); edges.add(edge1); edgeAttr.setAttribute(edge1.getIdentifier(), KEGG_RELATION_TYPE, type); CyEdge edge2 = Cytoscape.getCyEdge(maplinkNode, cpdNode, Semantics.INTERACTION, type, true, true); edges.add(edge2); // edgeAttr.setAttribute(edge2.getIdentifier(), // KEGG_RELATION_TYPE, type); } } } } return edges; } private List<CyEdge> mapReactionEdge() { final String pathwayID = pathway.getName(); final List<Reaction> reactions = pathway.getReaction(); final List<CyEdge> edges = new ArrayList<CyEdge>(); CyAttributes edgeAttr = Cytoscape.getEdgeAttributes(); Pattern pattern = Pattern.compile(".*01100"); if (pattern.matcher(pathwayID).matches()) { for (Reaction rea : reactions) { for (Substrate sub : rea.getSubstrate()) { CyNode subNode = nodeMap.get(sub.getId()); for (Product pro : rea.getProduct()) { CyNode proNode = nodeMap.get(pro.getId()); CyEdge edge = Cytoscape.getCyEdge(subNode, proNode, Semantics.INTERACTION, "cc", true); edges.add(edge); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); } } } } else { for (Reaction rea : reactions) { CyNode reaNode = nodeMap.get(rea.getId()); System.out.println(rea.getId()); System.out.println(reaNode.getIdentifier()); if (rea.getType().equals("irreversible")) { for (Substrate sub : rea.getSubstrate()) { CyNode subNode = nodeMap.get(sub.getId()); CyEdge edge = Cytoscape.getCyEdge(subNode, reaNode, Semantics.INTERACTION, "cr", true, true); edges.add(edge); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); } for (Product pro : rea.getProduct()) { CyNode proNode = nodeMap.get(pro.getId()); CyEdge edge = Cytoscape.getCyEdge(reaNode, proNode, Semantics.INTERACTION, "rc", true, true); edges.add(edge); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(edge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); } } else { for (Substrate sub : rea.getSubstrate()) { System.out.println(sub.getId()); CyNode subNode = nodeMap.get(sub.getId()); System.out.println(subNode.getIdentifier()); CyEdge subEdge = Cytoscape.getCyEdge(subNode, reaNode, Semantics.INTERACTION, "cr", true, true); edges.add(subEdge); edgeAttr.setAttribute(subEdge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(subEdge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); CyEdge proEdge = Cytoscape.getCyEdge(reaNode, subNode, Semantics.INTERACTION, "rc", true, true); edges.add(proEdge); edgeAttr.setAttribute(proEdge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(proEdge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); } for (Product pro : rea.getProduct()) { CyNode proNode = nodeMap.get(pro.getId()); CyEdge proEdge = Cytoscape.getCyEdge(reaNode, proNode, Semantics.INTERACTION, "rc", true, true); edges.add(proEdge); edgeAttr.setAttribute(proEdge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(proEdge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); CyEdge subEdge = Cytoscape.getCyEdge(proNode, reaNode, Semantics.INTERACTION, "cr", true, true); edges.add(subEdge); edgeAttr.setAttribute(subEdge.getIdentifier(), KEGG_NAME, rea.getName()); edgeAttr.setAttribute(subEdge.getIdentifier(), KEGG_REACTION_TYPE, rea.getType()); } } } } return edges; } protected void updateView(final CyNetwork network) { final String vsName = "KEGG: " + pathway.getTitle() + "(" + pathwayName + ")"; final VisualStyle defStyle = new VisualStyle(vsName); NodeAppearanceCalculator nac = defStyle.getNodeAppearanceCalculator(); EdgeAppearanceCalculator eac = defStyle.getEdgeAppearanceCalculator(); GlobalAppearanceCalculator gac = defStyle .getGlobalAppearanceCalculator(); // Default values final Color nodeColor = Color.WHITE; final Color nodeLineColor = new Color(20, 20, 20); final Color nodeLabelColor = new Color(30, 30, 30); final Color geneNodeColor = new Color(153, 255, 153); final Font nodeLabelFont = new Font("SansSerif", 7, Font.PLAIN); gac.setDefaultBackgroundColor(Color.white); final PassThroughMapping m = new PassThroughMapping("", KEGG_LABEL); final Calculator nodeLabelMappingCalc = new BasicCalculator(vsName + "-" + "NodeLabelMapping", m, VisualPropertyType.NODE_LABEL); nac.setCalculator(nodeLabelMappingCalc); nac.setNodeSizeLocked(false); nac.getDefaultAppearance().set(VisualPropertyType.NODE_FILL_COLOR, nodeColor); nac.getDefaultAppearance().set(VisualPropertyType.NODE_SHAPE, NodeShape.ROUND_RECT); nac.getDefaultAppearance().set(VisualPropertyType.NODE_BORDER_COLOR, nodeLineColor); nac.getDefaultAppearance().set(VisualPropertyType.NODE_LINE_WIDTH, 1); nac.getDefaultAppearance().set(VisualPropertyType.NODE_LABEL_COLOR, nodeLabelColor); nac.getDefaultAppearance().set(VisualPropertyType.NODE_FONT_FACE, nodeLabelFont); nac.getDefaultAppearance().set(VisualPropertyType.NODE_FONT_SIZE, 6); // Default Edge appr eac.getDefaultAppearance().set(VisualPropertyType.EDGE_TGTARROW_SHAPE, ArrowShape.DELTA); final DiscreteMapping edgeLineStyle = new DiscreteMapping( LineStyle.SOLID, KEGG_RELATION_TYPE, ObjectMapping.EDGE_MAPPING); final Calculator edgeLineStyleCalc = new BasicCalculator(vsName + "-" + "EdgeLineStyleMapping", edgeLineStyle, VisualPropertyType.EDGE_LINE_STYLE); edgeLineStyle.putMapValue(KEGGRelationType.MAPLINK.getTag(), LineStyle.LONG_DASH); eac.setCalculator(edgeLineStyleCalc); final DiscreteMapping nodeShape = new DiscreteMapping(NodeShape.RECT, KEGG_ENTRY_TYPE, ObjectMapping.NODE_MAPPING); final Calculator nodeShapeCalc = new BasicCalculator(vsName + "-" + "NodeShapeMapping", nodeShape, VisualPropertyType.NODE_SHAPE); nodeShape.putMapValue(KEGGEntryType.MAP.getTag(), NodeShape.ROUND_RECT); nodeShape.putMapValue(KEGGEntryType.GENE.getTag(), NodeShape.RECT); nodeShape.putMapValue(KEGGEntryType.ORTHOLOG.getTag(), NodeShape.RECT); nodeShape.putMapValue(KEGGEntryType.COMPOUND.getTag(), NodeShape.ELLIPSE); nac.setCalculator(nodeShapeCalc); final DiscreteMapping nodeColorMap = new DiscreteMapping(nodeColor, KEGG_ENTRY_TYPE, ObjectMapping.NODE_MAPPING); final Calculator nodeColorCalc = new BasicCalculator(vsName + "-" + "NodeColorMapping", nodeColorMap, VisualPropertyType.NODE_FILL_COLOR); nodeColorMap.putMapValue(KEGGEntryType.GENE.getTag(), geneNodeColor); nac.setCalculator(nodeColorCalc); final DiscreteMapping nodeBorderColorMap = new DiscreteMapping( nodeColor, KEGG_ENTRY_TYPE, ObjectMapping.NODE_MAPPING); final Calculator nodeBorderColorCalc = new BasicCalculator(vsName + "-" + "NodeBorderColorMapping", nodeBorderColorMap, VisualPropertyType.NODE_BORDER_COLOR); nodeBorderColorMap.putMapValue(KEGGEntryType.MAP.getTag(), Color.BLUE); nac.setCalculator(nodeBorderColorCalc); final DiscreteMapping nodeWidth = new DiscreteMapping(30, "ID", ObjectMapping.NODE_MAPPING); final Calculator nodeWidthCalc = new BasicCalculator(vsName + "-" + "NodeWidthMapping", nodeWidth, VisualPropertyType.NODE_WIDTH); final DiscreteMapping nodeHeight = new DiscreteMapping(30, "ID", ObjectMapping.NODE_MAPPING); final Calculator nodeHeightCalc = new BasicCalculator(vsName + "-" + "NodeHeightMapping", nodeHeight, VisualPropertyType.NODE_HEIGHT); nac.setCalculator(nodeHeightCalc); nac.setCalculator(nodeWidthCalc); final CyNetworkView view = Cytoscape.getNetworkView(network .getIdentifier()); final CyAttributes nodeAttr = Cytoscape.getNodeAttributes(); nodeWidth.setControllingAttributeName("ID", null, false); nodeHeight.setControllingAttributeName("ID", null, false); for (String key : nodeMap.keySet()) { for (Graphics nodeGraphics : entryMap.get(key).getGraphics()) { if (KEGGShape.getShape(nodeGraphics.getType()) != -1) { final String nodeID = nodeMap.get(key).getIdentifier(); final NodeView nv = view.getNodeView(nodeMap.get(key)); nv.setXPosition(Double.parseDouble(nodeGraphics.getX())); nv.setYPosition(Double.parseDouble(nodeGraphics.getY())); final double w = Double .parseDouble(nodeGraphics.getWidth()); nodeAttr.setAttribute(nodeID, "KEGG.nodeWidth", w); nodeWidth.putMapValue(nodeID, w); final double h = Double.parseDouble(nodeGraphics .getHeight()); nodeAttr.setAttribute(nodeID, "KEGG.nodeHeight", h); nodeHeight.putMapValue(nodeID, h); nv.setShape(KEGGShape.getShape(nodeGraphics.getType())); } } } Cytoscape.getVisualMappingManager().getCalculatorCatalog() .addVisualStyle(defStyle); Cytoscape.getVisualMappingManager().setVisualStyle(defStyle); view.setVisualStyle(defStyle.getName()); Cytoscape.getVisualMappingManager().setNetworkView(view); view.redrawGraph(false, true); } public int[] getNodeIdx() { return nodeIdx; } public int[] getEdgeIdx() { return edgeIdx; } }
package org.neuvoo.profileinspector; import java.io.*; import org.jargp.*; import java.util.Vector; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.regex.Pattern; public class ProfileInspector { private String action = ""; private String profile = ""; private String search = ""; private boolean verbose = false; private boolean minus = false; public Profile processProfile () throws ArgumentErrorException, IOException { if (this.action.equals("")) { this.action = "i"; } if (this.action.equals("i")) { if (this.profile.equals("")) { throw new ArgumentErrorException ("action i requires profile path"); } else { if (this.verbose) System.out.println("Starting profile investigation at " + this.profile); } } else { throw new ArgumentErrorException ("invalid action " + this.action); } return new Profile(this.profile, new ProfileEnvironment(), this.verbose, this.minus, this.search); } private static final ParameterDef[] ARG_DEFS = { new StringDef('a', "action", "the action to take with a/the profile"), new StringDef('p', "profile", "the path to the profile to investigate"), new StringDef('s', "search", "search for a string in the profile"), new BoolDef('v', "verbose", "Supress extra information normally printed prior to results"), new BoolDef('m', "minus", "Do not let the minus prefix vanish") }; public static void main (String args[]) { ProfileInspector profileInspector = new ProfileInspector(); Profile resultingProfile = null; if (args.length < 1 || args[0].indexOf("help") >= 0) { usage(); System.exit(0); } else { try { ArgumentProcessor.processArgs(args, ARG_DEFS, profileInspector); resultingProfile = profileInspector.processProfile(); } catch (ArgumentErrorException e) { System.err.println("Error processing command-line arguments: " + e.getMessage()); usage(); System.exit(255); } catch (Exception e) { System.err.println("Error proccessing:"); e.printStackTrace(); System.exit(1); } System.out.println(resultingProfile.getHumanOutput()); } } public static void usage () { System.out.println("Usage: java ProfileInspector [-a <action>] [options]"); System.out.println(""); System.out.println("Actions:"); System.out.println(" i Default. Investigate the profile, and print out\n" + " accumulated profile information (requires -p)"); System.out.println(""); System.out.println("Options:"); System.out.println(" -p <path> The path to the profile to investigate"); System.out.println(""); System.out.println(" -s <string> Search for any mention of string and report to\n" + " stderr."); } } class ProfileEnvironment { private HashMap<String,HashMap<String,Vector<String>>> variables = new HashMap<String,HashMap<String,Vector<String>>>(); public void setVars (String category, String key, Vector<String> value) { HashMap<String,Vector<String>> currCategory = this.variables.get(category); if (currCategory == null) { currCategory = new HashMap<String,Vector<String>>(); } currCategory.put(key, value); this.variables.put(category, currCategory); } public Vector<String> getVars (String category, String key) { HashMap<String,Vector<String>> currCategory = this.variables.get(category); if (currCategory == null) { currCategory = new HashMap<String,Vector<String>>(); } Vector<String> values = currCategory.get(key); if (values == null) { values = new Vector<String>(); } return values; } public HashMap<String,Vector<String>> getCategoryKeys (String category) { HashMap<String,Vector<String>> currCategory = this.variables.get(category); if (currCategory == null) { currCategory = new HashMap<String,Vector<String>>(); } return currCategory; } public HashMap<String,HashMap<String,Vector<String>>> getCategories () { return this.variables; } public void setCategoryKeys (String category, HashMap<String,Vector<String>> currCategory) { this.variables.put(category, currCategory); } } class ProfileFile { public static final int TYPE_IGNORE = 1; public static final int TYPE_2D = 2; // means there is only one lineRule public static final int TYPE_3D = 3; // means there is two lineRules public static final int TYPE_KEYVAL_BASH = 4; public static final int MAX_TYPE = TYPE_KEYVAL_BASH; private int type = TYPE_2D; public static final int NOEXISTS_CAN_BLANK = 1; public static final int NOEXISTS_CAN_IGNORE = 2; public static final int MAX_NOEXISTS = (NOEXISTS_CAN_IGNORE*2)-1; private boolean noExistsCanBlank = false; private boolean noExistsCanIgnore = false; public static final int EXCEPT_NO_BLANK = 1; public static final int EXCEPT_NO_COMMENT = 2; public static final int EXCEPT_NO_LINE_CONT = 4; public static final int MAX_EXCEPT = (EXCEPT_NO_LINE_CONT*2)-1; private boolean exceptNoBlank = false; private boolean exceptNoComment = false; private boolean exceptNoLineCont = false; // lineRule[][0] public static final int LINEPIECE_PREFIX_NONE = 1; public static final int LINEPIECE_PREFIX_MINUS = 2; // It's important MINUS is here so it doesn't mess up regexp with ranges (which use hyphens) public static final int LINEPIECE_PREFIX_PLUS = 4; public static final int LINEPIECE_PREFIX_ASTERIK = 8; public static final int LINEPIECE_PREFIX_SPECIAL_ONLY = 16; public static final String LINEPIECE_PREFIX_ALL = "-+*"; public static final int MAX_LINE_PREFIX = (LINEPIECE_PREFIX_SPECIAL_ONLY*2)-1; // lineRule[][1] public static final int LINEPIECE_TYPE_NUMBER = 1; public static final int LINEPIECE_TYPE_STRING = 2; public static final int LINEPIECE_TYPE_PACKAGE = 3; public static final int MAX_LINE_KEY = LINEPIECE_TYPE_PACKAGE; private int[][] lineRules = new int[][]{{LINEPIECE_PREFIX_NONE, LINEPIECE_TYPE_STRING}, {LINEPIECE_PREFIX_NONE, LINEPIECE_TYPE_STRING}}; public static final int INHERIT_NONE = 1; public static final int INHERIT_PARENT = 2; public static final int INHERIT_NO_APPEND = 4; public static final int INHERIT_APPEND_SPECIAL_ONLY = 8; public static final int MAX_INHERIT = (INHERIT_APPEND_SPECIAL_ONLY*2)-1; private boolean inherits = false; private boolean inheritsCanAppend = true; private boolean inheritsCanAppendSpecialOnly = false; public static final int DEPRECATED_NO = 1; public static final int DEPRECATED_YES = 2; public static final int MAX_DEPRECATED = DEPRECATED_YES; private int deprecation = DEPRECATED_NO; private String path = ""; private String fileName = ""; private int eapi = 0; private boolean verbose = false; private boolean showMinus = false; private String search = ""; public ProfileFile (String path, int type, int fileNonExistanceRules, int disallowedExceptions, int[][] lineRules, int inheritanceRules, int pmsDeprecationRules, boolean verbose, boolean showMinus, String search) { if (path != null && !path.equals("")) { this.path = path; this.fileName = new File(path).getName(); } else { throw new IllegalArgumentException ("Empty path"); } this.verbose = verbose; this.showMinus = showMinus; this.search = search; if (type > 0 && type <= MAX_TYPE) { this.type = type; } else { throw new IllegalArgumentException ("For path " + path + ", bad file type: " + type); } while (fileNonExistanceRules > 0) { if (fileNonExistanceRules >= NOEXISTS_CAN_IGNORE) { this.noExistsCanIgnore = true; fileNonExistanceRules -= NOEXISTS_CAN_IGNORE; } else if (fileNonExistanceRules >= NOEXISTS_CAN_BLANK) { this.noExistsCanBlank = true; fileNonExistanceRules -= NOEXISTS_CAN_BLANK; } else { throw new IllegalArgumentException ("For path " + path + ", bad rule number for non-existance rules: " + fileNonExistanceRules); } } while (disallowedExceptions > 0) { if (disallowedExceptions >= EXCEPT_NO_LINE_CONT) { this.exceptNoLineCont = true; disallowedExceptions -= EXCEPT_NO_LINE_CONT; } else if (disallowedExceptions >= EXCEPT_NO_COMMENT) { this.exceptNoComment = true; disallowedExceptions -= EXCEPT_NO_COMMENT; } else if (disallowedExceptions >= EXCEPT_NO_BLANK) { this.exceptNoBlank = true; disallowedExceptions -= EXCEPT_NO_BLANK; } else { throw new IllegalArgumentException ("For path " + path + ", bad rule number for disallowed exceptions: " + disallowedExceptions); } } if (lineRules.length > 0) { for (int i = 0; i < lineRules.length; i++) { if (lineRules[i].length < 2) { throw new IllegalArgumentException ("For path " + path + ", line part #" + i + " does not have the proper number of line rules: " + lineRules[i].length); } } this.lineRules = lineRules; } else { throw new IllegalArgumentException ("For path " + path + ", there are no line rules"); } while (inheritanceRules > 0) { if (inheritanceRules >= INHERIT_APPEND_SPECIAL_ONLY) { this.inheritsCanAppendSpecialOnly = true; inheritanceRules -= INHERIT_APPEND_SPECIAL_ONLY; } else if (inheritanceRules >= INHERIT_NO_APPEND) { this.inheritsCanAppend = false; inheritanceRules -= INHERIT_NO_APPEND; } else if (inheritanceRules >= INHERIT_PARENT) { this.inherits = true; inheritanceRules -= INHERIT_PARENT; } else if (inheritanceRules >= INHERIT_NONE) { this.inherits = false; inheritanceRules -= INHERIT_NONE; } else { throw new IllegalArgumentException ("For path " + path + ", bad rule number for inheritance: " + inheritanceRules); } } if (deprecation > 0 && deprecation <= MAX_DEPRECATED) { this.deprecation = deprecation; } else { throw new IllegalArgumentException ("For path " + path + ", bad rule number for deprecation: " + deprecation); } } public void mergeToEnvironment (ProfileEnvironment environment) throws FileNotFoundException, IOException { // Discern EAPI Vector<String> eapiData = environment.getVars("eapi", "list"); if (eapiData.size() > 0) { try { this.eapi = Integer.valueOf(eapiData.firstElement()); } catch (NumberFormatException e) { // ignore, just use default // PMS 5.2.2 } } // No inheritance? Then reset it. if (this.inherits == false) { environment.setCategoryKeys(this.fileName, new HashMap<String,Vector<String>>()); } // Open file BufferedReader br = null; boolean blankFile = false; try { br = new BufferedReader(new FileReader(path)); } catch (FileNotFoundException e) { if (verbose) System.err.println("File " + path + " does not exist."); if (this.noExistsCanBlank) { blankFile = true; } else if (this.noExistsCanIgnore) { return; // we don't exist } else { throw new FileNotFoundException ("Path not found, and does not appear optional: " + this.path); } } int lineNum = 0; // These variables sometimes need to exist beyond a line HashMap<String,Vector<String>> fileData = environment.getCategoryKeys(this.fileName); String key = ""; Vector<String> keyValues = null; boolean fileHasEnded = false; while (true) { // Read a line String line = ""; while (true) { // we allow for line continuations. Loop until full line is gathered if (!blankFile) { // we're dealing with an empty/non-existant file, so skip reading try { String newlyRead = br.readLine(); lineNum++; // Handle EOF gracefully if (newlyRead == null) { fileHasEnded = true; newlyRead = ""; } line += newlyRead; line.trim(); } catch (IOException ioe) { throw ioe; } } // Only continue if we have more data (blank files get to loop once; see end of loop) if (fileHasEnded && line.equals("")) { try { br.close(); } catch (Exception e) { // meh, we're done here anyway } finally { return; } } else { fileHasEnded = false; // file has not really ended. Proceed. } if (line.indexOf('#') > -1) { // comment cancels even line continuation so it comes first if (this.exceptNoComment) { System.err.println("Notice: file " + path + " line " + lineNum + ": possible comment where comment not allowed. Allowing it to be parsed by profile."); } else { line = line.substring(0, line.indexOf('#')).trim(); // Cut out comment // PMS 5.2.5 // Gentoo bug #326399: we're assuming all files with line continuation use these rules if (line.equals("")) { continue; // allowable comment line with no data but a comment; no need to parse it } } } if (line.endsWith("\\") || (this.type == this.TYPE_KEYVAL_BASH && !line.endsWith("\""))) { // line continuation // PMS 5.2.5 // // Gentoo bug #326399: we're assuming all files with line continuation use these rules if (this.exceptNoLineCont) { System.err.println("Notice: file " + path + " line " + lineNum + ": possible line continuation where line continuation not allowed. Allowing it to be parsed by profile."); } else { if (line.endsWith("\\")) { line = line.substring(0, line.lastIndexOf('\\')).trim(); } continue; // we need another line first! } } if (line.equals("") && !blankFile) { if (this.exceptNoBlank) { // blank lines aren't supposed to even exist System.err.println("Warning: file " + path + " line " + lineNum + ": blank line where blank is not allowed."); } continue; // skip the blanks } break; // done with line continuations } if (line.contains(this.search) && !this.search.equals("")) { System.err.println("Notice: search string found in file " + path + " line " + lineNum + ": " + line); } String[] pieces; if (this.type == TYPE_KEYVAL_BASH) { // strip the bash to a simple 3D format // This entire block uses PMS 5.2.4 // If there's no room for a variable name, there is no variable name, and that's bad. int equalsIndex = line.indexOf('='); if (equalsIndex < 1) { System.err.println ("Error: in file " + path + " line " + lineNum + ": equals sign in bad position or non-existant, which means the variable name couldn't be found. SKIPPING this line."); continue; } // Quotes are a big deal. Syntax is a big deal. String value = line.substring(equalsIndex+1, line.length()).trim(); if (!value.startsWith("\"") || !value.endsWith("\"")) { System.err.println ("Error: in file " + path + " line " + lineNum + ": variable data should begin and end with double quotes. SKIPPING this line."); continue; } value = value.substring(1, value.length()-1).trim(); // cut out the quotes. String variableName = line.substring(0, equalsIndex).trim(); // Some key validation if (!variableName.replaceAll("[a-zA-Z0-9_]","").equals("")) { // PMS 5.2.4 System.err.println ("Warning: in file " + path + " line " + lineNum + ": variable name " + variableName + " contains invalid characters."); } if (!Pattern.matches("[a-zA-Z]", Character.toString(variableName.charAt(0)))) { // PMS 5.2.4 System.err.println ("Warning: in file " + path + " line " + lineNum + ": variable name " + variableName + " begins with an invalid character."); } value = variableName + " " + value; // prepend the key so it becomes part of the pieces variable, just like the regular 3D format pieces = value.split("[ \t]+"); // Gentoo bug #326399: assuming tabs and spaces deliminate values } else { // everyone else is easy to parse pieces = line.split("[ \t]+"); // PMS 5.2.5 // Gentoo bug #326399: we're assuming all files with line continuation use these rules } if (pieces.length < 1) { pieces = new String[]{""}; // there needs to be at least one loop } if (this.type == TYPE_2D) { // TYPE_2D only wants one piece. if (pieces.length > 1) { System.err.println("Notice: file " + path + " line " + lineNum + ": possible syntax issue: there are spaces, indicating 3D data, in a 2D file. Allowing it to be parsed by profile as 2D anyway."); } pieces = new String[]{line}; } else if (pieces.length < 2) { // Everyone else wants at least two. if (pieces.length > 0 && this.type == TYPE_KEYVAL_BASH) { // there's a "variable=", but then inside the quotes immediately following there are no spaces. This is fine. } else { System.err.println ("Notice: in file " + path + " line " + lineNum + ": possible syntax issue: there are no spaces, indicating 2D data, in a 3D file. Allowing it to be parsed by profile as 3D anyway."); } } for (int i = 0; i < pieces.length; i++) { String piece = pieces[i]; // Key == 0, value == 1 int linePiece = 0; if (i > 0) { linePiece = 1; } // OK, time to gather linePiece rules // reasonable defaults boolean prefixCanIgnore = false; boolean prefixSpecialOnly = false; String prefixes = ""; int lineType = LINEPIECE_TYPE_STRING; for (int lri = 0; lri < 2; lri++) { int currLineRule = this.lineRules[linePiece][lri]; if (lri == 0) { // part one of the rule: what can we strip as a prefix? prefixCanIgnore = false; while (currLineRule > 0) { if (currLineRule >= LINEPIECE_PREFIX_SPECIAL_ONLY) { prefixSpecialOnly = true; currLineRule -= LINEPIECE_PREFIX_SPECIAL_ONLY; } else if (currLineRule >= LINEPIECE_PREFIX_ASTERIK) { prefixes += "*"; currLineRule -= LINEPIECE_PREFIX_ASTERIK; } else if (currLineRule >= LINEPIECE_PREFIX_PLUS) { prefixes += "+"; currLineRule -= LINEPIECE_PREFIX_PLUS; } else if (currLineRule >= LINEPIECE_PREFIX_MINUS) { prefixes += "-"; currLineRule -= LINEPIECE_PREFIX_MINUS; } else if (currLineRule >= LINEPIECE_PREFIX_NONE) { prefixCanIgnore = true; currLineRule -= LINEPIECE_PREFIX_NONE; } else { throw new IllegalArgumentException ("In file " + path + " line " + lineNum + ": bad rule number for allowed prefixes: " + currLineRule); } } } else if (lri == 1) { switch (currLineRule) { // part two: what type is this part stored as? case LINEPIECE_TYPE_NUMBER: if (this.type == TYPE_KEYVAL_BASH && linePiece == 0) { throw new IllegalArgumentException ("In file " + path + " line " + lineNum + ": when using TYPE_KEYVAL_BASH, cannot use LINEPIECE_TYPE_NUMBER for key type"); } lineType = LINEPIECE_TYPE_NUMBER; break; case LINEPIECE_TYPE_STRING: lineType = LINEPIECE_TYPE_STRING; break; case LINEPIECE_TYPE_PACKAGE: if (this.type == TYPE_KEYVAL_BASH) { System.err.println ("Warning: in file " + path + " line " + lineNum + ": while this utility can handle package atoms in bash-like files, PMS has neither allowed nor disallowed this."); } lineType = LINEPIECE_TYPE_PACKAGE; break; default: throw new IllegalArgumentException ("In file " + path + " line " + lineNum + ": bad rule number for piece type: " + currLineRule); } } } // We can't have conflicting rules. :) if (prefixCanIgnore == false && prefixes.equals("")) { throw new IllegalArgumentException ("In file " + path + " line " + lineNum + ": we were requested to not ignore prefixes but weren't told what prefixes were acceptable."); } if (prefixSpecialOnly && !this.isSpecialKey(key)) { // If only special variables are allowed to have prefixes, delete the prefixes variable so no prefix is recognized // PMS 5.3.1 prefixes = ""; } // Strip the prefix, and store it. Also store the line piece without its prefix. String pieceWithoutPrefix = piece; String piecePrefix = ""; if (!prefixes.equals("")) { piecePrefix = piece.replaceAll("^(["+prefixes+"]+).*", "$1"); // snag the prefix at the beginning if (Pattern.matches("^["+LINEPIECE_PREFIX_ALL+"]+", piece)) { // if there is a prefix if (prefixes.equals("")) { // should never happen (and we don't really need this warning: CFLAGS for example) System.err.println("Warning: in file " + path + " line " + lineNum + ": we did not desire a prefix, but there appears to be one in this piece: " + piece); } else { if (!Pattern.matches("^["+prefixes+"]+", piecePrefix)) { System.err.println("Warning: in file " + path + " line " + lineNum + ": there is an invalid prefix in this piece (which we will ignore): " + piece); } else { pieceWithoutPrefix = piece.substring(piecePrefix.length(), piece.length()); if (Pattern.matches("^["+LINEPIECE_PREFIX_ALL+"]+", Character.toString(pieceWithoutPrefix.charAt(0)))) { // still!? System.err.println("Warning: in file " + path + " line " + lineNum + ": we desired a prefix, and found one, but now there appears to be yet another prefix (which will not be processed) in this piece: " + piece); } } } } else if (!prefixes.equals("") && !prefixCanIgnore) { // if there is no prefix but we want one System.err.println("Warning: in file " + path + " line " + lineNum + ": it seems we desired a prefix, but there is none in this piece: " + piece); } } // Some special handling of number formats. if (lineType == LINEPIECE_TYPE_NUMBER) { if (this.exceptNoBlank && pieceWithoutPrefix.equals("")) { // Special scenario: allow number zero where blank is not allowed in a numeric field pieceWithoutPrefix = "0"; piece += "0"; } else { try { Double.valueOf(pieceWithoutPrefix); } catch (NumberFormatException e) { System.err.println ("Warning: in file " + path + " line " + lineNum + ": this piece is supposed to be numeric, but it has failed checks: " + piece); } } } // TODO: Some special handling of package formats if (linePiece == 0 && this.type != TYPE_2D) { // first piece, the key. We reset values for each line, but only in a 3D array. // This means a change in key, so... // Save data using current key before we update key to new one and reset data if (keyValues != null) { // Append previously collected data (if any exists and we're allowed) if (this.inheritsCanAppend && (!this.inheritsCanAppendSpecialOnly || this.isSpecialKey(key))) { Vector<String> existingValues = new Vector<String>(); if (fileData.containsKey(key)) { existingValues = fileData.get(key); } // otherwise we'll start a new one keyValues = this.mergeValues(existingValues, keyValues, prefixes); } fileData.put(key, keyValues); } keyValues = new Vector<String>(); // reset our data // We located our key! Save it for later! key = pieceWithoutPrefix; if (!piecePrefix.equals("")) { System.err.println ("Warning: in file " + path + " line " + lineNum + ": this piece has a prefix, but it is a key. Behavior for keys with prefixes is undefined in PMS, so we will ignore: " + piece); } } else { // First run for TYPE_2D. // This type is always on linePiece 1, functionally, so values needs only to be set once for the duration of the file if (keyValues == null) { keyValues = new Vector<String>(); key = "list"; // Key is always the same for 2D formats, making it store 2D in a 3D array. } // Find values that need to append to our growing list Vector<String> appendToKeyValues = new Vector<String>(); if (pieceWithoutPrefix.startsWith("$") && this.type == TYPE_KEYVAL_BASH) { // it's actually a variable, so expand it. // PMS 5.2.4 String variableName = pieceWithoutPrefix.substring(1, pieceWithoutPrefix.length()).replace("{","").replace("}",""); // cut off the $, and remove any curly brackets, since it means the same thing with or without // Expand variable to that variable's value(s) Vector<String> existingValues = new Vector<String>(); if (fileData.containsKey(variableName)) { existingValues = fileData.get(variableName); } appendToKeyValues.addAll(existingValues); } else { // Someone trying to be fancy? if (pieceWithoutPrefix.startsWith("$")) { System.err.println ("Warning: in file " + path + " line " + lineNum + ": this piece looks like a variable, but this file does not allow variables: " + piece); } appendToKeyValues.add(piece); } keyValues = this.mergeValues(keyValues, appendToKeyValues, ""); // just use for dup-checking. Prefixes will be applied later. (Doing prefixes twice means the prefixes are ineffective.) // Append if we're allowed to, otherwise replace. Vector<String> values; if (this.inheritsCanAppend && (!this.inheritsCanAppendSpecialOnly || this.isSpecialKey(key))) { // Get the existing values that we'll append to Vector<String> existingValues = new Vector<String>(); if (fileData.containsKey(key)) { existingValues = fileData.get(key); } // otherwise we'll start a new one values = this.mergeValues(existingValues, keyValues, prefixes); } else { values = keyValues; } fileData.put(key, values); } } environment.setCategoryKeys(this.fileName, fileData); if (br == null && line.equals("")) { // single loop execution is done return; } } } private Vector<String> mergeValues (Vector<String> existingValues, Vector<String> keyValues, String prefixesToIgnore) { // Locate duplicates and remove them before merging. String[] wasKeyValues = new String[0]; wasKeyValues = keyValues.toArray(wasKeyValues); // make a light-weight copy of old values so we can modify existingValues for (String newValue: wasKeyValues) { String newValueWithoutPrefix = newValue; if (!prefixesToIgnore.equals("")) { newValueWithoutPrefix = newValue.replaceAll("^["+prefixesToIgnore+"]+", ""); } if (!this.showMinus) { int minusPrefixPos = newValue.indexOf('-'); if (prefixesToIgnore.indexOf('-') > -1 && minusPrefixPos > -1 && minusPrefixPos < newValue.length() - newValueWithoutPrefix.length()) { // This has a - prefix, so it negates but does not appear in the list keyValues.remove(newValue); } } String[] wasExistingValues = new String[0]; wasExistingValues = existingValues.toArray(wasExistingValues); // make a light-weight copy of old values so we can modify existingValues for (String existingValue: wasExistingValues) { String existingValueWithoutPrefix = existingValue; if (!prefixesToIgnore.equals("")) { existingValueWithoutPrefix = existingValue.replaceAll("^["+prefixesToIgnore+"]+", ""); } if (newValueWithoutPrefix.equals(existingValueWithoutPrefix)) { // existingValue is overridden. existingValues.remove(existingValue); } } } Vector<String> values = new Vector<String>(); values.addAll(existingValues); values.addAll(keyValues); return values; } private boolean isSpecialKey (String key) { // This entire block is PMS 5.3.1 if ( key.equals("USE") || key.equals("USE_EXPAND") || key.equals("USE_EXPAND_HIDDEN") || key.equals("CONFIG_PROTECT") || key.equals("CONFIG_PROTECT_MASK") ) { return true; } else if (eapi == 4 && ( key.equals("IUSE_IMPLICIT") || key.equals("USE_EXPAND_IMPLICIT") || key.equals("USE_EXPAND_UNPREFIXED") ) ) { return true; } else { return false; } } public String getPath () { return this.path; } public int getEAPI () { return this.eapi; } public String getFileName () { return this.fileName; } public int getType () { return this.type; } } class Profile { private static HashMap<String, Vector<String>> allRelations = new HashMap<String, Vector<String>>(); // parent -> child private String path = ""; private ProfileEnvironment environment = null; private ProfileFile files[][]; private boolean verbose = false; private boolean showMinus = false; private String search = ""; private Vector<Profile> parents = new Vector<Profile>(); public Profile (String path, ProfileEnvironment environment, boolean verbose, boolean showMinus, String search) throws IOException, IllegalArgumentException { this.path = path; this.environment = environment; this.verbose = verbose; this.showMinus = showMinus; this.search = search; File pathFile = new File(this.path); String absolutePath = pathFile.getCanonicalPath(); // resolve symlinks, get absolute path. Used for cycle checking. if (!pathFile.exists()) { System.err.println("Warning: profile at " + this.path + " doesn't exist!"); } this.files = new ProfileFile[][]{ // files are listed in rounds: the ones that need to load before one are listed in a round before that one { // round one: it is special in that it gets processed before we announce we are processing this profile new ProfileFile( // PMS 5.2.1 this.path+"/parent", ProfileFile.TYPE_2D, ProfileFile.NOEXISTS_CAN_IGNORE, ProfileFile.EXCEPT_NO_BLANK + ProfileFile.EXCEPT_NO_COMMENT + ProfileFile.EXCEPT_NO_LINE_CONT, new int[][] { { ProfileFile.LINEPIECE_PREFIX_NONE, ProfileFile.LINEPIECE_TYPE_STRING } }, ProfileFile.INHERIT_NONE, ProfileFile.DEPRECATED_NO, this.verbose, this.showMinus, this.search ), new ProfileFile( // PMS 5.2.2 this.path+"/eapi", ProfileFile.TYPE_2D, ProfileFile.NOEXISTS_CAN_BLANK, ProfileFile.EXCEPT_NO_BLANK + ProfileFile.EXCEPT_NO_COMMENT + ProfileFile.EXCEPT_NO_LINE_CONT, new int[][] { { ProfileFile.LINEPIECE_PREFIX_NONE, ProfileFile.LINEPIECE_TYPE_NUMBER } }, ProfileFile.INHERIT_NONE, ProfileFile.DEPRECATED_NO, this.verbose, this.showMinus, this.search ), }, { // round two new ProfileFile( // PMS 5.2.3 this.path+"/deprecated", ProfileFile.TYPE_2D, ProfileFile.NOEXISTS_CAN_IGNORE, ProfileFile.EXCEPT_NO_BLANK + ProfileFile.EXCEPT_NO_COMMENT + ProfileFile.EXCEPT_NO_LINE_CONT, new int[][] { { ProfileFile.LINEPIECE_PREFIX_NONE, ProfileFile.LINEPIECE_TYPE_STRING } }, ProfileFile.INHERIT_NONE, ProfileFile.DEPRECATED_NO, this.verbose, this.showMinus, this.search ), new ProfileFile( // PMS 5.2.4 this.path+"/make.defaults", ProfileFile.TYPE_KEYVAL_BASH, ProfileFile.NOEXISTS_CAN_IGNORE, 0, new int[][] { { ProfileFile.LINEPIECE_PREFIX_NONE, ProfileFile.LINEPIECE_TYPE_STRING }, { ProfileFile.LINEPIECE_PREFIX_NONE+ProfileFile.LINEPIECE_PREFIX_SPECIAL_ONLY+ProfileFile.LINEPIECE_PREFIX_MINUS, ProfileFile.LINEPIECE_TYPE_STRING } }, ProfileFile.INHERIT_PARENT+ProfileFile.INHERIT_APPEND_SPECIAL_ONLY, ProfileFile.DEPRECATED_NO, this.verbose, this.showMinus, this.search ), new ProfileFile( // PMS 5.2.5 this.path+"/virtuals", ProfileFile.TYPE_3D, ProfileFile.NOEXISTS_CAN_IGNORE, ProfileFile.EXCEPT_NO_LINE_CONT, new int[][] { { ProfileFile.LINEPIECE_PREFIX_NONE, ProfileFile.LINEPIECE_TYPE_PACKAGE }, { ProfileFile.LINEPIECE_PREFIX_NONE, ProfileFile.LINEPIECE_TYPE_PACKAGE } }, ProfileFile.INHERIT_PARENT+ProfileFile.INHERIT_NO_APPEND, ProfileFile.DEPRECATED_YES, this.verbose, this.showMinus, this.search ), new ProfileFile( // PMS 5.2.7 this.path+"/packages", ProfileFile.TYPE_2D, ProfileFile.NOEXISTS_CAN_IGNORE, ProfileFile.EXCEPT_NO_LINE_CONT, new int[][] { { ProfileFile.LINEPIECE_PREFIX_NONE+ProfileFile.LINEPIECE_PREFIX_MINUS+ProfileFile.LINEPIECE_PREFIX_ASTERIK, ProfileFile.LINEPIECE_TYPE_PACKAGE } }, ProfileFile.INHERIT_PARENT, ProfileFile.DEPRECATED_NO, this.verbose, this.showMinus, this.search ), new ProfileFile( // PMS 5.2.9 this.path+"/package.mask", ProfileFile.TYPE_2D, ProfileFile.NOEXISTS_CAN_IGNORE, ProfileFile.EXCEPT_NO_LINE_CONT, new int[][] { { ProfileFile.LINEPIECE_PREFIX_NONE+ProfileFile.LINEPIECE_PREFIX_MINUS, ProfileFile.LINEPIECE_TYPE_PACKAGE } }, ProfileFile.INHERIT_PARENT, ProfileFile.DEPRECATED_NO, this.verbose, this.showMinus, this.search ), new ProfileFile( // PMS 5.2.10 this.path+"/package.provided", ProfileFile.TYPE_2D, ProfileFile.NOEXISTS_CAN_IGNORE, ProfileFile.EXCEPT_NO_LINE_CONT, new int[][] { { ProfileFile.LINEPIECE_PREFIX_NONE, ProfileFile.LINEPIECE_TYPE_PACKAGE } }, ProfileFile.INHERIT_PARENT, ProfileFile.DEPRECATED_NO, this.verbose, this.showMinus, this.search ), new ProfileFile( // PMS 5.2.11 this.path+"/package.use", ProfileFile.TYPE_3D, ProfileFile.NOEXISTS_CAN_IGNORE, ProfileFile.EXCEPT_NO_LINE_CONT, new int[][] { { ProfileFile.LINEPIECE_PREFIX_NONE, ProfileFile.LINEPIECE_TYPE_PACKAGE }, { ProfileFile.LINEPIECE_PREFIX_NONE+ProfileFile.LINEPIECE_PREFIX_MINUS, ProfileFile.LINEPIECE_TYPE_STRING } }, ProfileFile.INHERIT_PARENT, ProfileFile.DEPRECATED_NO, this.verbose, this.showMinus, this.search ), new ProfileFile( // PMS 5.2.12 this.path+"/package.use.force", ProfileFile.TYPE_3D, ProfileFile.NOEXISTS_CAN_IGNORE, ProfileFile.EXCEPT_NO_LINE_CONT, new int[][] { { ProfileFile.LINEPIECE_PREFIX_NONE, ProfileFile.LINEPIECE_TYPE_PACKAGE }, { ProfileFile.LINEPIECE_PREFIX_NONE+ProfileFile.LINEPIECE_PREFIX_MINUS, ProfileFile.LINEPIECE_TYPE_STRING }, }, ProfileFile.INHERIT_PARENT, ProfileFile.DEPRECATED_NO, this.verbose, this.showMinus, this.search ), new ProfileFile( // PMS 5.2.12 this.path+"/package.use.mask", ProfileFile.TYPE_3D, ProfileFile.NOEXISTS_CAN_IGNORE, ProfileFile.EXCEPT_NO_LINE_CONT, new int[][] { { ProfileFile.LINEPIECE_PREFIX_NONE, ProfileFile.LINEPIECE_TYPE_PACKAGE }, { ProfileFile.LINEPIECE_PREFIX_NONE+ProfileFile.LINEPIECE_PREFIX_MINUS, ProfileFile.LINEPIECE_TYPE_STRING }, }, ProfileFile.INHERIT_PARENT, ProfileFile.DEPRECATED_NO, this.verbose, this.showMinus, this.search ), new ProfileFile( // PMS 5.2.12 this.path+"/use.force", ProfileFile.TYPE_2D, ProfileFile.NOEXISTS_CAN_IGNORE, ProfileFile.EXCEPT_NO_LINE_CONT, new int[][] { { ProfileFile.LINEPIECE_PREFIX_NONE+ProfileFile.LINEPIECE_PREFIX_MINUS, ProfileFile.LINEPIECE_TYPE_STRING } }, ProfileFile.INHERIT_PARENT, ProfileFile.DEPRECATED_NO, this.verbose, this.showMinus, this.search ), new ProfileFile( // PMS 5.2.12 this.path+"/use.mask", ProfileFile.TYPE_2D, ProfileFile.NOEXISTS_CAN_IGNORE, ProfileFile.EXCEPT_NO_LINE_CONT, new int[][] { { ProfileFile.LINEPIECE_PREFIX_NONE+ProfileFile.LINEPIECE_PREFIX_MINUS, ProfileFile.LINEPIECE_TYPE_STRING } }, ProfileFile.INHERIT_PARENT, ProfileFile.DEPRECATED_NO, this.verbose, this.showMinus, this.search ) }, }; this.mergeFilesToEnvironment(this.files[0], this.environment); Vector<String> existingParents = new Vector<String>(); // by default blank, unless the key exists if (this.allRelations.containsKey(absolutePath)) { existingParents = this.allRelations.get(absolutePath); } Vector<String> parents = this.environment.getVars("parent", "list"); for (String parent: parents) { String absoluteParent = new File(this.path+"/"+parent).getCanonicalPath(); if (existingParents.contains(absoluteParent)) { // PMS 5.2.1 throw new IllegalArgumentException("Found a cycle, which results in a broken profile: child path " + this.path + " is trying to include parent path " + parent + " more than once."); } existingParents.add(absoluteParent); this.parents.add(new Profile(this.path+"/"+parent, this.environment, this.verbose, this.showMinus, this.search)); } this.allRelations.put(absolutePath, existingParents); if (verbose) System.out.println("Investigating profile at " + path); // we do this after because parents do investigation first // PMS 5.2.1 this.mergeFilesToEnvironment(this.files[1], this.environment); } public void mergeFilesToEnvironment(ProfileFile[] files, ProfileEnvironment environment) throws FileNotFoundException, IOException { for (ProfileFile currFile: files) { currFile.mergeToEnvironment(environment); } } public String getHumanOutput () { String results = ""; Set<String> leftOverCategoryNames = this.environment.getCategories().keySet(); for (ProfileFile[] round: this.files) { for (ProfileFile file: round) { String fileName = file.getFileName(); results += " if (file.getType() == ProfileFile.TYPE_2D) { Vector<String> values = this.environment.getVars(fileName, "list"); results += Profile.array2DToString(values, "", "\n", "\n") + "\n"; leftOverCategoryNames.remove(fileName); } else if (file.getType() == ProfileFile.TYPE_3D) { HashMap<String,Vector<String>> category = this.environment.getCategoryKeys(fileName); results += Profile.array3DToString(category, " ", " ", "") + "\n"; leftOverCategoryNames.remove(fileName); } else if (file.getType() == ProfileFile.TYPE_KEYVAL_BASH) { HashMap<String,Vector<String>> category = this.environment.getCategoryKeys(fileName); results += Profile.array3DToString(category, "=\"", " ", "\"") + "\n"; leftOverCategoryNames.remove(fileName); } } } if (verbose) { // Warn about unhandled data for (String categoryName: leftOverCategoryNames) { HashMap<String,Vector<String>> keys = this.environment.getCategoryKeys(categoryName); Set<String> keyNames = keys.keySet(); for (String keyName: keyNames) { System.err.println("Warning: unhandled data: " + keyName); } } } return results; } public static String array2DToString (Vector<String> array, String begin, String valueSeperator, String end) { String results = ""; results += begin; for (int v = 0; v < array.size(); v++) { results += array.get(v); if (v+1 < array.size()) { results += valueSeperator; } } results += end; return results; } public static String array3DToString (HashMap<String,Vector<String>> array, String beginSeperator, String valueSeperator, String endSeperator) { String results = ""; Iterator arrays = array.keySet().iterator(); while (arrays.hasNext()) { String arrayName = (String)arrays.next(); Vector<String> currAarrray = array.get(arrayName); if (currAarrray.size() > 0) { results += array2DToString(array.get(arrayName), arrayName+beginSeperator, valueSeperator, endSeperator+"\n"); } } return results; } }
package org.nutz.dao.impl.jdbc.derby; import java.util.List; import org.nutz.dao.DB; import org.nutz.dao.Dao; import org.nutz.dao.Sqls; import org.nutz.dao.entity.Entity; import org.nutz.dao.entity.MappingField; import org.nutz.dao.entity.PkType; import org.nutz.dao.entity.annotation.ColType; import org.nutz.dao.impl.entity.macro.SqlFieldMacro; import org.nutz.dao.impl.jdbc.mysql.MysqlJdbcExpert; import org.nutz.dao.jdbc.JdbcExpertConfigFile; import org.nutz.dao.jdbc.ValueAdaptor; import org.nutz.dao.pager.Pager; import org.nutz.dao.sql.Pojo; import org.nutz.dao.sql.Sql; import org.nutz.dao.util.Pojos; public class DerbyJdbcExpert extends MysqlJdbcExpert { public DerbyJdbcExpert(JdbcExpertConfigFile conf) { super(conf); } public String getDatabaseType() { return DB.DERBY.name(); } @Override public ValueAdaptor getAdaptor(MappingField ef) { if (ef.getTypeMirror().isBoolean()) return new DerbyBooleanAdaptor(); return super.getAdaptor(ef); } public void formatQuery(Pojo pojo) { Pager pager = pojo.getContext().getPager(); if (null != pager && pager.getPageNumber() > 0) pojo.append(Pojos.Items.wrapf(" OFFSET %d ROWS FETCH NEXT %d ROW ONLY", pager.getOffset(), pager.getPageSize())); } public void formatQuery(Sql sql) { Pager pager = sql.getContext().getPager(); if (null != pager && pager.getPageNumber() > 0) sql.setSourceSql(sql.getSourceSql() + String.format(" OFFSET %d ROWS FETCH NEXT %d ROW ONLY", pager.getOffset(), pager.getPageSize())); } protected String evalFieldType(MappingField mf) { if (mf.getCustomDbType() != null) return mf.getCustomDbType(); switch (mf.getColumnType()) { case INT : { int width = mf.getWidth(); if (width < 8) return "INT"; return "BIGINT"; } case DATETIME : return "TIMESTAMP"; case BOOLEAN : return "varchar(1)"; case BINARY : return "BLOB"; default : break; } return super.evalFieldType(mf); } public boolean createEntity(Dao dao, Entity<?> en) { StringBuilder sb = new StringBuilder("CREATE TABLE " + en.getTableName() + "("); for (MappingField mf : en.getMappingFields()) { sb.append('\n').append(mf.getColumnName()); sb.append(' ').append(evalFieldType(mf)); // @Name if (mf.isName() && en.getPkType() != PkType.NAME) { sb.append(" UNIQUE NOT NULL"); } else { // TimestampMySqlTimestampdefaultCURRENT_TIMESTAMP if (mf.isUnsigned()) sb.append(" UNSIGNED"); if (mf.isNotNull()) { sb.append(" NOT NULL"); } if (mf.isAutoIncreasement()) sb.append(" generated by default as identity"); if (mf.getColumnType() == ColType.TIMESTAMP) { if (mf.hasDefaultValue()) { sb.append(" ").append(getDefaultValue(mf)); } else { if (mf.isNotNull()) { sb.append(" DEFAULT 0"); } else { sb.append(" DEFAULT NULL"); } } } else { if (mf.hasDefaultValue()) sb.append(" DEFAULT '").append(getDefaultValue(mf)).append("'"); } } if (mf.hasColumnComment()) { sb.append(" COMMENT '").append(mf.getColumnComment()).append("'"); } sb.append(','); } List<MappingField> pks = en.getPks(); if (!pks.isEmpty()) { sb.append('\n'); sb.append("PRIMARY KEY ("); for (MappingField pk : pks) { sb.append(pk.getColumnName()).append(','); } sb.setCharAt(sb.length() - 1, ')'); sb.append("\n "); } sb.setCharAt(sb.length() - 1, ')'); if (en.hasTableComment()) { sb.append(" COMMENT='").append(en.getTableComment()).append("'"); } dao.execute(Sqls.create(sb.toString())); dao.execute(createIndexs(en).toArray(new Sql[0])); createRelation(dao, en); return true; } protected String createResultSetMetaSql(Entity<?> en) { return "SELECT * FROM " + en.getViewName() + " LIMIT 1"; } public Pojo fetchPojoId(Entity<?> en, MappingField idField) { String autoSql = "select IDENTITY_VAL_LOCAL() as id from " + en.getTableName(); Pojo autoInfo = new SqlFieldMacro(idField, autoSql); autoInfo.setEntity(en); return autoInfo; } }
package org.objectweb.proactive.core.rmi; import org.apache.log4j.Logger; import java.net.UnknownHostException; public class ClassServer implements Runnable { protected static Logger logger = Logger.getLogger(ClassServer.class.getName()); public static int DEFAULT_SERVER_BASE_PORT = 2001; protected static int DEFAULT_SERVER_PORT_INCREMENT = 20; protected static int MAX_RETRY = 50; private static java.util.Random random = new java.util.Random(); protected static int port; protected String hostname; static { String newport = System.getProperty("proactive.http.port"); if (newport != null) { DEFAULT_SERVER_BASE_PORT = Integer.valueOf(newport).intValue(); } else DEFAULT_SERVER_BASE_PORT = 2222; } private java.net.ServerSocket server = null; protected String paths; /** * Constructs a ClassServer that listens on a random port. The port number * used is the first one found free starting from a default base port. * obtains a class's bytecodes using the method <b>getBytes</b>. * @exception java.io.IOException if the ClassServer could not listen on any port. */ protected ClassServer() throws java.io.IOException { this(0, null); } protected ClassServer(int port_) throws java.io.IOException { if (port == 0) { port = boundServerSockect(DEFAULT_SERVER_BASE_PORT, MAX_RETRY); } else { port = port_; server = new java.net.ServerSocket(port); } hostname = java.net.InetAddress.getLocalHost().getHostAddress(); newListener(); // if (logger.isInfoEnabled()) { // logger.info("communication protocol = " +System.getProperty("proactive.communication.protocol")+", http server port = " + port); } /** * Constructs a ClassServer that listens on <b>port</b> and * obtains a class's bytecodes using the method <b>getBytes</b>. * @param port the port number * @exception java.io.IOException if the ClassServer could not listen * on <b>port</b>. */ protected ClassServer(int port_, String paths) throws java.io.IOException { this(port_); this.paths = paths; printMessage(); } /** * Constructs a ClassFileServer. * @param classpath the classpath where the server locates classes */ public ClassServer(String paths) throws java.io.IOException { this(0, paths); } public static boolean isPortAlreadyBound(int port) { java.net.Socket socket = null; try { socket = new java.net.Socket(java.net.InetAddress.getLocalHost(), port); // if we can connect to the port it means the server already exists return true; } catch (java.io.IOException e) { return false; } finally { try { if (socket != null) { socket.close(); } } catch (java.io.IOException e) { } } } private void printMessage() { if (logger.isDebugEnabled()) { logger.debug( "To use this ClassFileServer set the property java.rmi.server.codebase to http: hostname + ":" + port + "/"); } if (this.paths == null) { logger.info( " --> This ClassFileServer is reading resources from classpath"); } else { logger.info( " --> This ClassFileServer is reading resources from the following paths"); //for (int i = 0; i < codebases.length; i++) { logger.info(paths); //codebases[i].getAbsolutePath()); } } public static int getServerSocketPort() { return port; } public String getHostname() { return hostname; } public static String getUrl() { try { return "http: java.net.InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * The "listen" thread that accepts a connection to the * server, parses the header to obtain the class file name * and sends back the bytecodes for the class (or error * if the class is not found or the response was malformed). */ public void run() { java.net.Socket socket = null; // accept a connection while (true) { try { socket = server.accept(); ProActiveService service = (new ProActiveService(socket, paths)); service.start(); } catch (java.io.IOException e) { System.out.println("Class Server died: " + e.getMessage()); e.printStackTrace(); return; } finally { } } } private void newListener() { (new Thread(this, "ClassServer-" + hostname + ":" + port)).start(); } private int boundServerSockect(int basePortNumber, int numberOfTry) throws java.io.IOException { for (int i = 0; i < numberOfTry; i++) { try { server = new java.net.ServerSocket(basePortNumber); return basePortNumber; } catch (java.io.IOException e) { basePortNumber += random.nextInt(DEFAULT_SERVER_PORT_INCREMENT); } } throw new java.io.IOException( "ClassServer cannot create a ServerSocket after " + numberOfTry + " attempts !!!"); } }
// This file is part of JavaSMT, // an API wrapper for a collection of SMT solvers: package org.sosy_lab.java_smt.solvers.cvc5; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import io.github.cvc5.api.CVC5ApiException; import io.github.cvc5.api.Kind; import io.github.cvc5.api.Solver; import io.github.cvc5.api.Sort; import io.github.cvc5.api.Term; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.basicimpl.AbstractModel.CachingAbstractModel; public class CVC5Model extends CachingAbstractModel<Term, Sort, Solver> { private final ImmutableList<ValueAssignment> model; private final Solver solver; private final ImmutableList<Term> assertedExpressions; private final CVC5AbstractProver<?> prover; protected boolean closed = false; CVC5Model( CVC5AbstractProver<?> pProver, CVC5FormulaCreator pCreator, Collection<Term> pAssertedExpressions) { super(pCreator); solver = creator.getEnv(); prover = pProver; assertedExpressions = ImmutableList.copyOf(pAssertedExpressions); // We need to generate and save this at construction time as CVC4 has no functionality to give a // persistent reference to the model. If the SMT engine is used somewhere else, the values we // get out of it might change! model = generateModel(); } @Override public Term evalImpl(Term f) { Preconditions.checkState(!closed); return solver.getValue(f); } private ImmutableList<ValueAssignment> generateModel() { ImmutableSet.Builder<ValueAssignment> builder = ImmutableSet.builder(); // Using creator.extractVariablesAndUFs we wouldn't get accurate information anymore as we // translate all bound vars back to their free counterparts in the visitor! for (Term expr : assertedExpressions) { creator.extractVariablesAndUFs(expr, true, (name, f) -> builder.add(getAssignment(f))); // recursiveAssignmentFinder(builder, expr); } return builder.build().asList(); } @SuppressWarnings("unused") private void recursiveAssignmentFinder(ImmutableSet.Builder<ValueAssignment> builder, Term expr) { /* * In CVC5 consts are variables! Free variables (created with mkVar() can never have a value!) If you check */ /* if (expr.isConst() || expr.isNull()) { // We don't care about consts. return; } else if (expr.isVariable() && expr.getKind() == Kind.BOUND_VARIABLE) { // We don't care about bound vars (not in a UF), as they don't return a value. return; } else if (expr.isVariable() || expr.getOperator().getType().isFunction()) { // This includes free vars and UFs, as well as bound vars in UFs ! builder.add(getAssignment(expr)); } else if (expr.getKind() == Kind.FORALL || expr.getKind() == Kind.EXISTS) { // Body of the quantifier, with bound vars! Term body = expr.getChildren().get(1); recursiveAssignmentFinder(builder, body); } else { // Only nested terms (AND, OR, ...) are left for (Term child : expr) { recursiveAssignmentFinder(builder, child); } } */ } private ValueAssignment getAssignment(Term pKeyTerm) { List<Object> argumentInterpretation = new ArrayList<>(); try { if (pKeyTerm.getKind() == Kind.APPLY_UF) { // We don't want the first argument of uf applications as it is the declaration for (int i = 1; i < pKeyTerm.getNumChildren(); i++) { argumentInterpretation.add(evaluateImpl(pKeyTerm.getChild(i))); } } else { for (int i = 0; i < pKeyTerm.getNumChildren(); i++) { argumentInterpretation.add(evaluateImpl(pKeyTerm.getChild(i))); } } } catch (CVC5ApiException e) { // This should never trigger, if it does only the model is incomplete and the tests should // detect that } String nameStr = ""; try { if (pKeyTerm.hasSymbol()) { nameStr = pKeyTerm.getSymbol(); } else if (pKeyTerm.getKind().equals(Kind.APPLY_UF)) { nameStr = pKeyTerm.getChild(0).getSymbol(); } else { nameStr = "UF"; } } catch (CVC5ApiException e) { // Should never trigger } if (nameStr.startsWith("|") && nameStr.endsWith("|")) { nameStr = nameStr.substring(1, nameStr.length() - 1); } Term valueTerm = solver.getValue(pKeyTerm); Formula keyFormula = creator.encapsulateWithTypeOf(pKeyTerm); Formula valueFormula = creator.encapsulateWithTypeOf(valueTerm); BooleanFormula equation = creator.encapsulateBoolean(solver.mkTerm(Kind.EQUAL, pKeyTerm, valueTerm)); Object value = creator.convertValue(pKeyTerm, valueTerm); return new ValueAssignment( keyFormula, valueFormula, equation, nameStr, value, argumentInterpretation); } @Override public void close() { prover.unregisterModel(this); closed = true; } @Override protected ImmutableList<ValueAssignment> toList() { return model; } }
package speedy.comparison.operators; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import speedy.SpeedyConstants; import speedy.SpeedyConstants.ValueMatchResult; import speedy.comparison.ComparisonConfiguration; import speedy.comparison.TupleMapping; import speedy.comparison.InstanceMatch; import speedy.comparison.TupleMatch; import speedy.comparison.TupleMatches; import speedy.comparison.TupleWithTable; import speedy.comparison.ValueMapping; import speedy.model.database.ConstantValue; import speedy.model.database.IDatabase; import speedy.model.database.IValue; import speedy.model.database.NullValue; import speedy.utility.SpeedyUtility; import speedy.utility.combinatorics.GenericListGeneratorIterator; import speedy.utility.comparator.TupleMatchComparatorScore; public class FindHomomorphism { private final static Logger logger = LoggerFactory.getLogger(FindHomomorphism.class); public InstanceMatch findHomomorphism(IDatabase sourceDb, IDatabase destinationDb) { InstanceMatch result = new InstanceMatch(sourceDb, destinationDb); List<TupleWithTable> sourceTuples = SpeedyUtility.extractAllTuplesFromDatabase(sourceDb); List<TupleWithTable> destinationTuples = SpeedyUtility.extractAllTuplesFromDatabase(destinationDb); TupleMatches tupleMatches = findTupleMatches(sourceTuples, destinationTuples); if (tupleMatches.hasNonMatchingTuples()) { result.setNonMatchingTuples(tupleMatches.getNonMatchingTuples()); return result; } sortTupleMatches(tupleMatches); List<List<TupleMatch>> allTupleMatches = combineMatches(sourceTuples, tupleMatches); GenericListGeneratorIterator<TupleMatch> iterator = new GenericListGeneratorIterator<TupleMatch>(allTupleMatches); while (iterator.hasNext()) { List<TupleMatch> candidateHomomorphism = iterator.next(); TupleMapping homomorphism = checkIfIsHomomorphism(candidateHomomorphism); if (homomorphism != null) { result.setTupleMatch(homomorphism); result.setIsomorphism(checkIsomorphism(result)); break; } } return result; } private TupleMatches findTupleMatches(List<TupleWithTable> leftTuples, List<TupleWithTable> rightTuples) { TupleMatches tupleMatches = new TupleMatches(); for (TupleWithTable leftTuple : leftTuples) { for (TupleWithTable rightTuple : rightTuples) { TupleMatch match = checkMatch(leftTuple, rightTuple); if (match != null) { if (logger.isDebugEnabled()) logger.debug("Match found: " + match); tupleMatches.addTupleMatch(leftTuple, match); } } List<TupleMatch> matchesForTuple = tupleMatches.getMatchesForTuple(leftTuple); if (matchesForTuple == null) { if (logger.isInfoEnabled()) logger.info("Non matching tuple: " + leftTuple); tupleMatches.addNonMatchingTuple(leftTuple); if (ComparisonConfiguration.isStopIfNonMatchingTuples()) { return tupleMatches; } } } return tupleMatches; } private TupleMatch checkMatch(TupleWithTable sourceTuple, TupleWithTable destinationTuple) { if (!sourceTuple.getTable().equals(destinationTuple.getTable())) { return null; } if (logger.isDebugEnabled()) logger.debug("Comparing tuple: " + sourceTuple + " to tuple " + destinationTuple); ValueMapping valueMapping = new ValueMapping(); int score = 0; for (int i = 0; i < sourceTuple.getTuple().getCells().size(); i++) { if (sourceTuple.getTuple().getCells().get(i).getAttribute().equals(SpeedyConstants.OID)) { continue; } IValue sourceValue = sourceTuple.getTuple().getCells().get(i).getValue(); IValue destinationValue = destinationTuple.getTuple().getCells().get(i).getValue(); if (logger.isTraceEnabled()) logger.trace("Comparing values: '" + sourceValue + "', '" + destinationValue + "'"); ValueMatchResult matchResult = match(sourceValue, destinationValue); if (matchResult == ValueMatchResult.NOT_MATCHING) { if (logger.isTraceEnabled()) logger.trace("Values not match..."); return null; } valueMapping = updateValueMapping(valueMapping, sourceValue, destinationValue, matchResult); if (valueMapping == null) { if (logger.isTraceEnabled()) logger.trace("Conflicting mapping for values..."); return null; } score += score(matchResult); } TupleMatch tupleMatch = new TupleMatch(sourceTuple, destinationTuple, valueMapping, score); return tupleMatch; } private ValueMatchResult match(IValue sourceValue, IValue destinationValue) { if (sourceValue instanceof ConstantValue && destinationValue instanceof ConstantValue) { if (sourceValue.equals(destinationValue)) { return ValueMatchResult.EQUAL_CONSTANTS; } } if (sourceValue instanceof NullValue && destinationValue instanceof ConstantValue) { return ValueMatchResult.NULL_TO_CONSTANT; } if (sourceValue instanceof NullValue && destinationValue instanceof NullValue) { return ValueMatchResult.BOTH_NULLS; } return ValueMatchResult.NOT_MATCHING; } private int score(ValueMatchResult matchResult) { if (matchResult == ValueMatchResult.EQUAL_CONSTANTS) { return 1; } if (matchResult == ValueMatchResult.BOTH_NULLS) { return 1; } if (matchResult == ValueMatchResult.NULL_TO_CONSTANT) { return 0; } return 0; } private ValueMapping updateValueMapping(ValueMapping valueMapping, IValue sourceValue, IValue destinationValue, ValueMatchResult matchResult) { if (matchResult == ValueMatchResult.BOTH_NULLS || matchResult == ValueMatchResult.NULL_TO_CONSTANT) { IValue valueForSourceValue = valueMapping.getValueMapping(sourceValue); if (valueForSourceValue != null && !valueForSourceValue.equals(destinationValue)) { return null; } valueMapping.putValueMapping(sourceValue, destinationValue); } return valueMapping; } private void sortTupleMatches(TupleMatches tupleMatches) { for (TupleWithTable tuple : tupleMatches.getTuples()) { List<TupleMatch> matchesForTuple = tupleMatches.getMatchesForTuple(tuple); Collections.sort(matchesForTuple, new TupleMatchComparatorScore()); } } private List<List<TupleMatch>> combineMatches(List<TupleWithTable> sourceTuples, TupleMatches tupleMatches) { List<List<TupleMatch>> allTupleMatches = new ArrayList<List<TupleMatch>>(); for (TupleWithTable sourceTuple : sourceTuples) { allTupleMatches.add(tupleMatches.getMatchesForTuple(sourceTuple)); } return allTupleMatches; } private TupleMapping checkIfIsHomomorphism(List<TupleMatch> candidateHomomorphism) { TupleMapping homomorphism = new TupleMapping(); for (TupleMatch tupleMatch : candidateHomomorphism) { homomorphism = addTupleMatch(homomorphism, tupleMatch); if (homomorphism == null) { return null; } homomorphism.putTupleMapping(tupleMatch.getLeftTuple(), tupleMatch.getRightTuple()); } return homomorphism; } private TupleMapping addTupleMatch(TupleMapping homomorphism, TupleMatch tupleMatch) { for (IValue sourceValue : tupleMatch.getLeftToRightValueMapping().getKeys()) { IValue destinationValue = tupleMatch.getLeftToRightValueMapping().getValueMapping(sourceValue); IValue valueForSourceValueInHomomorphism = homomorphism.getLeftToRightMappingForValue(sourceValue); if (valueForSourceValueInHomomorphism != null && !valueForSourceValueInHomomorphism.equals(destinationValue)) { return null; } homomorphism.addLeftToRightMappingForValue(sourceValue, destinationValue); } return homomorphism; } private boolean checkIsomorphism(InstanceMatch instanceMatch) { if (!instanceMatch.hasHomomorphism()) { return false; } if (instanceMatch.getSourceDb().getSize() != instanceMatch.getTargetDb().getSize()) { return false; } if (!injective(instanceMatch)) { return false; } return true; } private boolean injective(InstanceMatch instanceMatch) { Collection<TupleWithTable> rightMatchedTuples = instanceMatch.getTupleMatch().getTupleMapping().values(); Set<TupleWithTable> distinctMatchedTuples = new HashSet<TupleWithTable>(rightMatchedTuples); if (rightMatchedTuples.size() != distinctMatchedTuples.size()) { return false; } Collection<IValue> rightMatchedNulls = instanceMatch.getTupleMatch().getLeftToRightValueMapping().getValues(); Set<IValue> distinctMatchedNulls = new HashSet<IValue>(rightMatchedNulls); if (rightMatchedNulls.size() != distinctMatchedNulls.size()) { return false; } for (IValue rightNull : distinctMatchedNulls) { if (rightNull instanceof ConstantValue) { return false; } } return true; } }
package string.sliding_window; import java.util.HashMap; public class MinimumWindowSubstring { //TAG: Facebook //TAG: Uber //TAG: LinkedIn //TAG: String //TAG: Sliding window //Difficulty: Hard /** * 76. Minimum Window Substring * * Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). For example, S = "ADOBECODEBANC" T = "ABC" Minimum window is "BANC". Note: If there is no such window in S that covers all characters in T, return the empty string "". If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. */ /* * Solution: * Sliding window problem * Keep a global min length * Keep a sliding window length of t, keep record the characters occurrence, increase right side of window, when all characters appeared in the window, keep update the global min length * Move left side while all characters appear at least once in the window, keep updating the global min * if some characters out of window, move right until new same character in the window * * Time: O(2n) left + right = O(n) * Space: O() */ public String minWindow(String s, String t) { if (s.length() == 0 || t.length() == 0 || s.length() < t.length()) return ""; HashMap<Character, Integer> map = new HashMap<>(); //Count represent how many chars currently fully matches //Min represent the min length of current valid substring //TempLeft is the left index which short the length as far as possible //Left and right represent the optimized left and right index of valid string int count = 0, min = Integer.MAX_VALUE, tempLeft = 0, left = 0, right = 0; char[] charsS = s.toCharArray(), charsT = t.toCharArray(); for (char c: charsT) { if (!map.containsKey(c)) map.put(c, 1); else map.put(c, map.get(c) + 1); } for (int i = 0; i < charsS.length; i++) { if (map.containsKey(charsS[i])) { int cur = map.get(charsS[i]); //If cur == 1 will became 0 in the future, then this char will be fully matched, increase count if (cur == 1) count++; map.put(charsS[i], cur - 1); } //If all matches update right index if (count == map.size() && min > i - tempLeft + 1) { min = i - tempLeft + 1; right = i; } //Short the valid length as much as possible while (count == map.size()) { if (map.containsKey(charsS[tempLeft])) { int cur = map.get(charsS[tempLeft]); if (cur == 0) count map.put(charsS[tempLeft], cur + 1); } //At this time, even count-- already, but tempLeft haven't ++, so tempLeft is still a valid left index, try to update left and also right if min could updated if (min > i - tempLeft + 1) { min = i - tempLeft + 1; left = tempLeft; /* The reason why update right too when only move tempLeft When tempLeft moves so count != map.size(), i need to move right to supply this character from right side When find one, the hashMap is updated to count != map.size(), but right not updated (while loop will not end depends on if left < right, so will not move to next for loop to update right) */ right = i; } tempLeft++; } } //If min hasn't update once, then no matched substring, otherwise use left and right index substring return min == Integer.MAX_VALUE ? "" : s.substring(left, right + 1); } }
package test.beast.app.beauti; import static org.fest.swing.edt.GuiActionRunner.execute; import static org.fest.swing.finder.JFileChooserFinder.findFileChooser; import java.awt.Component; import java.io.File; import java.util.Arrays; import javax.swing.JComboBox; import org.fest.swing.data.Index; import org.fest.swing.data.TableCell; import org.fest.swing.edt.GuiTask; import org.fest.swing.fixture.JButtonFixture; import org.fest.swing.fixture.JCheckBoxFixture; import org.fest.swing.fixture.JComboBoxFixture; import org.fest.swing.fixture.JFileChooserFixture; import org.fest.swing.fixture.JOptionPaneFixture; import org.fest.swing.fixture.JTabbedPaneFixture; import org.fest.swing.fixture.JTableCellFixture; import org.fest.swing.fixture.JTableFixture; import org.fest.swing.image.ScreenshotTaker; import org.junit.Test; import beast.app.util.Utils; public class BeautiRateTutorialTest extends BeautiBase { // file used to store, then reload xml final static String XML_FILE = "rsv.xml"; final static String PREFIX = "doc/tutorials/MEPs/figures/generated/BEAUti_"; @Test public void MEPTutorial() throws InterruptedException { long t0 = System.currentTimeMillis(); ScreenshotTaker screenshotTaker = new ScreenshotTaker(); beauti.frame.setSize(1024, 640); File dir = new File(PREFIX.substring(0, PREFIX.lastIndexOf('/'))); for (File file : dir.listFiles()) { file.delete(); } // 0. Load primate-mtDNA.nex warning("// 0. Load RSV2.nex"); importAlignment("examples/nexus", new File("RSV2.nex")); // load anolis.nex JTabbedPaneFixture f = beautiFrame.tabbedPane(); f.requireVisible(); f.requireTitle("Partitions", Index.atIndex(0)); String[] titles = f.tabTitles(); assertArrayEquals(titles,"[Partitions, Tip Dates, Site Model, Clock Model, Priors, MCMC]"); System.err.println(Arrays.toString(titles)); f = f.selectTab("Partitions"); JTableFixture t = beautiFrame.table(); t.selectCell(TableCell.row(0).column(0)); //0. Split partition... warning("0. Split partition..."); beautiFrame.button("Split").click(); JOptionPaneFixture dialog = new JOptionPaneFixture(robot()); dialog.comboBox().selectItem("1 + 2 + 3 frame 3"); dialog.okButton().click(); // check table t = beautiFrame.table(); printTableContents(t); checkTableContents(t, "[RSV2_1, RSV2, 129, 209, nucleotide, RSV2_1, RSV2_1, RSV2_1]*" + "[RSV2_2, RSV2, 129, 210, nucleotide, RSV2_2, RSV2_2, RSV2_2]*" + "[RSV2_3, RSV2, 129, 210, nucleotide, RSV2_3, RSV2_3, RSV2_3]" ); printBeautiState(f); assertStateEquals("Tree.t:RSV2_2", "clockRate.c:RSV2_2", "birthRate.t:RSV2_2", "Tree.t:RSV2_3", "clockRate.c:RSV2_3", "birthRate.t:RSV2_3", "Tree.t:RSV2_1", "birthRate.t:RSV2_1"); assertOperatorsEqual("StrictClockRateScaler.c:RSV2_2", "YuleBirthRateScaler.t:RSV2_2", "treeScaler.t:RSV2_2", "treeRootScaler.t:RSV2_2", "UniformOperator.t:RSV2_2", "SubtreeSlide.t:RSV2_2", "narrow.t:RSV2_2", "wide.t:RSV2_2", "WilsonBalding.t:RSV2_2", "strictClockUpDownOperator.c:RSV2_2", "StrictClockRateScaler.c:RSV2_3", "YuleBirthRateScaler.t:RSV2_3", "treeScaler.t:RSV2_3", "treeRootScaler.t:RSV2_3", "UniformOperator.t:RSV2_3", "SubtreeSlide.t:RSV2_3", "narrow.t:RSV2_3", "wide.t:RSV2_3", "WilsonBalding.t:RSV2_3", "strictClockUpDownOperator.c:RSV2_3", "YuleBirthRateScaler.t:RSV2_1", "treeScaler.t:RSV2_1", "treeRootScaler.t:RSV2_1", "UniformOperator.t:RSV2_1", "SubtreeSlide.t:RSV2_1", "narrow.t:RSV2_1", "wide.t:RSV2_1", "WilsonBalding.t:RSV2_1"); assertPriorsEqual("YuleModel.t:RSV2_1", "YuleModel.t:RSV2_2", "YuleModel.t:RSV2_3", "ClockPrior.c:RSV2_2", "YuleBirthRatePrior.t:RSV2_2", "ClockPrior.c:RSV2_3", "YuleBirthRatePrior.t:RSV2_3", "YuleBirthRatePrior.t:RSV2_1"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.RSV2_2", "TreeHeight.t:RSV2_2", "clockRate.c:RSV2_2", "YuleModel.t:RSV2_2", "birthRate.t:RSV2_2", "treeLikelihood.RSV2_3", "TreeHeight.t:RSV2_3", "clockRate.c:RSV2_3", "YuleModel.t:RSV2_3", "birthRate.t:RSV2_3", "treeLikelihood.RSV2_1", "TreeHeight.t:RSV2_1", "YuleModel.t:RSV2_1", "birthRate.t:RSV2_1"); //1a. Link trees... warning("1a. Link trees..."); f.selectTab("Partitions"); t = beautiFrame.table(); t.selectCells(TableCell.row(0).column(0), TableCell.row(1).column(0), TableCell.row(2).column(0)); JButtonFixture linkTreesButton = beautiFrame.button("Link Trees"); linkTreesButton.click(); printBeautiState(f); //1b. ...and call the tree "tree" warning("1b. ...and call the tree \"tree\""); f.selectTab("Partitions"); JTableCellFixture cell = beautiFrame.table().cell(TableCell.row(0).column(7)); Component editor = cell.editor(); JComboBoxFixture comboBox = new JComboBoxFixture(robot(), (JComboBox) editor); cell.startEditing(); comboBox.selectAllText(); comboBox.enterText("tree"); cell.stopEditing(); printBeautiState(f); assertStateEquals("clockRate.c:RSV2_2", "clockRate.c:RSV2_3", "Tree.t:tree", "birthRate.t:tree"); assertOperatorsEqual("StrictClockRateScaler.c:RSV2_2", "StrictClockRateScaler.c:RSV2_3", "YuleBirthRateScaler.t:tree", "treeScaler.t:tree", "treeRootScaler.t:tree", "UniformOperator.t:tree", "SubtreeSlide.t:tree", "narrow.t:tree", "wide.t:tree", "WilsonBalding.t:tree", "strictClockUpDownOperator.c:RSV2_3", "strictClockUpDownOperator.c:RSV2_2"); assertPriorsEqual("YuleModel.t:tree", "ClockPrior.c:RSV2_2", "ClockPrior.c:RSV2_3", "YuleBirthRatePrior.t:tree"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.RSV2_2", "clockRate.c:RSV2_2", "treeLikelihood.RSV2_3", "clockRate.c:RSV2_3", "treeLikelihood.RSV2_1", "TreeHeight.t:tree", "YuleModel.t:tree", "birthRate.t:tree"); //2a. Link clocks warning("2a. Link clocks"); f.selectTab("Partitions"); t = beautiFrame.table(); t.selectCells(TableCell.row(0).column(0), TableCell.row(1).column(0), TableCell.row(2).column(0)); JButtonFixture linkClocksButton = beautiFrame.button("Link Clock Models"); linkClocksButton.click(); //2b. and call the uncorrelated relaxed molecular clock "clock" warning("2b. and call the uncorrelated relaxed molecular clock \"clock\""); cell = beautiFrame.table().cell(TableCell.row(0).column(6)); editor = cell.editor(); comboBox = new JComboBoxFixture(robot(), (JComboBox) editor); cell.startEditing(); comboBox.selectAllText(); comboBox.enterText("clock"); cell.stopEditing(); printBeautiState(f); assertStateEquals("Tree.t:tree", "birthRate.t:tree"); assertOperatorsEqual("YuleBirthRateScaler.t:tree", "treeScaler.t:tree", "treeRootScaler.t:tree", "UniformOperator.t:tree", "SubtreeSlide.t:tree", "narrow.t:tree", "wide.t:tree", "WilsonBalding.t:tree"); assertPriorsEqual("YuleModel.t:tree", "YuleBirthRatePrior.t:tree"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.RSV2_2", "treeLikelihood.RSV2_3", "treeLikelihood.RSV2_1", "TreeHeight.t:tree", "YuleModel.t:tree", "birthRate.t:tree"); //3a. Link site models warning("3a. link site models"); f.selectTab("Partitions"); t = beautiFrame.table(); t.selectCells(TableCell.row(0).column(0), TableCell.row(1).column(0), TableCell.row(2).column(0)); JButtonFixture linkSiteModelsButton = beautiFrame.button("Link Site Models"); linkSiteModelsButton.click(); //3b. Set the site model to HKY (empirical) warning("3b. Set the site model to HKY (empirical)"); f.selectTab("Site Model"); beautiFrame.comboBox().selectItem("HKY"); JComboBoxFixture freqs = beautiFrame.comboBox("frequencies"); freqs.selectItem("Empirical"); beautiFrame.checkBox("mutationRate.isEstimated").check(); JCheckBoxFixture fixMeanMutationRate = beautiFrame.checkBox("FixMeanMutationRate"); fixMeanMutationRate.check(); screenshotTaker.saveComponentAsPng(beauti.frame, PREFIX + "Site_Model.png"); printBeautiState(f); //3c. Unlink site models warning("3c. unlink site models"); f.selectTab("Partitions"); t = beautiFrame.table(); t.selectCells(TableCell.row(0).column(0), TableCell.row(1).column(0), TableCell.row(2).column(0)); JButtonFixture unlinkSiteModelsButton = beautiFrame.button("Unlink Site Models"); unlinkSiteModelsButton.click(); printBeautiState(f); assertStateEquals("Tree.t:tree", "birthRate.t:tree", "kappa.s:RSV2_1", "mutationRate.s:RSV2_1", "kappa.s:RSV2_2", "mutationRate.s:RSV2_2", "kappa.s:RSV2_3", "mutationRate.s:RSV2_3"); assertOperatorsEqual("YuleBirthRateScaler.t:tree", "treeScaler.t:tree", "treeRootScaler.t:tree", "UniformOperator.t:tree", "SubtreeSlide.t:tree", "narrow.t:tree", "wide.t:tree", "WilsonBalding.t:tree", "KappaScaler.s:RSV2_1", "KappaScaler.s:RSV2_2", "KappaScaler.s:RSV2_3", "FixMeanMutationRatesOperator"); assertPriorsEqual("YuleModel.t:tree", "YuleBirthRatePrior.t:tree", "KappaPrior.s:RSV2_1", "KappaPrior.s:RSV2_2", "KappaPrior.s:RSV2_3"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.RSV2_2", "treeLikelihood.RSV2_3", "treeLikelihood.RSV2_1", "TreeHeight.t:tree", "YuleModel.t:tree", "birthRate.t:tree", "kappa.s:RSV2_1", "mutationRate.s:RSV2_1", "kappa.s:RSV2_2", "mutationRate.s:RSV2_2", "kappa.s:RSV2_3", "mutationRate.s:RSV2_3"); screenshotTaker.saveComponentAsPng(beauti.frame, PREFIX + "partition.png"); //4. set up tip dates f = f.selectTab("Tip Dates"); warning("4. Seting up tip dates"); beautiFrame.checkBox().click(); beautiFrame.button("Guess").click(); JOptionPaneFixture dialog2 = new JOptionPaneFixture(robot()); dialog2.textBox("SplitChar").deleteText().enterText("s"); screenshotTaker.saveComponentAsPng(dialog2.component(), PREFIX + "GuessDates.png"); dialog2.comboBox("delimiterCombo").selectItem("after last"); dialog2.okButton().click(); screenshotTaker.saveComponentAsPng(beauti.frame, PREFIX + "dates.png"); printBeautiState(f); assertStateEquals("Tree.t:tree", "birthRate.t:tree", "kappa.s:RSV2_1", "mutationRate.s:RSV2_1", "kappa.s:RSV2_2", "mutationRate.s:RSV2_2", "kappa.s:RSV2_3", "mutationRate.s:RSV2_3", "clockRate.c:clock"); assertOperatorsEqual("YuleBirthRateScaler.t:tree", "treeScaler.t:tree", "treeRootScaler.t:tree", "UniformOperator.t:tree", "SubtreeSlide.t:tree", "narrow.t:tree", "wide.t:tree", "WilsonBalding.t:tree", "KappaScaler.s:RSV2_1", "KappaScaler.s:RSV2_2", "KappaScaler.s:RSV2_3", "FixMeanMutationRatesOperator", "StrictClockRateScaler.c:clock", "strictClockUpDownOperator.c:clock"); assertPriorsEqual("YuleModel.t:tree", "YuleBirthRatePrior.t:tree", "KappaPrior.s:RSV2_1", "KappaPrior.s:RSV2_2", "KappaPrior.s:RSV2_3", "ClockPrior.c:clock"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.RSV2_2", "treeLikelihood.RSV2_3", "treeLikelihood.RSV2_1", "TreeHeight.t:tree", "YuleModel.t:tree", "birthRate.t:tree", "kappa.s:RSV2_1", "mutationRate.s:RSV2_1", "kappa.s:RSV2_2", "mutationRate.s:RSV2_2", "kappa.s:RSV2_3", "mutationRate.s:RSV2_3", "clockRate.c:clock"); //5. Change tree prior to Coalescent with constant pop size warning("5a. Change tree prior to Coalescent with constant pop size"); f.selectTab("Priors"); beautiFrame.comboBox("TreeDistribution").selectItem("Coalescent Constant Population"); warning("5b. Change clock prior to Log Normal with M = -5, S = 1.25"); beautiFrame.comboBox("clockRate.c:clock.distr").selectItem("Log Normal"); beautiFrame.button("ClockPrior.c:clock.editButton").click(); beautiFrame.textBox("M").selectAll().setText("-5"); beautiFrame.textBox("S").selectAll().setText("1.25"); screenshotTaker.saveComponentAsPng(beauti.frame, PREFIX + "priors.png"); printBeautiState(f); assertStateEquals("Tree.t:tree", "kappa.s:RSV2_1", "mutationRate.s:RSV2_1", "kappa.s:RSV2_2", "mutationRate.s:RSV2_2", "kappa.s:RSV2_3", "mutationRate.s:RSV2_3", "clockRate.c:clock", "popSize.t:tree"); assertOperatorsEqual("treeScaler.t:tree", "treeRootScaler.t:tree", "UniformOperator.t:tree", "SubtreeSlide.t:tree", "narrow.t:tree", "wide.t:tree", "WilsonBalding.t:tree", "KappaScaler.s:RSV2_1", "KappaScaler.s:RSV2_2", "KappaScaler.s:RSV2_3", "FixMeanMutationRatesOperator", "StrictClockRateScaler.c:clock", "strictClockUpDownOperator.c:clock", "PopSizeScaler.t:tree"); assertPriorsEqual("CoalescentConstant.t:tree", "ClockPrior.c:clock", "KappaPrior.s:RSV2_1", "KappaPrior.s:RSV2_2", "KappaPrior.s:RSV2_3", "PopSizePrior.t:tree"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.RSV2_2", "treeLikelihood.RSV2_3", "treeLikelihood.RSV2_1", "TreeHeight.t:tree", "kappa.s:RSV2_1", "mutationRate.s:RSV2_1", "kappa.s:RSV2_2", "mutationRate.s:RSV2_2", "kappa.s:RSV2_3", "mutationRate.s:RSV2_3", "clockRate.c:clock", "popSize.t:tree", "CoalescentConstant.t:tree"); //6. Run MCMC and look at results in Tracer, TreeAnnotator->FigTree warning("6. Setting up MCMC parameters"); f = f.selectTab("MCMC"); beautiFrame.textBox("chainLength").selectAll().setText("2000000"); beautiFrame.button("tracelog.editButton").click(); beautiFrame.textBox("logEvery").selectAll().setText("400"); beautiFrame.button("tracelog.editButton").click(); beautiFrame.button("treelog.t:tree.editButton").click(); beautiFrame.textBox("logEvery").selectAll().setText("400"); screenshotTaker.saveComponentAsPng(beauti.frame, PREFIX + "mcmc.png"); beautiFrame.button("treelog.t:tree.editButton").click(); printBeautiState(f); assertStateEquals("Tree.t:tree", "kappa.s:RSV2_1", "mutationRate.s:RSV2_1", "kappa.s:RSV2_2", "mutationRate.s:RSV2_2", "kappa.s:RSV2_3", "mutationRate.s:RSV2_3", "clockRate.c:clock", "popSize.t:tree"); assertOperatorsEqual("treeScaler.t:tree", "treeRootScaler.t:tree", "UniformOperator.t:tree", "SubtreeSlide.t:tree", "narrow.t:tree", "wide.t:tree", "WilsonBalding.t:tree", "KappaScaler.s:RSV2_1", "KappaScaler.s:RSV2_2", "KappaScaler.s:RSV2_3", "FixMeanMutationRatesOperator", "StrictClockRateScaler.c:clock", "strictClockUpDownOperator.c:clock", "PopSizeScaler.t:tree"); assertPriorsEqual("CoalescentConstant.t:tree", "ClockPrior.c:clock", "KappaPrior.s:RSV2_1", "KappaPrior.s:RSV2_2", "KappaPrior.s:RSV2_3", "PopSizePrior.t:tree"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.RSV2_2", "treeLikelihood.RSV2_3", "treeLikelihood.RSV2_1", "TreeHeight.t:tree", "kappa.s:RSV2_1", "mutationRate.s:RSV2_1", "kappa.s:RSV2_2", "mutationRate.s:RSV2_2", "kappa.s:RSV2_3", "mutationRate.s:RSV2_3", "clockRate.c:clock", "popSize.t:tree", "CoalescentConstant.t:tree"); //7. Run MCMC and look at results in Tracer, TreeAnnotator->FigTree warning("7. Run MCMC and look at results in Tracer, TreeAnnotator->FigTree"); makeSureXMLParses(); long t1 = System.currentTimeMillis(); System.err.println("total time: " + (t1 - t0)/1000 + " seconds"); } @Test public void MEPBSPTutorial() throws InterruptedException { if (true) {return;} try { long t0 = System.currentTimeMillis(); ScreenshotTaker screenshotTaker = new ScreenshotTaker(); beauti.frame.setSize(1024, 640); // 1. reaload XML file warning("1. reload rsv.xml"); String dir = "" + org.fest.util.Files.temporaryFolder(); String file = XML_FILE; if (!Utils.isMac()) { beautiFrame.menuItemWithPath("File", "Load").click(); JFileChooserFixture fileChooser = findFileChooser().using(robot()); fileChooser.setCurrentDirectory(new File(dir)); fileChooser.selectFile(new File(file)).approve(); } else { _file = new File(dir + "/" + file); execute(new GuiTask() { protected void executeInEDT() { doc.newAnalysis(); doc.setFileName(_file.getAbsolutePath()); try { doc.loadXML(new File(doc.getFileName())); } catch (Exception e) { e.printStackTrace(); } } }); } JTabbedPaneFixture f = beautiFrame.tabbedPane(); printBeautiState(f); // 2. change tree prior to BSP warning("2. change tree prior to BSP"); f.selectTab("Priors"); beautiFrame.comboBox("TreeDistribution").selectItem("Coalescent Bayesian Skyline"); screenshotTaker.saveComponentAsPng(beauti.frame, PREFIX + "priors2.png"); printBeautiState(f); // 3. change tree prior to BSP warning("3. change group and population size parameters"); beautiFrame.menuItemWithPath("View","Show Initialization panel").click(); beautiFrame.button("bPopSizes.t:tree.editButton").click(); beautiFrame.textBox("dimension").selectAll().setText("3"); beautiFrame.button("bPopSizes.t:tree.editButton").click(); beautiFrame.button("bGroupSizes.t:tree.editButton").click(); beautiFrame.textBox("dimension").selectAll().setText("3"); screenshotTaker.saveComponentAsPng(beauti.frame, PREFIX + "init.png"); printBeautiState(f); // 4. set chain-length to 10M, log every 10K warning("4. set chaing-length to 10M, log every 10K"); f = f.selectTab("MCMC"); beautiFrame.textBox("chainLength").selectAll().setText("10000000"); beautiFrame.button("tracelog.editButton").click(); beautiFrame.textBox("logEvery").selectAll().setText("10000"); beautiFrame.button("tracelog.editButton").click(); beautiFrame.button("treelog.t:tree.editButton").click(); beautiFrame.textBox("logEvery").selectAll().setText("10000"); beautiFrame.button("treelog.t:tree.editButton").click(); printBeautiState(f); // 5. save XML file warning("5. save XML file"); File fout = new File(org.fest.util.Files.temporaryFolder() + "/" + XML_FILE); if (fout.exists()) { fout.delete(); } saveFile(""+org.fest.util.Files.temporaryFolder(), XML_FILE); //4. Run MCMC and look at results in Tracer, TreeAnnotator->FigTree makeSureXMLParses(); long t1 = System.currentTimeMillis(); System.err.println("total time: " + (t1 - t0)/1000 + " seconds"); } catch (Exception e) { e.printStackTrace(); } } }
package com.akiban.server.test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.io.File; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.Callable; import com.akiban.ais.AISCloner; import com.akiban.ais.model.*; import com.akiban.ais.util.TableChangeValidator; import com.akiban.qp.expression.BoundExpressions; import com.akiban.qp.operator.QueryContext; import com.akiban.qp.operator.SimpleQueryContext; import com.akiban.qp.persistitadapter.PersistitAdapter; import com.akiban.qp.rowtype.Schema; import com.akiban.server.AkServerInterface; import com.akiban.server.AkServerUtil; import com.akiban.server.api.dml.scan.ScanFlag; import com.akiban.server.rowdata.RowDef; import com.akiban.server.rowdata.SchemaFactory; import com.akiban.server.service.ServiceManagerImpl; import com.akiban.server.service.config.ConfigurationService; import com.akiban.server.rowdata.RowData; import com.akiban.server.service.config.TestConfigService; import com.akiban.server.service.dxl.DXLService; import com.akiban.server.service.dxl.DXLTestHookRegistry; import com.akiban.server.service.dxl.DXLTestHooks; import com.akiban.server.service.lock.LockService; import com.akiban.server.service.routines.RoutineLoader; import com.akiban.server.service.servicemanager.GuicedServiceManager; import com.akiban.server.service.transaction.TransactionService; import com.akiban.server.service.tree.TreeService; import com.akiban.server.t3expressions.T3RegistryService; import com.akiban.server.t3expressions.TCastResolver; import com.akiban.server.types.ValueSource; import com.akiban.server.types.extract.ConverterTestUtils; import com.akiban.server.types3.Types3Switch; import com.akiban.server.types3.pvalue.PValueSource; import com.akiban.server.types3.pvalue.PValueSources; import com.akiban.server.util.GroupIndexCreator; import com.akiban.sql.StandardException; import com.akiban.sql.aisddl.AlterTableDDL; import com.akiban.sql.parser.AlterTableNode; import com.akiban.sql.parser.SQLParser; import com.akiban.sql.parser.StatementNode; import com.akiban.util.AssertUtils; import com.akiban.util.Strings; import com.akiban.util.tap.TapReport; import com.akiban.util.Undef; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import com.akiban.server.api.dml.scan.RowDataOutput; import com.akiban.server.store.PersistitStore; import com.akiban.server.store.Store; import com.akiban.util.ListUtils; import com.akiban.server.TableStatistics; import com.akiban.server.api.DDLFunctions; import com.akiban.server.api.DMLFunctions; import com.akiban.server.api.dml.scan.CursorId; import com.akiban.server.api.dml.scan.NewRow; import com.akiban.server.api.dml.scan.NiceRow; import com.akiban.server.api.dml.scan.RowOutput; import com.akiban.server.api.dml.scan.ScanAllRequest; import com.akiban.server.api.dml.scan.ScanRequest; import com.akiban.server.error.InvalidOperationException; import com.akiban.server.error.NoSuchTableException; import com.akiban.server.service.ServiceManager; import com.akiban.server.service.session.Session; import org.junit.Rule; import org.junit.rules.MethodRule; import org.junit.rules.TestName; import org.junit.rules.TestWatchman; import org.junit.runners.model.FrameworkMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>Base class for all API tests. Contains a @SetUp that gives you a fresh DDLFunctions and DMLFunctions, plus * various convenience testing methods.</p> */ public class ApiTestBase { private static final int MIN_FREE_SPACE = 256 * 1024 * 1024; private static final String TAPS = System.getProperty("it.taps"); protected final static Object UNDEF = Undef.only(); private static final Comparator<? super TapReport> TAP_REPORT_COMPARATOR = new Comparator<TapReport>() { @Override public int compare(TapReport o1, TapReport o2) { return o1.getName().compareTo(o2.getName()); } }; public static interface TestRowOutput extends RowOutput { public int getRowCount(); public void clear(); } public static class ListRowOutput implements TestRowOutput { private final List<NewRow> rows = new ArrayList<>(); private final List<NewRow> rowsUnmodifiable = Collections.unmodifiableList(rows); private int mark = 0; @Override public void output(NewRow row) { rows.add(row); } public List<NewRow> getRows() { return rowsUnmodifiable; } @Override public int getRowCount() { return rows.size(); } @Override public void clear() { rows.clear(); } @Override public void mark() { mark = rows.size(); } @Override public void rewind() { ListUtils.truncate(rows, mark); } } public static class CountingRowOutput implements TestRowOutput { private int count = 0; private int mark = 0; @Override public void output(NewRow row) { ++count; } @Override public void mark() { mark = count; } @Override public void rewind() { count = mark; } @Override public int getRowCount() { return count; } @Override public void clear() { count = 0; } } protected ApiTestBase(String suffix) { final String name = this.getClass().getSimpleName(); if (!name.endsWith(suffix)) { throw new RuntimeException( String.format("You must rename %s to something like Foo%s", name, suffix) ); } } private static ServiceManager sm; private Session session; private int aisGeneration; private final Set<RowUpdater> unfinishedRowUpdaters = new HashSet<>(); private static Map<String,String> lastStartupConfigProperties = null; private static boolean needServicesRestart = false; private boolean types3SwitchSave; protected static Set<Callable<Void>> beforeStopServices = new HashSet<>(); @Rule public static final TestName testName = new TestName(); protected String testName() { return testName.getMethodName(); } @Before public final void startTestServices() throws Exception { types3SwitchSave = Types3Switch.ON; Types3Switch.ON &= testSupportsPValues(); assertTrue("some row updaters were left over: " + unfinishedRowUpdaters, unfinishedRowUpdaters.isEmpty()); System.setProperty("akiban.home", System.getProperty("user.home")); try { ConverterTestUtils.setGlobalTimezone("UTC"); Map<String, String> startupConfigProperties = startupConfigProperties(); Map<String,String> propertiesForEquality = propertiesForEquality(startupConfigProperties); if (needServicesRestart || lastStartupConfigProperties == null || !lastStartupConfigProperties.equals(propertiesForEquality)) { // we need a shutdown if we needed a restart, or if the lastStartupConfigProperties are not null, // which (because of the condition on the "if" above) implies the last startup config properties // are different from this one's boolean needShutdown = needServicesRestart || lastStartupConfigProperties != null; if (needShutdown) { needServicesRestart = false; // clear the flag if it was set stopTestServices(); } int attempt = 1; while (!AkServerUtil.cleanUpDirectory(TestConfigService.dataDirectory())) { assertTrue("Too many directory failures", (attempt++ < 10)); TestConfigService.newDataDirectory(); } assertNull("lastStartupConfigProperties should be null", lastStartupConfigProperties); sm = createServiceManager(startupConfigProperties); sm.startServices(); ServiceManagerImpl.setServiceManager(sm); if (TAPS != null) { sm.getStatisticsService().reset(TAPS); sm.getStatisticsService().setEnabled(TAPS, true); } lastStartupConfigProperties = propertiesForEquality; } session = sm.getSessionService().createSession(); } catch (Exception e) { handleStartupFailure(e); } } @Rule public MethodRule exceptionCatchingRule = new TestWatchman() { @Override public void failed(Throwable e, FrameworkMethod method) { needServicesRestart = true; } }; /** * Handle a failure during services startup. The default implementation is to just throw the exception, and * most tests should <em>not</em> override this. It's designed solely as a testing hook for FailureOnStartupIT. * @param e the startup exception * @throws Exception the startup exception */ void handleStartupFailure(Exception e) throws Exception { throw e; } protected ServiceManager createServiceManager(Map<String, String> startupConfigProperties) { TestConfigService.setOverrides(startupConfigProperties); return new GuicedServiceManager(serviceBindingsProvider()); } /** Specify special service bindings. * If you override this, you need to override {@link #startupConfigProperties} * to return something different so that the special services aren't shared * with other tests. */ protected GuicedServiceManager.BindingsConfigurationProvider serviceBindingsProvider() { return GuicedServiceManager.testUrls(); } @After public final void tearDownAllTables() throws Exception { Types3Switch.ON = types3SwitchSave; if (lastStartupConfigProperties == null) return; // services never started up Set<RowUpdater> localUnfinishedUpdaters = new HashSet<>(unfinishedRowUpdaters); unfinishedRowUpdaters.clear(); dropAllTables(); assertTrue("not all updaters were used: " + localUnfinishedUpdaters, localUnfinishedUpdaters.isEmpty()); String openCursorsMessage = null; if (sm.serviceIsStarted(DXLService.class)) { DXLTestHooks dxlTestHooks = DXLTestHookRegistry.get(); // Check for any residual open cursors if (dxlTestHooks.openCursorsExist()) { openCursorsMessage = "open cursors remaining:" + dxlTestHooks.describeOpenCursors(); } } if (TAPS != null) { TapReport[] reports = sm.getStatisticsService().getReport(TAPS); Arrays.sort(reports, TAP_REPORT_COMPARATOR); for (TapReport report : reports) { long totalNanos = report.getCumulativeTime(); double totalSecs = ((double) totalNanos) / 1000000000.0d; double secsPer = totalSecs / report.getOutCount(); System.err.printf("%s:\t in=%d out=%d time=%.2f sec (%d nanos, %.5f sec per out)%n", report.getName(), report.getInCount(), report.getOutCount(), totalSecs, totalNanos, secsPer ); } } session.close(); if (openCursorsMessage != null) { fail(openCursorsMessage); } needServicesRestart |= runningOutOfSpace(); } private static boolean runningOutOfSpace() { return TestConfigService.dataDirectory().getFreeSpace() < MIN_FREE_SPACE; } private static void beforeStopServices(boolean crash) throws Exception { for (Callable<Void> callable : beforeStopServices) { callable.call(); } } public final void stopTestServices() throws Exception { beforeStopServices(false); ServiceManagerImpl.setServiceManager(null); if (lastStartupConfigProperties == null) { return; } lastStartupConfigProperties = null; sm.stopServices(); } public final void crashTestServices() throws Exception { beforeStopServices(true); sm.crashServices(); sm = null; session = null; lastStartupConfigProperties = null; } public final void restartTestServices(Map<String, String> properties) throws Exception { ServiceManagerImpl.setServiceManager(null); sm = createServiceManager( properties ); sm.startServices(); session = sm.getSessionService().createSession(); lastStartupConfigProperties = propertiesForEquality(properties); ddl(); // loads up the schema manager et al ServiceManagerImpl.setServiceManager(sm); } public final Session createNewSession() { return sm.getSessionService().createSession(); } protected Map<String, String> defaultPropertiesToPreserveOnRestart() { return Collections.singletonMap( TestConfigService.DATA_PATH_KEY, TestConfigService.dataDirectory().getAbsolutePath()); } protected boolean defaultDoCleanOnUnload() { return true; } public final void safeRestartTestServices() throws Exception { safeRestartTestServices(defaultPropertiesToPreserveOnRestart()); } public final void safeRestartTestServices(Map<String, String> propertiesToPreserve) throws Exception { /* * Need this because deleting Trees currently is not transactional. Therefore after * restart we recover the previous trees and forget about the deleteTree operations. * TODO: remove when transaction Tree management is done. */ treeService().getDb().checkpoint(); final boolean original = TestConfigService.getDoCleanOnUnload(); try { TestConfigService.setDoCleanOnUnload(defaultDoCleanOnUnload()); crashTestServices(); // TODO: WHY doesn't this work with stop? } finally { TestConfigService.setDoCleanOnUnload(original); } restartTestServices(propertiesToPreserve); } protected final DMLFunctions dml() { return dxl().dmlFunctions(); } protected final DDLFunctions ddl() { return dxl().ddlFunctions(); } protected final Store store() { return sm.getStore(); } protected final PersistitStore persistitStore() { return store().getPersistitStore(); } protected final AkServerInterface akServer() { return sm.getAkSserver(); } protected String akibanFK(String childCol, String parentTable, String parentCol) { return String.format("GROUPING FOREIGN KEY (%s) REFERENCES \"%s\" (%s)", childCol, parentTable, parentCol ); } protected final Session session() { return session; } protected final PersistitAdapter persistitAdapter(Schema schema) { return new PersistitAdapter(schema, store(), treeService(), session(), configService()); } protected final QueryContext queryContext(PersistitAdapter adapter) { return new SimpleQueryContext(adapter) { @Override public ServiceManager getServiceManager() { return sm; } }; } protected final AkibanInformationSchema ais() { return ddl().getAIS(session()); } protected final ServiceManager serviceManager() { return sm; } protected final TCastResolver castResolver() { return sm.getServiceByClass(T3RegistryService.class).getCastsResolver(); } protected final ConfigurationService configService() { return sm.getConfigurationService(); } protected final DXLService dxl() { return sm.getDXL(); } protected final TreeService treeService() { return sm.getTreeService(); } protected final TransactionService txnService() { return sm.getServiceByClass(TransactionService.class); } protected final LockService lockService() { return sm.getServiceByClass(LockService.class); } protected final RoutineLoader routineLoader() { return sm.getServiceByClass(RoutineLoader.class); } protected final int aisGeneration() { return aisGeneration; } protected final void updateAISGeneration() { aisGeneration = ddl().getGenerationAsInt(session()); } protected Map<String, String> startupConfigProperties() { return Collections.emptyMap(); } // Property.equals() does not include the value. protected Map<String,String> propertiesForEquality(Map<String, String> properties) { Map<String,String> result = new HashMap<>(properties.size()); for (Map.Entry<String, String> p : properties.entrySet()) { result.put(p.getKey(), p.getValue()); } return result; } /** * A simple unique (per class) property that can be returned for tests * overriding the {@link #startupConfigProperties()} and/or * {@link #serviceBindingsProvider()} methods. */ protected Map<String, String> uniqueStartupConfigProperties(Class clazz) { return Collections.singletonMap( "test.services", clazz.getName() ); } protected AkibanInformationSchema createFromDDL(ServiceManager sm, String schema, String ddl) { SchemaFactory schemaFactory = new SchemaFactory(schema); return schemaFactory.ais(sm, ddl().getAIS(session()), ddl); } protected static final class SimpleColumn { public final String columnName; public final String typeName; public final Long param1; public final Long param2; public SimpleColumn(String columnName, String typeName) { this(columnName, typeName, null, null); } public SimpleColumn(String columnName, String typeName, Long param1, Long param2) { this.columnName = columnName; this.typeName = typeName; this.param1 = param1; this.param2 = param2; } } protected void runAlter(String schema, QueryContext queryContext, String sql) { SQLParser parser = new SQLParser(); StatementNode node; try { node = parser.parseStatement(sql); } catch(StandardException e) { throw new RuntimeException(e); } org.junit.Assert.assertTrue("is alter node", node instanceof AlterTableNode); AlterTableDDL.alterTable(ddl(), dml(), session(), schema, (AlterTableNode) node, queryContext); updateAISGeneration(); } protected final int createTableFromTypes(String schema, String table, boolean firstIsPk, boolean createIndexes, SimpleColumn... columns) { AISBuilder builder = new AISBuilder(); builder.userTable(schema, table); int colPos = 0; SimpleColumn pk = firstIsPk ? columns[0] : new SimpleColumn("id", "int"); builder.column(schema, table, pk.columnName, colPos++, pk.typeName, null, null, false, false, null, null); builder.index(schema, table, Index.PRIMARY_KEY_CONSTRAINT, true, Index.PRIMARY_KEY_CONSTRAINT); builder.indexColumn(schema, table, Index.PRIMARY_KEY_CONSTRAINT, pk.columnName, 0, true, null); for(int i = firstIsPk ? 1 : 0; i < columns.length; ++i) { SimpleColumn sc = columns[i]; String name = sc.columnName == null ? "c" + (colPos + 1) : sc.columnName; builder.column(schema, table, name, colPos++, sc.typeName, sc.param1, sc.param2, true, false, null, null); if(createIndexes) { builder.index(schema, table, name, false, Index.KEY_CONSTRAINT); builder.indexColumn(schema, table, name, name, 0, true, null); } } UserTable tempTable = builder.akibanInformationSchema().getUserTable(schema, table); ddl().createTable(session(), tempTable); updateAISGeneration(); return tableId(schema, table); } protected final int createTableFromTypes(String schema, String table, boolean firstIsPk, boolean createIndexes, String... typeNames) { SimpleColumn simpleColumns[] = new SimpleColumn[typeNames.length]; for(int i = 0; i < typeNames.length; ++i) { simpleColumns[i] = new SimpleColumn(null, typeNames[i]); } return createTableFromTypes(schema, table, firstIsPk, createIndexes, simpleColumns); } protected final int createTable(String schema, String table, String definition) throws InvalidOperationException { String ddl = String.format("CREATE TABLE \"%s\" (%s)", table, definition); AkibanInformationSchema tempAIS = createFromDDL(serviceManager(), schema, ddl); UserTable tempTable = tempAIS.getUserTable(schema, table); ddl().createTable(session(), tempTable); updateAISGeneration(); return ddl().getTableId(session(), new TableName(schema, table)); } protected final int createTable(String schema, String table, String... definitions) throws InvalidOperationException { assertTrue("must have at least one definition element", definitions.length >= 1); StringBuilder unifiedDef = new StringBuilder(); for (String definition : definitions) { unifiedDef.append(definition).append(','); } unifiedDef.setLength(unifiedDef.length() - 1); return createTable(schema, table, unifiedDef.toString()); } protected final void createSequence (String schema, String name, String definition) { String ddl = String.format("CREATE SEQUENCE %s %s", name, definition); AkibanInformationSchema tempAIS = createFromDDL(serviceManager(), schema, ddl); Sequence sequence = tempAIS.getSequence(new TableName(schema, name)); ddl().createSequence(session(), sequence); updateAISGeneration(); } protected final void createView(String schema, String name, String definition) { String ddl = String.format("CREATE VIEW %s AS %s", name, definition); AkibanInformationSchema tempAIS = createFromDDL(serviceManager(), schema, ddl); View view = tempAIS.getView(new TableName(schema, name)); ddl().createView(session(), view); updateAISGeneration(); } protected final int createTable(TableName tableName, String... definitions) throws InvalidOperationException { return createTable(tableName.getSchemaName(), tableName.getTableName(), definitions); } private AkibanInformationSchema createUniqueIndexInternal(String schema, String table, String indexName, String... indexCols) { return createIndexInternal(schema, table, indexName, true, indexCols); } private AkibanInformationSchema createIndexInternal(String schema, String table, String indexName, String... indexCols) { return createIndexInternal(schema, table, indexName, false, indexCols); } private AkibanInformationSchema createIndexInternal(String schema, String table, String indexName, boolean unique, String... indexCols) { String ddl = String.format("CREATE %s INDEX \"%s\" ON \"%s\".\"%s\"(%s)", unique ? "UNIQUE" : "", indexName, schema, table, Strings.join(Arrays.asList(indexCols), ",")); return createFromDDL(serviceManager(), schema, ddl); } protected final TableIndex createIndex(String schema, String table, String indexName, String... indexCols) { AkibanInformationSchema tempAIS = createIndexInternal(schema, table, indexName, indexCols); Index tempIndex = tempAIS.getUserTable(schema, table).getIndex(indexName); ddl().createIndexes(session(), Collections.singleton(tempIndex)); updateAISGeneration(); return ddl().getTable(session(), new TableName(schema, table)).getIndex(indexName); } protected final TableIndex createUniqueIndex(String schema, String table, String indexName, String... indexCols) { AkibanInformationSchema tempAIS = createUniqueIndexInternal(schema, table, indexName, indexCols); Index tempIndex = tempAIS.getUserTable(schema, table).getIndex(indexName); ddl().createIndexes(session(), Collections.singleton(tempIndex)); updateAISGeneration(); return ddl().getTable(session(), new TableName(schema, table)).getIndex(indexName); } protected final TableIndex createSpatialTableIndex(String schema, String table, String indexName, int firstSpatialArgument, int dimensions, String... indexCols) { AkibanInformationSchema tempAIS = AISCloner.clone(createIndexInternal(schema, table, indexName, indexCols)); TableIndex tempIndex = tempAIS.getUserTable(schema, table).getIndex(indexName); tempIndex.markSpatial(firstSpatialArgument, dimensions); ddl().createIndexes(session(), Collections.singleton(tempIndex)); updateAISGeneration(); return ddl().getTable(session(), new TableName(schema, table)).getIndex(indexName); } protected final TableIndex createGroupingFKIndex(String schema, String table, String indexName, String... indexCols) { assertTrue("grouping fk index must start with __akiban", indexName.startsWith("__akiban")); AkibanInformationSchema tempAIS = AISCloner.clone(createIndexInternal(schema, table, indexName, indexCols)); UserTable userTable = tempAIS.getUserTable(schema, table); TableIndex tempIndex = userTable.getIndex(indexName); userTable.removeIndexes(Collections.singleton(tempIndex)); TableIndex fkIndex = TableIndex.create(tempAIS, userTable, indexName, 0, false, "FOREIGN KEY"); for(IndexColumn col : tempIndex.getKeyColumns()) { IndexColumn.create(fkIndex, col.getColumn(), col.getPosition(), col.isAscending(), col.getIndexedLength()); } ddl().createIndexes(session(), Collections.singleton(fkIndex)); updateAISGeneration(); return ddl().getTable(session(), new TableName(schema, table)).getIndex(indexName); } protected final TableIndex createTableIndex(int tableId, String indexName, boolean unique, String... columns) { AkibanInformationSchema temp = AISCloner.clone(ais()); return createTableIndex(temp.getUserTable(tableId), indexName, unique, columns); } protected final TableIndex createTableIndex(UserTable table, String indexName, boolean unique, String... columns) { TableIndex index = new TableIndex(table, indexName, 0, unique, "KEY"); int pos = 0; for (String columnName : columns) { Column column = table.getColumn(columnName); IndexColumn.create(index, column, pos++, true, null); } ddl().createIndexes(session(), Collections.singleton(index)); return getUserTable(table.getTableId()).getIndex(indexName); } /** @deprecated **/ protected final GroupIndex createGroupIndex(String groupName, String indexName, String tableColumnPairs) { return createGroupIndex(ais().getGroup(groupName).getName(), indexName, tableColumnPairs); } /** @deprecated **/ protected final GroupIndex createGroupIndex(String groupName, String indexName, String tableColumnPairs, Index.JoinType joinType) { return createGroupIndex(ais().getGroup(groupName).getName(), indexName, tableColumnPairs, joinType); } protected final GroupIndex createGroupIndex(TableName groupName, String indexName, String tableColumnPairs) throws InvalidOperationException { return createGroupIndex(groupName, indexName, tableColumnPairs, Index.JoinType.LEFT); } protected final GroupIndex createGroupIndex(TableName groupName, String indexName, String tableColumnPairs, Index.JoinType joinType) throws InvalidOperationException { AkibanInformationSchema ais = ddl().getAIS(session()); final Index index; index = GroupIndexCreator.createIndex(ais, groupName, indexName, tableColumnPairs, joinType); ddl().createIndexes(session(), Collections.singleton(index)); return ddl().getAIS(session()).getGroup(groupName).getIndex(indexName); } protected final GroupIndex createSpatialGroupIndex(TableName groupName, String indexName, int firstSpatialArgument, int dimensions, String tableColumnPairs, Index.JoinType joinType) throws InvalidOperationException { AkibanInformationSchema ais = ddl().getAIS(session()); Index index = GroupIndexCreator.createIndex(ais, groupName, indexName, tableColumnPairs, joinType); index.markSpatial(firstSpatialArgument, dimensions); ddl().createIndexes(session(), Collections.singleton(index)); return ddl().getAIS(session()).getGroup(groupName).getIndex(indexName); } protected final FullTextIndex createFullTextIndex(ServiceManager sm, String schema, String table, String indexName, String... indexCols) { AkibanInformationSchema tempAIS = createIndexInternal(schema, table, indexName, "FULL_TEXT(" + Strings.join(Arrays.asList(indexCols), ",") + ")"); Index tempIndex = tempAIS.getUserTable(schema, table).getFullTextIndex(indexName); ddl().createIndexes(session(), Collections.singleton(tempIndex)); updateAISGeneration(); return ddl().getUserTable(session(), new TableName(schema, table)).getFullTextIndex(indexName); } protected int createTablesAndIndexesFromDDL(String schema, String ddl) { SchemaFactory schemaFactory = new SchemaFactory(schema); // Insert DDL into the System AkibanInformationSchema ais = schemaFactory.ais(serviceManager(), ddl(), session(), ddl); // sort DDL to find first root table of the user schema ais = schemaFactory.ais (serviceManager(), ddl); List<UserTable> tables = new ArrayList<>(ais.getUserTables().values()); Collections.sort(tables, new Comparator<UserTable>() { @Override public int compare(UserTable t1, UserTable t2) { return t1.getTableId().compareTo(t2.getTableId()); } }); updateAISGeneration(); return ddl().getTableId(session(), tables.get(0).getName()); } protected int loadSchemaFile(String schemaName, File file) throws Exception { String sql = Strings.dumpFileToString(file); return createTablesAndIndexesFromDDL(schemaName, sql); } protected void loadDataFile(String schemaName, File file) throws Exception { String tableName = file.getName().replace(".dat", ""); int tableId = tableId(schemaName, tableName); for (String line : Strings.dumpFile(file)) { String[] cols = line.split("\t"); NewRow row = createNewRow(tableId); for (int i = 0; i < cols.length; i++) row.put(i, cols[i]); dml().writeRow(session(), row); } } /** * Expects an exact number of rows. This checks both the countRowExactly and countRowsApproximately * methods on DMLFunctions. * @param tableId the table to count * @param rowsExpected how many rows we expect * @throws InvalidOperationException for various reasons :) */ protected final void expectRowCount(int tableId, long rowsExpected) throws InvalidOperationException { TableStatistics tableStats = dml().getTableStatistics(session(), tableId, true); assertEquals("table ID", tableId, tableStats.getRowDefId()); assertEquals("rows by TableStatistics", rowsExpected, tableStats.getRowCount()); } protected static RuntimeException unexpectedException(Throwable cause) { return new RuntimeException("unexpected exception", cause); } protected final List<RowData> scanFull(ScanRequest request) { try { return RowDataOutput.scanFull(session(), aisGeneration(), dml(), request); } catch (InvalidOperationException e) { throw new TestException(e); } } protected final List<NewRow> scanAll(ScanRequest request) throws InvalidOperationException { ListRowOutput output = new ListRowOutput(); CursorId cursorId = dml().openCursor(session(), aisGeneration(), request); dml().scanSome(session(), cursorId, output); dml().closeCursor(session(), cursorId); return output.getRows(); } protected final ScanRequest scanAllIndexRequest(TableIndex index) throws InvalidOperationException { final Set<Integer> columns = new HashSet<>(); for(IndexColumn icol : index.getKeyColumns()) { columns.add(icol.getColumn().getPosition()); } return new ScanAllRequest(index.getTable().getTableId(), columns, index.getIndexId(), null); } protected final List<NewRow> scanAllIndex(TableIndex index) throws InvalidOperationException { return scanAll(scanAllIndexRequest(index)); } protected final void writeRow(int tableId, Object... values) { dml().writeRow(session(), createNewRow(tableId, values)); } protected final RowUpdater update(NewRow oldRow) { RowUpdater updater = new RowUpdaterImpl(oldRow); unfinishedRowUpdaters.add(updater); return updater; } protected final RowUpdater update(int tableId, Object... values) { NewRow oldRow = createNewRow(tableId, values); return update(oldRow); } protected final int writeRows(NewRow... rows) throws InvalidOperationException { for (NewRow row : rows) { dml().writeRow(session(), row); } return rows.length; } protected final void deleteRow(int tableId, Object... values) { dml().deleteRow(session(), createNewRow(tableId, values), false); } protected final void expectRows(ScanRequest request, NewRow... expectedRows) throws InvalidOperationException { assertEquals("rows scanned", Arrays.asList(expectedRows), scanAll(request)); } protected final ScanAllRequest scanAllRequest(int tableId) { return scanAllRequest(tableId, false); } protected final ScanAllRequest scanAllRequest(int tableId, boolean includingInternal) { Table uTable = ddl().getTable(session(), tableId); Set<Integer> allCols = new HashSet<>(); int MAX = includingInternal ? uTable.getColumnsIncludingInternal().size() : uTable.getColumns().size(); for (int i=0; i < MAX; ++i) { allCols.add(i); } return new ScanAllRequest(tableId, allCols); } protected final int indexId(String schema, String table, String index) { AkibanInformationSchema ais = ddl().getAIS(session()); UserTable userTable = ais.getUserTable(schema, table); Index aisIndex = userTable.getIndex(index); if (aisIndex == null) { throw new RuntimeException("no such index: " + index); } return aisIndex.getIndexId(); } protected final CursorId openFullScan(String schema, String table, String index) throws InvalidOperationException { AkibanInformationSchema ais = ddl().getAIS(session()); UserTable userTable = ais.getUserTable(schema, table); Index aisIndex = userTable.getIndex(index); if (aisIndex == null) { throw new RuntimeException("no such index: " + index); } return openFullScan( userTable.getTableId(), aisIndex.getIndexId() ); } protected final CursorId openFullScan(int tableId, int indexId) throws InvalidOperationException { Table uTable = ddl().getTable(session(), tableId); Set<Integer> allCols = new HashSet<>(); for (int i=0, MAX=uTable.getColumns().size(); i < MAX; ++i) { allCols.add(i); } ScanRequest request = new ScanAllRequest(tableId, allCols, indexId, EnumSet.of(ScanFlag.START_AT_BEGINNING, ScanFlag.END_AT_END) ); return dml().openCursor(session(), aisGeneration(), request); } protected static <T> Set<T> set(T... items) { return new HashSet<>(Arrays.asList(items)); } protected static <T> T[] array(Class<T> ofClass, T... items) { if (ofClass == null) { throw new IllegalArgumentException( "T[] of null class; you probably meant the array(Object...) overload " +"with a null for the first element. Use array(Object.class, null, ...) instead" ); } return items; } protected static Object[] array(Object... items) { return array(Object.class, items); } protected static <T> T get(NewRow row, int field, Class<T> castAs) { Object obj = row.get(field); return castAs.cast(obj); } public static Object getObject(PValueSource pvalue) { if (pvalue.isNull()) return null; if (pvalue.hasCacheValue()) return pvalue.getObject(); switch (PValueSources.pUnderlying(pvalue)) { case BOOL: return pvalue.getBoolean(); case INT_8: return pvalue.getInt8(); case INT_16: return pvalue.getInt16(); case UINT_16: return pvalue.getUInt16(); case INT_32: return pvalue.getInt32(); case INT_64: return pvalue.getInt64(); case FLOAT: return pvalue.getFloat(); case DOUBLE: return pvalue.getDouble(); case BYTES: return pvalue.getBytes(); case STRING: return pvalue.getString(); default: throw new AssertionError(pvalue); } } public static boolean isNull(BoundExpressions row, int pos) { return Types3Switch.ON ? row.pvalue(pos).isNull() : row.eval(pos).isNull(); } public static Long getLong(BoundExpressions row, int field) { final Long result; if (Types3Switch.ON) { PValueSource pvalue = row.pvalue(field); if (pvalue.isNull()) { result = null; } else { switch (PValueSources.pUnderlying(pvalue)) { case INT_8: result = (long) pvalue.getInt8(); break; case INT_16: result = (long) pvalue.getInt16(); break; case UINT_16: result = (long) pvalue.getUInt16(); break; case INT_32: result = (long) pvalue.getInt32(); break; case INT_64: result = pvalue.getInt64(); break; default: throw new AssertionError(pvalue); } } } else { ValueSource value = row.eval(field); if (value.isNull()) { result = null; } else { switch (value.getConversionType()) { case INT: result = value.getInt(); break; case LONG: result = value.getLong(); break; case U_BIGINT: BigInteger bigInt = value.getUBigInt(); result = bigInt.longValue(); if (!bigInt.equals(BigInteger.valueOf(result))) throw new AssertionError("overflow: " + bigInt); break; case U_INT: result = value.getUInt(); break; case NULL: result = null; break; default: throw new AssertionError(value); } } } return result; } protected final void expectFullRows(int tableId, NewRow... expectedRows) throws InvalidOperationException { ScanRequest all = scanAllRequest(tableId); expectRows(all, expectedRows); expectRowCount(tableId, expectedRows.length); } protected final List<NewRow> convertRowDatas(List<RowData> rowDatas) { List<NewRow> ret = new ArrayList<>(rowDatas.size()); for(RowData rowData : rowDatas) { NewRow newRow = NiceRow.fromRowData(rowData, ddl().getRowDef(session(), rowData.getRowDefId())); ret.add(newRow); } return ret; } protected static Set<CursorId> cursorSet(CursorId... cursorIds) { Set<CursorId> set = new HashSet<>(); for (CursorId id : cursorIds) { if(!set.add(id)) { fail(String.format("while adding %s to %s", id, set)); } } return set; } public NewRow createNewRow(int tableId, Object... columns) { return createNewRow(getRowDef(tableId), columns); } public static NewRow createNewRow(RowDef rowDef, Object... columns) { NewRow row = new NiceRow(rowDef.getRowDefId(), rowDef); for (int i=0; i < columns.length; ++i) { if (columns[i] != UNDEF) { row.put(i, columns[i] ); } } return row; } protected final void dropAllTables() throws InvalidOperationException { dropAllTables(session()); } protected final void dropAllTables(Session session) throws InvalidOperationException { for(Routine routine : ddl().getAIS(session).getRoutines().values()) { TableName name = routine.getName(); if (!name.getSchemaName().equals(TableName.SQLJ_SCHEMA) && !name.getSchemaName().equals(TableName.SYS_SCHEMA) && !name.getSchemaName().equals(TableName.SECURITY_SCHEMA)) { routineLoader().unloadRoutine(session(), name); ddl().dropRoutine(session(), name); } } for(SQLJJar jar : ddl().getAIS(session).getSQLJJars().values()) { ddl().dropSQLJJar(session(), jar.getName()); } for(View view : ddl().getAIS(session).getViews().values()) { // In case one view references another, avoid having to delete in proper order. view.getTableColumnReferences().clear(); } for(View view : ddl().getAIS(session).getViews().values()) { ddl().dropView(session, view.getName()); } // Note: Group names, being derived, can change across DDL. Save root names instead. Set<TableName> groupRoots = new HashSet<>(); for(UserTable table : ddl().getAIS(session).getUserTables().values()) { if(table.getParentJoin() == null && !TableName.INFORMATION_SCHEMA.equals(table.getName().getSchemaName()) && !TableName.SECURITY_SCHEMA.equals(table.getName().getSchemaName())) { groupRoots.add(table.getName()); } } for(TableName rootName : groupRoots) { ddl().dropGroup(session, getUserTable(rootName).getGroup().getName()); } // Now sanity check Set<TableName> uTables = new HashSet<>(ddl().getAIS(session).getUserTables().keySet()); for (Iterator<TableName> iter = uTables.iterator(); iter.hasNext();) { String schemaName = iter.next().getSchemaName(); if (TableName.INFORMATION_SCHEMA.equals(schemaName) || TableName.SECURITY_SCHEMA.equals(schemaName)) { iter.remove(); } } Assert.assertEquals("user table count", Collections.<TableName>emptySet(), uTables); Set<TableName> views = new HashSet<>(ddl().getAIS(session).getViews().keySet()); Assert.assertEquals("user table count", Collections.<TableName>emptySet(), views); } protected static <T> void assertEqualLists(String message, List<? extends T> expected, List<? extends T> actual) { AssertUtils.assertCollectionEquals(message, expected, actual); } protected static class TestException extends RuntimeException { private final InvalidOperationException cause; public TestException(String message, InvalidOperationException cause) { super(message, cause); this.cause = cause; } public TestException(InvalidOperationException cause) { super(cause); this.cause = cause; } @Override public InvalidOperationException getCause() { assert super.getCause() == cause; return cause; } } protected final int tableId(String schema, String table) { return tableId(new TableName(schema, table)); } protected final int tableId(TableName tableName) { try { return ddl().getTableId(session(), tableName); } catch (NoSuchTableException e) { throw new TestException(e); } } protected final TableName tableName(int tableId) { try { return ddl().getTableName(session(), tableId); } catch (NoSuchTableException e) { throw new TestException(e); } } protected final TableName tableName(String schema, String table) { return new TableName(schema, table); } protected final UserTable getUserTable(String schema, String name) { return getUserTable(tableName(schema, name)); } protected final UserTable getUserTable(TableName name) { return ddl().getUserTable(session(), name); } protected final RowDef getRowDef(int rowDefId) { return getUserTable(rowDefId).rowDef(); } protected final RowDef getRowDef(String schema, String table) { return getUserTable(schema, table).rowDef(); } protected final RowDef getRowDef(TableName tableName) { return getUserTable(tableName).rowDef(); } protected final UserTable getUserTable(int tableId) { final Table table; try { table = ddl().getTable(session(), tableId); } catch (NoSuchTableException e) { throw new TestException(e); } if (table.isUserTable()) { return (UserTable) table; } throw new RuntimeException("not a user table: " + table); } protected final Map<TableName,UserTable> getUserTables() { return stripAISTables(ddl().getAIS(session()).getUserTables()); } private static <T extends Table> Map<TableName,T> stripAISTables(Map<TableName,T> map) { final Map<TableName,T> ret = new HashMap<>(map); for(Iterator<TableName> iter=ret.keySet().iterator(); iter.hasNext(); ) { if(TableName.INFORMATION_SCHEMA.equals(iter.next().getSchemaName())) { iter.remove(); } } return ret; } protected void expectIndexes(int tableId, String... expectedIndexNames) { UserTable table = getUserTable(tableId); Set<String> expectedIndexesSet = new TreeSet<>(Arrays.asList(expectedIndexNames)); Set<String> actualIndexes = new TreeSet<>(); for (Index index : table.getIndexes()) { String indexName = index.getIndexName().getName(); boolean added = actualIndexes.add(indexName); assertTrue("duplicate index name: " + indexName, added); } assertEquals("indexes in " + table.getName(), expectedIndexesSet, actualIndexes); } protected void expectIndexColumns(int tableId, String indexName, String... expectedColumns) { UserTable table = getUserTable(tableId); List<String> expectedColumnsList = Arrays.asList(expectedColumns); Index index = table.getIndex(indexName); assertNotNull(indexName + " was null", index); List<String> actualColumns = new ArrayList<>(); for (IndexColumn indexColumn : index.getKeyColumns()) { actualColumns.add(indexColumn.getColumn().getName()); } assertEquals(indexName + " columns", actualColumns, expectedColumnsList); } public interface RowUpdater { void to(Object... values); void to(NewRow newRow); } private class RowUpdaterImpl implements RowUpdater { @Override public void to(Object... values) { NewRow newRow = createNewRow(oldRow.getTableId(), values); to(newRow); } @Override public void to(NewRow newRow) { boolean removed = unfinishedRowUpdaters.remove(this); dml().updateRow(session(), oldRow, newRow, null); assertTrue("couldn't remove row updater " + toString(), removed); } @Override public String toString() { return "RowUpdater for " + oldRow; } private RowUpdaterImpl(NewRow oldRow) { this.oldRow = oldRow; } private final NewRow oldRow; } protected <T> T transactionally(Callable<T> callable) throws Exception { txnService().beginTransaction(session); try { T value = callable.call(); txnService().commitTransaction(session); return value; } finally { txnService().rollbackTransactionIfOpen(session); } } protected <T> T transactionallyUnchecked(Callable<T> callable) { try { return transactionally(callable); } catch (Exception e) { throw new RuntimeException(e); } } protected void transactionallyUnchecked(final Runnable runnable) { transactionallyUnchecked(new Callable<Void>() { @Override public Void call() throws Exception { runnable.run(); return null; } }); } protected boolean usingPValues() { return Types3Switch.ON && testSupportsPValues(); } protected boolean testSupportsPValues() { return true; } protected DDLFunctions ddlForAlter() { return ddl(); } protected void runAlter(TableChangeValidator.ChangeLevel expectedChangeLevel, String defaultSchema, String sql) { runAlter(session(), ddlForAlter(), dml(), null, expectedChangeLevel, defaultSchema, sql); updateAISGeneration(); } protected static void runAlter(Session session, DDLFunctions ddl, DMLFunctions dml, QueryContext context, TableChangeValidator.ChangeLevel expectedChangeLevel, String defaultSchema, String sql) { SQLParser parser = new SQLParser(); StatementNode node; try { node = parser.parseStatement(sql); } catch(StandardException e) { throw new RuntimeException(e); } assertTrue("is alter node", node instanceof AlterTableNode); TableChangeValidator.ChangeLevel level = AlterTableDDL.alterTable(ddl, dml, session, defaultSchema, (AlterTableNode) node, context); assertEquals("ChangeLevel", expectedChangeLevel, level); } }
package com.alibaba.json.bvt; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.fastjson.util.IOUtils; public class CharTypesTest extends TestCase { static byte[] specicalFlags_singleQuotes = IOUtils.specicalFlags_singleQuotes; static byte[] specicalFlags_doubleQuotes = IOUtils.specicalFlags_doubleQuotes; public void test_0() throws Exception { Assert.assertTrue(isSpecial_doubleQuotes('\n')); Assert.assertTrue(isSpecial_doubleQuotes('\r')); Assert.assertTrue(isSpecial_doubleQuotes('\b')); Assert.assertTrue(isSpecial_doubleQuotes('\f')); Assert.assertTrue(isSpecial_doubleQuotes('\"')); Assert.assertFalse(isSpecial_doubleQuotes('0')); Assert.assertTrue(isSpecial_doubleQuotes('\0')); Assert.assertFalse(isSpecial_doubleQuotes('')); Assert.assertFalse(isSpecial_doubleQuotes('')); } public static boolean isSpecial_doubleQuotes(char ch) { return ch < specicalFlags_doubleQuotes.length && specicalFlags_doubleQuotes[ch] != 0; } }
package com.alibaba.json.bvt; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializeConfig; import junit.framework.TestCase; import java.util.Currency; public class CurrencyTest5 extends TestCase { public void test_0() throws Exception { SerializeConfig config = new SerializeConfig(); config.put(Currency.class , config.createJavaBeanSerializer(Currency.class)); JSONObject jsonObject = new JSONObject(); jsonObject.put("value", Currency.getInstance("CNY")); String text = JSON.toJSONString(jsonObject, config); System.out.println(text); String str1 = "{\"value\":{\"currencyCode\":\"CNY\",\"displayName\":\"Chinese Yuan\",\"symbol\":\"CNY\"}}"; String str2 = "{\"value\":{\"currencyCode\":\"CNY\",\"displayName\":\"\",\"symbol\":\"\"}}"; String str3 = "{\"value\":{\"currencyCode\":\"CNY\",\"displayName\":\"Chinese Yuan\",\"numericCodeAsString\":\"156\",\"symbol\":\"CN¥\"}}"; assertTrue(text.equals(str1) || text.equals(str2) || text.equals(str3)); Currency currency = JSON.parseObject(text, VO.class).value; assertSame(Currency.getInstance("CNY"), currency); } public static class VO { public Currency value; } }
package com.arhs.mojo.pack200; import com.arhs.mojo.pack200.pack.PackMojo; import java.io.File; /** * Unit tests for {@code PackMojo} class. * * @author Cyril Schumacher * @version 1.0 * @since 2014-12-02 */ public class PackMojoTest extends AbstractMojoTest { //<editor-fold desc="Constants section."> /** * Original JAR file. */ private static final String JAR_FILE_ORIGINAL = "src/test/resources/my-applet.original.jar"; //</editor-fold> //<editor-fold desc="Methods section."> private PackMojo packMojo; private File inputJarFile; @Override public void setUp() throws Exception { super.setUp(); // Get mojo object. packMojo = createMojoByPomFile("src/test/resources/pom/pack-log.xml", "pack"); // Create a JAR file by the "inputFile" parameter. inputJarFile = copyJar(packMojo.target, packMojo.inputFile, JAR_FILE_ORIGINAL); } @Override public void tearDown() throws Exception { super.tearDown(); // Clean generated files inputJarFile.delete(); packMojo.outputFile.delete(); packMojo.logFile.delete(); } /** * Test for create a compressed JAR file. * @throws Exception */ public void testPack() throws Exception { packMojo.execute(); } /** * Test for create a compressed JAR file and create a log file. * @throws Exception */ public void testPackLogFile() throws Exception { packMojo.execute(); // Checks if input JAR file, log file and output file exists. assertTrue("No input JAR file was created.", inputJarFile.exists()); assertTrue("No log file was created.", packMojo.logFile.exists()); assertTrue("No output JAR file was created.", packMojo.outputFile.exists()); } //</editor-fold> }
package com.cloudbees.groovy.cps; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.junit.Assert; import org.junit.Test; import static java.util.Arrays.*; /** * @author Kohsuke Kawaguchi */ public class BasicTest extends Assert { Builder b = new Builder(); // useful fragment of expressions Expression $x = b.getLocalVariable("x"); Expression $y = b.getLocalVariable("y"); Expression $z = b.getLocalVariable("z"); // 3 => 3 @Test public void constant() { assertEquals(3, run(b.constant(3))); } // 1==1, aka ScriptBytecodeAdapter.compareEqual(1,1) => true @Test public void onePlusOne() { assertEquals(true, run( b.staticCall(ScriptBytecodeAdapter.class, "compareEqual", b.constant(1), b.constant(1)))); } // x=1; y=2; x+y => 3 @Test public void variable() { assertEquals(3, run( b.setLocalVariable("x", b.constant(1)), b.setLocalVariable("y", b.constant(2)), b.plus($x, $y) )); } /* sum = 0; for (x=0; x<10; x++) { sum += x; } sum => 45; */ @Test public void forLoop() { assertEquals(45, run( b.setLocalVariable("sum", b.constant(0)), b.forLoop( b.setLocalVariable("x", b.constant(0)), b.lessThan($x, b.constant(10)), b.localVariableAssignOp("x", "plus", b.constant(1)), b.sequence(// for loop body b.localVariableAssignOp("sum", "plus", $x) )), b.getLocalVariable("sum") )); } /** * Makes sure the return statement prevents the rest of the code from executing. * * x=0; return x; x+=1; => 0 */ @Test public void returnStatement() { assertEquals(0, run( b.setLocalVariable("x", b.constant(0)), b._return($x), b.localVariableAssignOp("x", "plus", b.constant(1)), b.plus($x, $y) )); } @Test public void asyncCallingAsync() { class Op { public Function add(int x, int y) { return new Function(asList("x", "y"), b.sequence( b.setLocalVariable("z",b.functionCall($x,"plus",$y)), b._return($z) )); } } // z=5; new Op().add(1,2)+z => 8 assertEquals(3, run( b.setLocalVariable("z", b.constant(0)), // part of the test is to ensure this 'z' is separated from 'z' in the add function b.plus( b.functionCall(b.constant(new Op()), "add", b.constant(1), b.constant(2)), $z))); } private Object run(Expression... bodies) { Env e = new Env(null); e.returnAddress = Continuation.HALT; Next p = new Next(b.sequence(bodies), e, Continuation.HALT); return p.resume().yield; } }
package com.dua3.utility.text; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.UncheckedIOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Assert; import org.junit.Test; import com.dua3.utility.io.IOUtil; public class MarkDownTest { public static void main(String[] args) throws Exception { Charset cs = StandardCharsets.UTF_8; if (args.length == 0) { System.out.println(getAnsi()); } if (args.length== 1 && args[0].equals("-update")) { System.err.println("WARNING! This will overwrite expected unit test results!!!\nEnter 'YES' to continue."); if (!"YES".equals(new BufferedReader(new InputStreamReader(System.in, cs)).readLine())) { System.err.println("aborted."); System.exit(1); } String html = getHtml(); Path htmlPath = Paths.get(MarkDownTest.class.getResource("syntax.html").toURI()); try (PrintStream out = new PrintStream(htmlPath.toFile(), cs.name())) { out.print(html); System.out.println("Wrote new expected unit test result."); System.err.println("Copy " + htmlPath + " to resources folder to permanently update tests."); } } } static String getHtml() { String mdText = getTestDataSource(); RichText richText = MarkDownUtil.convert(mdText); return HtmlBuilder.toHtml(richText, MarkDownStyle::getAttributes); } static String getAnsi() { String mdText = getTestDataSource(); RichText richText = MarkDownUtil.convert(mdText); return AnsiBuilder.toAnsi(richText, MarkDownStyle::getAttributes); } @Test public void testMarkDown() { String htmlActual = getHtml(); String htmlExpected = getTestDataExpectedHtml(); Assert.assertEquals(htmlExpected, htmlActual); } public static String getTestData(String filename) { try { return IOUtil.read(Paths.get(MarkDownTest.class.getResource(filename).toURI()), StandardCharsets.UTF_8); } catch (IOException e) { throw new UncheckedIOException(e); } catch (URISyntaxException e) { throw new IllegalStateException(); } } public static String getTestDataSource() { return getTestData("syntax.md"); } public static String getTestDataExpectedHtml() { return getTestData("syntax.html"); } }
package com.jcabi.github; import com.jcabi.aspects.Tv; import org.apache.commons.lang3.RandomStringUtils; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Assume; import org.junit.Test; /** * Test case for {@link RtAssignees}. * @author Paul Polishchuk (ppol@ua.fm) * @version $Id$ * @since 0.7 */ public final class RtAssigneesITCase { /** * RtAssignees can iterate over assignees. * @throws Exception Exception If some problem inside */ @Test public void iteratesAssignees() throws Exception { final Iterable<User> users = new Smarts<User>( new Bulk<User>( RtAssigneesITCase.repo().assignees().iterate() ) ); for (final User user : users) { MatcherAssert.assertThat( user.login(), Matchers.notNullValue() ); } } /** * RtAssignees can check if user is assignee for this repo. * @throws Exception Exception If some problem inside */ @Test public void checkUserIsAssigneeForRepo() throws Exception { MatcherAssert.assertThat( RtAssigneesITCase.repo().assignees().check(coordinates().user()), Matchers.is(true) ); } /** * RtAssignees can check if user is NOT assignee for this repo. * @throws Exception Exception If some problem inside */ @Test public void checkUserIsNotAssigneeForRepo() throws Exception { MatcherAssert.assertThat( RtAssigneesITCase.repo() .assignees() .check(RandomStringUtils.randomAlphabetic(Tv.TEN)), Matchers.is(false) ); } /** * Create and return repo to test. * @return Repo * @throws Exception If some problem inside */ private static Repo repo() throws Exception { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); final Github github = new RtGithub(key); return github.repos().get(RtAssigneesITCase.coordinates()); } /** * Create and return repo coordinates to test on. * @return Coordinates */ private static Coordinates coordinates() { return new Coordinates.Simple( System.getProperty("failsafe.github.repo") ); } }
package com.mars.test.java; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Test; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.Random; @Slf4j public class TestInputStream { @Test public void testStringToInputStream() throws IOException { String sampleString = "asdkfjsadkjflasj"; InputStream stream = new ByteArrayInputStream(sampleString.getBytes(StandardCharsets.UTF_8)); } @Test public void testInputStreamToString() throws IOException { String expect = "These word form input stream"; InputStream stream = new ByteArrayInputStream(expect.getBytes(StandardCharsets.UTF_8)); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuffer stringBuffer = new StringBuffer(); String str = ""; while ((str = reader.readLine()) != null) { stringBuffer.append(str); } String actual = stringBuffer.toString(); log.info("actual = " + actual); } }
package com.rox.emu.mem; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; import static junit.framework.TestCase.fail; public class ReadOnlyMemoryTest { int[] memoryValues = new int[] {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}; private Memory memory; @Before public void setUp(){ memory = new ReadOnlyMemory(memoryValues); } @Test public void testByteCreatedMemory(){ final Memory byteMemory = new ReadOnlyMemory(new byte[] {0x10, 0x20, 0x30, 0x40, 0x50}); assertEquals(0x20, byteMemory.getByte(1)); try{ byteMemory.setByteAt(0, 42); fail("Writing to read only memory should throw an exception."); }catch(RuntimeException e){} } @Test public void testExplicitlySizedMemory(){ assertEquals(20, memory.getSize()); try { memory.setByteAt(10, 0); fail("Should not be able to access memory outside the size of addressable memory"); }catch(RuntimeException e){} } @Test public void testRead(){ assertEquals(5, memory.getByte(5)); } @Test public void testReadBlock(){ int[] expected = new int[] {0,1,2,3}; int[] actual = memory.getBlock(0, 4); assertTrue("Expected " + Arrays.toString(expected) + ", got " + Arrays.toString(actual), Arrays.equals(expected, actual)); } @Test public void testReadBlockWithZeroSize(){ int[] expected = new int[] {}; int[] actual = memory.getBlock(0, 0); assertTrue("Expected " + Arrays.toString(expected) + ", got " + Arrays.toString(actual), Arrays.equals(expected, actual)); } @Test public void testReadBlockWithNegativeSize(){ try { memory.getBlock(4, 0); fail("Requesting a negatively sized memory block should throw an IllegalArgumentException"); }catch(IllegalArgumentException e){} } @Test public void testReset(){ int[] actual = memory.getBlock(0, 20); memory.reset(); assertTrue("Expected " + Arrays.toString(memoryValues) + ", got " + Arrays.toString(actual),Arrays.equals(memoryValues, actual)); } @Test public void testReadWord(){ assertEquals(((1<<8) | 2), memory.getWord(1)); } @Test public void testWrite(){ try { memory.setByteAt(0, 0); fail("Writing to read only memory should throw an exception."); }catch (RuntimeException e){} } @Test public void testWriteBlock(){ try { memory.setBlock(0, new int[] {0,1,2,3,4,5}); fail("Writing to read only memory should throw an exception."); }catch (RuntimeException e){} } }
package de.gmcs.builder; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; import de.gmcs.builder.model.DomainObject; import de.gmcs.builder.model.PrivateObject; public class GenericBuilderTest { @Test public void test() throws Exception { DomainObject result = GenericBuilder.getInstance(DomainObject.class) .with("setAttribute", "attributeValue") .with("setProperty", "property", Integer.valueOf(3)) .build(); assertThat(result.getAttribute(), is("attributeValue")); assertThat(result.getProperty("property"), is(3)); } @Test public void testParametrizedConstructor() throws Exception { DomainObject result = GenericBuilder.getInstance(DomainObject.class, "attributeValue") .with("setProperty", "property", Integer.valueOf(3)) .build(); assertThat(result.getAttribute(), is("attributeValue")); assertThat(result.getProperty("property"), is(3)); } @Test public void testFactoryMethod() throws Exception { PrivateObject result = GenericBuilder.getInstanceFromFactoryMethod(PrivateObject.class, "getInstance") .with("setAttribute", "attribute") .build(); assertThat(result.getAttribute(), is("attribute")); } @Test public void testFactoryMethodWithArgs() throws Exception { PrivateObject result = GenericBuilder.getInstanceFromFactoryMethod(PrivateObject.class, "getInstance", "attribute") .build(); assertThat(result.getAttribute(), is("attribute")); } @Test(expected = GenericBuilderException.class) public void testMissingFactoryMethod() throws Exception { GenericBuilder.getInstanceFromFactoryMethod(PrivateObject.class, "getInstanceMissing"); } @Test(expected = GenericBuilderException.class) public void testMissingMethod() throws Exception { GenericBuilder.getInstance(DomainObject.class) .with("setMissing", "attributeValue") .build(); } @Test(expected = GenericBuilderException.class) public void testPrivateConstructor() throws Exception { GenericBuilder.getInstance(PrivateObject.class); } }
package guitests; import static org.junit.Assert.assertTrue; import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import org.junit.Test; import seedu.taskboss.commons.exceptions.IllegalValueException; import seedu.taskboss.logic.commands.RenameCategoryCommand; import seedu.taskboss.logic.parser.RenameCategoryCommandParser; import seedu.taskboss.testutil.TaskBuilder; import seedu.taskboss.testutil.TestTask; //@@author A0144904H public class RenameCategoryCommandTest extends TaskBossGuiTest { @Test public void renameCategory_Long_Command_success() throws IllegalValueException { TestTask sampleA = td.alice; TestTask sampleB = td.benson; TestTask[] taskList = {sampleA, sampleB}; assertRenameCategoryResult("name friends Project", taskList); } @Test public void renameCategory_Short_Command_success() throws IllegalValueException { TestTask sampleA = td.alice; TestTask sampleB = td.benson; TestTask[] taskList = {sampleA, sampleB}; assertRenameCategoryResult("n friends Project", taskList); } private void assertRenameCategoryResult(String command, TestTask[] taskList) throws IllegalValueException { TestTask sampleA; TestTask sampleB; sampleA = new TaskBuilder().withName("Alice Pauline") .withInformation("123, Jurong West Ave 6, #08-111") .withPriorityLevel("Yes") .withStartDateTime("Feb 18, 2017 5pm") .withEndDateTime("Mar 28, 2017 5pm") .withCategories("Project").build(); sampleB = new TaskBuilder().withName("Benson Meier") .withInformation("311, Clementi Ave 2, #02-25") .withPriorityLevel("No") .withStartDateTime("Feb 23, 2017 10pm") .withEndDateTime("Jun 28, 2017 5pm") .withCategories("owesMoney", "Project").build(); TestTask[] taskListExpected = {sampleA, sampleB}; commandBox.runCommand(command); assertResultMessage(RenameCategoryCommand.MESSAGE_SUCCESS); assertTrue(taskListPanel.isListMatching(taskListExpected)); } @Test public void rename_unsuccessful() { //old category name == new category name commandBox.runCommand("name friends friends"); assertResultMessage(RenameCategoryCommandParser.ERROR_SAME_FIELDS); //invalid number of fields commandBox.runCommand("name friends bestfriends forever"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, RenameCategoryCommand.MESSAGE_USAGE)); //category name with a single non-alphanumerical character commandBox.runCommand("name owesMoney myMoney!"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, RenameCategoryCommandParser.ERROR_NON_ALPHANUMERIC)); //category name with all non-alphanumerical characters commandBox.runCommand("name owesMoney !!!"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, RenameCategoryCommandParser.ERROR_NON_ALPHANUMERIC)); //specified category to be re-named does not exist commandBox.runCommand("name superman batman"); assertResultMessage("[superman] " + RenameCategoryCommand.MESSAGE_DOES_NOT_EXIST_CATEGORY); } }
package net.greghaines.jesque; import static net.greghaines.jesque.TestUtils.createJedis; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.greghaines.jesque.worker.Worker; import net.greghaines.jesque.worker.WorkerImpl; import org.junit.Before; import org.junit.Test; import redis.clients.jedis.Jedis; public class InfiniteTest { private static final Config config = new ConfigBuilder().withJobPackage("net.greghaines.jesque").build(); @Before public void resetRedis() throws Exception { final Jedis jedis = createJedis(config); try { jedis.flushDB(); } finally { jedis.quit(); } } @Test public void dummy(){} @SuppressWarnings("unchecked") // @Test public void dontStopNow() throws InterruptedException { for (int i = 0; i < 5; i++) { final List<Job> jobs = new ArrayList<Job>(30); for (int j = 0; j < 30; j++) { jobs.add(new Job("TestAction", new Object[]{j, 2.3, true, "test", Arrays.asList("inner", 4.5)})); } TestUtils.enqueueJobs("foo" + i, jobs, config); jobs.clear(); for (int j = 0; j < 5; j++) { jobs.add(new Job("FailAction")); } TestUtils.enqueueJobs("bar", jobs, config); } final Worker worker = new WorkerImpl(config, Arrays.asList("foo0", "bar","baz"), Arrays.asList(TestAction.class, FailAction.class)); final Thread workerThread = new Thread(worker); workerThread.start(); TestUtils.enqueueJobs("inf", Arrays.asList(new Job("InfiniteAction")), config); final Worker worker2 = new WorkerImpl(config, Arrays.asList("inf"), Arrays.asList(InfiniteAction.class)); final Thread workerThread2 = new Thread(worker2); workerThread2.start(); workerThread.join(); } }
package org.alltiny.math.vector; import junit.framework.Assert; import org.junit.Test; /** * This test ensures that {@link Matrix} is working correctly. */ public class MatrixTest { @Test(expected = IllegalArgumentException.class) public void testMatrixRejectsNull() { new Matrix((Vector[])null); } @Test(expected = IllegalArgumentException.class) public void testMatrixRejectsEmptyVectorArray() { new Matrix(); } @Test(expected = IllegalArgumentException.class) public void testMatrixRejectsNullVectors() { new Matrix(new Vector[]{null}); } @Test(expected = IllegalArgumentException.class) public void testMatrixRejectsNullVectorsInArray() { new Matrix(new Vector(1), null); } @Test(expected = IllegalArgumentException.class) public void testMatrixRejectsVectorsWithDifferentLength() { new Matrix(new Vector(1), new Vector(1, 2)); } @Test(expected = IllegalArgumentException.class) public void testMatrixRejectsVectorsWithZeroElements() { new Matrix(new Vector()); } @Test public void testRowExtraction() { Matrix m = new Matrix(new Vector(1,2), new Vector(3,4)); Assert.assertEquals("row should be", new Vector(1,2), m.getRow(0)); Assert.assertEquals("row should be", new Vector(3,4), m.getRow(1)); } @Test public void testColumnExtraction() { Matrix m = new Matrix(new Vector(1,2), new Vector(3,4)); Assert.assertEquals("column should be", new Vector(1,3), m.getColumn(0)); Assert.assertEquals("column should be", new Vector(2,4), m.getColumn(1)); } @Test public void testSingleValueExtraction() { Matrix m = new Matrix(new Vector(1,2), new Vector(3,4)); Assert.assertEquals("value on (0,0) should be", 1d, m.get(0,0)); Assert.assertEquals("value on (0,1) should be", 2d, m.get(0,1)); Assert.assertEquals("value on (1,0) should be", 3d, m.get(1,0)); Assert.assertEquals("value on (1,0) should be", 4d, m.get(1,1)); } @Test public void testAddingTwoMatrices() { Matrix m1 = new Matrix(new Vector(1,2), new Vector(3,4)); Matrix m2 = new Matrix(new Vector(5,6), new Vector(7,8)); Matrix m = m1.add(m2); Assert.assertEquals("value on (0,0) should be", 6d, m.get(0,0)); Assert.assertEquals("value on (0,1) should be", 8d, m.get(0,1)); Assert.assertEquals("value on (1,0) should be", 10d, m.get(1,0)); Assert.assertEquals("value on (1,0) should be", 12d, m.get(1,1)); } @Test(expected = IllegalDimensionException.class) public void testAddingMatricesWithDifferentRowDimensions() { new Matrix(new Vector(1,2), new Vector(3,4)).add(new Matrix(new Vector(5,6))); } @Test(expected = IllegalDimensionException.class) public void testAddingMatricesWithDifferentColumnDimensions() { new Matrix(new Vector(1,2), new Vector(3,4)).add(new Matrix(new Vector(5d), new Vector(6d))); } @Test public void testMultiplyingTwoMatrices() { Matrix a = new Matrix(new Vector(3,2,1), new Vector(1,0,2)); Matrix b = new Matrix(new Vector(1,2), new Vector(0,1), new Vector(4,0)); Matrix m = a.mul(b); Assert.assertEquals("value on (0,0) should be", 7d, m.get(0,0)); Assert.assertEquals("value on (0,1) should be", 8d, m.get(0,1)); Assert.assertEquals("value on (1,0) should be", 9d, m.get(1,0)); Assert.assertEquals("value on (1,0) should be", 2d, m.get(1,1)); } @Test(expected = IllegalDimensionException.class) public void testMultiplyingMatricesWithWrongDimensions() { Matrix a = new Matrix(new Vector(1,2,3), new Vector(4,5,6), new Vector(7,8,9)); Matrix b = new Matrix(new Vector(1,2), new Vector(0,1)); a.mul(b); } @Test public void testMatricesWithPositiveZeroAndNegativeZeroEqual() { Assert.assertEquals("Matrices with positive zero and negative zero equal each other", new Matrix(new Vector(0,1)), new Matrix(new Vector(-0d,1))); Assert.assertTrue("Matrices with positive zero and negative zero produce the same hash", new Matrix(new Vector(0,1)).equals(new Matrix(new Vector(-0d,1)))); } @Test public void testMatrixEqualsWithSameMatrix() { Matrix m = new Matrix(new Vector(1,5),new Vector(2,6)); Assert.assertTrue("Matrices should equal itself", m.equals(m)); } @Test public void testMatrixNotEqualsString() { Assert.assertFalse("Matrices should equal itself", new Matrix(new Vector(7,3),new Vector(8,4)).equals("foobar")); } @Test public void testMatricesWithZeroAndNegativeZeroCreateTheSameHash() { Assert.assertEquals("Matrices with positive zero and negative zero produce the same hash", new Matrix(new Vector(0,1)).hashCode(), new Matrix(new Vector(-0d,1)).hashCode()); } @Test public void testToString() { Assert.assertEquals("toString should be", "Matrix[Vector[7.0, 3.0], Vector[8.0, 4.0]]", new Matrix(new Vector(7,3),new Vector(8,4)).toString()); } }
package org.kohsuke.github; import com.fasterxml.jackson.databind.exc.MismatchedInputException; import com.fasterxml.jackson.databind.exc.ValueInstantiationException; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import org.hamcrest.CoreMatchers; import org.junit.Test; import java.io.IOException; import java.time.Duration; import java.util.Date; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.IsInstanceOf.instanceOf; /** * Test showing the behavior of OkHttpConnector with and without cache. * <p> * Key take aways: * * <ul> * <li>These tests are artificial and intended to highlight the differences in behavior between scenarios. However, the * differences they indicate are stark.</li> * <li>Caching reduces rate limit consumption by at least a factor of two in even the simplest case.</li> * <li>The OkHttp cache is pretty smart and will often connect read and write requests made on the same client and * invalidate caches.</li> * <li>Changes made outside the current client cause the OkHttp cache to return stale data. This is expected and correct * behavior.</li> * <li>"max-age=0" addresses the problem of external changes by revalidating caches for each request. This produces the * same number of requests as OkHttp without caching, but those requests only count towards the GitHub rate limit if * data has changes.</li> * </ul> * * @author Liam Newman */ public class GHRateLimitTest extends AbstractGitHubWireMockTest { GHRateLimit rateLimit = null; GHRateLimit previousLimit = null; public GHRateLimitTest() { useDefaultGitHub = false; } @Override protected WireMockConfiguration getWireMockOptions() { return super.getWireMockOptions().extensions(templating.newResponseTransformer()); } @Test public void testGitHubRateLimit() throws Exception { // Customized response that templates the date to keep things working snapshotNotAllowed(); assertThat(mockGitHub.getRequestCount(), equalTo(0)); // 4897 is just the what the limit was when the snapshot was taken previousLimit = GHRateLimit.fromHeaderRecord(new GHRateLimit.Record(5000, 4897, (templating.testStartDate.getTime() + Duration.ofHours(1).toMillis()) / 1000L)); // /user gets response with rate limit information gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).build(); gitHub.getMyself(); assertThat(mockGitHub.getRequestCount(), equalTo(1)); // Since we already had rate limit info these don't request again rateLimit = gitHub.lastRateLimit(); verifyRateLimitValues(previousLimit, previousLimit.getRemaining()); previousLimit = rateLimit; GHRateLimit headerRateLimit = rateLimit; // Give this a moment Thread.sleep(1000); // ratelimit() uses headerRateLimit if available and headerRateLimit is not expired assertThat(gitHub.rateLimit(), equalTo(headerRateLimit)); assertThat(mockGitHub.getRequestCount(), equalTo(1)); // Give this a moment Thread.sleep(1000); // Always requests new info rateLimit = gitHub.getRateLimit(); assertThat(mockGitHub.getRequestCount(), equalTo(2)); // Because remaining and reset date are unchanged, the header should be unchanged as well assertThat(gitHub.lastRateLimit(), sameInstance(headerRateLimit)); // rate limit request is free, remaining is unchanged verifyRateLimitValues(previousLimit, previousLimit.getRemaining()); previousLimit = rateLimit; // Give this a moment Thread.sleep(1000); // Always requests new info rateLimit = gitHub.getRateLimit(); assertThat(mockGitHub.getRequestCount(), equalTo(3)); // Because remaining and reset date are unchanged, the header should be unchanged as well assertThat(gitHub.lastRateLimit(), sameInstance(headerRateLimit)); // rate limit request is free, remaining is unchanged verifyRateLimitValues(previousLimit, previousLimit.getRemaining()); previousLimit = rateLimit; gitHub.getOrganization(GITHUB_API_TEST_ORG); assertThat(mockGitHub.getRequestCount(), equalTo(4)); // Because remaining has changed the header should be different assertThat(gitHub.lastRateLimit(), not(sameInstance(headerRateLimit))); assertThat(gitHub.lastRateLimit(), not(equalTo(headerRateLimit))); rateLimit = gitHub.lastRateLimit(); // Org costs limit to query verifyRateLimitValues(previousLimit, previousLimit.getRemaining() - 1); previousLimit = rateLimit; headerRateLimit = rateLimit; // ratelimit() should prefer headerRateLimit when it is most recent and not expired assertThat(gitHub.rateLimit(), sameInstance(headerRateLimit)); assertThat(mockGitHub.getRequestCount(), equalTo(4)); // AT THIS POINT WE SIMULATE A RATE LIMIT RESET // Give this a moment Thread.sleep(2000); // Always requests new info rateLimit = gitHub.getRateLimit(); assertThat(mockGitHub.getRequestCount(), equalTo(5)); // rate limit request is free, remaining is unchanged date is later verifyRateLimitValues(previousLimit, previousLimit.getRemaining(), true); previousLimit = rateLimit; // When getRateLimit() succeeds, headerRateLimit updates as usual as well (if needed) // These are separate instances, but should be equal assertThat(gitHub.rateLimit(), not(sameInstance(rateLimit))); // Verify different record instances can be compared assertThat(gitHub.rateLimit().getCore(), equalTo(rateLimit.getCore())); // Verify different instances can be compared // TODO: This is not work currently because the header rate limit has unknowns for records other than core. // assertThat(gitHub.rateLimit(), equalTo(rateLimit)); assertThat(gitHub.rateLimit(), not(sameInstance(headerRateLimit))); assertThat(gitHub.rateLimit(), sameInstance(gitHub.lastRateLimit())); assertThat(mockGitHub.getRequestCount(), equalTo(5)); } private void verifyRateLimitValues(GHRateLimit previousLimit, int remaining) { verifyRateLimitValues(previousLimit, remaining, false); } private void verifyRateLimitValues(GHRateLimit previousLimit, int remaining, boolean changedResetDate) { // Basic checks of values assertThat(rateLimit, notNullValue()); assertThat(rateLimit.getLimit(), equalTo(previousLimit.getLimit())); assertThat(rateLimit.getRemaining(), equalTo(remaining)); // Check that the reset date of the current limit is not older than the previous one long diffMillis = rateLimit.getResetDate().getTime() - previousLimit.getResetDate().getTime(); assertThat(diffMillis, greaterThanOrEqualTo(0L)); if (changedResetDate) { assertThat(diffMillis, greaterThan(1000L)); } else { assertThat(diffMillis, lessThanOrEqualTo(1000L)); } // Additional checks for record values assertThat(rateLimit.getCore().getLimit(), equalTo(rateLimit.getLimit())); assertThat(rateLimit.getCore().getRemaining(), equalTo(rateLimit.getRemaining())); assertThat(rateLimit.getCore().getResetEpochSeconds(), equalTo(rateLimit.getResetEpochSeconds())); assertThat(rateLimit.getCore().getResetDate(), equalTo(rateLimit.getResetDate())); // Additional checks for deprecated values assertThat(rateLimit.limit, equalTo(rateLimit.getLimit())); assertThat(rateLimit.remaining, equalTo(rateLimit.getRemaining())); assertThat(rateLimit.reset.getTime(), equalTo(rateLimit.getResetEpochSeconds())); } @Test public void testGitHubEnterpriseDoesNotHaveRateLimit() throws Exception { // Customized response that results in file not found the same as GitHub Enterprise snapshotNotAllowed(); assertThat(mockGitHub.getRequestCount(), equalTo(0)); GHRateLimit rateLimit = null; Date lastReset = new Date(System.currentTimeMillis() / 1000L); // Give this a moment Thread.sleep(1000); // Before any queries, rate limit starts as null but may be requested gitHub = GitHub.connectToEnterprise(mockGitHub.apiServer().baseUrl(), "bogus", "bogus"); assertThat(mockGitHub.getRequestCount(), equalTo(0)); assertThat(gitHub.lastRateLimit(), CoreMatchers.nullValue()); rateLimit = gitHub.rateLimit(); assertThat(rateLimit.getCore(), instanceOf(GHRateLimit.UnknownLimitRecord.class)); assertThat(rateLimit.getLimit(), equalTo(GHRateLimit.UnknownLimitRecord.unknownLimit)); assertThat(rateLimit.getRemaining(), equalTo(GHRateLimit.UnknownLimitRecord.unknownRemaining)); assertThat(rateLimit.getResetDate().compareTo(lastReset), equalTo(1)); lastReset = rateLimit.getResetDate(); assertThat(mockGitHub.getRequestCount(), equalTo(1)); // last is still null, because it actually means lastHeaderRateLimit assertThat(gitHub.lastRateLimit(), CoreMatchers.nullValue()); assertThat(mockGitHub.getRequestCount(), equalTo(1)); // Give this a moment Thread.sleep(1000); // First call to /user gets response without rate limit information gitHub = GitHub.connectToEnterprise(mockGitHub.apiServer().baseUrl(), "bogus", "bogus"); gitHub.getMyself(); assertThat(mockGitHub.getRequestCount(), equalTo(2)); assertThat(gitHub.lastRateLimit(), CoreMatchers.nullValue()); rateLimit = gitHub.rateLimit(); assertThat(rateLimit.getCore(), instanceOf(GHRateLimit.UnknownLimitRecord.class)); assertThat(rateLimit.getLimit(), equalTo(GHRateLimit.UnknownLimitRecord.unknownLimit)); assertThat(rateLimit.getRemaining(), equalTo(GHRateLimit.UnknownLimitRecord.unknownRemaining)); assertThat(rateLimit.getResetDate().compareTo(lastReset), equalTo(1)); lastReset = rateLimit.getResetDate(); assertThat(mockGitHub.getRequestCount(), equalTo(3)); // Give this a moment Thread.sleep(1000); // Always requests new info rateLimit = gitHub.getRateLimit(); assertThat(mockGitHub.getRequestCount(), equalTo(4)); assertThat(rateLimit.getCore(), instanceOf(GHRateLimit.UnknownLimitRecord.class)); assertThat(rateLimit.getLimit(), equalTo(GHRateLimit.UnknownLimitRecord.unknownLimit)); assertThat(rateLimit.getRemaining(), equalTo(GHRateLimit.UnknownLimitRecord.unknownRemaining)); assertThat(rateLimit.getResetDate().compareTo(lastReset), equalTo(1)); // Give this a moment Thread.sleep(1000); // last is still null, because it actually means lastHeaderRateLimit assertThat(gitHub.lastRateLimit(), CoreMatchers.nullValue()); // ratelimit() tries not to make additional requests, uses queried rate limit since header not available Thread.sleep(1000); assertThat(gitHub.rateLimit(), sameInstance(rateLimit)); // Second call to /user gets response with rate limit information gitHub = GitHub.connectToEnterprise(mockGitHub.apiServer().baseUrl(), "bogus", "bogus"); gitHub.getMyself(); assertThat(mockGitHub.getRequestCount(), equalTo(5)); // Since we already had rate limit info these don't request again rateLimit = gitHub.lastRateLimit(); assertThat(rateLimit, notNullValue()); assertThat(rateLimit.getLimit(), equalTo(5000)); assertThat(rateLimit.getRemaining(), equalTo(4978)); // The previous record was an "Unknown", so even though this records resets sooner we take it assertThat(rateLimit.getResetDate().compareTo(lastReset), equalTo(-1)); lastReset = rateLimit.getResetDate(); GHRateLimit headerRateLimit = rateLimit; // Give this a moment Thread.sleep(1000); // ratelimit() uses headerRateLimit if available and headerRateLimit is not expired assertThat(gitHub.rateLimit(), sameInstance(headerRateLimit)); assertThat(mockGitHub.getRequestCount(), equalTo(5)); // Give this a moment Thread.sleep(1000); // Always requests new info rateLimit = gitHub.getRateLimit(); assertThat(mockGitHub.getRequestCount(), equalTo(6)); assertThat(rateLimit.getCore(), instanceOf(GHRateLimit.UnknownLimitRecord.class)); assertThat(rateLimit.getLimit(), equalTo(GHRateLimit.UnknownLimitRecord.unknownLimit)); assertThat(rateLimit.getRemaining(), equalTo(GHRateLimit.UnknownLimitRecord.unknownRemaining)); assertThat(rateLimit.getResetDate().compareTo(lastReset), equalTo(1)); // ratelimit() should prefer headerRateLimit when getRateLimit fails and headerRateLimit is not expired assertThat(gitHub.rateLimit(), equalTo(headerRateLimit)); assertThat(mockGitHub.getRequestCount(), equalTo(6)); // Wait for the header Thread.sleep(1000); } @Test public void testGitHubRateLimitWithBadData() throws Exception { snapshotNotAllowed(); gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).build(); gitHub.getMyself(); try { gitHub.getRateLimit(); fail("Invalid rate limit missing some records should throw"); } catch (Exception e) { assertThat(e, instanceOf(HttpException.class)); assertThat(e.getCause(), instanceOf(IOException.class)); assertThat(e.getCause().getCause(), instanceOf(ValueInstantiationException.class)); assertThat(e.getCause().getCause().getMessage(), containsString( "Cannot construct instance of `org.kohsuke.github.GHRateLimit`, problem: `java.lang.NullPointerException`")); } try { gitHub.getRateLimit(); fail("Invalid rate limit record missing a value should throw"); } catch (Exception e) { assertThat(e, instanceOf(HttpException.class)); assertThat(e.getCause(), instanceOf(IOException.class)); assertThat(e.getCause().getCause(), instanceOf(MismatchedInputException.class)); assertThat(e.getCause().getCause().getMessage(), containsString("Missing required creator property 'reset' (index 2)")); } } // These tests should behave the same, showing server time adjustment working @Test public void testGitHubRateLimitExpirationServerFiveMinutesAhead() throws Exception { executeExpirationTest(); } @Test public void testGitHubRateLimitExpirationServerFiveMinutesBehind() throws Exception { executeExpirationTest(); } private void executeExpirationTest() throws Exception { // Customized response that templates the date to keep things working snapshotNotAllowed(); assertThat(mockGitHub.getRequestCount(), equalTo(0)); GHRateLimit rateLimit = null; GHRateLimit headerRateLimit = null; // Give this a moment Thread.sleep(1000); // /user gets response with rate limit information gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).build(); gitHub.getMyself(); assertThat(mockGitHub.getRequestCount(), equalTo(1)); // Since we already had rate limit info these don't request again headerRateLimit = gitHub.lastRateLimit(); rateLimit = gitHub.rateLimit(); assertThat(rateLimit, notNullValue()); assertThat("rateLimit() selects header instance when not expired, does not ask server", rateLimit, sameInstance(headerRateLimit)); // Nothing changes still valid Thread.sleep(1000); assertThat("rateLimit() selects header instance when not expired, does not ask server", gitHub.rateLimit(), sameInstance(headerRateLimit)); assertThat("lastRateLimit() always selects header instance, does not ask server", gitHub.lastRateLimit(), sameInstance(headerRateLimit)); assertThat(mockGitHub.getRequestCount(), equalTo(1)); // This time, rateLimit() should find an expired record and get a new one. Thread.sleep(3000); assertThat("Header instance has expired", gitHub.lastRateLimit().isExpired(), is(true)); assertThat("rateLimit() will ask server when header instance expires and it has not called getRateLimit() yet", gitHub.rateLimit(), not(sameInstance(rateLimit))); assertThat("lastRateLimit() (header instance) is populated as part of internal call to getRateLimit()", gitHub.lastRateLimit(), not(sameInstance(rateLimit))); assertThat("After request, rateLimit() selects header instance since it has been refreshed", gitHub.rateLimit(), sameInstance(gitHub.lastRateLimit())); headerRateLimit = gitHub.lastRateLimit(); assertThat(mockGitHub.getRequestCount(), equalTo(2)); // This time, rateLimit() should find an expired header record, but a valid returned record Thread.sleep(4000); rateLimit = gitHub.rateLimit(); // Using custom data to have a header instance that expires before the queried instance assertThat( "if header instance expires but queried instance is valid, ratelimit() uses it without asking server", gitHub.rateLimit(), not(sameInstance(gitHub.lastRateLimit()))); assertThat("ratelimit() should almost never return a return a GHRateLimit that is already expired", gitHub.rateLimit().isExpired(), is(false)); assertThat("Header instance hasn't been reloaded", gitHub.lastRateLimit(), sameInstance(headerRateLimit)); assertThat("Header instance has expired", gitHub.lastRateLimit().isExpired(), is(true)); assertThat(mockGitHub.getRequestCount(), equalTo(2)); // Finally they both expire and rateLimit() should find both expired and get a new record Thread.sleep(2000); headerRateLimit = gitHub.rateLimit(); assertThat("rateLimit() has asked server for new information", gitHub.rateLimit(), not(sameInstance(rateLimit))); assertThat("rateLimit() has asked server for new information", gitHub.lastRateLimit(), not(sameInstance(rateLimit))); assertThat("rateLimit() selects header instance when not expired, does not ask server", gitHub.rateLimit(), sameInstance((gitHub.lastRateLimit()))); assertThat(mockGitHub.getRequestCount(), equalTo(3)); } private static GHRepository getRepository(GitHub gitHub) throws IOException { return gitHub.getOrganization("github-api-test-org").getRepository("github-api"); } }
package org.takes.facets.auth; import com.google.common.collect.ImmutableMap; import java.io.IOException; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.Mockito; import org.takes.Response; import org.takes.rq.RqFake; import org.takes.rs.RsWithBody; import org.takes.rs.RsWithStatus; import org.takes.rs.RsWithType; /** * Test case for {@link PsByFlag}. * @author Yegor Bugayenko (yegor@teamed.io) * @version $Id$ * @since 0.10 */ public final class PsByFlagTest { /** * PsByFlag can skip if nothing found. * @throws IOException If some problem inside */ @Test public void skipsIfNothingFound() throws IOException { MatcherAssert.assertThat( new PsByFlag( new PsByFlag.Pair( "test", new PsFake(true) ) ).enter( new RqFake("GET", "/?PsByFlag=x") ).hasNext(), Matchers.is(false) ); } /** * PsByFlag finds flag and authenticates user. * @throws IOException If some problem inside */ @Test public void flagIsFoundUserAuthenticated() throws IOException { MatcherAssert.assertThat( new PsByFlag( new PsByFlag.Pair( "some-key", new PsFake(true) ) ).enter( new RqFake("POST", "/?PsByFlag=some-key") ).next().urn(), Matchers.is("urn:test:1") ); } /** * PsByFlag wraps response with authenticated user. * @throws IOException If some problem inside */ @Test public void exitTest() throws IOException { final Response response = new RsWithStatus( new RsWithType( new RsWithBody("<html>This is test response</html>"), "text/html" ), 200 ); MatcherAssert.assertThat( new PsByFlag( ImmutableMap.of( "key", (Pass) new PsFake(true) ) ).exit(response, Mockito.mock(Identity.class)), Matchers.is(response) ); } /** * Checks PsByFlag equals method. * @throws Exception If some problem inside */ @Test public void equalsAndHashCodeEqualTest() throws Exception { EqualsVerifier.forClass(PsByFlag.class) .suppress(Warning.TRANSIENT_FIELDS) .verify(); } }
package seedu.task.commons.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class ConfigTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void toString_defaultObject_stringReturned() { String defaultConfigAsString = "App title : Suru - Task Manager\n" + "Current log level : INFO\n" + "Preference file Location : preferences.json\n" + "Local data file location : data/taskmanager.xml\n" + "TaskManager name : suru"; System.out.println(new Config().toString()); assertEquals(defaultConfigAsString, new Config().toString()); } @Test public void equalsMethod() { Config defaultConfig = new Config(); assertNotNull(defaultConfig); assertTrue(defaultConfig.equals(defaultConfig)); } }
package codeine.mail; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import codeine.configuration.Links; import codeine.jsons.labels.LabelJsonProvider; import codeine.jsons.mails.AlertsCollectionType; import codeine.jsons.mails.CollectorNotificationJson; import codeine.model.Constants; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimaps; import com.google.inject.Inject; public class AggregateMailPrepare { private static final Logger log = Logger.getLogger(AggregateMailPrepare.class); private static final int MAX_MAIL_SIZE = 100000; @Inject private Links links; @Inject private LabelJsonProvider labelJsonProvider; public List<Mail> prepare(List<NotificationContent> notificationContent, AlertsCollectionType alertsCollectionType) { List<Mail> $ = Lists.newArrayList(); for (NotificationContent item : notificationContent) { StringBuilder content = new StringBuilder(); content.append("Hi,\nBelow are alerts from monitors in codeine for policy " + alertsCollectionType + ".\n"); content.append("For more info: " + links.getWebServerLandingPage() + "\n"); content.append("Enjoy!\n\n"); content.append("========================================================================\n"); ImmutableListMultimap<String, CollectorNotificationJson> byNode = createSummary(item, content); for (CollectorNotificationJson notification : item.notifications()) { String nodeName = notification.node() == null ? "unknown" : notification.node().alias(); String version = notification.version() == null ? Constants.NO_VERSION : labelJsonProvider .labelForVersion(notification.version(), notification.project_name()); content.append("Project : " + notification.project_name() + "\n"); content.append("Node : " + nodeName + "\n"); content.append("Server : " + notification.peer() + "\n"); long time = notification.time(); content.append("Time on node : " + formatTime(time) + "\n"); content.append("Version : " + version + "\n"); content.append("Monitor : " + notification.collector_name() + "\n"); content.append("Output\n" + notification.output() + "\n"); content.append("========================================================================\n"); } String stringContent = ""; if (content.length() > MAX_MAIL_SIZE) { log.warn("mail was too big to user " + item.user()); stringContent = content.substring(0, MAX_MAIL_SIZE) + "\n...Mail was too long..."; } else { stringContent = content.toString(); } $.add(new Mail(Lists.newArrayList(item.user()), trimStringToMaxLength( "Aggregated alerts from codeine for policy " + alertsCollectionType + " on nodes: " + byNode.keySet(), 100), stringContent)); } return $; } private String trimStringToMaxLength(String s, int size) { if (s.length() > size) { String substring = s.substring(0, size); int lastIndexOf = substring.lastIndexOf(" "); return lastIndexOf == -1 ? substring + "... and some more." : substring.substring(0, lastIndexOf) + "... and some more."; } return s; } private ImmutableListMultimap<String, CollectorNotificationJson> createSummary(NotificationContent item, StringBuilder content) { Function<CollectorNotificationJson, String> f = new Function<CollectorNotificationJson, String>() { @Override public String apply(CollectorNotificationJson notification) { return notification.node() == null ? "unknown" : notification.node().alias(); } }; ImmutableListMultimap<String, CollectorNotificationJson> byNode = Multimaps.index(item.notifications(), f); Function<CollectorNotificationJson, String> function = new Function<CollectorNotificationJson, String>() { @Override public String apply(CollectorNotificationJson input) { return input.project_name() + "/" + input.collector_name(); } }; if (byNode.values().size() < 2) { log.debug("will not append summary"); return byNode; } content.append("Summary:\n"); for (String n : byNode.keySet()) { content.append(n + " -> " + trimStringToMaxLength(Collections2.transform(byNode.get(n), function).toString(), 250) + " \n"); } content.append("========================================================================\n"); return byNode; } private String formatTime(long time) { return new SimpleDateFormat("HH:mm:ss dd/MM/yyyy").format(new Date(time)); } // public static void main(String[] args) { // System.out.println(formatTime(System.currentTimeMillis())); // public static void main(String[] args) { // AggregateMailPrepare aggregateMailSender = new AggregateMailPrepare(); // NotificationContent notificationContent2 = new // NotificationContent("oshai"); // NodeJson node = new NodeJson("itstl1043:12345"); // notificationContent2.add(Lists.newArrayList(new // CollectorNotificationJson("collector_name", "project_name", // "outputdfgdfg\n\n\nsadkljfhsdfaklh", false, node))); // List<NotificationContent> notificationContent = // Lists.newArrayList(notificationContent2); // List<Mail> mails = aggregateMailSender.prepare(notificationContent ); // Send.mail(mails.get(0)); }
package com.sherpasteven.recarded; public class Card { private String name; private int quantity; private Quality quality; private String catagory; private String series; private Boolean tradable; private String comments; private List<images> images; private User owner; public Card(String name, int quantity, Quality quality, String catagory, String series, Boolean tradable, String comments, List<images> images, User owner){ this.name = name; this.quantity = quantity; this.quality = quality; this.catagory = catagory; this.series = series; this.tradable = tradable; this.comments = comments; this.images = images; this.owner = owner; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public Quality getQuality() { return quality; } public void setQuality(Quality quality) { this.quality = quality; } public String getCatagory() { return catagory; } public void setCatagory(String catagory) { this.catagory = catagory; } public String getSeries() { return series; } public void setSeries(String series) { this.series = series; } public Boolean getTradable() { return tradable; } public void setTradable(Boolean tradable) { this.tradable = tradable; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public List<images> getImages() { return images; } public void setImages(List<images> images) { this.images = images; } }
package org.skywalking.apm.agent.core.context.ids; import java.nio.ByteBuffer; import java.nio.ByteOrder; import org.skywalking.apm.agent.core.context.ids.base64.Base64; import org.skywalking.apm.network.proto.UniqueId; /** * @author wusheng */ public class ID { private static final Base64.Encoder ENCODER = Base64.getEncoder(); private static final Base64.Decoder DECODER = Base64.getDecoder(); private long part1; private long part2; private long part3; public ID(long part1, long part2, long part3) { this.part1 = part1; this.part2 = part2; this.part3 = part3; } public ID(String base64String) { int index = 0; for (int part = 0; part < 3; part++) { String encodedString; char potentialTypeChar = base64String.charAt(index); long value; if (potentialTypeChar == ' encodedString = base64String.substring(index + 1, index + 5); index += 5; value = ByteBuffer.wrap(DECODER.decode(encodedString)).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(0); } else if (potentialTypeChar == '$') { encodedString = base64String.substring(index + 1, index + 9); index += 8; value = ByteBuffer.wrap(DECODER.decode(encodedString)).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get(0); } else { encodedString = base64String.substring(index + 1, index + 13); index += 12; value = ByteBuffer.wrap(DECODER.decode(encodedString)).order(ByteOrder.LITTLE_ENDIAN).asLongBuffer().get(0); } if (part == 0) { part1 = value; } else if (part == 1) { part2 = value; } else { part3 = value; } } } public String toBase64() { return long2Base64(part1) + long2Base64(part2) + long2Base64(part3); } private String long2Base64(long partN) { if (partN < 0) { throw new IllegalArgumentException("negative value."); } if (partN < 32768) { // 0 - 32767 // "#" as a prefix of a short value with base64 encoding. byte[] data = new byte[2]; ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put((short)partN); return '#' + ENCODER.encodeToString(data); } else if (partN <= 2147483647) { // 32768 - 2147483647 // "$" as a prefix of an integer value (greater than a short) with base64 encoding. byte[] data = new byte[4]; ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().put((int)partN); return '$' + ENCODER.encodeToString(data); } else { // > 2147483647 // a long value (greater than an integer) byte[] data = new byte[8]; ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).asLongBuffer().put(partN); return ENCODER.encodeToString(data); } } @Override public String toString() { return part1 + "." + part2 + '.' + part3; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ID id = (ID)o; if (part1 != id.part1) return false; if (part2 != id.part2) return false; return part3 == id.part3; } @Override public int hashCode() { int result = (int)(part1 ^ (part1 >>> 32)); result = 31 * result + (int)(part2 ^ (part2 >>> 32)); result = 31 * result + (int)(part3 ^ (part3 >>> 32)); return result; } public UniqueId transform() { return UniqueId.newBuilder().addIdParts(part1).addIdParts(part2).addIdParts(part3).build(); } }
package com.samourai.wallet.send.soroban.meeting; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.samourai.soroban.client.cahoots.SorobanCahootsInitiator; import com.samourai.wallet.R; import com.samourai.wallet.SamouraiActivity; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.rpc.PaymentCode; import com.samourai.wallet.cahoots.AndroidSorobanClientService; import com.samourai.wallet.cahoots.CahootsType; import com.samourai.wallet.fragments.PaynymSelectModalFragment; import com.samourai.wallet.send.cahoots.SorobanCahootsActivity; import com.samourai.wallet.tor.TorManager; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.whirlpool.client.wallet.beans.WhirlpoolAccount; import com.squareup.picasso.Picasso; import org.apache.commons.lang3.StringUtils; import io.matthewnelson.topl_service.TorServiceController; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class SorobanMeetingSendActivity extends SamouraiActivity { private static final String TAG = "SorobanMeetingSend"; private SorobanCahootsInitiator sorobanCahootsInitiator; private static final int TIMEOUT_MS = 120000; private WhirlpoolAccount account; private CahootsType cahootsType; private long sendAmount; private String sendAddress; private TextView paynymDisplayName, textViewConnecting; private ImageView paynymAvatar; private View paynymSelect; private Button sendButton; private ProgressBar progressBar; private Disposable sorobanDisposable; private String pcode; public static Intent createIntent(Context ctx, int account, CahootsType type, long amount, String address, String pcode) { Intent intent = new Intent(ctx, SorobanMeetingSendActivity.class); intent.putExtra("_account", account); intent.putExtra("type", type.getValue()); intent.putExtra("sendAmount", amount); intent.putExtra("sendAddress", address); if (!StringUtils.isEmpty(pcode)) { intent.putExtra("pcode", pcode); } return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_soroban_meeting_send); setSupportActionBar(findViewById(R.id.toolbar_soroban_meeting)); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); setTitle("Select Cahoots counterparty"); } paynymSelect = findViewById(R.id.paynym_select); paynymDisplayName = findViewById(R.id.paynym_display_name); textViewConnecting = findViewById(R.id.textViewConnecting); paynymAvatar = findViewById(R.id.img_paynym_avatar); sendButton = findViewById(R.id.send_button); progressBar = findViewById(R.id.progressBar); paynymSelect.setOnClickListener(v -> selectPCode()); sendButton.setOnClickListener(v -> send()); if (TorManager.INSTANCE.isConnected() && !PrefsUtil.getInstance(getApplication()).getValue(PrefsUtil.OFFLINE, false)) { parsePayloadIntent(); } else { String message = ""; if (!TorManager.INSTANCE.isConnected()) { message = "Tor connection is required for online cahoots ? do you want to continue ?"; } new AlertDialog.Builder(this) .setTitle("Confirm") .setMessage(message) .setCancelable(true) .setPositiveButton(R.string.yes, (dialog, whichButton) -> { progressBar.setVisibility(View.VISIBLE); PrefsUtil.getInstance(getApplicationContext()).setValue(PrefsUtil.OFFLINE, false); TorServiceController.startTor(); TorManager.INSTANCE.getTorStateLiveData().observe(SorobanMeetingSendActivity.this, torState -> { if (torState == TorManager.TorState.ON) { parsePayloadIntent(); progressBar.setVisibility(View.GONE); } }); }).setNegativeButton(R.string.no, (dialog, whichButton) -> { finish(); }).show(); } } private void parsePayloadIntent() { try { if (getIntent().hasExtra("_account")) { account = WhirlpoolAccount.find(getIntent().getIntExtra("_account", 0)).get(); } if (getIntent().hasExtra("type")) { int type = getIntent().getIntExtra("type", -1); cahootsType = CahootsType.find(type).get(); } if (getIntent().hasExtra("sendAmount")) { sendAmount = getIntent().getLongExtra("sendAmount", 0); } if (getIntent().hasExtra("sendAddress")) { sendAddress = getIntent().getStringExtra("sendAddress"); } if (cahootsType == null || sendAmount <= 0) { throw new Exception("Invalid arguments"); } sorobanCahootsInitiator = AndroidSorobanClientService.getInstance(getApplicationContext()).initiator(); if (getIntent().hasExtra("pcode")) { setPCode(getIntent().getStringExtra("pcode")); } else { selectPCode(); } } catch (Exception e) { Toast.makeText(getApplicationContext(), "Cahoots error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); e.printStackTrace(); finish(); } } private void selectPCode() { PaynymSelectModalFragment paynymSelectModalFragment = PaynymSelectModalFragment.newInstance(code -> setPCode(code), true); paynymSelectModalFragment.show(getSupportFragmentManager(), "paynym_select"); } private void setPCode(String pcode) { this.pcode = pcode; paynymDisplayName.setText(BIP47Meta.getInstance().getDisplayLabel(pcode)); Picasso.with(getApplicationContext()) .load(com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + pcode + "/avatar") .into(paynymAvatar); sendButton.setVisibility(View.VISIBLE); send(); } private void send() { setSending(true); Toast.makeText(getApplicationContext(), "Sending Cahoots request...", Toast.LENGTH_LONG).show(); try { PaymentCode paymentCode = new PaymentCode(pcode); // send meeting request sorobanDisposable = sorobanCahootsInitiator.sendMeetingRequest(paymentCode, cahootsType) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(meetingRequest -> { Toast.makeText(getApplicationContext(), "Waiting for Cahoots response...", Toast.LENGTH_LONG).show(); // meeting request sent, receive response sorobanDisposable = sorobanCahootsInitiator.receiveMeetingResponse(paymentCode, meetingRequest, TIMEOUT_MS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(sorobanResponse -> { if (sorobanResponse.isAccept()) { Toast.makeText(getApplicationContext(), "Cahoots request accepted!", Toast.LENGTH_LONG).show(); Intent intent = SorobanCahootsActivity.createIntentSender(this, account.getAccountIndex(), cahootsType, sendAmount, sendAddress, pcode); startActivity(intent); } else { Toast.makeText(getApplicationContext(), "Cahoots request refused!", Toast.LENGTH_LONG).show(); } setSending(false); }, error -> { setSending(false); Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_LONG).show(); error.printStackTrace(); }); }, error -> { setSending(false); Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_LONG).show(); error.printStackTrace(); } ); } catch (Exception e) { setSending(false); e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } private void setSending(boolean sending) { progressBar.setVisibility(sending ? View.VISIBLE : View.INVISIBLE); textViewConnecting.setVisibility(sending ? View.VISIBLE : View.INVISIBLE); sendButton.setVisibility(sending ? View.INVISIBLE : View.VISIBLE); } @Override protected void onResume() { super.onResume(); AppUtil.getInstance(this).setIsInForeground(true); AppUtil.getInstance(this).checkTimeOut(); } private void clearDisposable() { if (sorobanDisposable != null && !sorobanDisposable.isDisposed()) { sorobanDisposable.dispose(); sorobanDisposable = null; } } @Override public void finish() { clearDisposable(); super.finish(); } @Override public void onBackPressed() {// cancel cahoots request clearDisposable(); super.onBackPressed(); } }
package openfoodfacts.github.scrachx.openfood.fragments; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import com.loopj.android.http.RequestParams; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.OnClick; import butterknife.OnItemClick; import butterknife.OnItemLongClick; import openfoodfacts.github.scrachx.openfood.R; import openfoodfacts.github.scrachx.openfood.models.FoodUserClientUsage; import openfoodfacts.github.scrachx.openfood.models.SaveItem; import openfoodfacts.github.scrachx.openfood.models.SendProduct; import openfoodfacts.github.scrachx.openfood.views.SaveProductOfflineActivity; import openfoodfacts.github.scrachx.openfood.views.adapters.SaveListAdapter; public class OfflineEditFragment extends BaseFragment { private ArrayList<SaveItem> saveItems; @Bind(R.id.listOfflineSave) ListView listView; @Bind(R.id.buttonSendAll) Button buttonSend; private String loginS, passS; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return createView(inflater, container, R.layout.fragment_offline_edit); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final SharedPreferences settings = getContext().getSharedPreferences("login", 0); saveItems = new ArrayList<>(); loginS = settings.getString("user", ""); passS = settings.getString("pass", ""); buttonSend.setEnabled(false); } @OnItemClick(R.id.listOfflineSave) protected void OnClickListOffline(int position) { SaveItem si = (SaveItem) listView.getItemAtPosition(position); SharedPreferences settings = getActivity().getSharedPreferences("temp", 0); SharedPreferences.Editor editor = settings.edit(); editor.putString("barcode", si.getBarcode()); editor.apply(); Intent intent = new Intent(getActivity(), SaveProductOfflineActivity.class); startActivity(intent); } @OnItemLongClick(R.id.listOfflineSave) protected boolean OnLongClickListOffline(int position) { final int lapos = position; new MaterialDialog.Builder(getActivity()) .title(R.string.txtDialogsTitle) .content(R.string.txtDialogsContentDelete) .positiveText(R.string.txtYes) .negativeText(R.string.txtNo) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { String barcode = saveItems.get(lapos).getBarcode(); SendProduct.deleteAll(SendProduct.class, "barcode = ?", barcode); final SaveListAdapter sl = (SaveListAdapter) listView.getAdapter(); saveItems.remove(lapos); getActivity().runOnUiThread(new Runnable() { public void run() { sl.notifyDataSetChanged(); } }); } @Override public void onNegative(MaterialDialog dialog) { // void implementation } }) .show(); return true; } @OnClick(R.id.buttonSendAll) protected void onSendAllProducts() { new MaterialDialog.Builder(getActivity()) .title(R.string.txtDialogsTitle) .content(R.string.txtDialogsContentSend) .positiveText(R.string.txtYes) .negativeText(R.string.txtNo) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { List<SendProduct> listSaveProduct = SendProduct.listAll(SendProduct.class); FoodUserClientUsage user = new FoodUserClientUsage(); for (int i = 0; i < listSaveProduct.size(); i++) { SendProduct sp = listSaveProduct.get(i); if (sp.getBarcode().isEmpty() || sp.getImgupload_front().isEmpty() || sp.getImgupload_ingredients().isEmpty() || sp.getImgupload_nutrition().isEmpty() || sp.getStores().isEmpty() || sp.getWeight().isEmpty() || sp.getName().isEmpty()) { // Do nothing } else { RequestParams params = new RequestParams(); params.put("code", sp.getBarcode()); if(!loginS.isEmpty() && !passS.isEmpty()) { params.put("user_id", loginS); params.put("password", passS); } params.put("product_name", sp.getName()); params.put("quantity", sp.getWeight() + " " + sp.getWeight_unit()); params.put("stores", sp.getStores()); params.put("comment", "added with the new Android app"); compressImage(sp.getImgupload_ingredients()); compressImage(sp.getImgupload_nutrition()); compressImage(sp.getImgupload_front()); user.post(getActivity(), params, sp.getImgupload_front().replace(".png", "_small.png"), sp.getImgupload_ingredients().replace(".png", "_small.png"), sp.getImgupload_nutrition().replace(".png", "_small.png"), sp.getBarcode(), listView, i, saveItems); } } } @Override public void onNegative(MaterialDialog dialog) { return; } }) .show(); } @Override public void onResume() { super.onResume(); new FillAdapter().execute(getActivity()); } public class FillAdapter extends AsyncTask<Context, Void, Context> { @Override protected void onPreExecute() { saveItems.clear(); List<SendProduct> listSaveProduct = SendProduct.listAll(SendProduct.class); if (listSaveProduct.size() == 0) { Toast.makeText(getActivity(), R.string.txtNoData, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getActivity(), R.string.txtLoading, Toast.LENGTH_LONG).show(); } } @Override protected Context doInBackground(Context... ctx) { List<SendProduct> listSaveProduct = SendProduct.listAll(SendProduct.class); int imageIcon = R.drawable.ic_ok; for (int i = 0; i < listSaveProduct.size(); i++) { SendProduct sp = listSaveProduct.get(i); if (sp.getBarcode().isEmpty() || sp.getImgupload_front().isEmpty() || sp.getStores().isEmpty() || sp.getWeight().isEmpty() || sp.getName().isEmpty()) { imageIcon = R.drawable.ic_no; } Bitmap imgUrl = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(sp.getImgupload_front()), 200, 200, true); saveItems.add(new SaveItem(sp.getName(), imageIcon, imgUrl, sp.getBarcode())); } return ctx[0]; } @Override protected void onPostExecute(Context ctx) { List<SendProduct> listSaveProduct = SendProduct.listAll(SendProduct.class); if (listSaveProduct.size() > 0) { SaveListAdapter adapter = new SaveListAdapter(ctx, saveItems); listView.setAdapter(adapter); buttonSend.setEnabled(true); for (SendProduct sp : listSaveProduct) { if (sp.getBarcode().isEmpty() || sp.getImgupload_front().isEmpty() || sp.getImgupload_ingredients().isEmpty() || sp.getImgupload_nutrition().isEmpty() || sp.getStores().isEmpty() || sp.getWeight().isEmpty() || sp.getName().isEmpty()) { buttonSend.setEnabled(false); } } } else { //Do nothing } } } protected void compressImage(String url) { File fileFront = new File(url); Bitmap bt = decodeFile(fileFront); OutputStream fOutFront = null; File smallFileFront = new File(url.replace(".png", "_small.png")); try { fOutFront = new FileOutputStream(smallFileFront); bt.compress(Bitmap.CompressFormat.PNG, 100, fOutFront); fOutFront.flush(); fOutFront.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // Decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f) { try { // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f), null, o); // The new size we want to scale to final int REQUIRED_SIZE = 300; // Find the correct scale value. It should be the power of 2. int scale = 1; while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE) { scale *= 2; } // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); } catch (FileNotFoundException e) { } return null; } }
package org.theotech.ceaselessandroid.fragment; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.joanzapata.iconify.widget.IconTextView; import com.squareup.picasso.Picasso; import com.squareup.picasso.Transformation; import org.theotech.ceaselessandroid.R; import org.theotech.ceaselessandroid.cache.CacheManager; import org.theotech.ceaselessandroid.cache.LocalDailyCacheManagerImpl; import org.theotech.ceaselessandroid.scripture.ScriptureData; import org.theotech.ceaselessandroid.util.AnalyticsUtils; import org.theotech.ceaselessandroid.util.Constants; import org.theotech.ceaselessandroid.util.Installation; import java.io.File; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import jp.wasabeef.picasso.transformations.BlurTransformation; public class ScriptureCardSupportFragment extends Fragment implements ICardPageFragment { private static final String TAG = ScriptureCardSupportFragment.class.getSimpleName(); @Bind(R.id.verse_image) ImageView verseImage; @Bind(R.id.verse_image_reflection) ImageView verseImageReflection; @Bind(R.id.verse_text_container) RelativeLayout verseTextContainer; @Bind(R.id.verse_title) TextView verseTitle; @Bind(R.id.verse_text) TextView verseText; @Bind(R.id.verse_share) IconTextView verseShare; private CacheManager cacheManager = null; public ScriptureCardSupportFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); cacheManager = LocalDailyCacheManagerImpl.getInstance(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // create view and bind View view = inflater.inflate(R.layout.fragment_support_scripture_card, container, false); ButterKnife.bind(this, view); drawVerseImage(); // verse title and text final ScriptureData scriptureData = getScripture(); verseShare.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent sharingIntent = new Intent(Intent.ACTION_SEND); sharingIntent.setType("text/plain"); String shareContent = scriptureData.getText() + " " + scriptureData.getCitation() + " " + scriptureData.getLink(); sharingIntent.putExtra(Intent.EXTRA_TEXT, shareContent); AnalyticsUtils.sendEventWithCategory(AnalyticsUtils.getDefaultTracker(getActivity()), getString(R.string.ga_scripture_card_actions), getString(R.string.ga_tapped_share_scripture), Installation.id(getActivity())); startActivity(Intent.createChooser(sharingIntent, "Share via")); } }); return view; } private ScriptureData getScripture() { ScriptureData scriptureData = cacheManager.getCachedScripture(); if (scriptureData == null) { scriptureData = new ScriptureData(getString(R.string.default_verse_text), getString(R.string.default_verse_citation), getString(R.string.default_verse_link), null); } populateVerse(scriptureData.getCitation(), scriptureData.getText()); return scriptureData; } private void drawVerseImage() { File currentBackgroundImage = new File(getActivity().getCacheDir(), Constants.CURRENT_BACKGROUND_IMAGE); List<Transformation> transformations = new ArrayList<>(); transformations.add(new BlurTransformation(getActivity(), 25, 4)); if (currentBackgroundImage.exists()) { Log.d(TAG, "Showing verse image"); Picasso.with(getActivity()).load(currentBackgroundImage) .fit() .centerCrop() .into(verseImage); Picasso.with(getActivity()).load(currentBackgroundImage) .fit() .centerCrop() .transform(transformations) .into(verseImageReflection); } else { Log.d(TAG, "Showing default verse image"); Picasso.with(getActivity()).load(R.drawable.at_the_beach) .fit() .centerCrop() .into(verseImage); Picasso.with(getActivity()).load(R.drawable.at_the_beach) .fit() .centerCrop() .transform(transformations) .into(verseImageReflection); } } private void populateVerse(String citation, String text) { verseTitle.setText(citation); verseText.setText(text); } @Override public String getCardName() { return "VerseCard"; } }
package vocabletrainer.heinecke.aron.vocabletrainer.Activities; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.util.SparseBooleanArray; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import vocabletrainer.heinecke.aron.vocabletrainer.Activities.lib.TableListAdapter; import vocabletrainer.heinecke.aron.vocabletrainer.R; import vocabletrainer.heinecke.aron.vocabletrainer.lib.Database; import vocabletrainer.heinecke.aron.vocabletrainer.lib.Storage.Table; import static vocabletrainer.heinecke.aron.vocabletrainer.lib.Database.ID_RESERVED_SKIP; import static vocabletrainer.heinecke.aron.vocabletrainer.lib.Database.MIN_ID_TRESHOLD; /** * List selector activity */ public class ListActivity extends AppCompatActivity { /** * Set whether multi-select is enabled or not<br> * Boolean expected */ public static final String PARAM_MULTI_SELECT = "multiselect"; /** * Param key for return of selected lists<br> * This key contains a {@link Table} object or a {@link List} of {@link Table} */ public static final String RETURN_LISTS = "selected"; /** * Pass this flag as true to call this as an deletion activity */ public static final String PARAM_DELETE_FLAG = "delete"; /** * Optional Param key for already selected lists, available when multiselect is set<br> * Expect a {@link List} of {@link Table} */ public static final String PARAM_SELECTED = "selected"; private static final String TAG = "ListActivity"; Database db; List<Table> tables; private boolean multiselect; private ListView listView; private TableListAdapter adapter; private boolean delete; private Button bOk; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); db = new Database(this.getBaseContext()); setContentView(R.layout.activity_list_selector); Intent intent = getIntent(); // handle passed params multiselect = intent.getBooleanExtra(PARAM_MULTI_SELECT, false); delete = intent.getBooleanExtra(PARAM_DELETE_FLAG, false); bOk = (Button) findViewById(R.id.btnOkSelect); // setup listview initListView(); loadTables((ArrayList<Table>) intent.getSerializableExtra(PARAM_SELECTED)); updateOkButton(); } @Override public void onResume() { super.onResume(); loadTables(null); } @Override public void onBackPressed() { Intent returnIntent = new Intent(); setResult(Activity.RESULT_CANCELED, returnIntent); finish(); } /** * Load tables from db * * @param tickedTables already selected tables, can be null */ private void loadTables(List<Table> tickedTables) { tables = db.getTables(); adapter.setAllUpdated(tables); if (tickedTables != null) { for (int i = 0; i < adapter.getCount(); i++) { Table tbl = adapter.getItem(i); if (tbl.getId() >= MIN_ID_TRESHOLD && tickedTables.contains(tbl)) { listView.setItemChecked(i, true); } } } } /** * Setup list view */ private void initListView() { listView = (ListView) findViewById(R.id.listVIewLstSel); ArrayList<Table> tables = new ArrayList<>(); adapter = new TableListAdapter(this, R.layout.table_list_view, tables, multiselect); listView.setAdapter(adapter); if (multiselect) { setTitle(R.string.ListSelector_Title_Training); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listView.setItemsCanFocus(false); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { updateOkButton(); } }); bOk.setVisibility(View.VISIBLE); bOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ArrayList<Table> selectedTables = new ArrayList<Table>(10); final SparseBooleanArray checkedItems = listView.getCheckedItemPositions(); int chkItemsCount = checkedItems.size(); for (int i = 0; i < chkItemsCount; ++i) { if (checkedItems.valueAt(i)) { selectedTables.add(adapter.getItem(checkedItems.keyAt(i))); } } Log.d(TAG, "returning with " + selectedTables.size() + " selected items"); Intent returnIntent = new Intent(); returnIntent.putExtra(RETURN_LISTS, selectedTables); setResult(Activity.RESULT_OK, returnIntent); finish(); } }); } else { if (delete) { setTitle(R.string.ListSelector_Title_Delete); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { Table table = adapter.getItem(position); if (table.getId() != ID_RESERVED_SKIP) { showDeleteDialog(table); } } }); } else { setTitle(R.string.ListSelector_Title_Edit); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { Table table = adapter.getItem(position); if (table.getId() != ID_RESERVED_SKIP) { Intent returnIntent = new Intent(); returnIntent.putExtra(RETURN_LISTS, table); setResult(Activity.RESULT_OK, returnIntent); finish(); } } }); } } } /** * Update enabled state of OK button */ private void updateOkButton(){ bOk.setEnabled(listView.getCheckedItemCount() > 0); } /** * Show delete dialog for table * * @param tableToDelete */ private void showDeleteDialog(final Table tableToDelete) { final AlertDialog.Builder finishedDiag = new AlertDialog.Builder(this); finishedDiag.setTitle(R.string.ListSelector_Diag_delete_Title); finishedDiag.setMessage(String.format(getText(R.string.ListSelector_Diag_delete_Msg).toString(), tableToDelete.getName(), tableToDelete.getNameA(), tableToDelete.getNameB())); finishedDiag.setPositiveButton(R.string.ListSelector_Diag_delete_btn_Delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { db.deleteTable(tableToDelete); adapter.removeEntryUpdated(tableToDelete); } }); finishedDiag.setNegativeButton(R.string.ListSelector_Diag_delete_btn_Cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }); finishedDiag.show(); } }
package org.ovirt.engine.core.dao; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.List; import java.util.Map; import org.junit.Test; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.VmTemplateStatus; import org.ovirt.engine.core.compat.Guid; public class VmTemplateDAOTest extends BaseDAOTestCase { private static final Guid EXISTING_TEMPLATE_ID = new Guid("1b85420c-b84c-4f29-997e-0eb674b40b79"); private static final Guid DELETABLE_TEMPLATE_ID = new Guid("1b85420c-b84c-4f29-997e-0eb674b40b80"); private static final Guid STORAGE_DOMAIN_ID = new Guid("72e3a666-89e1-4005-a7ca-f7548004a9ab"); private static final Guid VDS_GROUP_ID = new Guid("b399944a-81ab-4ec5-8266-e19ba7c3c9d1"); private VmTemplateDAO dao; private VmTemplate newVmTemplate; private VmTemplate existingTemplate; @Override public void setUp() throws Exception { super.setUp(); dao = dbFacade.getVmTemplateDAO(); existingTemplate = dao.get( new Guid("1b85420c-b84c-4f29-997e-0eb674b40b79")); newVmTemplate = new VmTemplate(); newVmTemplate.setId(Guid.NewGuid()); newVmTemplate.setname("NewVmTemplate"); newVmTemplate.setvds_group_id(VDS_GROUP_ID); } /** * Ensures an id is required. */ @Test public void testGetWithInvalidId() { VmTemplate result = dao.get(Guid.NewGuid()); assertNull(result); } /** * Ensures that the right template is returned. */ @Test public void testGet() { VmTemplate result = dao.get(EXISTING_TEMPLATE_ID); assertGetResult(result); } /** * Ensures that all templates are returned. */ @Test public void testGetAll() { List<VmTemplate> result = dao.getAll(); assertGetAllResult(result); } /** * Ensures the right set of templates are returned. */ @Test public void testGetAllForStorageDomain() { List<VmTemplate> result = dao.getAllForStorageDomain(STORAGE_DOMAIN_ID); assertGetAllResult(result); } /** * Asserts that the right collection containing the vm templates is returned for a privileged user with filtering enabled */ @Test public void testGetAllForStorageDomainWithPermissionsForPriviligedUser() { List<VmTemplate> result = dao.getAllForStorageDomain(STORAGE_DOMAIN_ID, PRIVILEGED_USER_ID, true); assertGetAllResult(result); } /** * Asserts that an empty collection is returned for a non privileged user with filtering enabled */ @Test public void testGetAllForStorageDomainWithPermissionsForUnpriviligedUser() { List<VmTemplate> result = dao.getAllForStorageDomain(STORAGE_DOMAIN_ID, UNPRIVILEGED_USER_ID, true); assertNotNull(result); assertTrue(result.isEmpty()); } /** * Asserts that the right collection containing the vm templates is returned for a non privileged user with filtering disabled */ @Test public void testGetAllForStorageDomainWithPermissionsDisabledForUnpriviligedUser() { List<VmTemplate> result = dao.getAllForStorageDomain(STORAGE_DOMAIN_ID, UNPRIVILEGED_USER_ID, false); assertGetAllResult(result); } /** * Ensures the right set of templates are returned. */ @Test public void testGetAllTemplatesRelatedToQuotaId() { List<VmTemplate> result = dao.getAllTemplatesRelatedToQuotaId(FixturesTool.QUOTA_GENERAL); assertGetAllResult(result); } /** * Ensures that the templates for the given vds group are returned. */ @Test public void testGetAllForVdsGroup() { List<VmTemplate> result = dao.getAllForVdsGroup(VDS_GROUP_ID); assertGetAllResult(result); for (VmTemplate template : result) { assertEquals(VDS_GROUP_ID, template.getvds_group_id()); } } /** * Ensures that the templates for the give image are returned. */ @Test public void testGetAllForImage() { Map<Boolean, List<VmTemplate>> result = dao.getAllForImage(FixturesTool.TEMPLATE_IMAGE_ID); assertEquals("Wrong number of keys", 1, result.size()); for (List<VmTemplate> templates : result.values()) { assertEquals("Wrong number of templates", 1, templates.size()); } } /** * Ensures that saving a template works as expected. */ @Test public void testSave() { dao.save(newVmTemplate); VmTemplate result = dbFacade.getVmTemplateDAO().get(newVmTemplate.getId()); assertNotNull(result); assertEquals(newVmTemplate, result); } /** * Ensures that updating a template works as expected. */ @Test public void testUpdate() { existingTemplate.setdescription("This is an updated description"); dao.update(existingTemplate); VmTemplate result = dbFacade.getVmTemplateDAO().get(existingTemplate.getId()); assertNotNull(result); assertEquals(existingTemplate, result); } /** * Ensures updating the status aspect of the VM Template works. */ @Test public void testUpdateStatus() { VmTemplate before = dao.get(existingTemplate.getId()); before.setstatus(VmTemplateStatus.Locked); dao.updateStatus(existingTemplate.getId(), VmTemplateStatus.Locked); VmTemplate after = dao.get(existingTemplate.getId()); assertEquals(before, after); } /** * Ensures that removing a template works as expected. */ @Test public void testRemove() { VmTemplate before = dbFacade.getVmTemplateDAO().get(DELETABLE_TEMPLATE_ID); assertNotNull(before); dao.remove(DELETABLE_TEMPLATE_ID); VmTemplate after = dbFacade.getVmTemplateDAO().get(DELETABLE_TEMPLATE_ID); assertNull(after); } /** * Asserts that the right template is returned for a privileged user with filtering enabled */ @Test public void testGetWithPermissionsForPriviligedUser() { VmTemplate result = dao.get(EXISTING_TEMPLATE_ID, PRIVILEGED_USER_ID, true); assertGetResult(result); } /** * Asserts that no result is returned for a non privileged user with filtering enabled */ @Test public void testGetWithPermissionsForUnpriviligedUser() { VmTemplate result = dao.get(EXISTING_TEMPLATE_ID, UNPRIVILEGED_USER_ID, true); assertNull(result); } /** * Asserts that the right template is returned for a non privileged user with filtering disabled */ @Test public void testGetWithPermissionsDisabledForUnpriviligedUser() { VmTemplate result = dao.get(EXISTING_TEMPLATE_ID, UNPRIVILEGED_USER_ID, false); assertGetResult(result); } private static void assertGetResult(VmTemplate result) { assertNotNull(result); assertEquals(EXISTING_TEMPLATE_ID, result.getId()); } private static void assertGetAllResult(List<VmTemplate> result) { assertNotNull(result); assertFalse(result.isEmpty()); } }
package org.jboss.hal.testsuite.test.configuration.container; import org.apache.commons.lang3.RandomStringUtils; import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.graphene.page.Page; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.dmr.ModelNode; import org.jboss.hal.testsuite.category.Standalone; import org.jboss.hal.testsuite.cli.CliClient; import org.jboss.hal.testsuite.cli.CliClientFactory; import org.jboss.hal.testsuite.dmr.Dispatcher; import org.jboss.hal.testsuite.dmr.ResourceAddress; import org.jboss.hal.testsuite.dmr.ResourceVerifier; import org.jboss.hal.testsuite.finder.Application; import org.jboss.hal.testsuite.finder.FinderNames; import org.jboss.hal.testsuite.finder.FinderNavigation; import org.jboss.hal.testsuite.fragment.ConfigFragment; import org.jboss.hal.testsuite.fragment.config.resourceadapters.ConfigPropertiesFragment; import org.jboss.hal.testsuite.fragment.config.resourceadapters.ConfigPropertyWizard; import org.jboss.hal.testsuite.fragment.shared.table.ResourceTableRowFragment; import org.jboss.hal.testsuite.page.config.IIOPPage; import org.jboss.hal.testsuite.page.config.StandaloneConfigurationPage; import org.junit.*; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Harald Pehl */ @RunWith(Arquillian.class) @Category(Standalone.class) public class IIOPTestCase { private static final Logger log = LoggerFactory.getLogger(IIOPTestCase.class); private static final String KEY_VALUE = RandomStringUtils.randomAlphanumeric(5); private static final String VALUE = RandomStringUtils.randomAlphanumeric(5); @Drone WebDriver browser; private FinderNavigation navigation; private FinderNavigation transactionNavigation; private ModelNode path = new ModelNode("/subsystem=iiop-openjdk"); private ResourceAddress address = new ResourceAddress(path); private ModelNode transactionPath = new ModelNode("/subsystem=transactions"); private ResourceAddress transactionAddress = new ResourceAddress(transactionPath); Dispatcher dispatcher = new Dispatcher(); ResourceVerifier verifier = new ResourceVerifier(dispatcher); private CliClient cliClient = CliClientFactory.getClient(); @Page IIOPPage page; @Before public void before() { transactionNavigation = new FinderNavigation(browser, StandaloneConfigurationPage.class) .addAddress(FinderNames.CONFIGURATION, FinderNames.SUBSYSTEMS) .addAddress(FinderNames.SUBSYSTEM, "Transactions"); navigation = new FinderNavigation(browser, StandaloneConfigurationPage.class) .addAddress(FinderNames.CONFIGURATION, FinderNames.SUBSYSTEMS) .addAddress(FinderNames.SUBSYSTEM, "IIOP"); navigation.selectRow().invoke(FinderNames.VIEW); Application.waitUntilVisible(); } @After public void after(){ cliClient.reload(); } @Test @InSequence(0) public void expectErrorForInvalidNumberToReclaimValue() { page.switchToEditMode(); ConfigFragment editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().text("number-to-reclaim", "-1"); boolean finished = editPanelFragment.save(); assertFalse("Config wasn't supposed to be saved, read-write view should be active.", finished); verifier.verifyAttribute(address, "number-to-reclaim", "undefined"); } @Test @InSequence(1) public void numberToReclaimValueTest() { page.switchToEditMode(); ConfigFragment editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().text("number-to-reclaim", "5"); boolean finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); verifier.verifyAttribute(address, "number-to-reclaim", "5"); page.switchToEditMode(); editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().text("number-to-reclaim", ""); finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); verifier.verifyAttribute(address, "number-to-reclaim","undefined"); } @Test @InSequence(2) public void expectErrorForInvalidHighWaterMarkValue() { page.switchToEditMode(); ConfigFragment editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().text("high-water-mark", "-1"); boolean finished = editPanelFragment.save(); log.debug("f : " + finished); assertFalse("Config wasn't supposed to be saved, read-write view should be active.", finished); verifier.verifyAttribute(address, "high-water-mark","undefined"); } @Test @InSequence(3) public void highWaterMarkValueTest() { page.switchToEditMode(); ConfigFragment editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().text("high-water-mark", "7"); boolean finished = editPanelFragment.save(); assertTrue("onfig should be saved and closed.", finished); verifier.verifyAttribute(address, "high-water-mark", "7"); page.switchToEditMode(); editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().text("high-water-mark", ""); finished = editPanelFragment.save(); assertTrue("onfig should be saved and closed.", finished); verifier.verifyAttribute(address, "high-water-mark", "undefined"); } @Test @InSequence(4) public void setAuthMethodValues() { page.switchToEditMode(); ConfigFragment editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().select("auth-method", "none"); boolean finished = editPanelFragment.save(); log.debug("f : " + finished); assertTrue("Config should be saved and closed.", finished); verifier.verifyAttribute(address, "auth-method", "none"); page.switchToEditMode(); editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().select("auth-method", ""); finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); //when setting undefined ("") value , value is set to default verifier.verifyAttribute(address, "auth-method", "username_password"); page.switchToEditMode(); editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().select("auth-method", "username_password"); finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); verifier.verifyAttribute(address, "auth-method", "username_password"); } @Test @InSequence(5) public void addProperty(){ ConfigPropertiesFragment properties = page.getConfig().propertiesConfig(); page.waitUntilPropertiesAreVisible(); ConfigPropertyWizard wizard = properties.addProperty(); boolean result = wizard.name(KEY_VALUE).value(VALUE).finish(); assertTrue("Property shoudl be added and wizard closed.",result); List<ResourceTableRowFragment> actual = page.getResourceManager().getResourceTable().getAllRows(); assertEquals("Talbe should have one row.", 1, actual.size()); } @Test @InSequence(6) public void removeProperty(){ ConfigPropertiesFragment properties = page.getConfig().propertiesConfig(); page.waitUntilPropertiesAreVisible(); properties.removeProperty(KEY_VALUE); List<ResourceTableRowFragment> actual = page.getResourceManager().getResourceTable().getAllRows(); assertEquals("Talbe should be empty.", 0, actual.size()); } @Test @InSequence(9) public void setTransactionsToNoneWithEnablingJTS() { page.switchToEditMode(); ConfigFragment editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().select("transactions", "none"); boolean finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); verifier.verifyAttribute(address, "transactions", "none"); transactionNavigation.selectRow().invoke("View"); Application.waitUntilVisible(); page.switchToEditMode(); editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().checkbox("jts", true); finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); verifier.verifyAttribute(transactionAddress, "jts", true); } @Test @InSequence(10) public void setTransactionsToSpecWithDisablingJTS() { page.switchToEditMode(); ConfigFragment editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().select("transactions", "spec"); boolean finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); verifier.verifyAttribute(address, "transactions", "spec"); transactionNavigation.selectRow().invoke("View"); Application.waitUntilVisible(); page.switchToEditMode(); editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().checkbox("jts", false); finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); verifier.verifyAttribute(transactionAddress, "jts", false); } @Test @InSequence(7) public void setRealmValues() { page.switchToEditMode(); ConfigFragment editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().text("realm", VALUE); boolean finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); verifier.verifyAttribute(address, "realm", VALUE); page.switchToEditMode(); editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().text("realm", ""); finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); verifier.verifyAttribute(address, "realm", "undefined"); } @Test @InSequence(8) public void setSecurityDomainValues() { page.switchToEditMode(); ConfigFragment editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().text("security-domain", VALUE); boolean finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); verifier.verifyAttribute(address, "security-domain", VALUE); page.switchToEditMode(); editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().text("security-domain", ""); finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); verifier.verifyAttribute(address, "security-domain", "undefined"); } }
package org.intermine.bio.dataconversion; import org.intermine.bio.io.gff3.GFF3Record; import org.intermine.metadata.Model; import org.intermine.xml.full.Item; import java.util.List; /** * A converter/retriever for the AipGff dataset via GFF files. */ public class AipGffGFF3RecordHandler extends GFF3RecordHandler { /** * Create a new AipGffGFF3RecordHandler for the given data model. * @param model the model for which items will be created */ public AipGffGFF3RecordHandler (Model model) { super(model); refsAndCollections.put("Exon", "transcripts"); refsAndCollections.put("MRNA", "gene"); refsAndCollections.put("TransposonFragment", "transposableelements"); refsAndCollections.put("PseudogenicExon","pseudogenictranscripts"); refsAndCollections.put("PseudogenicTranscript","pseudogene"); } /** * {@inheritDoc} */ @Override public void process(GFF3Record record) { // This method is called for every line of GFF3 file(s) being read. Features and their // locations are already created but not stored so you can make changes here. Attributes // are from the last column of the file are available in a map with the attribute name as // the key. For example: Item feature = getFeature(); // String symbol = record.getAttributes().get("symbol"); // feature.setAttrinte("symbol", symbol); // Any new Items created can be stored by calling addItem(). For example: // String geneIdentifier = record.getAttributes().get("gene"); // gene = createItem("Gene"); // gene.setAttribute("primaryIdentifier", geneIdentifier); // addItem(gene); // You should make sure that new Items you create are unique, i.e. by storing in a map by // some identifier. String clsName = feature.getClassName(); if("Gene".equals(clsName) || "MRNA".equals(clsName) || "TransposableElementGene".equals(clsName)|| "Pseudogene".equals(clsName) || "PseudogenicTranscript".equals(clsName)){ if(record.getAttributes().get("Note") != null){ String note = record.getAttributes().get("Note").iterator().next(); if(note != null){ feature.setAttribute("Note", note); } } } if("TransposableElement".equals(clsName)|| "Gene".equals(clsName) || "MRNA".equals(clsName)){ List<String> aliases = record.getAliases(); if(aliases != null){ String alias = aliases.get(0); StringBuilder sb = new StringBuilder(alias); for (int i=1; i < aliases.size(); i++){ sb.append(" ").append(aliases.get(i)); } feature.setAttribute("Alias",sb.toString()); } } if("MRNA".equals(clsName)){ if(record.getAttributes().get("computational_description") != null){ String comp_descr = record.getAttributes().get("computational_description").iterator().next(); if(comp_descr != null){ feature.setAttribute("computational_description",comp_descr ); } } if(record.getAttributes().get("curator_summary") != null){ String cur_summary = record.getAttributes().get("curator_summary").iterator().next(); if(cur_summary != null){ feature.setAttribute("curator_summary", cur_summary); } } } } }
package org.intermine.bio.dataconversion; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeSet; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.intermine.bio.util.BioUtil; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.xml.full.Item; public class PubMedGeneConverter extends BioFileConverter { protected static final Logger LOG = Logger.getLogger(PubMedGeneConverter.class); private String referencesFileName; private Set<String> taxonIds = new HashSet<String>(); private Map<Integer, String> publications = new HashMap<Integer, String>(); private String datasetRefId; private String datasourceRefId; protected IdResolver rslv; private Map<Integer, String> organisms = new HashMap<Integer, String>(); private Map<String, Item> genes = new HashMap<String, Item>(); private Set<String> genesToRemove = new TreeSet<String>(); private Set<String> genesResolved = new HashSet<String>(); /** * @param writer item writer * @param model model * @throws ObjectStoreException if can't store the datasource/dataset */ public PubMedGeneConverter(ItemWriter writer, Model model) throws ObjectStoreException { super(writer, model); Item datasource = createItem("DataSource"); datasource.setAttribute("name", "NCBI"); store(datasource); datasourceRefId = datasource.getIdentifier(); Item dataset = createItem("DataSet"); dataset.setAttribute("name", "PubMed to gene mapping"); dataset.setReference("dataSource", datasourceRefId); store(dataset); datasetRefId = dataset.getIdentifier(); } /** * Sets the list of taxonIds that should be imported * * @param taxonIds a space-separated list of taxonIds */ public void setPubmedOrganisms(String taxonIds) { this.taxonIds = new HashSet<String>(Arrays.asList(StringUtils.split(taxonIds, " "))); } /** * Process references file and gene information file. Implementation based on the fact * that both files are sorted by the organism id. This is checked and if it is not true * an exception is thrown. * {@inheritDoc} */ public void process(Reader reader) throws Exception { // init resolver if (rslv == null) { if (taxonIds.contains("6239")) { IdResolverService.getWormIdResolver(); taxonIds.remove("6239"); rslv = IdResolverService.getIdResolverByOrganism(taxonIds); taxonIds.add("6239"); } else if (taxonIds.contains("9606")) { IdResolverService.getHumanIdResolver(); taxonIds.remove("9606"); rslv = IdResolverService.getIdResolverByOrganism(taxonIds); taxonIds.add("9606"); } else { rslv = IdResolverService.getIdResolverByOrganism(taxonIds); } } try { ReferencesFileProcessor proc = new ReferencesFileProcessor(reader); Iterator<PubMedReference> it = proc.getReferencesIterator(); /* Uses ReferencesFileProcessor to obtain iterator over data in * references file. In each iteration data for one organism is * obtained from references file and is processed by GenesFileProcessor. * Genes are saved by GenesFileProcessor, organisms and publications * are saved by this convertor (GenesFileProcessor is not in use since IM 1.1). * Procedure is based on the fact that both files are sorted by organism id. */ while (it.hasNext()) { PubMedReference ref = it.next(); Integer organismId = ref.getOrganism(); if (!taxonIds.isEmpty() && !taxonIds.contains(organismId.toString())) { continue; } Map<Integer, List<String>> geneToPub = convertAndStorePubs(ref.getReferences()); for (Entry<Integer, List<String>> e: geneToPub.entrySet()) { processGene(e.getKey(), e.getValue(), organismId, createOrganism(organismId)); } storeGenes(); } } catch (ReferencesProcessorException ex) { throw new RuntimeException("Conversion failed. File: " + getReferencesFileName(), ex); } catch (Throwable ex) { throw new RuntimeException("Conversion failed.", ex); } finally { if (reader != null) { reader.close(); } } } private Map<Integer, List<String>> convertAndStorePubs( Map<Integer, List<Integer>> geneToPub) throws ObjectStoreException { Map<Integer, List<String>> ret = new HashMap<Integer, List<String>>(); for (Integer geneId : geneToPub.keySet()) { List<Integer> pubs = geneToPub.get(geneId); List<String> list = new ArrayList<String>(); for (Integer pubId : pubs) { String pubRefId = publications.get(pubId); if (pubRefId == null) { Item pub = createPublication(pubId); pubRefId = pub.getIdentifier(); publications.put(pubId, pubRefId); store(pub); } list.add(pubRefId); } ret.put(geneId, list); } return ret; } private Item createPublication(Integer pubId) { Item pub = createItem("Publication"); pub.setAttribute("pubMedId", pubId.toString()); return pub; } /** * @return file name of file with references between gene ids and publication ids */ public String getReferencesFileName() { return referencesFileName; } /** * @param fileName file name * {@link #getReferencesFileName()} */ public void setReferencesFileName(String fileName) { this.referencesFileName = fileName; } private String createOrganism(Integer organismId) { Integer taxonId = BioUtil.replaceStrain(organismId); String refId = organisms.get(taxonId); if (refId != null) { return refId; } Item organism = createItem("Organism"); organism.setAttribute("taxonId", taxonId.toString()); try { store(organism); } catch (ObjectStoreException e) { throw new RuntimeException("storing organism failed", e); } refId = organism.getIdentifier(); organisms.put(taxonId, refId); return refId; } private Item createGene(String ncbiGeneId, String taxonId, String organismRefId) { Item gene = createItem("Gene"); String pid = resolveToPrimIdentifier(taxonId, ncbiGeneId); if (pid == null) { return null; } if (genesResolved == null) { genesResolved.add(pid); } else { if (genesResolved.contains(pid)) { // HACK for Wormbase LOG.info("Duplicated id: " + pid); return null; } else { genesResolved.add(pid); } } if ("9606".equals(taxonId)) { gene.setAttribute("symbol", pid); } else { gene.setAttribute("primaryIdentifier", pid); } gene.setReference("organism", organismRefId); gene.setCollection("dataSets", new ArrayList<String>(Collections.singleton(datasetRefId))); return gene; } private String resolveToPrimIdentifier(String taxonId, String identifier) { if (rslv == null || !rslv.hasTaxon(taxonId)) { return identifier; } int resCount = rslv.countResolutions(taxonId, identifier); if (resCount != 1) { // not process return null; } return rslv.resolveId(taxonId, identifier).iterator().next(); } private void storeGenes() { try { List<Item> gs = new ArrayList<Item>(); for (String id : genes.keySet()) { gs.add(genes.get(id)); } store(gs); } catch (ObjectStoreException e) { throw new RuntimeException("storing genes collection failed", e); } genes = new HashMap<String, Item>(); } private void processGene(Integer ncbiGeneId, List<String> publications, Integer taxonId, String organismRefId) { taxonId = BioUtil.replaceStrain(taxonId); Item gene = createGene(ncbiGeneId.toString(), taxonId.toString(), organismRefId); if (gene == null) { return; } for (String pubRefId : publications) { gene.addToCollection("publications", pubRefId); } genes.put("" + ncbiGeneId, gene); } }
package br.eti.rslemos.brill.events; import static org.mockito.Mockito.*; import static org.hamcrest.CoreMatchers.*; import java.util.Arrays; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import br.eti.rslemos.brill.Context; import br.eti.rslemos.brill.Rule; import br.eti.rslemos.brill.RuleBasedTagger; import br.eti.rslemos.tagger.DefaultSentence; import br.eti.rslemos.tagger.Sentence; import br.eti.rslemos.tagger.Tagger; import br.eti.rslemos.tagger.Token; @SuppressWarnings("unchecked") public class RuleBasedTaggerListenerBehavior { @Mock private RuleBasedTaggerListener listener; private RuleBasedTagger tagger;; @Mock private Tagger baseTagger; @Mock private Rule rule1; @Mock private Rule rule2; @Mock private Token token1; @Mock private Token token2; private Sentence sentence; @BeforeMethod public void setUp() { MockitoAnnotations.initMocks(this); tagger = new RuleBasedTagger(); tagger.addRuleBasedTaggerListener(listener); tagger.setBaseTagger(baseTagger); tagger.setRules(Arrays.asList(rule1, rule2)); sentence = new DefaultSentence(Arrays.asList(token1, token2)); } @Test public void shouldAcceptListeners() { //tagger.addRuleBasedTaggerListener(listener); tagger.removeRuleBasedTaggerListener(listener); } @Test public void shouldNotifyTaggingStartAndFinish() { tagger.tag(sentence); InOrder order = inOrder(listener, baseTagger); order.verify(listener).taggingSentence(eventWithSentence()); order.verify(baseTagger).tag(anySentence()); order.verify(listener).sentenceTagged(eventWithSentence()); } @Test public void shouldNotifyBaseTaggingStartAndFinish() { tagger.tag(sentence); InOrder order = inOrder(listener, baseTagger); order.verify(listener).taggingSentence(anyEvent()); order.verify(listener).beforeBaseTagger(eventWithSentence()); order.verify(baseTagger).tag(anySentence()); order.verify(listener).afterBaseTagger(eventWithSentence()); order.verify(listener).sentenceTagged(anyEvent()); } @Test public void shouldNotifyRuleApplicationStartAndFinish() { tagger.tag(sentence); InOrder order = inOrder(listener); order.verify(listener).afterBaseTagger(anyEvent()); order.verify(listener).beforeRuleApplication(eventWithSentenceAndRule(rule1)); order.verify(listener).afterRuleApplication(eventWithSentenceAndRule(rule1)); order.verify(listener).beforeRuleApplication(eventWithSentenceAndRule(rule2)); order.verify(listener).afterRuleApplication(eventWithSentenceAndRule(rule2)); order.verify(listener).sentenceTagged(anyEvent()); } @Test public void shouldNotifyContextAdvanceAndCommit() { // override ruleset tagger.setRules(Arrays.asList(rule1)); tagger.tag(sentence); InOrder order = inOrder(listener); order.verify(listener).beforeRuleApplication(anyEvent()); order.verify(listener).advance(argThat(matchesEvent(is(sameInstance(tagger)), is(sameInstance(sentence)), is(sameInstance(rule1)), is(not(nullValue(Context.class))), is(tokenExternallyEquals(token1)), is(equalTo(false))))); order.verify(listener).advance(argThat(matchesEvent(is(sameInstance(tagger)), is(sameInstance(sentence)), is(sameInstance(rule1)), is(not(nullValue(Context.class))), is(tokenExternallyEquals(token2)), is(equalTo(false))))); order.verify(listener).commit(argThat(matchesEvent(is(sameInstance(tagger)), is(sameInstance(sentence)), is(sameInstance(rule1)), is(not(nullValue(Context.class))), is(nullValue(Token.class)), is(equalTo(false))))); order.verify(listener).afterRuleApplication(anyEvent()); } @Test public void shouldNotifyContextualRuleApplication() { // override ruleset tagger.setRules(Arrays.asList(rule1)); tagger.tag(sentence); InOrder order = inOrder(listener, rule1); order.verify(listener).advance(anyEvent()); order.verify(rule1).apply(anyContext()); order.verify(listener).ruleApplied(argThat(matchesEvent(is(sameInstance(tagger)), is(sameInstance(sentence)), is(sameInstance(rule1)), is(not(nullValue(Context.class))), is(nullValue(Token.class)), is(equalTo(false))))); order.verify(listener).advance(anyEvent()); order.verify(rule1).apply(anyContext()); order.verify(listener).ruleApplied(argThat(matchesEvent(is(sameInstance(tagger)), is(sameInstance(sentence)), is(sameInstance(rule1)), is(not(nullValue(Context.class))), is(nullValue(Token.class)), is(equalTo(false))))); order.verify(listener).commit(anyEvent()); order.verify(listener, never()).ruleApplied(anyEvent()); order.verify(rule1, never()).apply(anyContext()); } private static Matcher<Token> tokenExternallyEquals(Token token) { return new CustomTokenMatcher(token); } private static class CustomTokenMatcher extends BaseMatcher<Token> { private final Token wanted; public CustomTokenMatcher(Token wanted) { this.wanted = wanted; } @Override public boolean matches(Object item) { if (!(item instanceof Token)) return false; Token other = (Token) item; String wantedWord = wanted.getWord(); Object wantedTag = wanted.getTag(); String actualWord = other.getWord(); Object actualTag = other.getTag(); return (wantedWord != null ? wantedWord.equals(actualWord) : actualWord == null) && (wantedTag != null ? wantedTag.equals(actualTag) : actualTag == null); } @Override public void describeTo(Description description) { description.appendText("externally like "); String wantedWord = wanted.getWord(); if (wantedWord != null) description.appendText("\""); description.appendText(wantedWord); if (wantedWord != null) description.appendText("\""); description.appendText("/"); description.appendValue(wanted.getTag()); } } private static Matcher<RuleBasedTaggerEvent> matchesEvent( Matcher<RuleBasedTagger> taggerMatcher, Matcher<Sentence> sentenceMatcher, Matcher<Rule> ruleMatcher, Matcher<Context> contextMatcher, Matcher<Token> tokenMatcher, Matcher<Boolean> ruleAppliesMatcher) { return new CustomEventMatcher(taggerMatcher, sentenceMatcher, ruleMatcher, contextMatcher, tokenMatcher, ruleAppliesMatcher); } private static class CustomEventMatcher extends BaseMatcher<RuleBasedTaggerEvent> { private final Matcher<RuleBasedTagger> sourceMatcher; private final Matcher<Sentence> onSentenceMatcher; private final Matcher<Rule> actingRuleMatcher; private final Matcher<Context> contextMatcher; private final Matcher<Token> tokenMatcher; private final Matcher<Boolean> ruleAppliesMatcher; public CustomEventMatcher( Matcher<RuleBasedTagger> sourceMatcher, Matcher<Sentence> onSentenceMatcher, Matcher<Rule> actingRuleMatcher, Matcher<Context> contextMatcher, Matcher<Token> tokenMatcher, Matcher<Boolean> ruleAppliesMatcher) { this.sourceMatcher = sourceMatcher; this.onSentenceMatcher = onSentenceMatcher; this.actingRuleMatcher = actingRuleMatcher; this.contextMatcher = contextMatcher; this.tokenMatcher = tokenMatcher; this.ruleAppliesMatcher = ruleAppliesMatcher; } @Override public boolean matches(Object item) { if (!(item instanceof RuleBasedTaggerEvent)) return false; RuleBasedTaggerEvent other = (RuleBasedTaggerEvent) item; return sourceMatcher.matches(other.getSource()) && onSentenceMatcher.matches(other.getOnSentence()) && actingRuleMatcher.matches(other.getActingRule()) && contextMatcher.matches(other.getContext()) && tokenMatcher.matches(other.getToken()) && ruleAppliesMatcher.matches(matches(other.doesRuleApplies())); } @Override public void describeTo(Description description) { description.appendText(RuleBasedTaggerEvent.class.getName()); description.appendText("("); description.appendText("source ").appendDescriptionOf(sourceMatcher).appendText(", "); description.appendText("onSentence ").appendDescriptionOf(onSentenceMatcher).appendText(", "); description.appendText("actingRule ").appendDescriptionOf(actingRuleMatcher).appendText(", "); description.appendText("context ").appendDescriptionOf(contextMatcher).appendText(", "); description.appendText("token ").appendDescriptionOf(tokenMatcher).appendText(", "); description.appendText("does rule applies? ").appendDescriptionOf(ruleAppliesMatcher); description.appendText(")"); } } private static Sentence<String> anySentence() { return (Sentence<String>) anyObject(); } private static RuleBasedTaggerEvent<String> anyEvent() { return (RuleBasedTaggerEvent<String>) anyObject(); } private static Context<String> anyContext() { return (Context<String>) anyObject(); } private RuleBasedTaggerEvent eventWithSentence() { return argThat(matchesEvent(is(sameInstance(tagger)), is(sameInstance(sentence)), is(nullValue(Rule.class)), is(nullValue(Context.class)), is(nullValue(Token.class)), is(equalTo(false)))); } private RuleBasedTaggerEvent eventWithSentenceAndRule(Rule rule) { return argThat(matchesEvent(is(sameInstance(tagger)), is(sameInstance(sentence)), is(sameInstance(rule)), is(nullValue(Context.class)), is(nullValue(Token.class)), is(equalTo(false)))); } }
package ch.elexis.core.ui.preferences; import java.util.List; import java.util.stream.Collectors; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.beans.PojoProperties; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.IValueChangeListener; import org.eclipse.core.databinding.observable.value.ValueChangeEvent; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.CellLabelProvider; import org.eclipse.jface.viewers.CheckboxCellEditor; import org.eclipse.jface.viewers.EditingSupport; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.MenuAdapter; import org.eclipse.swt.events.MenuEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import ch.elexis.admin.ACE; import ch.elexis.admin.AccessControlDefaults; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.jdt.NonNull; import ch.elexis.core.ui.UiDesk; import ch.elexis.core.ui.icons.Images; import ch.elexis.core.ui.preferences.inputs.PrefAccessDenied; import ch.elexis.core.ui.util.BooleanNotConverter; import ch.elexis.core.ui.util.viewers.DefaultLabelProvider; import ch.elexis.data.Query; import ch.elexis.data.Role; public class RolesToAccessRightsPreferencePage extends PreferencePage implements IWorkbenchPreferencePage, IValueChangeListener { private DataBindingContext m_bindingContext; private WritableValue wv = new WritableValue(null, Role.class); private Text txti18n; private TreeViewer treeViewer; private Text txtRoleName; private MenuItem mntmNewRole; private TableViewer tableViewerRoles; private MenuItem mntmRemoveRole; /** * Create the preference page. */ public RolesToAccessRightsPreferencePage(){ setTitle("Rollen und Rechte"); noDefaultAndApplyButton(); } /** * Create contents of the preference page. * * @param parent */ @Override public Control createContents(Composite parent){ if (!CoreHub.acl.request(AccessControlDefaults.ACL_USERS)) { return new PrefAccessDenied(parent); } Composite container = new Composite(parent, SWT.NULL); container.setLayout(new GridLayout(1, false)); SashForm sashForm = new SashForm(container, SWT.NONE); sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); Composite compositeRoles = new Composite(sashForm, SWT.NONE); GridLayout gl_compositeRoles = new GridLayout(1, false); gl_compositeRoles.verticalSpacing = 2; gl_compositeRoles.marginWidth = 0; gl_compositeRoles.marginHeight = 0; compositeRoles.setLayout(gl_compositeRoles); tableViewerRoles = new TableViewer(compositeRoles, SWT.BORDER); Table tableRoles = tableViewerRoles.getTable(); tableRoles.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); Menu menu = new Menu(tableRoles); tableRoles.setMenu(menu); menu.addMenuListener(new MenuAdapter() { @Override public void menuShown(MenuEvent e){ super.menuShown(e); Role r = (Role) wv.getValue(); mntmRemoveRole.setEnabled(!r.isSystemRole()); } }); mntmNewRole = new MenuItem(menu, SWT.NONE); mntmNewRole.setText("Rolle hinzufügen"); mntmNewRole.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ Role newRole = new Role(false); updateRolesList(); tableViewerRoles.setSelection(new StructuredSelection(newRole)); } }); mntmRemoveRole = new MenuItem(menu, SWT.NONE); mntmRemoveRole.setText("Rolle löschen"); mntmRemoveRole.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ Role r = (Role) wv.getValue(); r.delete(); updateRolesList(); } }); Composite composite = new Composite(compositeRoles, SWT.NONE); GridLayout gl_composite = new GridLayout(2, false); gl_composite.marginWidth = 0; gl_composite.horizontalSpacing = 0; gl_composite.verticalSpacing = 0; gl_composite.marginHeight = 0; composite.setLayout(gl_composite); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); txtRoleName = new Text(composite, SWT.BORDER); txtRoleName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txtRoleName.setMessage("Bezeichnung"); Link linkChangeRoleName = new Link(composite, SWT.NONE); linkChangeRoleName.setText(UserManagementPreferencePage.CHANGE_LINK); linkChangeRoleName.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ String newRoleName = txtRoleName.getText(); if (Role.verifyRoleNameNotTaken(newRoleName)) { setErrorMessage(null); Role r = (Role) wv.getValue(); Role changedRole = r.setRoleName(newRoleName); updateRolesList(); tableViewerRoles.setSelection(new StructuredSelection(changedRole)); } else { setErrorMessage("Rollenname bereits vergeben."); } } }); txti18n = new Text(compositeRoles, SWT.BORDER); txti18n.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); txti18n.setMessage("Lokale Bezeichnung"); txti18n.setBounds(0, 0, 64, 19); tableViewerRoles.setContentProvider(ArrayContentProvider.getInstance()); tableViewerRoles.setLabelProvider(new DefaultLabelProvider() { @Override public Image getColumnImage(Object element, int columnIndex){ Role r = (Role) element; if (r.isSystemRole()) { return Images.IMG_LOCK_CLOSED.getImage(); } else { return Images.IMG_EMPTY_TRANSPARENT.getImage(); } } }); tableViewerRoles.addSelectionChangedListener((e) -> { StructuredSelection ss = (StructuredSelection) e.getSelection(); wv.setValue(ss == null ? null : ss.getFirstElement()); }); treeViewer = new TreeViewer(sashForm, SWT.FULL_SELECTION); final Tree tree = treeViewer.getTree(); tree.setHeaderVisible(true); tree.setLinesVisible(true); treeViewer.setContentProvider(new ACETreeContentProvider()); treeViewer.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell){ ACE a = (ACE) cell.getElement(); cell.setText(a.getLocalizedName()); } }); treeViewer.setSorter(new ViewerSorter() { @Override public int compare(Viewer viewer, Object e1, Object e2){ ACE t1 = (ACE) e1; ACE t2 = (ACE) e2; return t1.getLocalizedName().compareToIgnoreCase(t2.getLocalizedName()); } }); TreeViewerColumn tvc_right = new TreeViewerColumn(treeViewer, SWT.NONE); TreeColumn tc_right = tvc_right.getColumn(); tc_right.setWidth(-1); tc_right.setWidth(280); tc_right.setText("Recht"); tvc_right.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell){ ACE a = (ACE) cell.getElement(); cell.setText(a.getLocalizedName()); } }); final CheckboxCellEditor cbce = new CheckboxCellEditor(); final CellLabelProvider clp = new CellLabelProvider() { @Override public void update(ViewerCell cell){ TreeColumn tc = tree.getColumn(cell.getColumnIndex()); Role role = (Role) tc.getData("role"); ACE ace = (ACE) cell.getElement(); int val = determineChildAndSelfStates(role, ace); switch (val) { case 3: if (ace.getChildren(true).size() > 1) { cell.setText("A"); cell.setForeground(UiDesk.getColor(UiDesk.COL_BLUE)); } else { cell.setText("x"); } break; case 2: cell.setText("v"); break; case 1: cell.setText("x"); break; default: cell.setText(""); cell.setForeground(UiDesk.getColor(UiDesk.COL_BLACK)); } } }; Query<Role> qbe = new Query<Role>(Role.class); List<Role> roles = qbe.execute(); for (Role role : roles) { TreeViewerColumn tvc = new TreeViewerColumn(treeViewer, SWT.CENTER); tvc.getViewer().setData("role", role); TreeColumn tc = tvc.getColumn(); tc.setData("role", role); tc.setWidth(20); tc.setText(role.getLabel().charAt(0) + ""); tvc.setLabelProvider(clp); EditingSupport es = new EditingSupport(tvc.getViewer()) { @Override protected void setValue(Object element, Object value){ BusyIndicator.showWhile(UiDesk.getDisplay(), new Runnable() { @Override public void run(){ Role role = (Role) tc.getData("role"); ACE ace = (ACE) element; if (isChecked(ace, role)) { CoreHub.acl.revoke(role, ace); } else { CoreHub.acl.grant(role, ace); } getViewer().update(element, null); } }); } @Override protected Object getValue(Object element){ // irrelevant, not represented in UI; // done via LabelProvider, hence // we skip evaluation of this value return true; } @Override protected CellEditor getCellEditor(Object element){ return cbce; } @Override protected boolean canEdit(Object element){ return true; } }; tvc.setEditingSupport(es); } sashForm.setWeights(new int[] { 3, 7 }); Composite compositeBottom = new Composite(container, SWT.NONE); compositeBottom.setLayout(new GridLayout(1, false)); compositeBottom.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, false, 1, 1)); Link linkResetDefaults = new Link(compositeBottom, 0); linkResetDefaults.setText("<a>Standard-Rechte wiederherstellen</a>"); linkResetDefaults.setBounds(0, 0, 43, 15); linkResetDefaults.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ boolean ret = MessageDialog.openQuestion(UiDesk.getTopShell(), "Standard-Rechte wiederherstellen", "Sind Sie sicher?"); if (ret) { ACE.initializeACEDefaults(true); refreshViewer(); } } }); m_bindingContext = initDataBindings(); wv.addValueChangeListener(this); treeViewer.setInput(ACE.getAllDefinedRootACElements()); tableViewerRoles.setInput(roles); return container; } private void updateRolesList(){ Query<Role> qbe = new Query<Role>(Role.class); tableViewerRoles.setInput(qbe.execute()); } /** * Initialize the preference page. */ public void init(IWorkbench workbench){ // Initialize the preference page } // the user selected a different role @Override public void handleValueChange(ValueChangeEvent event){ Role r = (Role) wv.getValue(); txtRoleName.setText((r == null) ? "" : r.getRoleName()); } private void refreshViewer(){ treeViewer.refresh(); } private class ACETreeContentProvider implements ITreeContentProvider { @Override public void dispose(){} @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput){} public Object[] getElements(Object inputElement){ return (Object[]) inputElement; } public Object[] getChildren(Object parentElement){ ACE a = (ACE) parentElement; return ACE.getAllDefinedACElements().stream().filter(p -> p.getParent().equals(a)) .toArray(); } @Override public Object getParent(Object element){ ACE a = (ACE) element; ACE parent = a.getParent(); if (ACE.ACE_ROOT.equals(parent)) return null; return parent; } public boolean hasChildren(Object element){ ACE a = (ACE) element; return ACE.getAllDefinedACElements().stream().filter(p -> p.getParent().equals(a)) .count() > 0d; } } private boolean isGrayed(ACE ace, Role role){ if (role == null || ace == null) return false; int state = determineChildAndSelfStates(role, ace); return (state == 1 || state == 2); } private boolean isChecked(ACE ace, Role r){ if (r == null || ace == null) return false; int state = determineChildAndSelfStates(r, ace); return (state > 0); } /** * Check the state of the current ACE its parents and children, where <code>state</code> is * <ul> * <li><code>0</code>: not allowed, none of the children, and no parents</li> * <li><code>1</code>: allowed via grant to a parent</li> * <li><code>2</code>: allowed by self</li> * <li><code>3</code>: allowed, by entire chain (all children are allowed)</li> * </ul> * * @param r * @param ace * @return <code>state</code> as determined */ private int determineChildAndSelfStates(@NonNull Role r, @NonNull ACE ace){ if (CoreHub.acl.request(r, ace.getParent())) return 1; List<ACE> chain = ace.getChildren(true); List<Boolean> chainRights = chain.stream().map(ace2 -> CoreHub.acl.request(r, ace2)).collect(Collectors.toList()); long trues = chainRights.stream().filter(p -> p.booleanValue() == true).count(); if (trues == 0) return 0; if (trues == chainRights.size()) return 3; return 2; } protected DataBindingContext initDataBindings(){ DataBindingContext bindingContext = new DataBindingContext(); IObservableValue observeTextTxti18nObserveWidget = WidgetProperties.text(SWT.Modify).observe(txti18n); IObservableValue wvTranslatedLabelObserveDetailValue = PojoProperties.value(Role.class, "translatedLabel", String.class).observeDetail(wv); bindingContext.bindValue(observeTextTxti18nObserveWidget, wvTranslatedLabelObserveDetailValue, null, null); IObservableValue observeEnabledTxtRoleNameObserveWidget = WidgetProperties.enabled().observe(txtRoleName); IObservableValue wvSystemRoleObserveDetailValue = PojoProperties.value(Role.class, "systemRole", boolean.class).observeDetail(wv); UpdateValueStrategy strategy = new UpdateValueStrategy(); strategy.setConverter(new BooleanNotConverter()); bindingContext.bindValue(observeEnabledTxtRoleNameObserveWidget, wvSystemRoleObserveDetailValue, new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER), strategy); return bindingContext; } }
package com.python.pydev.refactoring.refactorer; import java.io.File; import org.python.pydev.core.TestDependent; import org.python.pydev.editor.actions.PySelection; import org.python.pydev.editor.codecompletion.revisited.CodeCompletionTestsBase; import org.python.pydev.editor.codecompletion.revisited.modules.CompiledModule; import org.python.pydev.editor.model.ItemPointer; import org.python.pydev.editor.refactoring.RefactoringRequest; public class SearchTest extends CodeCompletionTestsBase { public static void main(String[] args) { try { SearchTest test = new SearchTest(); test.setUp(); test.testSearch13(); test.tearDown(); junit.textui.TestRunner.run(SearchTest.class); } catch (Throwable e) { e.printStackTrace(); } } private Refactorer refactorer; protected void setUp() throws Exception { super.setUp(); CompiledModule.COMPILED_MODULES_ENABLED = true; this.restorePythonPath(false); refactorer = new Refactorer(); } protected void tearDown() throws Exception { CompiledModule.COMPILED_MODULES_ENABLED = true; super.tearDown(); } public void testSearch1() throws Exception { //searching for import. //Line contents (1): //from toimport import Test1 String line = "from toimport import Test1"; RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"testlib/unittest/relative/testrelative.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, line.length()); refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.TEST_PYSRC_LOC+"testlib/unittest/relative/toimport.py"), pointers[0].file); assertEquals(0, pointers[0].start.line); assertEquals(6, pointers[0].start.column); } public void testSearch2() throws Exception { String line = "from testlib.unittest import testcase as t"; RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"testlib/unittest/anothertest.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, line.length()); refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.TEST_PYSRC_LOC+"testlib/unittest/testcase.py"), pointers[0].file); //found the module assertEquals(0, pointers[0].start.line); assertEquals(0, pointers[0].start.column); } public void testSearch3() throws Exception { String line = "from testlib.unittest import testcase as t"; // "from testlib.unittest import test" < -- that's the cursor pos RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"testlib/unittest/anothertest.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, line.length()-9); refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.TEST_PYSRC_LOC+"testlib/unittest/testcase.py"), pointers[0].file); //found the module assertEquals(0, pointers[0].start.line); assertEquals(0, pointers[0].start.column); } public void testSearch4() throws Exception { String line = "from testlib.unittest import testcase as t"; // "from testlib.unitt" < -- that's the cursor pos RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"testlib/unittest/anothertest.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, line.length()-24); refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.TEST_PYSRC_LOC+"testlib/unittest/__init__.py"), pointers[0].file); //found the module assertEquals(0, pointers[0].start.line); assertEquals(0, pointers[0].start.column); } public void testSearch5() throws Exception { //ring line = "from testlib.unittest import testcase as t"; // "from " < -- that's the cursor pos RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"testlib/unittest/anothertest.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, 6); refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.TEST_PYSRC_LOC+"testlib/__init__.py"), pointers[0].file); //found the module assertEquals(0, pointers[0].start.line); assertEquals(0, pointers[0].start.column); } public void testSearch6() throws Exception { //from testlib.unittest import testcase as t String line = "class AnotherTest(t.TestCase):"; // "from " < -- that's the cursor pos RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"testlib/unittest/anothertest.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, 2, line.length() - 5); refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.TEST_PYSRC_LOC+"testlib/unittest/testcase.py"), pointers[0].file); //found the module assertEquals(8, pointers[0].start.line); assertEquals(6, pointers[0].start.column); } public void testSearch7() throws Exception { // from static import TestStatic // print TestStatic.static1 // class TestStaticExt(TestStatic): // def __init__(self): // print self.static1 String line = "print TestStatic.static1"; RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"extendable/static2.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, 1, line.length()); refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.TEST_PYSRC_LOC+"extendable/static.py"), pointers[0].file); //found the module assertEquals(3, pointers[0].start.line); assertEquals(8, pointers[0].start.column); } public void testSearch8() throws Exception { // from static import TestStatic // print TestStatic.static1 // class TestStaticExt(TestStatic): // def __init__(self): // print self.static1 String line = " print self.static1"; RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"extendable/static2.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, 4, line.length()); refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.TEST_PYSRC_LOC+"extendable/static.py"), pointers[0].file); //found the module assertEquals(3, pointers[0].start.line); assertEquals(8, pointers[0].start.column); } public void testSearch9() throws Exception { // from static import TestStatic // print TestStatic.static1 // class TestStaticExt(TestStatic): // def __init__(self): // print self.static1 // from extendable.dependencies.file2 import Test String line = " from extendable.dependencies.file2 import Test"; RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"extendable/static2.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, 5, line.length()); refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.TEST_PYSRC_LOC+"extendable/dependencies/file2.py"), pointers[0].file); //found the module assertEquals(0, pointers[0].start.line); assertEquals(6, pointers[0].start.column); } public void testSearch10() throws Exception { // from static import TestStatic // print TestStatic.static1 // class TestStaticExt(TestStatic): // def __init__(self): // print self.static1 // from extendable.dependencies.file2 import Test // import extendable.dependencies.file2.Test String line = " import extendable.dependencies.file2.Test"; RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"extendable/static2.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, 6, line.length()); refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.TEST_PYSRC_LOC+"extendable/dependencies/file2.py"), pointers[0].file); //found the module assertEquals(0, pointers[0].start.line); assertEquals(6, pointers[0].start.column); } public void testSearch11() throws Exception { // from static import TestStatic // print TestStatic.static1 // class TestStaticExt(TestStatic): // def __init__(self): // print self.static1 // from extendable.dependencies.file2 import Test // import extendable.dependencies.file2.Test String line = " import extendable.dependencies.file2.Test"; RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"extendable/static2.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, 6, line.length()-7); //find the file2 module itself refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.TEST_PYSRC_LOC+"extendable/dependencies/file2.py"), pointers[0].file); //found the module assertEquals(0, pointers[0].start.line); assertEquals(0, pointers[0].start.column); } public void testSearch12() throws Exception { // from static import TestStatic // print TestStatic.static1 // class TestStaticExt(TestStatic): // def __init__(self): // print self.static1 // from extendable.dependencies.file2 import Test // import extendable.dependencies.file2.Test String line = " import extendable.dependencies.file2.Test"; RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"extendable/static2.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, 6, line.length()-16); //find the dependencies module itself refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.TEST_PYSRC_LOC+"extendable/dependencies/__init__.py"), pointers[0].file); //found the module assertEquals(0, pointers[0].start.line); assertEquals(0, pointers[0].start.column); } public void testSearch13() throws Exception { // from f1 import * // print Class1 String line = "print Class1"; RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"testrecwild/__init__.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, 1, line.length()); refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.TEST_PYSRC_LOC+"testrecwild/f2.py"), pointers[0].file); //found the module assertEquals(0, pointers[0].start.line); assertEquals(6, pointers[0].start.column); } public void testBuiltinSearch() throws Exception { // import os String line = "import os"; RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"simpleosimport.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, 0, line.length()); //find the os module refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.PYTHON_LIB+"os.py"), pointers[0].file); //found the module assertEquals(0, pointers[0].start.line); assertEquals(0, pointers[0].start.column); } public void testBuiltinSearch2() throws Exception { // import os.path.normpath String line = "import os.path.normpath"; RefactoringRequest refactoringRequest = new RefactoringRequest(new File(TestDependent.TEST_PYSRC_LOC+"definitions/__init__.py")); refactoringRequest.ps = new PySelection(refactoringRequest.doc, 0, line.length()); //find the os.path.normpath func pos refactoringRequest.nature = nature; ItemPointer[] pointers = refactorer.findDefinition(refactoringRequest); assertEquals(1, pointers.length); assertEquals(new File(TestDependent.PYTHON_LIB+"ntpath.py"), pointers[0].file); //found the module assertTrue(440 == pointers[0].start.line || 439 == pointers[0].start.line); //depends on python version assertEquals(0, pointers[0].start.column); } }
package org.jboss.forge.container.modules; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import org.jboss.weld.resources.spi.ResourceLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class provides file-system orientated scanning * * @author Pete Muir * @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> */ public class ModularFileSystemURLHandler { private static final Logger log = LoggerFactory.getLogger(ModularFileSystemURLHandler.class); @SuppressWarnings("unused") private ResourceLoader resourceLoader; public ModularFileSystemURLHandler(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public void handle(Collection<String> paths, List<String> discoveredClasses, List<URL> discoveredBeansXmlUrls) { for (String urlPath : paths) { try { ModularFileSystemURLHandler.log.trace("scanning: " + urlPath); if (urlPath.startsWith("file:")) { urlPath = urlPath.substring(5); } if (urlPath.indexOf('!') > 0) { urlPath = urlPath.substring(0, urlPath.indexOf('!')); } File file = new File(urlPath); if (file.isDirectory()) { handleDirectory(file, null, discoveredClasses, discoveredBeansXmlUrls); } else { handleArchiveByFile(file, discoveredClasses, discoveredBeansXmlUrls); } } catch (IOException ioe) { ModularFileSystemURLHandler.log.warn("could not read entries", ioe); } } } private void handleArchiveByFile(File file, List<String> discoveredClasses, List<URL> discoveredBeansXmlUrls) throws IOException { try { log.trace("archive: " + file); String archiveUrl = "jar:" + file.toURI().toURL().toExternalForm() + "!/"; ZipFile zip = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); handle(name, new URL(archiveUrl + name), discoveredClasses, discoveredBeansXmlUrls); } } catch (ZipException e) { throw new RuntimeException("Error handling file " + file, e); } } protected void handleDirectory(File file, String path, List<String> discoveredClasses, List<URL> discoveredBeansXmlUrls) { handleDirectory(file, path, new File[0], discoveredClasses, discoveredBeansXmlUrls); } private void handleDirectory(File file, String path, File[] excludedDirectories, List<String> discoveredClasses, List<URL> discoveredBeansXmlUrls) { for (File excludedDirectory : excludedDirectories) { if (file.equals(excludedDirectory)) { log.trace("skipping excluded directory: " + file); return; } } log.trace("handling directory: " + file); for (File child : file.listFiles()) { String newPath = (path == null) ? child.getName() : (path + '/' + child.getName()); if (child.isDirectory()) { handleDirectory(child, newPath, excludedDirectories, discoveredClasses, discoveredBeansXmlUrls); } else { try { handle(newPath, child.toURI().toURL(), discoveredClasses, discoveredBeansXmlUrls); } catch (MalformedURLException e) { log.error("Error loading file " + newPath); } } } } protected void handle(String name, URL url, List<String> discoveredClasses, List<URL> discoveredBeansXmlUrls) { if (name.endsWith(".class")) { String className = filenameToClassname(name); discoveredClasses.add(className); } else if (name.endsWith("beans.xml")) { discoveredBeansXmlUrls.add(url); } } /** * Convert a path to a class file to a class name */ public static String filenameToClassname(String filename) { return filename.substring(0, filename.lastIndexOf(".class")).replace('/', '.').replace('\\', '.'); } }
package org.jboss.forge.container.services; import java.lang.reflect.Method; import javax.enterprise.inject.spi.InjectionPoint; import org.jboss.forge.container.Addon; import org.jboss.forge.container.AddonRegistry; import org.jboss.forge.container.util.Addons; import org.jboss.forge.container.util.Assert; import org.jboss.forge.proxy.ForgeProxy; import org.jboss.forge.proxy.Proxies; public class ExportedInstanceLazyLoader implements ForgeProxy { private final Class<?> serviceType; private final AddonRegistry registry; private final InjectionPoint injectionPoint; private Object delegate; public ExportedInstanceLazyLoader(AddonRegistry registry, Class<?> serviceType, InjectionPoint injectionPoint) { this.registry = registry; this.serviceType = serviceType; this.injectionPoint = injectionPoint; } public static Object create(AddonRegistry registry, InjectionPoint injectionPoint, Class<?> serviceType) { ExportedInstanceLazyLoader callback = new ExportedInstanceLazyLoader(registry, serviceType, injectionPoint); return Proxies.enhance(serviceType, callback); } @Override public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { try { if (thisMethod.getDeclaringClass().getName().equals(ForgeProxy.class.getName())) { return delegate; } } catch (Exception e) { } if (delegate == null) delegate = loadObject(); return thisMethod.invoke(delegate, args); } private Object loadObject() throws Exception { Object result = null; for (Addon addon : registry.getServiceRegistries().keySet()) { Addons.waitUntilStarted(addon); if (serviceType.getClassLoader().equals(addon.getClassLoader())) { ServiceRegistry serviceRegistry = addon.getServiceRegistry(); ExportedInstance<?> instance = serviceRegistry.getExportedInstance(serviceType); Assert.notNull(instance, "Exported Instance not found in originating ServiceRegistry."); if (instance instanceof ExportedInstanceImpl) // FIXME remove the need for this implementation coupling result = ((ExportedInstanceImpl<?>) instance).get(new LocalServiceInjectionPoint(injectionPoint, serviceType)); else result = instance.get(); break; } } if (result == null) { throw new IllegalStateException("Remote service [" + serviceType.getName() + "] is not registered."); } return result; } @Override public Object getDelegate() { return delegate; } }
package io.openshift.appdev.missioncontrol.core.api; /** * That holds all status messages that we send to the clients via * websockets to inform them about the status of their project */ public enum StatusMessage { GITHUB_CREATE("Creating your new GitHub repository"), GITHUB_PUSHED("Pushing your customized Booster code into the repo"), OPENSHIFT_CREATE("Creating your project on OpenShift Online"), OPENSHIFT_PIPELINE("Setting up your build pipeline"), GITHUB_WEBHOOK("Configuring to trigger builds on Git pushes"); StatusMessage(String message) { this.message = message; } private final String message; public String getMessage() { return message; } @Override public String toString() { return message; } }
package com.thingtrack.konekti.view.addon.ui; import java.io.Serializable; import org.vaadin.peter.buttongroup.ButtonGroup; import com.thingtrack.konekti.view.addon.data.BindingSource; import com.thingtrack.konekti.view.addon.data.BindingSource.IndexChangeEvent; import com.thingtrack.konekti.view.addon.data.BindingSource.IndexChangeListener; import com.vaadin.annotations.AutoGenerated; import com.vaadin.terminal.ThemeResource; import com.vaadin.terminal.gwt.client.MouseEventDetails; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Component; import com.vaadin.ui.ComponentContainer; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Window.CloseEvent; import com.vaadin.ui.Window.CloseListener; @SuppressWarnings("serial") public class BoxToolbar extends AbstractToolbar { @AutoGenerated private HorizontalLayout toolbarLayout; @AutoGenerated private Button btnPrint; @AutoGenerated private Button btnFilter; @AutoGenerated private Button btnAttach; @AutoGenerated private Button btnImport; /*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */ private Object register; // navigator button listeners private ClickPrintButtonListener listenerPrintButton = null; private ClickAttachButtonListener listenerAttachButton = null; private ClickFilterButtonListener listenerFilterButton = null; private ClickImportButtonListener listenerImportButton = null; /** * The constructor should first build the main layout, set the * composition root and then do any custom initialization. * * The constructor will not be automatically regenerated by the * visual editor. */ public BoxToolbar(int position, final BindingSource<?> bindingSource) { super(position, bindingSource); buildMainLayout(); // TODO add user code here btnFilter.setDescription("Filtrar Tabla"); btnFilter.addListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { if(listenerFilterButton != null) listenerFilterButton.filterButtonClick(new ClickNavigationEvent(btnFilter, event.getComponent())); } }); btnPrint.setDescription("Imprimir Tabla"); btnPrint.addListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { if(listenerPrintButton != null) listenerPrintButton.printButtonClick(new ClickNavigationEvent(btnPrint, event.getComponent())); } }); btnAttach.setDescription("Adjuntar Fichero"); btnAttach.addListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { try { attachFile(); } catch (IllegalArgumentException e) { throw new RuntimeException("¡No se pudo mostrar el formulario para adjuntar ficheros!", e); } catch (IllegalAccessException e) { throw new RuntimeException("¡No se pudo mostrar el formulario para adjuntar ficheros!", e); } if(listenerAttachButton != null) listenerAttachButton.attachButtonClick(new ClickNavigationEvent(btnAttach, event.getComponent())); } }); btnImport.setDescription("Importar Fichero"); btnImport.setVisible(false); btnImport.addListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { try { importFile(); } catch (IllegalArgumentException e) { throw new RuntimeException("¡No se pudo mostrar el formulario para importar ficheros!", e); } catch (IllegalAccessException e) { throw new RuntimeException("¡No se pudo mostrar el formulario para importar ficheros!", e); } } }); } public void setImportButton(boolean visible) { this.btnImport.setVisible(visible); } @Override public int getPosition() { return this.position; } @Override public ComponentContainer getContent() { return this.toolbarLayout; } @Override public BindingSource<?> getBindingSource() { return this.bindingSource; } @Override public void setBindingSource(BindingSource<?> bindingSource) { this.bindingSource = bindingSource; // add change index binding source if (bindingSource != null) { bindingSource.addListenerToolBar((IndexChangeListener)this); // initialize binding source //bindingSource.Initialize(); } } public void addListenerPrintButton(ClickPrintButtonListener listener) { this.listenerPrintButton = listener; } public void addListenerAttachButton(ClickAttachButtonListener listener) { this.listenerAttachButton = listener; } public void addListenerFilterButton(ClickFilterButtonListener listener) { this.listenerFilterButton = listener; } public void addListenerImportButton(ClickImportButtonListener listener) { this.listenerImportButton = listener; } public interface ClickPrintButtonListener extends Serializable { public void printButtonClick(ClickNavigationEvent event); } public interface ClickAttachButtonListener extends Serializable { public void attachButtonClick(ClickNavigationEvent event); } public interface ClickFilterButtonListener extends Serializable { public void filterButtonClick(ClickNavigationEvent event); } public interface ClickImportButtonListener extends Serializable { public void importButtonClick(ClickNavigationEvent event); } public class ClickNavigationEvent extends ClickEvent { private int index; private Object register; private byte[] file; public ClickNavigationEvent(Button button, Component source) { button.super(source); } public ClickNavigationEvent(Button button, byte[] file, Component source) { button.super(source); this.file = file; } public ClickNavigationEvent(Button button, Component source, MouseEventDetails details) { button.super(source, details); } public ClickNavigationEvent(Button button, Component source, MouseEventDetails details, Object register, int index) { button.super(source, details); this.index = index; this.register = register; } public int getIndex() { return this.index; } public Object getRegister() { return this.register; } public byte[] getFile() { return this.file; } } @Override public void bindingSourceIndexChange(IndexChangeEvent event) { if (bindingSource != null) { // TODO Auto-generated method stub } } @AutoGenerated private void buildMainLayout() { // toolbarLayout toolbarLayout = buildToolbarLayout(); addComponent(toolbarLayout); } public void attachFile() throws IllegalArgumentException, IllegalAccessException { int index = bindingSource.getIndex(); if (index == 0) return; register = bindingSource.getItemId(); AttachmentViewForm attachmentViewForm = new AttachmentViewForm(); attachmentViewForm.setEntity(register); getApplication().getMainWindow().addWindow(attachmentViewForm); } private void importFile() throws IllegalArgumentException, IllegalAccessException { final UploadViewForm uploadViewForm = new UploadViewForm(null, null); uploadViewForm.setWidth("300px"); uploadViewForm.setHeight("-1px"); uploadViewForm.addListener(new CloseListener() { @Override public void windowClose(CloseEvent e) { byte[] file = uploadViewForm.getFile(); if(listenerImportButton != null) listenerImportButton.importButtonClick(new ClickNavigationEvent(btnImport, file, e.getComponent())); } }); getApplication().getMainWindow().addWindow(uploadViewForm); } @AutoGenerated private HorizontalLayout buildToolbarLayout() { // common part: create layout toolbarLayout = new HorizontalLayout(); toolbarLayout.setImmediate(false); toolbarLayout.setSpacing(true); ButtonGroup toolBoxButtonGroup = new ButtonGroup(); toolbarLayout.addComponent(toolBoxButtonGroup); toolbarLayout.setExpandRatio(toolBoxButtonGroup, 1.0f); // btnFilter btnFilter = new Button(); btnFilter.setImmediate(true); btnFilter.setWidth("-1px"); btnFilter.setHeight("-1px"); btnFilter.setIcon(new ThemeResource("../konekti/images/icons/box-toolbar/funnel.png")); toolBoxButtonGroup.addButton(btnFilter); // btnAttach btnAttach = new Button(); btnAttach.setImmediate(true); btnAttach.setWidth("-1px"); btnAttach.setHeight("-1px"); btnAttach.setIcon(new ThemeResource("../konekti/images/icons/box-toolbar/paper-clip.png")); toolBoxButtonGroup.addButton(btnAttach); // btnPrint btnPrint = new Button(); btnPrint.setImmediate(true); btnPrint.setWidth("-1px"); btnPrint.setHeight("-1px"); btnPrint.setIcon(new ThemeResource("../konekti/images/icons/box-toolbar/printer.png")); toolBoxButtonGroup.addButton(btnPrint); // btnPrint btnImport = new Button(); btnImport.setImmediate(true); btnImport.setWidth("-1px"); btnImport.setHeight("-1px"); btnImport.setIcon(new ThemeResource("../konekti/images/icons/servicetemplate-module/document-excel.png")); toolBoxButtonGroup.addButton(btnImport); return toolbarLayout; } @Override protected void updateLabels() { btnPrint.setDescription(getI18N().getMessage("com.thingtrack.konekti.view.addon.ui.BoxToolbar.btnPrint.description")); btnFilter.setDescription(getI18N().getMessage("com.thingtrack.konekti.view.addon.ui.BoxToolbar.btnFilter.description")); btnAttach.setDescription(getI18N().getMessage("com.thingtrack.konekti.view.addon.ui.BoxToolbar.btnAttach.description")); btnImport.setDescription(getI18N().getMessage("com.thingtrack.konekti.view.addon.ui.BoxToolbar.btnImport.description")); } }
package gamelog; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * * @author gmein */ public class GameLog { private final ReadWriteLock rwl = new ReentrantReadWriteLock(); private final Lock rlock; private final Lock wlock; private final GameLogState state; private ArrayList<GameLogEntry> log = new ArrayList<>(); private final HashMap<Object, GameLogObserver> observers = new HashMap<>(); private int start = 0; private int end = 0; private int minRead = 0; GameLog(GameLogState state) { rlock = rwl.readLock(); wlock = rwl.writeLock(); this.state = state; } void addLogEntries(List<GameLogEntry> list) { wlock.lock(); try { log.addAll(list); end += list.size(); } finally { wlock.unlock(); } } GameLogObserver addObserver(Object client) { GameLogObserver obs; synchronized (observers) { obs = new GameLogObserver(this); observers.put(client, obs); } return obs; } void removeObserver(Object client) { synchronized (observers) { observers.remove(client); } } void collapseRead() { wlock.lock(); try { // process all read items into state log, for (int i = 0; i < minRead - start; i++) { state.addEntry(log.get(i)); } // take the sublist of unread items, make it the new list, ArrayList<GameLogEntry> newLog = new ArrayList<>(); newLog.addAll(log.subList(minRead - start, end - start)); log = newLog; // and adjust the "start" offset start -= end - minRead; } finally { wlock.unlock(); } } // needs rewrite with concept of observers ArrayList<GameLogEntry> getNewItems(GameLogObserver obs) { ArrayList<GameLogEntry> result = new ArrayList<>(); rlock.lock(); try { // copy the new items to the result result.addAll(log.subList(obs.maxRead - start, end - start)); // update maxRead, and possibly minRead // need to lock this, multiple threads might want to do it synchronized (observers) { // if we were at minRead and have new items, we might need to move it if (obs.maxRead == minRead && end > minRead) { int currentMin = end; for (GameLogObserver o : observers.values()) { if (o.maxRead < currentMin) { currentMin = o.maxRead; } } // record new minimum minRead = currentMin; } // set our new maxRead obs.maxRead = end; } } finally { rlock.unlock(); } return result; } GameLogState getNewGameLogState() { GameLogState result = null; wlock.lock(); try { result = state.clone(); } finally { wlock.unlock(); } return result; } }
package com.example.android.sunshine2; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.format.Time; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.support.v4.app.Fragment; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ForecastFragment extends Fragment { ArrayAdapter<String> mForecastAdapter; public ForecastFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Add this line in order for this fragment to handle menu events. setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.forecastfragment, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_refresh) { FetchWeatherTask weatherTask = new FetchWeatherTask(); weatherTask.execute("94043"); return true; } return super.onOptionsItemSelected(item); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Create some dummy data for the ListView. Here's a sample weekly forecast String[] data = { "Mon 6/23 - Sunny - 31/17", "Tue 6/24 - Foggy - 21/8", "Wed 6/25 - Cloudy - 22/17", "Thurs 6/26 - Rainy - 18/11", "Fri 6/27 - Foggy - 21/10", "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18", "Sun 6/29 - Sunny - 20/7" }; List<String> weekForecast = new ArrayList<String>(Arrays.asList(data)); mForecastAdapter = new ArrayAdapter<String>( getActivity(), // The current context (this activity) R.layout.list_item_forecast, // The name of the layout ID. R.id.list_item_forecast_textview, // The ID of the textview to populate. weekForecast); View rootView = inflater.inflate(R.layout.fragment_main, container, false); ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast); listView.setAdapter(mForecastAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { String forecast = mForecastAdapter.getItem(position); // Toast.makeText(getActivity(), forecast, Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getActivity(), DetailActivity.class) .putExtra(Intent.EXTRA_TEXT, forecast); startActivity(intent); } }); return rootView; } public class FetchWeatherTask extends AsyncTask<String, Void, String[]> { private final String LOG_TAG = FetchWeatherTask.class.getSimpleName(); /* The date/time conversion code is going to be moved outside the asynctask later, * so for convenience we're breaking it out into its own method now. */ private String getReadableDateString(long time){ // Because the API returns a unix timestamp (measured in seconds), // it must be converted to milliseconds in order to be converted to valid date. SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd"); return shortenedDateFormat.format(time); } /** * Prepare the weather high/lows for presentation. */ private String formatHighLows(double high, double low) { // For presentation, assume the user doesn't care about tenths of a degree. long roundedHigh = Math.round(high); long roundedLow = Math.round(low); String highLowStr = roundedHigh + "/" + roundedLow; return highLowStr; } /** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException { // These are the names of the JSON objects that need to be extracted. final String OWM_LIST = "list"; final String OWM_WEATHER = "weather"; final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_DESCRIPTION = "main"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); String[] resultStrs = new String[numDays]; for(int i = 0; i < weatherArray.length(); i++) { // For now, using the format "Day, description, hi/low" String day; String description; String highAndLow; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". long dateTime; // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay+i); day = getReadableDateString(dateTime); // description is in a child array called "weather", which is 1 element long. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); double high = temperatureObject.getDouble(OWM_MAX); double low = temperatureObject.getDouble(OWM_MIN); highAndLow = formatHighLows(high, low); resultStrs[i] = day + " - " + description + " - " + highAndLow; } for (String s : resultStrs) { Log.v(LOG_TAG, "Forecast entry: " + s); } return resultStrs; } @Override protected String[] doInBackground(String... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; } // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 7; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; final String APPID_PARAM = "APPID"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon() .appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format) .appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY) .build(); URL url = new URL(builtUri.toString()); Log.v(LOG_TAG, "Built URI " + builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); Log.v(LOG_TAG, "Forecast string: " + forecastJsonStr); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } try { return getWeatherDataFromJson(forecastJsonStr, numDays); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } // This will only happen if there was an error getting or parsing the forecast. return null; } @Override protected void onPostExecute(String[] result) { if (result != null) { mForecastAdapter.clear(); for(String dayForecastStr : result) { mForecastAdapter.add(dayForecastStr); } // New data is back from the server. Hooray! } } } }
package com.boissinot.jenkins.csvexporter.batch; import com.boissinot.jenkins.csvexporter.batch.delegator.JobItemReaderDelegator; import com.boissinot.jenkins.csvexporter.batch.delegator.JobItemReaderFolderDelegator; import com.boissinot.jenkins.csvexporter.batch.delegator.JobItemReaderRemoteInstanceDelegator; import com.boissinot.jenkins.csvexporter.domain.InputSBJobObj; import com.boissinot.jenkins.csvexporter.exception.ExportException; import com.boissinot.jenkins.csvexporter.service.extractor.jenkins.FunctionalJobTypeRetriever; import com.boissinot.jenkins.csvexporter.service.http.ResourceContentFetcher; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.annotation.BeforeStep; import org.springframework.batch.item.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Gregory Boissinot */ public class JobItemReader implements ItemReader<InputSBJobObj> { private ResourceContentFetcher resourceContentFetcher; public JobItemReader(ResourceContentFetcher resourceContentFetcher) { this.resourceContentFetcher = resourceContentFetcher; } /* Computed */ private List<String> urls = new ArrayList<String>(); private JobItemReaderDelegator delegator; private Map<String, String> moduleMap; /* Managed */ private boolean onFolder; private String folderPath; private String jenkinsURL; public void setOnFolder(String onFolder) { if (onFolder == null) { this.onFolder = false; } this.onFolder = Boolean.valueOf(onFolder); } public void setFolderPath(String folderPath) { this.folderPath = folderPath; } public void setJenkinsURL(String jenkinsURL) { this.jenkinsURL = jenkinsURL; } @BeforeStep private void beforeAnyRead(StepExecution stepExecution) { JobExecution jobExecution = stepExecution.getJobExecution(); ExecutionContext executionContext = jobExecution.getExecutionContext(); moduleMap = (Map<String, String>) executionContext.get("moduleMap"); if (onFolder) { delegator = new JobItemReaderFolderDelegator(folderPath); } else { delegator = new JobItemReaderRemoteInstanceDelegator(jenkinsURL); } urls = delegator.buildURLs(); } @Override public InputSBJobObj read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException { try { if (urls.size() == 0) { return null; } String url = urls.remove(0); return readJob(url); } catch (Exception e) { throw new ExportException(e); } } private InputSBJobObj readJob(String jobURL) throws IOException { String jobName = delegator.getJobName(jobURL); FunctionalJobTypeRetriever jobTypeRetriever = new FunctionalJobTypeRetriever(); FunctionalJobTypeRetriever.JOB_TYPE jobType = jobTypeRetriever.getJobType(jobName); String configXmlContent = resourceContentFetcher.getContent(jobURL + "/config.xml"); InputSBJobObj inputSBJobObj = new InputSBJobObj( jobName, jobType.getType(), jobType.getLanguage(), configXmlContent, moduleMap); return inputSBJobObj; } }
package com.telefonica.iot.cygnus.aggregation; import com.google.gson.JsonElement; import com.telefonica.iot.cygnus.interceptors.NGSIEvent; import com.telefonica.iot.cygnus.utils.NGSIUtils; import java.util.*; /** * The type Ngsi generic aggregator. */ public abstract class NGSIGenericAggregator { /** * The Aggregation of processed entityes. */ protected LinkedHashMap<String, ArrayList<JsonElement>> aggregation; /** * The Aggregation of processed entityes. */ protected LinkedHashMap<String, ArrayList<JsonElement>> lastData; /** * The Md aggregations for sinks who store on a diferent destination metadata. */ protected Map<String, String> mdAggregations; private String service; private String servicePathForData; private String servicePathForNaming; private String entityForNaming; private String entityType; private String attribute; private String schemeName; private String dbName; private String tableName; private String collectionName; private String orgName; private String pkgName; private String resName; private String hdfsFolder; private String hdfsFile; private String hiveFields; private String csvString; private String lastDataTimestampKey; private String lastDataUniqueKey; private boolean attrNativeTypes; private boolean enableGrouping; private boolean enableEncoding; private boolean enableNameMappings; private boolean enableGeoParse; private boolean attrMetadataStore; private boolean enableUTCRecvTime; private String lastDataMode; private long lastDataTimestamp; private String lastDataTimestampKeyOnAggregation; private String lastDataUniqueKeyOnAggragation; /** * Gets aggregation. * * @return the aggregation */ public LinkedHashMap<String, ArrayList<JsonElement>> getAggregation() { if (aggregation == null) { return new LinkedHashMap<>(); } else { return aggregation; } } //getAggregation /** * Gets aggregation to persist. This means that the returned aggregation will not have metadata * in case that attrMetadataStore is set to false. Also, added fields for processing purposes * will be removed from the aggregation (like attrType on Column mode). * * @return the aggregation to persist */ public LinkedHashMap<String, ArrayList<JsonElement>> getAggregationToPersist() { if (aggregation == null) { return new LinkedHashMap<>(); } else { return NGSIUtils.linkedHashMapWithoutDefaultFields(aggregation, attrMetadataStore); } } //getAggregationToPersist /** * Sets aggregation. * * @param aggregation the aggregation */ public void setAggregation(LinkedHashMap<String, ArrayList<JsonElement>> aggregation) { this.aggregation = aggregation; } //setAggregation /** * Gets last data. * * @return the last data */ public LinkedHashMap<String, ArrayList<JsonElement>> getLastData() { if (lastData == null) { return new LinkedHashMap<>(); } else { return lastData; } } /** * Sets last data. * * @param lastData the last data */ public void setLastData(LinkedHashMap<String, ArrayList<JsonElement>> lastData) { this.lastData = lastData; } /** * Gets last data to persist.This means that the returned aggregation will not have metadata * in case that attrMetadataStore is set to false. Also, added fields for processing purposes * will be removed from the aggregation (like attrType on Column mode). * * @return the last data */ public LinkedHashMap<String, ArrayList<JsonElement>> getLastDataToPersist() { if (lastData == null) { return new LinkedHashMap<>(); } else { return NGSIUtils.linkedHashMapWithoutDefaultFields(lastData, attrMetadataStore); } } /** * Gets collection name. * * @param enableLowercase the enable lowercase * @return the collection name */ public String getCollectionName(boolean enableLowercase) { if (enableLowercase) { return collectionName.toLowerCase(); } else { return collectionName; } } //getCollectionName /** * Gets md aggregations. * * @return the md aggregations */ public Map<String, String> getMdAggregations() { if (mdAggregations == null) { return new HashMap<>(); } else { return mdAggregations; } } //getMdAggregations /** * Gets csv string. For HDFS sink. * * @return the csv string */ public String getCsvString() { return csvString; } //getCsvString /** * Sets csv string. * * @param csvString the csv string */ public void setCsvString(String csvString) { this.csvString = csvString; } //setCsvString /** * Gets last data timestamp key. * * @return the last value timestamp key */ public String getLastDataTimestampKey() { return lastDataTimestampKey; } /** * Sets last data timestamp key. * * @param lastDataTimestampKey the last value timestamp key */ public void setLastDataTimestampKey(String lastDataTimestampKey) { this.lastDataTimestampKey = lastDataTimestampKey; } /** * Get LastDataMode string * * @return the boolean */ public String getLastDataMode() { return lastDataMode; } /** * Is enable last data boolean. * * @return the boolean */ public boolean isEnableLastData() { return lastDataMode.equals("upsert") || lastDataMode.equals("both"); } /** * Sets last data mode. * * @param lastDataMode the last data mode to set */ public void setLastDataMode(String lastDataMode) { this.lastDataMode = lastDataMode; } /** * Gets last data unique key. * * @return the last data unique key */ public String getLastDataUniqueKey() { return lastDataUniqueKey; } /** * Sets last data unique key. * * @param lastDataUniqueKey the last data unique key */ public void setLastDataUniqueKey(String lastDataUniqueKey) { this.lastDataUniqueKey = lastDataUniqueKey; } /** * Gets last data tiemstamp key on aggregation. * * @return the last data tiemstamp key on aggregation */ public String getLastDataTimestampKeyOnAggregation() { return lastDataTimestampKeyOnAggregation; } /** * Sets last data tiemstamp key on aggregation. * * @param lastDataTimestampKeyOnAggregation the last data tiemstamp key on aggregation */ public void setLastDataTimestampKeyOnAggregation(String lastDataTimestampKeyOnAggregation) { this.lastDataTimestampKeyOnAggregation = lastDataTimestampKeyOnAggregation; } /** * Gets last data key on aggragation. * * @return the last data key on aggragation */ public String getLastDataUniqueKeyOnAggragation() { return lastDataUniqueKeyOnAggragation; } /** * Sets last data key on aggragation. * * @param lastDataUniqueKeyOnAggragation the last data key on aggragation */ public void setLastDataUniqueKeyOnAggragation(String lastDataUniqueKeyOnAggragation) { this.lastDataUniqueKeyOnAggragation = lastDataUniqueKeyOnAggragation; } /** * Gets hdfs folder. For HDFS sink. * * @param enableLowercase the enable lowercase * @return the hdfs folder */ public String getHdfsFolder(boolean enableLowercase) { if (enableLowercase) { return hdfsFolder.toLowerCase(); } else { return hdfsFolder; } } //getHdfsFolder /** * Sets hdfs folder. * * @param hdfsFolder the hdfs folder */ public void setHdfsFolder(String hdfsFolder) { this.hdfsFolder = hdfsFolder; } //setHdfsFolder /** * Gets hdfs file. * * @param enableLowercase the enable lowercase * @return the hdfs file as it was stored. if enableLowercase is true, then the returned String is on lowerCase. */ public String getHdfsFile(boolean enableLowercase) { if (enableLowercase) { return hdfsFile.toLowerCase(); } else { return hdfsFile; } } //getHdfsFile /** * Is enable utc recv time boolean. * * @return the boolean */ public boolean isEnableUTCRecvTime() { return enableUTCRecvTime; } //isEnableUTCRecvTime /** * Sets enable utc recv time. This is used to add UTC format to RECV_TIME field on aggregation. * * @param enableUTCRecvTime the enable utc recv time. */ public void setEnableUTCRecvTime(boolean enableUTCRecvTime) { this.enableUTCRecvTime = enableUTCRecvTime; } //setEnableUTCRecvTime /** * Sets hdfs file. * * @param hdfsFile the hdfs file */ public void setHdfsFile(String hdfsFile) { this.hdfsFile = hdfsFile; } //setHdfsFile /** * Sets md aggregations. * * @param mdAggregations the md aggregations */ public void setMdAggregations(Map<String, String> mdAggregations) { this.mdAggregations = mdAggregations; } //setMdAggregations /** * Sets attr metadata store. This is used to remove metadata for aggregation. If true, then the method * getAggregationToPersist will crop metadata fields. * * @param attrMetadataStore the attr metadata store */ public void setAttrMetadataStore(boolean attrMetadataStore) { this.attrMetadataStore = attrMetadataStore; } //setAttrMetadataStore /** * Is attr metadata store boolean. * * @return the boolean */ public boolean isAttrMetadataStore() { return attrMetadataStore; } //isAttrMetadataStore /** * Is enable geo parse boolean. Postgis flag to process geometry types. * * @return the boolean */ public boolean isEnableGeoParse() { return enableGeoParse; } //isEnableGeoParse /** * Sets enable geo parse. * * @param enableGeoParse the enable geo parse */ public void setEnableGeoParse(boolean enableGeoParse) { this.enableGeoParse = enableGeoParse; } //setEnableGeoParse /** * Gets long timestamp of the record stored on the last data collection * * @return lastDataTimestamp the long */ public long getLastDataTimestamp() { return lastDataTimestamp; } /** * Sets long timestamp of the record stored on the last data collection * * @param lastDataTimestamp the timestamp of the record on the last data collection */ public void setLastDataTimestamp(long lastDataTimestamp) { this.lastDataTimestamp = lastDataTimestamp; } /** * Sets collection name. * * @param collectionName the collection name */ public void setCollectionName(String collectionName) { this.collectionName = collectionName; } //setCollectionName /** * Gets service. * * @return the service */ public String getService() { return service; } //getService /** * Gets hive fields. * * @return the hive fields */ public String getHiveFields() { return hiveFields; } //getHiveFields /** * Sets hive fields. * * @param hiveFields the hive fields */ public void setHiveFields(String hiveFields) { this.hiveFields = hiveFields; } //setHiveFields /** * Sets service. * * @param service the service */ public void setService(String service) { this.service = service; } //setService /** * Gets service scheme name for Postgis/Postgres * * @return the scheme name for Postgis/Postgres */ public String getSchemeName(boolean enableLowercase) { if (enableLowercase) { return schemeName.toLowerCase(); } else { return schemeName; } } /** * Sets service scheme name for Postgis/Postgres * * @param schemeName the scheme name for Postgis/Postgres */ public void setSchemeName(String schemeName) { this.schemeName = schemeName; } /** * Gets service path for data. * * @return the service path for data */ public String getServicePathForData() { return servicePathForData; } //getServicePathForData /** * Sets service path for data. * * @param servicePathForData the service path for data */ public void setServicePathForData(String servicePathForData) { this.servicePathForData = servicePathForData; } //setServicePathForData /** * Gets service path for naming. * * @return the service path for naming */ public String getServicePathForNaming() { return servicePathForNaming; } //getServicePathForNaming /** * Sets service path for naming. * * @param servicePathForNaming the service path for naming */ public void setServicePathForNaming(String servicePathForNaming) { this.servicePathForNaming = servicePathForNaming; } //setServicePathForNaming /** * Gets entity for naming. * * @return the entity for naming */ public String getEntityForNaming() { return entityForNaming; } //getEntityForNaming /** * Sets entity for naming. * * @param entityForNaming the entity for naming */ public void setEntityForNaming(String entityForNaming) { this.entityForNaming = entityForNaming; } //setEntityForNaming /** * Gets entity type. * * @return the entity type */ public String getEntityType() { return entityType; } //getEntityType /** * Sets entity type. * * @param entityType the entity type */ public void setEntityType(String entityType) { this.entityType = entityType; } //setEntityType /** * Gets attribute. * * @return the attribute */ public String getAttribute() { return attribute; } //getAttribute /** * Sets attribute. * * @param attribute the attribute */ public void setAttribute(String attribute) { this.attribute = attribute; } //setAttribute /** * Gets db name. * * @param enableLowercase the enable lowercase. If enableLowercase is true, then the returned String is on lowerCase. * @return the db name */ public String getDbName(boolean enableLowercase) { if (enableLowercase) { return dbName.toLowerCase(); } else { return dbName; } } //getDbName /** * Sets db name. * * @param dbName the db name */ public void setDbName(String dbName) { this.dbName = dbName; } //setDbName /** * Gets table name. * * @param enableLowercase the enable lowercase. If enableLowercase is true, then the returned String is on lowerCase. * @return the table name */ public String getTableName(boolean enableLowercase) { if (enableLowercase) { return tableName.toLowerCase(); } else { return tableName; } } //getTableName /** * Sets table name. * * @param tableName the table name */ public void setTableName(String tableName) { this.tableName = tableName; } //setTableName /** * Gets org name. * * @param enableLowercase the enable lowercase. If enableLowercase is true, then the returned String is on lowerCase. * @return the org name */ public String getOrgName(boolean enableLowercase) { if (enableLowercase) { return orgName.toLowerCase(); } else { return orgName; } } //getOrgName /** * Sets org name. * * @param orgName the org name */ public void setOrgName(String orgName) { this.orgName = orgName; } //setOrgName /** * Gets pkg name. * * @param enableLowercase the enable lowercase. If enableLowercase is true, then the returned String is on lowerCase. * @return the pkg name */ public String getPkgName(boolean enableLowercase) { if (enableLowercase) { return pkgName.toLowerCase(); } else { return pkgName; } } //getPkgName /** * Sets pkg name. * * @param pkgName the pkg name */ public void setPkgName(String pkgName) { this.pkgName = pkgName; } //setPkgName /** * Gets res name. * * @param enableLowercase the enable lowercase. If enableLowercase is true, then the returned String is on lowerCase. * @return the res name */ public String getResName(boolean enableLowercase) { if (enableLowercase) { return resName.toLowerCase(); } else { return resName; } } //getResName /** * Sets res name. * * @param resName the res name */ public void setResName(String resName) { this.resName = resName; } //setResName /** * Is attr native types boolean. * * @return the boolean */ public boolean isAttrNativeTypes() { return attrNativeTypes; } //isAttrNativeTypes /** * Sets attr native types. * * @param attrNativeTypes the attr native types */ public void setAttrNativeTypes(boolean attrNativeTypes) { this.attrNativeTypes = attrNativeTypes; } //setAttrNativeTypes /** * Is enable grouping boolean. * * @return the boolean */ public boolean isEnableGrouping() { return enableGrouping; } //isEnableGrouping /** * Sets enable grouping. * * @param enableGrouping the enable grouping */ public void setEnableGrouping(boolean enableGrouping) { this.enableGrouping = enableGrouping; } //setEnableGrouping /** * Is enable encoding boolean. * * @return the boolean */ public boolean isEnableEncoding() { return enableEncoding; } //isEnableEncoding /** * Sets enable encoding. * * @param enableEncoding the enable encoding */ public void setEnableEncoding(boolean enableEncoding) { this.enableEncoding = enableEncoding; } //setEnableEncoding /** * Is enable name mappings boolean. * * @return the boolean */ public boolean isEnableNameMappings() { return enableNameMappings; } //isEnableNameMappings /** * Sets enable name mappings. * * @param enableNameMappings the enable name mappings */ public void setEnableNameMappings(boolean enableNameMappings) { this.enableNameMappings = enableNameMappings; } //setEnableNameMappings /** * Aggregate declaration for child classes. * * @param cygnusEvent the cygnus event */ public abstract void aggregate(NGSIEvent cygnusEvent); /** * Initialize declaration for child classes. * * @param cygnusEvent the cygnus event */ public abstract void initialize(NGSIEvent cygnusEvent); }
package org.neo4j.server.plugin.cypher; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.Map; import javax.ws.rs.core.Response.Status; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.kernel.impl.annotations.Documented; import org.neo4j.server.WrappingNeoServerBootstrapper; import org.neo4j.server.rest.AbstractRestFunctionalTestBase; import org.neo4j.server.rest.RESTDocsGenerator; import org.neo4j.server.rest.domain.JsonHelper; import org.neo4j.server.rest.web.PropertyValueException; import org.neo4j.test.GraphDescription; import org.neo4j.test.GraphDescription.Graph; import org.neo4j.test.GraphDescription.NODE; import org.neo4j.test.GraphDescription.PROP; import org.neo4j.test.GraphDescription.REL; import org.neo4j.test.GraphHolder; import org.neo4j.test.ImpermanentGraphDatabase; import org.neo4j.test.TestData; import org.neo4j.test.TestData.Title; public class CypherPluginFunctionalTest extends AbstractRestFunctionalTestBase { private static final String ENDPOINT = "http://localhost:7474/db/data/ext/CypherPlugin/graphdb/execute_query"; /** * A simple query returning all nodes connected to node 1, returning the * node and the name property, if it exists, otherwise `null`: */ @Test @Documented @Title( "Send a Query" ) @Graph( nodes = { @NODE( name = "I", setNameProperty = true ), @NODE( name = "you", setNameProperty = true ), @NODE( name = "him", setNameProperty = true, properties = { @PROP( key = "age", value = "25", type = GraphDescription.PropType.INTEGER ) } ) }, relationships = { @REL( start = "I", end = "him", type = "know", properties = {} ), @REL( start = "I", end = "you", type = "know", properties = {} ) } ) public void testPropertyColumn() throws UnsupportedEncodingException { String script = "start x = (" + data.get().get( "I" ).getId() + ") match (x) -[r]-> (n) return type(r), n.name?, n.age?"; gen.get().expectedStatus( Status.OK.getStatusCode() ).payload( "{\"query\": \"" + script + "\"}" ).description( formatCypher( script ) ); String response = gen.get().post( ENDPOINT ).entity(); assertTrue( response.contains( "you" ) ); assertTrue( response.contains( "him" ) ); assertTrue( response.contains( "25" ) ); assertTrue( !response.contains( "\"x\"" ) ); } @Test @Documented @Title( "Send a Query" ) @Graph( "I know you" ) public void error_gets_returned_as_json() throws UnsupportedEncodingException, Exception { String script = "start x = (" + data.get().get( "I" ).getId() + ") return x.dummy"; gen.get().expectedStatus( Status.BAD_REQUEST.getStatusCode() ).payload( "{\"query\": \"" + script + "\"}" ).description( formatCypher( script ) ); String response = gen.get().post( ENDPOINT ).entity(); assertEquals(3, ((Map) JsonHelper.jsonToMap( response )).size()); } private String formatCypher( String script ) { return "_Cypher query_\n\n" + "[source,cypher]\n" + "----\n" + script + "\n } /** * Paths can be returned * together with other return types by just * specifying returns. */ @Test @Documented @Graph( "I know you" ) public void return_paths() throws UnsupportedEncodingException, Exception { String script = "start x = (" + data.get().get( "I" ).getId() + ") match path = (x--friend) return path, friend.name"; gen.get().expectedStatus( Status.OK.getStatusCode() ).payload( "{\"query\": \"" + script + "\"}" ).description( formatCypher( script ) ); String response = gen.get().post( ENDPOINT ).entity(); assertEquals(2, ((Map) JsonHelper.jsonToMap( response )).size()); assertTrue(response.contains( "data" )); assertTrue(response.contains( "you" )); } }
package com.galois.qrstream.lib; import android.app.Activity; import android.app.Fragment; import android.hardware.Camera; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.TextView; import android.view.ViewGroup; import android.widget.Button; import com.galois.qrstream.image.YuvImage; import com.galois.qrstream.qrpipe.IProgress; import com.galois.qrstream.qrpipe.Receive; import java.io.IOException; import java.util.concurrent.ArrayBlockingQueue; public class ReceiveFragment extends Fragment implements SurfaceHolder.Callback, Constants { private Camera camera; private SurfaceView camera_window; private Button capture; private final ArrayBlockingQueue frameQueue = new ArrayBlockingQueue<YuvImage>(1); private Receive receiveQrpipe; private DecodeThread decodeThread; private TextView statusLine; private final Progress progress = new Progress(); public ReceiveFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.receive_fragment, container, false); camera_window = (SurfaceView)rootView.findViewById(R.id.camera_window); statusLine = (TextView)rootView.findViewById(R.id.receive_status); capture = (Button)rootView.findViewWithTag("capture"); capture.setOnClickListener(new CaptureClick()); return rootView; } @Override public void onResume(){ super.onResume(); camera = Camera.open(); Camera.Parameters params = camera.getParameters(); Preview previewCallback = new Preview(frameQueue, params.getPreviewSize()); camera.setPreviewCallback(previewCallback); camera_window.getHolder().addCallback(this); DisplayUpdate displayUpdate = new DisplayUpdate(getActivity()); progress.setStateHandler(displayUpdate); startPipe(params, progress); } @Override public void onPause(){ super.onPause(); camera.setPreviewCallback(null); stopPipe(); } @Override public void surfaceCreated(SurfaceHolder holder) { } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { try { camera.setPreviewDisplay(holder); camera.startPreview(); } catch (IOException e) { e.printStackTrace(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { camera.stopPreview(); camera.release(); } public static class CaptureClick implements View.OnClickListener{ @Override public void onClick(View v) { Log.d("qstream", "Capture Pushed"); } } public void startPipe(Camera.Parameters params, IProgress progress) { if(decodeThread == null) { Camera.Size previewSize = params.getPreviewSize(); receiveQrpipe = new Receive(previewSize.height, previewSize.width, progress); decodeThread = new DecodeThread(); decodeThread.setReceiver(receiveQrpipe); decodeThread.setQueue(frameQueue); decodeThread.start(); } else { Log.e(APP_TAG, "Error: DecodeThread already running"); } } public void stopPipe() { // Threads can only be suggested to stop decodeThread.cont = false; } public class DisplayUpdate extends Handler { private final Activity activity; public DisplayUpdate(Activity activity) { this.activity = activity; } @Override public void handleMessage(Message msg) { Log.d(APP_TAG, "DisplayUpdate.handleMessage"); final Bundle params = msg.getData(); activity.runOnUiThread(new Runnable() { @Override public void run() { statusLine.setText(params.getString("message")); } }); } } }
package com.plugin.gcm; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.android.gcm.GCMBaseIntentService; @SuppressLint("NewApi") public class GCMIntentService extends GCMBaseIntentService { private static final String TAG = "GCMIntentService"; public GCMIntentService() { super("GCMIntentService"); } @Override public void onRegistered(Context context, String regId) { Log.v(TAG, "onRegistered: "+ regId); JSONObject json; try { json = new JSONObject().put("event", "registered"); json.put("regid", regId); Log.v(TAG, "onRegistered: " + json.toString()); // Send this JSON data to the JavaScript application above EVENT should be set to the msg type // In this case this is the registration ID PushPlugin.sendJavascript( json ); } catch( JSONException e) { // No message to the user is sent, JSON failed Log.e(TAG, "onRegistered: JSON exception"); } } @Override public void onUnregistered(Context context, String regId) { Log.d(TAG, "onUnregistered - regId: " + regId); } @Override protected void onMessage(Context context, Intent intent) { Log.d(TAG, "onMessage - context: " + context); // Extract the payload from the message Bundle extras = intent.getExtras(); if (extras != null) { // if we are in the foreground, just surface the payload, else post it to the statusbar //xxx Log.d(TAG, "COMPU: MESSAGE RECEVIED"); Log.d(TAG, "COMPU: " + preferences.getString("mt.com.compu.PushPlugin.deliveryReceiptURL", "this is a test")); Log.d(TAG, "COMPU: MESSAGE RECEVIED"); //xxx if (PushPlugin.isInForeground()) { extras.putBoolean("foreground", true); PushPlugin.sendExtras(extras); } else { extras.putBoolean("foreground", false); PushPlugin.sendExtras(extras); // Send a notification if there is a message if (extras.getString("message") != null && extras.getString("message").length() != 0) { createNotification(context, extras); } } } } public void createNotification(Context context, Bundle extras) { NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String appName = getAppName(this); Intent notificationIntent = new Intent(this, PushHandlerActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); notificationIntent.putExtra("pushBundle", extras); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); int defaults = Notification.DEFAULT_ALL; if (extras.getString("defaults") != null) { try { defaults = Integer.parseInt(extras.getString("defaults")); } catch (NumberFormatException e) {} } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setDefaults(defaults) .setSmallIcon(context.getApplicationInfo().icon) .setWhen(System.currentTimeMillis()) .setContentTitle(extras.getString("title")) .setTicker(extras.getString("title")) .setContentIntent(contentIntent) .setAutoCancel(true); String message = extras.getString("message"); if (message != null) { mBuilder.setContentText(message); } else { mBuilder.setContentText("<missing message content>"); } String msgcnt = extras.getString("msgcnt"); if (msgcnt != null) { mBuilder.setNumber(Integer.parseInt(msgcnt)); } int notId = 0; try { notId = Integer.parseInt(extras.getString("notId")); } catch(NumberFormatException e) { Log.e(TAG, "Number format exception - Error parsing Notification ID: " + e.getMessage()); } catch(Exception e) { Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage()); } mNotificationManager.notify((String) appName, notId, mBuilder.build()); } private static String getAppName(Context context) { CharSequence appName = context .getPackageManager() .getApplicationLabel(context.getApplicationInfo()); return (String)appName; } @Override public void onError(Context context, String errorId) { Log.e(TAG, "onError - errorId: " + errorId); } }
package com.armandgray.seeme.views; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.CursorAdapter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.armandgray.seeme.NoteEditorActivity; import com.armandgray.seeme.R; import com.armandgray.seeme.db.DatabaseHelper; import com.armandgray.seeme.db.NotesProvider; import com.armandgray.seeme.models.User; import com.armandgray.seeme.services.HttpService; import com.armandgray.seeme.utils.NotesLvAdapter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import static android.app.Activity.RESULT_OK; import static com.armandgray.seeme.MainActivity.ACTIVE_USER; import static com.armandgray.seeme.MainActivity.API_URI; import static com.armandgray.seeme.network.HttpHelper.sendGetRequest; import static com.armandgray.seeme.network.HttpHelper.sendPostRequest; /** * A simple {@link Fragment} subclass. */ public class NotesFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String POST_NOTES_URI = API_URI + "/notes/post?"; private static final String GET_NOTES_URI = API_URI + "/notes/get?"; private static final String TAG = "NOTES_FRAGMENT"; private static final int EDITOR_REQUEST_CODE = 1001; private static final String USER_NOT_FOUND = "User Not Found!"; private static final String NOTES_UPLOADED = "Notes Uploaded"; private static final String PREPARE_UPDATE_ERROR = "Prepare Update Error!"; private static final String UPDATE_QUERY_ERROR = "Update Query Error!"; private static final String INTERNAL_UPDATE_ERROR = "Internal Update Error!"; private String[] responseArray = {USER_NOT_FOUND, PREPARE_UPDATE_ERROR, NOTES_UPLOADED, UPDATE_QUERY_ERROR, INTERNAL_UPDATE_ERROR}; private CursorAdapter adapter; private User activeUser; private BroadcastReceiver httpBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "http Broadcast Received"); handleHttpResponse(intent.getStringExtra(HttpService.HTTP_SERVICE_STRING_PAYLOAD), intent.getStringArrayExtra(HttpService.HTTP_SERVICE_NOTES_PAYLOAD)); } }; public NotesFragment() {} public static NotesFragment newInstance(User activeUser) { Bundle args = new Bundle(); args.putParcelable(ACTIVE_USER, activeUser); NotesFragment fragment = new NotesFragment(); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_notes, container, false); activeUser = getArguments().getParcelable(ACTIVE_USER); adapter = new NotesLvAdapter(getContext(), null, 0); ListView lvNotes = (ListView) rootView.findViewById(R.id.lvNotes); lvNotes.setAdapter(adapter); getLoaderManager().initLoader(0, null, this); lvNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(getContext(), NoteEditorActivity.class); Uri uri = Uri.parse(NotesProvider.CONTENT_URI + "/" + id); intent.putExtra(NotesProvider.CONTENT_ITEM_TYPE, uri); startActivityForResult(intent, EDITOR_REQUEST_CODE); } }); FloatingActionButton fabDelete = (FloatingActionButton) rootView.findViewById(R.id.fabDelete); fabDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivityForResult(new Intent(getContext(), NoteEditorActivity.class), EDITOR_REQUEST_CODE); } }); return rootView; } @Override public void onResume() { super.onResume(); if (getUserVisibleHint()) { LocalBroadcastManager.getInstance(getActivity().getApplicationContext()) .registerReceiver(httpBroadcastReceiver, new IntentFilter(HttpService.HTTP_SERVICE_MESSAGE)); sendGetNotesRequest(); } } private void sendGetNotesRequest() { String url = GET_NOTES_URI + "username=" + activeUser.getUsername(); sendGetRequest(url, getContext()); } private Loader<Cursor> restartLoader() { return getLoaderManager().restartLoader(0, null, this); } private void handleHttpResponse(String response, String[] arrayExtra) { if (response != null && response.equals(USER_NOT_FOUND)) { getActivity().getContentResolver().delete(NotesProvider.CONTENT_URI, null, null); restartLoader(); return; } if (arrayExtra != null && arrayExtra.length != 0) { updateSqliteDatabase(arrayExtra); } } private void updateSqliteDatabase(String[] arrayExtra) { getActivity().getContentResolver().delete(NotesProvider.CONTENT_URI, null, null); for (String note : arrayExtra) { insertNote(note); } restartLoader(); } private void insertNote(String note) { ContentValues values = new ContentValues(); values.put(DatabaseHelper.NOTE_TEXT, note); getActivity().getContentResolver().insert(NotesProvider.CONTENT_URI, values); restartLoader(); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(getContext(), NotesProvider.CONTENT_URI, null, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { adapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { adapter.swapCursor(null); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == EDITOR_REQUEST_CODE && resultCode == RESULT_OK) { sendPostNotesRequest(); restartLoader(); } } private void sendPostNotesRequest() { JSONObject json = new JSONObject(); JSONArray jsonArray = new JSONArray(); Cursor cursor = getActivity().getContentResolver() .query(NotesProvider.CONTENT_URI, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); String url = POST_NOTES_URI + "username=" + activeUser.getUsername(); sendPostRequest(url, getNotesJson(cursor, json, jsonArray), getContext()); } } private String getNotesJson(Cursor cursor, JSONObject json, JSONArray jsonArray) { String noteText; try { do { noteText = cursor.getString(cursor.getColumnIndex(DatabaseHelper.NOTE_TEXT)); jsonArray.put(cursor.getPosition(), noteText); } while (cursor.moveToNext()); json = new JSONObject(); json.put("notes", jsonArray); } catch (JSONException e) { e.printStackTrace(); } return json.toString(); } @Override public void onPause() { super.onPause(); if (!getUserVisibleHint()) { LocalBroadcastManager.getInstance(getActivity().getApplicationContext()) .unregisterReceiver(httpBroadcastReceiver); } } }
package com.anthony.shakeitoff; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.hardware.Camera; import android.widget.ImageButton; import android.widget.TextView; import java.util.Calendar; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; public class MainActivity extends Activity implements SensorEventListener { public static final String TAG = "MainActivity"; private ShakeListener mShaker; private boolean useFrontComera = false; private SurfaceView preview = null; private SurfaceHolder previewHolder = null; private Camera camera = null; //checks the direction of spinning private SensorManager cSensorManager; private boolean canSpin = false; private boolean spinDir = false; private float currentDegree = 0f; private float startDegree = 0f; private float prevDegree = 0f; private int prevTime = 0; TextView tvHeading; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // make the app fullscreen requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_camera); // set up camera preview preview = (SurfaceView)findViewById(R.id.preview); previewHolder = preview.getHolder(); previewHolder.addCallback(surfaceCallback); previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); //Text view that will tell the user what degree for testing tvHeading = (TextView) findViewById(R.id.tvHeading); //initialize your android device sensor capabilities cSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); // set up the shake listener and back button for after picture taken final ImageButton backButton = ((ImageButton)findViewById(R.id.back_button)); backButton.setEnabled(false); mShaker = new ShakeListener(this); mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () { public void onShake() { takePicture(); backButton.setEnabled(true); } }); backButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (camera != null && cameraConfigured && !inPreview) startPreview(); backButton.setEnabled(false); } } ); ((ImageButton)findViewById(R.id.swap_camera_button)).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (camera != null) { camera.release(); camera = null; } useFrontComera = !useFrontComera; camera = openCamera(useFrontComera); } } ); } @Override public void onResume() { super.onResume(); cSensorManager.registerListener(this, cSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME); mShaker.resume(); camera = openCamera(useFrontComera); startPreview(); } @Override public void onPause() { stopPreview(); camera.release(); camera = null; mShaker.pause(); cSensorManager.unregisterListener(this); super.onPause(); } // get the largest preview size (by area) that still fits inside the layout private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) { Camera.Size result = null; for (Camera.Size size : parameters.getSupportedPreviewSizes()) { if (size.width <= width && size.height <= height) { if (result == null || size.width * size.height > result.width * result.height) result = size; } } return result; } private boolean cameraConfigured = false; private boolean inPreview = false; private void initPreview(int width, int height) { if (camera != null && previewHolder.getSurface() != null) { try { camera.setPreviewDisplay(previewHolder); } catch (Throwable t) { Log.e(TAG, "Exception in setPreviewDisplay()", t); } if (!cameraConfigured) { Camera.Parameters parameters = camera.getParameters(); Camera.Size size = getBestPreviewSize(width, height, parameters); if (size != null) { parameters.setPreviewSize(size.width, size.height); camera.setParameters(parameters); cameraConfigured = true; } } } } private void startPreview() { if (cameraConfigured && camera != null && !inPreview) { camera.startPreview(); inPreview = true; } } private void stopPreview() { if (cameraConfigured && camera != null && inPreview) { inPreview = false; camera.stopPreview(); } } SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback() { public void surfaceCreated(SurfaceHolder holder) {} public void surfaceDestroyed(SurfaceHolder holder) {} public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // recreate the preview when the screen dimensions change initPreview(width, height); startPreview(); } }; private Camera openCamera(boolean frontCamera) { Camera cam = null; Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); for (int i = 0; i < Camera.getNumberOfCameras(); i++) { Camera.getCameraInfo(i, cameraInfo); if ((frontCamera && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) || (!frontCamera && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)) { try { cam = Camera.open(i); } catch (RuntimeException e) { Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage()); } } } return cam; } //MOD FUNCTIONS ARE REQUIRED IN ORDER TO WORK WITH DEGREES /*private float modDeg(float deg){ deg = deg % 360; if(deg < 0){ deg = deg + 360; } return deg; }*/ private boolean suckit = false; private boolean detectRoll = false; private boolean[] checkpointsR = new boolean[4]; private boolean fullRollTurn = false; private void setDetectRoll(boolean detectRoll){ this.detectRoll = detectRoll; } private boolean areAllTrue(boolean[] array){ for(boolean b : array) if (!b) return false; return true; } private void detectingRoll(){ setDetectRoll(true); for(int i = 0; i < 4; i++){ if((currentDegree > 90 * i && currentDegree < 90 * (i + 1))){ checkpointsR[i] = true; } } if(areAllTrue(checkpointsR) && currentDegree > 0 && currentDegree > 45){ fullRollTurn = true; //reset checkpoints for(int i = 0; i < 4; i++){ checkpointsR[i] = false; } } } @Override public void onSensorChanged(SensorEvent event){ float degree = Math.round(event.values[0]); Calendar c = Calendar.getInstance(); int curSeconds = c.get(Calendar.SECOND); if((prevDegree > degree - 5) && (prevDegree < degree + 5)) { if (prevTime + 1 < curSeconds) { canSpin = true; } } else { prevDegree = degree; } if(canSpin){ detectingRoll(); } if(fullRollTurn){ suckit = true; canSpin = false; takePicture(); fullRollTurn = false; } tvHeading.setText("Heading: " + Float.toString(degree) + "canSpin" + canSpin + "circle: " + suckit); //I don't know why this is here so im commenting it out currentDegree = degree; } @Override public void onAccuracyChanged(Sensor sensor, int accuracy){ //not in use } private void takePicture() { // takes a picture and stops the image preview if (camera != null && cameraConfigured && inPreview) { inPreview = false; camera.takePicture(null, null, pictureSaver); // take picture with JPEG callback } } private Camera.PictureCallback pictureSaver = new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { // To be safe, you should check that the SDCard is mounted using Environment.getExternalStorageState() before doing this. // This location works best if you want the created images to be shared between applications and persist after your app has been uninstalled. File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "ShakeItOff"); // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d(TAG, "Error creating picture directory"); return; } } String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date()); File pictureFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg"); try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); } catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage()); } catch (IOException e) { Log.d(TAG, "Error accessing file: " + e.getMessage()); } // add the picture to the gallery Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri contentUri = Uri.fromFile(pictureFile); mediaScanIntent.setData(contentUri); MainActivity.this.sendBroadcast(mediaScanIntent); } }; }
package time; /** * * @author Yifei Zhu * * This class can be able to -get date, hour, min, second -get or print * time and date in 12 format and 24 format -compare to "date and time" * The default time format is in 24 hours * * default--24 printing--12 */ public class Time implements Comparable<Time> { private int hour; private int minute; private int second; private Date date; private String dayOfWeek; public Time(int hour, int minute, int second, Date date, String dayOfWeek) { // //time this.hour = hour; this.minute = minute; this.second = second; this.date=date; this.dayOfWeek=dayOfWeek; } public int getHour() { return hour; } public void setHour(int hour) { this.hour = hour; } public int getMinute() { return minute; } public void setMinute(int minute) { this.minute = minute; } public int getSecond() { return second; } public void setSecond(int second) { this.second = second; } public Date getDate() { return date; } public void setDate(Date d) { this.date = d; } public String getDayOfWeek() { return dayOfWeek; } public void setDayOfWeek(String dayOfWeek) { this.dayOfWeek = dayOfWeek; } public String get24Format() { return hour + ":" + minute + ":" + second; } public String get12Format() { if (this.hour > 12) { return (this.hour - 12) + ":" + this.minute + ":" + this.second + "PM"; } else { return this.get24Format() + "AM"; } } public String toString(int format) { if (format == 12) { return this.toString() + " " + get12Format(); } return this.toString() + " " + get24Format(); } public int compareTo(Time dt) { if(dt==null) return -1 ; //TODO return -1? if(date.compareTo(dt.getDate())!=0) { return date.compareTo(dt.getDate()); } //if date are the same //hour is different if(this.getHour()!=dt.getHour()) { return this.getHour()-dt.getHour(); } //if also have the else if(this.getMinute()!=dt.getHour()) { return this.getMinute()-dt.getHour(); } else if(this.getSecond()!=dt.getSecond()) { return this.getSecond()-dt.getSecond(); } else { return 0; } } }
package org.ccnx.ccn.impl; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.NotYetConnectedException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.ArrayList; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.ccnx.ccn.CCNFilterListener; import org.ccnx.ccn.CCNInterestListener; import org.ccnx.ccn.ContentVerifier; import org.ccnx.ccn.KeyManager; import org.ccnx.ccn.config.SystemConfiguration; import org.ccnx.ccn.impl.InterestTable.Entry; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.content.ContentEncodingException; import org.ccnx.ccn.profiles.ccnd.CCNDaemonProfile; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.protocol.MalformedContentNameStringException; import org.ccnx.ccn.protocol.PublisherPublicKeyDigest; import org.ccnx.ccn.protocol.WirePacket; /** * The low level interface to ccnd. Connects to a ccnd and maintains the connection by sending * heartbeats to it. Other functions include reading and writing interests and content * to/from the ccnd, starting handler threads to feed interests and content to registered handlers, * and refreshing unsatisfied interests. * * This class attempts to notice when a ccnd has died and to reconnect to a ccnd when it is restarted. * * It also handles the low level output "tap" functionality - this allows inspection or logging of * all the communications with ccnd. * * Starts a separate thread to listen to, decode and handle incoming data from ccnd. */ public class CCNNetworkManager implements Runnable { public static final int DEFAULT_AGENT_PORT = 9695; // ccnx registered port public static final String DEFAULT_AGENT_HOST = "localhost"; public static final String PROP_AGENT_PORT = "ccn.agent.port"; public static final String PROP_AGENT_HOST = "ccn.agent.host"; public static final String PROP_TAP = "ccn.tap"; public static final String ENV_TAP = "CCN_TAP"; // match C library public static final int MAX_PAYLOAD = 8800; // number of bytes in UDP payload public static final int SOCKET_TIMEOUT = 1000; // period to wait in ms. public static final int PERIOD = 2000; // period for occasional ops in ms. public static final int HEARTBEAT_PERIOD = 3500; public static final int MAX_PERIOD = PERIOD * 8; public static final String KEEPALIVE_NAME = "/HereIAm"; public static final int THREAD_LIFE = 8; // in seconds /** * Definitions for which network protocol to use. This allows overriding * the current default. */ public enum NetworkProtocol { UDP (17), TCP (6); NetworkProtocol(Integer i) { this._i = i; } private final Integer _i; public Integer value() { return _i; } } public static final String PROP_AGENT_PROTOCOL_KEY = "ccn.agent.protocol"; public static final NetworkProtocol DEFAULT_PROTOCOL = NetworkProtocol.UDP; public static final String PROP_AGENT_PREFIX_REG = "ccn.agent.prefix_reg"; public static final String ENV_AGENT_PREFIX_REG = "CCND_TRYFIB"; public static final boolean DEFAULT_PREFIX_REG = false; // Until ccnd gets updated /* * This ccndId is set on the first connection with 'ccnd' and is the * 'device name' that all of our control communications will use to * ensure that we are talking to our local 'ccnd'. */ protected static Integer _idSyncer = new Integer(0); protected static PublisherPublicKeyDigest _ccndId = null; protected Integer _faceID = null; protected CCNDIdGetter _getter = null; /* * Static singleton. */ protected Thread _thread = null; // the main processing thread protected ThreadPoolExecutor _threadpool = null; // pool service for callback threads protected DatagramChannel _channel = null; // for use by run thread only! protected Selector _selector = null; protected Throwable _error = null; // Marks error state of socket protected boolean _run = true; // protected ContentObject _keepalive; protected FileOutputStream _tapStreamOut = null; protected FileOutputStream _tapStreamIn = null; protected long _lastHeartbeat = 0; protected int _port = DEFAULT_AGENT_PORT; protected String _host = DEFAULT_AGENT_HOST; protected NetworkProtocol _protocol = DEFAULT_PROTOCOL; // For handling protocol to speak to ccnd, must have keys protected KeyManager _keyManager; protected int _localPort = -1; // Tables of interests/filters: users must synchronize on collection protected InterestTable<InterestRegistration> _myInterests = new InterestTable<InterestRegistration>(); protected InterestTable<Filter> _myFilters = new InterestTable<Filter>(); protected boolean _usePrefixReg = DEFAULT_PREFIX_REG; private Timer _periodicTimer = null; private boolean _timersSetup = false; /** * Do scheduled writes of heartbeats and interest refreshes */ private class PeriodicWriter extends TimerTask { // TODO Interest refresh time is supposed to "decay" over time but there are currently // unresolved problems with this. public void run() { long ourTime = new Date().getTime(); if ((ourTime - _lastHeartbeat) > HEARTBEAT_PERIOD) { _lastHeartbeat = ourTime; heartbeat(); } long minRefreshTime = PERIOD + ourTime; // Library.finest("Refreshing interests (size " + _myInterests.size() + ")"); // Re-express interests that need to be re-expressed try { synchronized (_myInterests) { for (Entry<InterestRegistration> entry : _myInterests.values()) { InterestRegistration reg = entry.value(); if (ourTime > reg.nextRefresh) { Log.finer("Refresh interest: {0}", reg.interest); // Temporarily back out refresh period decay //reg.nextRefreshPeriod = (reg.nextRefreshPeriod * 2) > MAX_PERIOD ? MAX_PERIOD //: reg.nextRefreshPeriod * 2; reg.nextRefresh += reg.nextRefreshPeriod; try { write(reg.interest); } catch (NotYetConnectedException nyce) {} } if (minRefreshTime > reg.nextRefresh) minRefreshTime = reg.nextRefresh; } } } catch (ContentEncodingException xmlex) { Log.severe("Processing thread failure (Malformed datagram): {0}", xmlex.getMessage()); Log.warningStackTrace(xmlex); } long checkDelay = minRefreshTime - System.currentTimeMillis(); if (checkDelay < 0) checkDelay = 0; if (checkDelay > PERIOD) checkDelay = PERIOD; _periodicTimer.schedule(new PeriodicWriter(), checkDelay); } } /* private class PeriodicWriter extends TimerTask */ /** * Send the heartbeat. Also attempt to detect ccnd going down. */ private void heartbeat() { try { ByteBuffer heartbeat = ByteBuffer.allocate(1); if (_channel.isConnected()) _channel.write(heartbeat); } catch (IOException io) { // We do not see errors on send typically even if // agent is gone, so log each but do not track Log.warning("Error sending heartbeat packet: {0}", io.getMessage()); try { if (_channel.isConnected()) _channel.disconnect(); } catch (IOException e) {} } } /** * First time startup of timing stuff after first registration * We don't bother to "unstartup" if everything is deregistered */ private void setupTimers() { if (!_timersSetup) { _timersSetup = true; heartbeat(); // Create timer for heartbeats and other periodic behavior _periodicTimer = new Timer(true); _periodicTimer.schedule(new PeriodicWriter(), PERIOD); } } /** Generic superclass for registration objects that may have a listener * Handles invalidation and pending delivery consistently to enable * subclass to call listener callback without holding any library locks, * yet avoid delivery to a cancelled listener. */ protected abstract class ListenerRegistration implements Runnable { protected Object listener; protected CCNNetworkManager manager; public Semaphore sema = null; //used to block thread waiting for data or null if none public Object owner = null; protected boolean deliveryPending = false; protected long id; public abstract void deliver(); /** * This is called when removing interest or content handlers. It's purpose * is to insure that once the remove call begins it completes atomically without more * handlers being triggered. */ public void invalidate() { // There may be a pending delivery in progress, and it doesn't // happen while holding this lock because that would give the // application callback code power to block library processing. // Instead, we use a flag that is checked and set under this lock // to be sure that on exit from invalidate() there will be // no future deliveries based on the now-invalid registration. while (true) { synchronized (this) { // Make invalid, this will prevent any new delivery that comes // along from doing anything. this.listener = null; this.sema = null; // Return only if no delivery is in progress now (or if we are // called out of our own handler) if (!deliveryPending || (Thread.currentThread().getId() == id)) { return; } } Thread.yield(); } } /** * Calls the client handler */ public void run() { id = Thread.currentThread().getId(); synchronized (this) { // Mark us pending delivery, so that any invalidate() that comes // along will not return until delivery has finished this.deliveryPending = true; } try { // Delivery may synchronize on this object to access data structures // but should hold no locks when calling the listener deliver(); } catch (Exception ex) { Log.warning("failed delivery: {0}", ex); } finally { synchronized(this) { this.deliveryPending = false; } } } /** Equality based on listener if present, so multiple objects can * have the same interest registered without colliding */ public boolean equals(Object obj) { if (obj instanceof ListenerRegistration) { ListenerRegistration other = (ListenerRegistration)obj; if (this.owner == other.owner) { if (null == this.listener && null == other.listener){ return super.equals(obj); } else if (null != this.listener && null != other.listener) { return this.listener.equals(other.listener); } } } return false; } public int hashCode() { if (null != this.listener) { if (null != owner) { return owner.hashCode() + this.listener.hashCode(); } else { return this.listener.hashCode(); } } else { return super.hashCode(); } } } /* protected abstract class ListenerRegistration implements Runnable */ /** * Record of Interest * listener must be set (non-null) for cases of standing Interest that holds * until canceled by the application. The listener should be null when a * thread is blocked waiting for data, in which case the thread will be * blocked on semaphore. */ protected class InterestRegistration extends ListenerRegistration { public final Interest interest; protected ArrayList<ContentObject> data = new ArrayList<ContentObject>(1); //data for waiting thread protected long nextRefresh; // next time to refresh the interest protected long nextRefreshPeriod = PERIOD * 2; // period to wait before refresh // All internal client interests must have an owner public InterestRegistration(CCNNetworkManager mgr, Interest i, CCNInterestListener l, Object owner) { manager = mgr; interest = i; listener = l; this.owner = owner; if (null == listener) { sema = new Semaphore(0); } nextRefresh = new Date().getTime() + nextRefreshPeriod; } /** * Return true if data was added */ public synchronized boolean add(ContentObject obj) { // Add a copy of data, not the original data object, so that // the recipient cannot disturb the buffers of the sender // We need this even when data comes from network, since receive // buffer will be reused while recipient thread may proceed to read // from buffer it is handed boolean hasData = (null == data); if (!hasData) this.data.add(obj.clone()); return !hasData; } /** * This used to be called just data, but its similarity * to a simple accessor made the fact that it cleared the data * really confusing and error-prone... * Pull the available data out for processing. * @return */ public synchronized ArrayList<ContentObject> popData() { ArrayList<ContentObject> result = this.data; this.data = new ArrayList<ContentObject>(1); return result; } /** * Deliver content to a registered handler */ public void deliver() { try { if (null != this.listener) { // Standing interest: call listener callback ArrayList<ContentObject> results = null; CCNInterestListener listener = null; synchronized (this) { if (this.data.size() > 0) { results = this.data; this.data = new ArrayList<ContentObject>(1); listener = (CCNInterestListener)this.listener; } } // Call into client code without holding any library locks if (null != results) { Log.finer("Interest callback (" + results.size() + " data) for: {0}", this.interest.name()); synchronized (this) { // DKS -- dynamic interests, unregister the interest here and express new one if we have one // previous interest is final, can't update it this.deliveryPending = false; } manager.unregisterInterest(this); // paul r. note - contract says interest will be gone after the call into user's code. // Eventually this may be modified for "pipelining". // DKS TODO tension here -- what object does client use to cancel? // Original implementation had expressInterest return a descriptor // used to cancel it, perhaps we should go back to that. Otherwise // we may need to remember at least the original interest for cancellation, // or a fingerprint representation that doesn't include the exclude filter. // DKS even more interesting -- how do we update our interest? Do we? // it's final now to avoid contention, but need to change it or change // the registration. Interest updatedInterest = listener.handleContent(results, interest); // Possibly we should optimize here for the case where the same interest is returned back // (now we would unregister it, then reregister it) but need to be careful that the timing // behavior is right if we do that if (null != updatedInterest) { Log.finer("Interest callback: updated interest to express: {0}", updatedInterest.name()); // luckily we saved the listener // if we want to cancel this one before we get any data, we need to remember the // updated interest in the listener manager.expressInterest(this.owner, updatedInterest, listener); } } else { Log.finer("Interest callback skipped (no data) for: {0}", this.interest.name()); } } else { synchronized (this) { if (null != this.sema) { Log.finer("Data consumes pending get: {0}", this.interest.name()); // Waiting thread will pickup data -- wake it up // If this interest came from net or waiting thread timed out, // then no thread will be waiting but no harm is done Log.finest("releasing {0}", this.sema); this.sema.release(); } } if (null == this.sema) { // this is no longer valid registration Log.finer("Interest callback skipped (not valid) for: {0}", this.interest.name()); } } } catch (Exception ex) { Log.warning("failed to deliver data: {0}", ex); Log.warningStackTrace(ex); } } /** * Start a thread to deliver data to a registered handler */ public void run() { synchronized (this) { // For now only one piece of data may be delivered per InterestRegistration // This might change when "pipelining" is implemented if (deliveryPending) return; } super.run(); } } /* protected class InterestRegistration extends ListenerRegistration */ /** * Record of a filter describing portion of namespace for which this * application can respond to interests. Used to deliver incoming interests * to registered interest handlers */ protected class Filter extends ListenerRegistration { public ContentName prefix; /* Also used to remember registration with ccnd */ protected ArrayList<Interest> interests= new ArrayList<Interest>(1); protected Integer faceId = null; public Filter(CCNNetworkManager mgr, ContentName n, CCNFilterListener l, Object o) { prefix = n; listener = l; owner = o; manager = mgr; } public synchronized void add(Interest i) { interests.add(i); } /** * Deliver interest to a registered handler */ public void deliver() { try { ArrayList<Interest> results = null; CCNFilterListener listener = null; synchronized (this) { if (this.interests.size() > 0) { results = interests; interests = new ArrayList<Interest>(1); listener = (CCNFilterListener)this.listener; } } if (null != results) { // Call into client code without holding any library locks Log.finer("Filter callback ({0} interests) for: {1}", results.size(), prefix); listener.handleInterests(results); } else { Log.finer("Filter callback skipped (no interests) for: {0}", prefix); } } catch (RuntimeException ex) { Log.warning("failed to deliver interest: {0}", ex); } } @Override public String toString() { return prefix.toString(); } } /* protected class Filter extends ListenerRegistration */ private class CCNDIdGetter implements Runnable { CCNNetworkManager _networkManager; KeyManager _keyManager; public CCNDIdGetter(CCNNetworkManager networkManager, KeyManager keyManager) { _networkManager = networkManager; _keyManager = keyManager; } public void run() { boolean isNull = false; PublisherPublicKeyDigest sentID = null; synchronized (_idSyncer) { isNull = (null == _ccndId); } if (isNull) { sentID = fetchCCNDId(_networkManager, _keyManager); if (null == sentID) { Log.severe("CCNDIdGetter: call to fetchCCNDId returned null."); } synchronized(_idSyncer) { _ccndId = sentID; Log.info("CCNDIdGetter: ccndId {0}", ContentName.componentPrintURI(sentID.digest())); } } /* null == _ccndId */ } /* run() */ } /* private class CCNDIdGetter implements Runnable */ /** * The constructor. Attempts to connect to a ccnd at the currently specified port number * @throws IOException if the port is invalid */ public CCNNetworkManager(KeyManager keyManager) throws IOException { _keyManager = keyManager; // Determine port at which to contact agent String portval = System.getProperty(PROP_AGENT_PORT); if (null != portval) { try { _port = new Integer(portval); } catch (Exception ex) { throw new IOException("Invalid port '" + portval + "' specified in " + PROP_AGENT_PORT); } Log.warning("Non-standard CCN agent port " + _port + " per property " + PROP_AGENT_PORT); } String hostval = System.getProperty(PROP_AGENT_HOST); if (null != hostval && hostval.length() > 0) { _host = hostval; Log.warning("Non-standard CCN agent host " + _host + " per property " + PROP_AGENT_HOST); } String proto = System.getProperty(PROP_AGENT_PROTOCOL_KEY); if (null != proto) { boolean found = false; for (NetworkProtocol p : NetworkProtocol.values()) { String pAsString = p.toString(); if (proto.equalsIgnoreCase(pAsString)) { Log.warning("CCN agent protocol changed to " + pAsString + "per property"); _protocol = p; found = true; break; } } if (!found) { throw new IOException("Invalid protocol '" + proto + "' specified in " + PROP_AGENT_PROTOCOL_KEY); } } else { _protocol = DEFAULT_PROTOCOL; } String prefix = System.getProperty(PROP_AGENT_PREFIX_REG); if (null == prefix) { prefix = System.getenv(ENV_AGENT_PREFIX_REG); } if (null != prefix) { /* if the property is anything other than 'false' assume using prefix registration */ if (prefix.equalsIgnoreCase("false")) { _usePrefixReg = false; } else { _usePrefixReg = true; } Log.warning("CCN agent use of prefix registration changed to " + _usePrefixReg + "per property"); } else { _usePrefixReg = DEFAULT_PREFIX_REG; } Log.info("Contacting CCN agent at " + _host + ":" + _port); String tapname = System.getProperty(PROP_TAP); if (null == tapname) { tapname = System.getenv(ENV_TAP); } if (null != tapname) { long msecs = new Date().getTime(); long secs = msecs/1000; msecs = msecs % 1000; String unique_tapname = tapname + "-T" + Thread.currentThread().getId() + "-" + secs + "-" + msecs; setTap(unique_tapname); } // Socket is to belong exclusively to run thread started here _channel = DatagramChannel.open(); _channel.connect(new InetSocketAddress(_host, _port)); _channel.configureBlocking(false); _selector = Selector.open(); _channel.register(_selector, SelectionKey.OP_READ); _localPort = _channel.socket().getLocalPort(); Log.info("Connection to CCN agent using local port number: " + _localPort); // Create callback threadpool and main processing thread _threadpool = (ThreadPoolExecutor)Executors.newCachedThreadPool(); _threadpool.setKeepAliveTime(THREAD_LIFE, TimeUnit.SECONDS); _thread = new Thread(this, "CCNNetworkManager"); _thread.start(); } /** * Shutdown the connection to ccnd and all threads associated with this network manager */ public void shutdown() { Log.info("Shutdown requested"); _run = false; if (_periodicTimer != null) _periodicTimer.cancel(); _selector.wakeup(); try { setTap(null); _channel.close(); } catch (IOException io) { // Ignore since we're shutting down } } /** * Turns on writing of all packets to a file for test/debug * Overrides any previous setTap or environment/property setting. * Pass null to turn off tap. * @param pathname name of tap file */ public void setTap(String pathname) throws IOException { // Turn off any active tap if (null != _tapStreamOut) { FileOutputStream closingStream = _tapStreamOut; _tapStreamOut = null; closingStream.close(); } if (null != _tapStreamIn) { FileOutputStream closingStream = _tapStreamIn; _tapStreamIn = null; closingStream.close(); } if (pathname != null && pathname.length() > 0) { _tapStreamOut = new FileOutputStream(new File(pathname + "_out")); _tapStreamIn = new FileOutputStream(new File(pathname + "_in")); Log.info("Tap writing to {0}", pathname); } } /** * Get the CCN Name of the 'ccnd' we're connected to. * * @return the CCN Name of the 'ccnd' this CCNNetworkManager is connected to. */ public PublisherPublicKeyDigest getCCNDId() { /* * Now arrange to have the ccndId read. We can't do that here because we need * to return back to the create before we know we get the answer back. We can * cause the prefix registration to wait. */ PublisherPublicKeyDigest sentID = null; boolean doFetch = false; synchronized (_idSyncer) { if (null == _ccndId) { doFetch = true; } else { return _ccndId; } } if (doFetch) { sentID = fetchCCNDId(this, _keyManager); if (null == sentID) { Log.severe("getCCNDId: call to fetchCCNDId returned null."); return null; } } synchronized (_idSyncer) { _ccndId = sentID; return _ccndId; } } public KeyManager getKeyManager() { return _keyManager; } public void setKeyManager(KeyManager manager) { _keyManager = manager; } /** * Write content to ccnd * * @param co the content * @return the same content that was passed into the method * * TODO - code doesn't actually throw either of these exceptions but need to fix upper * level code to compensate when they are removed. * @throws IOException * @throws InterruptedException */ public ContentObject put(ContentObject co) throws IOException, InterruptedException { try { write(co); } catch (ContentEncodingException e) { Log.warning("Exception in lowest-level put for object {1}! {1}", co.name(), e); } return co; } /** * get content matching an interest from ccnd. Expresses an interest, waits for ccnd to * return matching the data, then removes the interest and returns the data to the caller. * * TODO should probably handle InterruptedException at this level instead of throwing it to * higher levels * * @param interest the interest * @param timeout time to wait for return in ms * @return ContentObject or null on timeout * @throws IOException on incorrect interest data * @throws InterruptedException if process is interrupted during wait */ public ContentObject get(Interest interest, long timeout) throws IOException, InterruptedException { Log.fine("get: {0}", interest); InterestRegistration reg = new InterestRegistration(this, interest, null, null); expressInterest(reg); Log.finest("blocking for {0} on {1}", interest.name(), reg.sema); // Await data to consume the interest if (timeout == SystemConfiguration.NO_TIMEOUT) reg.sema.acquire(); // currently no timeouts else reg.sema.tryAcquire(timeout, TimeUnit.MILLISECONDS); Log.finest("unblocked for {0} on {1}", interest.name(), reg.sema); // Typically the main processing thread will have registered the interest // which must be undone here, but no harm if never registered unregisterInterest(reg); ArrayList<ContentObject> result = reg.popData(); return result.size() > 0 ? result.get(0) : null; } /** * We express interests to the ccnd and register them within the network manager * * @param caller must not be null * @param interest the interest * @param callbackListener listener to callback on receipt of data * @throws IOException on incorrect interest */ public void expressInterest( Object caller, Interest interest, CCNInterestListener callbackListener) throws IOException { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. if (null == callbackListener) { throw new NullPointerException("expressInterest: callbackListener cannot be null"); } Log.fine("expressInterest: {0}", interest); InterestRegistration reg = new InterestRegistration(this, interest, callbackListener, caller); expressInterest(reg); } private void expressInterest(InterestRegistration reg) throws IOException { try { registerInterest(reg); write(reg.interest); } catch (ContentEncodingException e) { unregisterInterest(reg); throw e; } } /** * Cancel this query with all the repositories we sent * it to. * * @param caller must not be null * @param interest * @param callbackListener */ public void cancelInterest(Object caller, Interest interest, CCNInterestListener callbackListener) { if (null == callbackListener) { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. throw new NullPointerException("cancelInterest: callbackListener cannot be null"); } Log.fine("cancelInterest: {0}", interest.name()); // Remove interest from repeated presentation to the network. unregisterInterest(caller, interest, callbackListener); } /** * Register a standing interest filter with callback to receive any * matching interests seen. Any interests whose prefix completely matches "filter" will * be delivered to the listener * * @param caller must not be null * @param filter ContentName containing prefix of interests to match * @param callbackListener a CCNFilterListener * @throws IOException */ public void setInterestFilter(Object caller, ContentName filter, CCNFilterListener callbackListener) throws IOException { Log.fine("setInterestFilter: {0}", filter); if ((null == _keyManager) || (!_keyManager.initialized() || (null == _keyManager.getDefaultKeyID()))) { Log.warning("Cannot set interest filter -- key manager not ready!"); throw new IOException("Cannot set interest filter -- key manager not ready!"); } // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. setupTimers(); synchronized (_myFilters) { _myFilters.add(filter, new Filter(this, filter, callbackListener, caller)); } // tell ccnd to send me interests that start to filter } /** * Unregister a standing interest filter * * @param caller must not be null * @param filter currently registered filter * @param callbackListener the CCNFilterListener registered to it */ public void cancelInterestFilter(Object caller, ContentName filter, CCNFilterListener callbackListener) { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. Log.fine("cancelInterestFilter: {0}", filter); synchronized (_myFilters) { Entry<Filter> found = _myFilters.remove(filter, new Filter(this, filter, callbackListener, caller)); if (null != found) { found.value().invalidate(); } } } protected void write(ContentObject data) throws ContentEncodingException { WirePacket packet = new WirePacket(data); writeInner(packet); Log.finest("Wrote content object: {0}", data.name()); } protected void write(Interest interest) throws ContentEncodingException { WirePacket packet = new WirePacket(interest); writeInner(packet); } // DKS TODO unthrown exception private void writeInner(WirePacket packet) throws ContentEncodingException { try { byte[] bytes = packet.encode(); ByteBuffer datagram = ByteBuffer.wrap(bytes); synchronized (_channel) { int result = _channel.write(datagram); Log.finest("Wrote datagram (" + datagram.position() + " bytes, result " + result + ")"); if (null != _tapStreamOut) { try { _tapStreamOut.write(bytes); } catch (IOException io) { Log.warning("Unable to write packet to tap stream for debugging"); } } } } catch (IOException io) { // We do not see errors on send typically even if // agent is gone, so log each but do not track Log.warning("Error sending packet: " + io.toString()); } } /** * Pass things on to the network stack. */ private InterestRegistration registerInterest(InterestRegistration reg) { // Add to standing interests table setupTimers(); Log.finest("registerInterest for {0}, and obj is " + _myInterests.hashCode(), reg.interest.name()); synchronized (_myInterests) { _myInterests.add(reg.interest, reg); } return reg; } private void unregisterInterest(Object caller, Interest interest, CCNInterestListener callbackListener) { InterestRegistration reg = new InterestRegistration(this, interest, callbackListener, caller); unregisterInterest(reg); } /** * @param reg - registration to unregister * * Important Note: This can indirectly need to obtain the lock for "reg" with the lock on * "myInterests" held. Therefore it can't be called when holding the lock for "reg". */ private void unregisterInterest(InterestRegistration reg) { synchronized (_myInterests) { Entry<InterestRegistration> found = _myInterests.remove(reg.interest, reg); if (null != found) { found.value().invalidate(); } } } /** * Thread method: this thread will handle reading datagrams and * the periodic re-expressing of standing interests */ public void run() { if (! _run) { Log.warning("CCNNetworkManager run() called after shutdown"); return; } // Allocate datagram buffer: want to wrap array to ensure backed by // array to permit decoding byte[] buffer = new byte[MAX_PAYLOAD]; ByteBuffer datagram = ByteBuffer.wrap(buffer); WirePacket packet = new WirePacket(); Log.info("CCNNetworkManager processing thread started"); while (_run) { try { try { if (_selector.select(SOCKET_TIMEOUT) != 0) { // Note: we're selecting on only one channel to get // the ability to use wakeup, so there is no need to // inspect the selected-key set datagram.clear(); // make ready for new read synchronized (_channel) { _channel.read(datagram); // queue readers and writers } Log.finest("Read datagram (" + datagram.position() + " bytes)"); _selector.selectedKeys().clear(); if (null != _error) { Log.info("Receive error cleared"); _error = null; } datagram.flip(); // make ready to decode if (null != _tapStreamIn) { byte [] b = new byte[datagram.limit()]; datagram.get(b); _tapStreamIn.write(b); datagram.rewind(); } packet.clear(); packet.decode(datagram); } else { // This was a timeout or wakeup, no data packet.clear(); if (!_run) { // exit immediately if wakeup for shutdown break; } if (!_channel.isConnected()) { /* * This is the case where we noticed that the connect to ccnd went away. We * try to reconnect, and if successful, we need to re-register our collection * of prefix registrations. */ _channel.connect(new InetSocketAddress(_host, _port)); if (_channel.isConnected()) { _selector = Selector.open(); _channel.register(_selector, SelectionKey.OP_READ); _localPort = _channel.socket().getLocalPort(); _faceID = null; Log.info("Reconnecting to CCN agent at " + _host + ":" + _port + "on local port" + _localPort); } } } } catch (IOException io) { // We see IOException on receive every time if agent is gone // so track it to log only start and end of outages if (null == _error) { Log.info("Unable to receive from agent: is it still running?"); } _error = io; packet.clear(); } if (!_run) { // exit immediately if wakeup for shutdown break; } // If we got a data packet, hand it back to all the interested // parties (registered interests and getters). for (ContentObject co : packet.data()) { Log.fine("Data from net: {0}", co.name()); // SystemConfiguration.logObject("Data from net:", co); deliverData(co); // External data never goes back to network, never held onto here // External data never has a thread waiting, so no need to release sema } for (Interest interest : packet.interests()) { Log.fine("Interest from net: {0}", interest); InterestRegistration oInterest = new InterestRegistration(this, interest, null, null); deliverInterest(oInterest); // External interests never go back to network } // for interests } catch (Exception ex) { Log.severe("Processing thread failure (UNKNOWN): " + ex.getMessage()); Log.warningStackTrace(ex); } } _threadpool.shutdown(); Log.info("Shutdown complete"); } /** * Internal delivery of interests to pending filter listeners * @param ireg */ protected void deliverInterest(InterestRegistration ireg) { // Call any listeners with matching filters synchronized (_myFilters) { for (Filter filter : _myFilters.getValues(ireg.interest.name())) { if (filter.owner != ireg.owner) { Log.finer("Schedule delivery for interest: {0}", ireg.interest); filter.add(ireg.interest); _threadpool.execute(filter); } } } } /** * Deliver data to blocked getters and registered interests * @param co */ protected void deliverData(ContentObject co) { synchronized (_myInterests) { for (InterestRegistration ireg : _myInterests.getValues(co)) { if (ireg.add(co)) { // this is a copy of the data _threadpool.execute(ireg); } } } } protected PublisherPublicKeyDigest fetchCCNDId(CCNNetworkManager mgr, KeyManager keyManager) { try { Interest interested = new Interest(CCNDaemonProfile.ping); interested.nonce(Interest.generateNonce()); interested.scope(1); ContentObject contented = mgr.get(interested, 500); if (null == contented) { String msg = ("fetchCCNDId: Fetch of content from ping uri failed due to timeout."); Log.severe(msg); return null; } PublisherPublicKeyDigest sentID = contented.signedInfo().getPublisherKeyID(); // TODO: This needs to be fixed once the KeyRepository is fixed to provide a KeyManager if (null != keyManager) { ContentVerifier verifyer = new ContentObject.SimpleVerifier(sentID, keyManager); if (!verifyer.verify(contented)) { String msg = ("fetchCCNDId: Fetch of content reply from ping failed to verify."); Log.severe(msg); return null; } } return sentID; } catch (InterruptedException e) { Log.warningStackTrace(e); return null; } catch (MalformedContentNameStringException e) { String reason = e.getMessage(); Log.warningStackTrace(e); String msg = ("fetchCCNDId: Unexpected MalformedContentNameStringException in call creating: " + CCNDaemonProfile.ping + " reason: " + reason); Log.severe(msg); return null; } catch (IOException e) { String reason = e.getMessage(); Log.warningStackTrace(e); String msg = ("fetchCCNDId: Unexpected IOException in call getting ping Interest reason: " + reason); Log.severe(msg); return null; } } /* PublisherPublicKeyDigest fetchCCNDId() */ }
package org.ccnx.ccn.impl; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.NotYetConnectedException; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import java.util.TreeMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import org.ccnx.ccn.CCNContentHandler; import org.ccnx.ccn.CCNFilterListener; import org.ccnx.ccn.CCNInterestHandler; import org.ccnx.ccn.CCNInterestListener; import org.ccnx.ccn.ContentVerifier; import org.ccnx.ccn.KeyManager; import org.ccnx.ccn.config.SystemConfiguration; import org.ccnx.ccn.impl.CCNStats.CCNEnumStats; import org.ccnx.ccn.impl.CCNStats.CCNEnumStats.IStatsEnum; import org.ccnx.ccn.impl.InterestTable.Entry; import org.ccnx.ccn.impl.encoding.XMLEncodable; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.content.ContentEncodingException; import org.ccnx.ccn.profiles.ccnd.CCNDaemonException; import org.ccnx.ccn.profiles.ccnd.PrefixRegistrationManager; import org.ccnx.ccn.profiles.ccnd.PrefixRegistrationManager.ForwardingEntry; import org.ccnx.ccn.profiles.context.ServiceDiscoveryProfile; import org.ccnx.ccn.profiles.security.KeyProfile; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.protocol.PublisherPublicKeyDigest; import org.ccnx.ccn.protocol.WirePacket; /** * The low level interface to ccnd. This provides the main data API between the java library * and ccnd. Access to ccnd can be either via TCP or UDP. This is controlled by the * SystemConfiguration.AGENT_PROTOCOL property and currently defaults to TCP. * * The write API is implemented by methods of this class but users should typically access these via the * CCNHandle API rather than directly. * * The read API is implemented in a thread that continuously reads from ccnd. Whenever the thread reads * a complete packet, it calls back a handler or handlers that have been previously setup by users. Since * there is only one callback thread, users must take care to avoid slow or blocking processing directly * within the callback. This is similar to the restrictions on the event dispatching thread in Swing. The * setup of callback handlers should also normally be done via the CCNHandle API. * * The class also has a separate timer process which is used to refresh unsatisfied interests and to * keep UDP connections alive by sending a heartbeat packet at regular intervals. * * The class attempts to notice when a ccnd has died and to reconnect to a ccnd when it is restarted. * * It also handles the low level output "tap" functionality - this allows inspection or logging of * all the communications with ccnd. * */ @SuppressWarnings("deprecation") public class CCNNetworkManager implements Runnable { public static final int DEFAULT_AGENT_PORT = 9695; // ccnx registered port public static final String DEFAULT_AGENT_HOST = "localhost"; public static final String PROP_AGENT_PORT = "ccn.agent.port"; public static final String PROP_AGENT_HOST = "ccn.agent.host"; public static final String PROP_TAP = "ccn.tap"; public static final String ENV_TAP = "CCN_TAP"; // match C library public static final int PERIOD = 2000; // period for occasional ops in ms. public static final int MAX_PERIOD = PERIOD * 8; public static final String KEEPALIVE_NAME = "/HereIAm"; public static final int THREAD_LIFE = 8; // in seconds public static final int MAX_PAYLOAD = 8800; // number of bytes in UDP payload // These are to make log messages from CCNNetworkManager intelligable when // there are multiple managers running protected final static AtomicInteger _managerIdCount = new AtomicInteger(0); protected final int _managerId; protected final String _managerIdString; /** * Definitions for which network protocol to use. This allows overriding * the current default. */ public enum NetworkProtocol { UDP (17), TCP (6); NetworkProtocol(Integer i) { this._i = i; } private final Integer _i; public Integer value() { return _i; } } /* * This ccndId is set on the first connection with 'ccnd' and is the * 'device name' that all of our control communications will use to * ensure that we are talking to our local 'ccnd'. */ protected static Integer _idSyncer = new Integer(0); protected static PublisherPublicKeyDigest _ccndId = null; protected Integer _faceID = null; protected CCNDIdGetter _getter = null; protected Thread _thread = null; // the main processing thread protected CCNNetworkChannel _channel = null; protected boolean _run = true; protected FileOutputStream _tapStreamOut = null; protected FileOutputStream _tapStreamIn = null; protected long _lastHeartbeat = 0; protected int _port = DEFAULT_AGENT_PORT; protected String _host = DEFAULT_AGENT_HOST; protected NetworkProtocol _protocol = SystemConfiguration.AGENT_PROTOCOL; // For handling protocol to speak to ccnd, must have keys protected KeyManager _keyManager; // Tables of interests/filters protected InterestTable<InterestRegistration> _myInterests = new InterestTable<InterestRegistration>(); protected InterestTable<Filter> _myFilters = new InterestTable<Filter>(); // Prefix registration handling. Only one registration change (add or remove a registration) with ccnd is // allowed at once. Before attempting a registration change, users must check _registrationChangeInProgress and wait // for it to clear before continuing. _registeredPrefixes must be locked on access. It is also used to lock // access to _registrationChangeInProgress. public static final boolean DEFAULT_PREFIX_REG = true; // Should we use prefix registration? (TODO - this is pretty much obsolete // - it was used during the transition to prefix registration and // should probably be removed) protected boolean _usePrefixReg = DEFAULT_PREFIX_REG; protected PrefixRegistrationManager _prefixMgr = null; protected TreeMap<ContentName, RegisteredPrefix> _registeredPrefixes = new TreeMap<ContentName, RegisteredPrefix>(); protected Boolean _registrationChangeInProgress = false; // Periodic timer protected Timer _periodicTimer = null; protected Object _timersSetupLock = new Object(); protected Boolean _timersSetup = false; // Attempt to break up non returning handlers protected static final long NOT_IN_HANDLER = -1; protected long _handlerCallTime = NOT_IN_HANDLER; // Time handler was called /** * Keep track of prefixes that are actually registered with ccnd (as opposed to Filters used * to dispatch interests). There may be several filters for each registered prefix. */ public class RegisteredPrefix implements CCNContentHandler { private int _refCount = 0; private ForwardingEntry _forwarding = null; // FIXME: The lifetime of a prefix is returned in seconds, not milliseconds. The refresh code needs // to understand this. This isn't a problem for now because the lifetime we request when we register a // prefix we use Integer.MAX_VALUE as the requested lifetime. private long _lifetime = -1; // in seconds protected long _nextRefresh = -1; public RegisteredPrefix(ForwardingEntry forwarding) { _forwarding = forwarding; if (null != forwarding) { _lifetime = forwarding.getLifetime(); _nextRefresh = System.currentTimeMillis() + (_lifetime / 2); } } /** * Catch results of prefix deregistration. We can then unlock registration to allow * new registrations or deregistrations. Note that we wait for prefix registration to * complete during the setInterestFilter call but we don't wait for deregistration to * complete during cancelInterestFilter. This is because we need to insure that we see * interests for our prefix after a registration, but we don't need to worry about spurious * interests arriving after a deregistration because they can't be delivered anyway. However * to insure registrations are done correctly, we must wait for a pending deregistration * to complete before starting another registration or deregistration. */ public Interest handleContent(ContentObject data, Interest interest) { synchronized (_registeredPrefixes) { if (Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE)) Log.fine(Log.FAC_NETMANAGER, "Cancel registration completed for {0}", _forwarding.getPrefixName()); _registrationChangeInProgress = false; _registeredPrefixes.notifyAll(); _registeredPrefixes.remove(_forwarding.getPrefixName()); } return null; } } /** * Do scheduled interest, registration refreshes, and UDP heartbeats. * Called periodically. Each instance calculates when it should next be called. * TODO - registrations are currently always set to never expire so we don't need to * refresh them here yet. At some point this should be fixed. */ private class PeriodicWriter extends TimerTask { public void run() { boolean refreshError = false; if (_protocol == NetworkProtocol.UDP) { if (!_channel.isConnected()) { //we are not connected. reconnect attempt is in the heartbeat function... _channel.heartbeat(); } } if (!_channel.isConnected()) { //we tried to reconnect and failed, try again next loop Log.fine(Log.FAC_NETMANAGER, "Not Connected to ccnd, try again in {0}ms", CCNNetworkChannel.SOCKET_TIMEOUT); _lastHeartbeat = 0; if (_run) _periodicTimer.schedule(new PeriodicWriter(), CCNNetworkChannel.SOCKET_TIMEOUT); return; } long ourTime = System.currentTimeMillis(); long minInterestRefreshTime = PERIOD + ourTime; // Re-express interests that need to be re-expressed // TODO Interest refresh time is supposed to "decay" over time but there are currently // unresolved problems with this. try { for (Entry<InterestRegistration> entry : _myInterests.values()) { InterestRegistration reg = entry.value(); // allow some slop for scheduling if (ourTime + 20 > reg.nextRefresh) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Refresh interest: {0}", reg.interest); _lastHeartbeat = ourTime; reg.nextRefresh = ourTime + reg.nextRefreshPeriod; try { write(reg.interest); } catch (NotYetConnectedException nyce) { refreshError = true; } } if (minInterestRefreshTime > reg.nextRefresh) minInterestRefreshTime = reg.nextRefresh; } } catch (ContentEncodingException xmlex) { Log.severe(Log.FAC_NETMANAGER, "PeriodicWriter interest refresh thread failure (Malformed datagram): {0}", xmlex.getMessage()); Log.warningStackTrace(xmlex); refreshError = true; } // Re-express prefix registrations that need to be re-expressed // FIXME: The lifetime of a prefix is returned in seconds, not milliseconds. The refresh code needs // to understand this. This isn't a problem for now because the lifetime we request when we register a // prefix we use Integer.MAX_VALUE as the requested lifetime. // FIXME: so lets not go around the loop doing nothing... for now. long minFilterRefreshTime = PERIOD + ourTime; /* if (_usePrefixReg) { synchronized (_registeredPrefixes) { for (ContentName prefix : _registeredPrefixes.keySet()) { RegisteredPrefix rp = _registeredPrefixes.get(prefix); if (null != rp._forwarding && rp._lifetime != -1 && rp._nextRefresh != -1) { if (ourTime > rp._nextRefresh) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Refresh registration: {0}", prefix); rp._nextRefresh = -1; try { ForwardingEntry forwarding = _prefixMgr.selfRegisterPrefix(prefix); if (null != forwarding) { rp._lifetime = forwarding.getLifetime(); // filter.nextRefresh = new Date().getTime() + (filter.lifetime / 2); _lastHeartbeat = System.currentTimeMillis(); rp._nextRefresh = _lastHeartbeat + (rp._lifetime / 2); } rp._forwarding = forwarding; } catch (CCNDaemonException e) { Log.warning(e.getMessage()); // XXX - don't think this is right rp._forwarding = null; rp._lifetime = -1; rp._nextRefresh = -1; refreshError = true; } } if (minFilterRefreshTime > rp._nextRefresh) minFilterRefreshTime = rp._nextRefresh; } } // for (Entry<Filter> entry: _myFilters.values()) } // synchronized (_myFilters) } // _usePrefixReg */ if (refreshError) { Log.warning(Log.FAC_NETMANAGER, "we have had an error when refreshing an interest or prefix registration... do we need to reconnect to ccnd?"); } // Try to bring back the run thread if its hung // TODO - do we want to keep this in permanently? if (_handlerCallTime != NOT_IN_HANDLER) { long delta = System.currentTimeMillis() - _handlerCallTime; if (delta > SystemConfiguration.MAX_TIMEOUT) { // Print out what the thread was doing first Throwable t = new Throwable("Handler took too long to return - stack trace follows"); t.setStackTrace(_thread.getStackTrace()); Log.logStackTrace(Log.FAC_NETMANAGER, Level.SEVERE, t); _thread.interrupt(); _handlerCallTime = NOT_IN_HANDLER; } } // Calculate when we should next be run long currentTime = System.currentTimeMillis(); long checkInterestDelay = minInterestRefreshTime - currentTime; if (checkInterestDelay < 0) checkInterestDelay = 0; if (checkInterestDelay > PERIOD) checkInterestDelay = PERIOD; long checkPrefixDelay = minFilterRefreshTime - currentTime; if (checkPrefixDelay < 0) checkPrefixDelay = 0; if (checkPrefixDelay > PERIOD) checkPrefixDelay = PERIOD; long useMe; if (checkInterestDelay < checkPrefixDelay) { useMe = checkInterestDelay; } else { useMe = checkPrefixDelay; } if (_protocol == NetworkProtocol.UDP) { //we haven't sent anything... maybe need to send a heartbeat if ((currentTime - _lastHeartbeat) >= CCNNetworkChannel.HEARTBEAT_PERIOD) { _lastHeartbeat = currentTime; _channel.heartbeat(); } //now factor in heartbeat time long timeToHeartbeat = CCNNetworkChannel.HEARTBEAT_PERIOD - (currentTime - _lastHeartbeat); if (useMe > timeToHeartbeat) useMe = timeToHeartbeat; } if (useMe < 20) { useMe = 20; } if (_run) _periodicTimer.schedule(new PeriodicWriter(), useMe); } /* run */ } /* private class PeriodicWriter extends TimerTask */ /** * First time startup of processing thread and periodic timer after first registration. We do this * after the first registration rather than at startup, because in some cases network managers get * created (via a CCNHandle) that are never used. We don't want to burden the JVM with more processing * until we are sure we are going to be used (which can't happen until there is a registration, * either of an interest in which case we expect to receive matching data, or of a prefix in * which case we expect to receive interests). * * We don't bother to "unstartup" if everything is deregistered * @throws IOException */ private void setupTimers() throws IOException { synchronized (_timersSetupLock) { if (!_timersSetup) { // Create main processing thread _thread = new Thread(this, "CCNNetworkManager " + _managerId); _thread.start(); _timersSetup = true; _channel.init(); if (_protocol == NetworkProtocol.UDP) { _channel.heartbeat(); _lastHeartbeat = System.currentTimeMillis(); } // Create timer for periodic behavior _periodicTimer = new Timer(true); _periodicTimer.schedule(new PeriodicWriter(), PERIOD); } } } /** Generic superclass for registration objects that may have a callback handler */ protected class CallbackHandlerRegistration { protected Object handler; public Semaphore sema = null; //used to block thread waiting for data or null if none public Object owner = null; /** Equality based on handler if present, so multiple objects can * have the same interest registered without colliding */ public boolean equals(Object obj) { if (obj instanceof CallbackHandlerRegistration) { CallbackHandlerRegistration other = (CallbackHandlerRegistration)obj; if (this.owner == other.owner) { if (null == this.handler && null == other.handler){ return super.equals(obj); } else if (null != this.handler && null != other.handler) { return this.handler.equals(other.handler); } } } return false; } public int hashCode() { if (null != this.handler) { if (null != owner) { return owner.hashCode() + this.handler.hashCode(); } else { return this.handler.hashCode(); } } else { return super.hashCode(); } } } /** * Record of Interest * This is the mechanism that calls a user contentHandler when a ContentObject * that matches their interest is received by the network manager. * * handler must be set (non-null) for cases of standing Interest that holds * until canceled by the application. The listener should be null when a * thread is blocked waiting for data, in which case the thread will be * blocked on semaphore. */ protected class InterestRegistration extends CallbackHandlerRegistration { public final Interest interest; protected long nextRefresh; // next time to refresh the interest protected long nextRefreshPeriod = SystemConfiguration.INTEREST_REEXPRESSION_DEFAULT; // period to wait before refresh protected ContentObject content; // All internal client interests must have an owner public InterestRegistration(Interest i, Object h, Object owner) { interest = i; handler = h; this.owner = owner; if (null == handler) { sema = new Semaphore(0); } nextRefresh = System.currentTimeMillis() + nextRefreshPeriod; } /** * Deliver content to a registered handler */ public void deliver(ContentObject co) { try { if (null != this.handler) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Content callback (" + co + " data) for: {0}", this.interest.name()); unregisterInterest(this); // Callback the client - we can't hold any locks here! Interest updatedInterest; if (handler instanceof CCNInterestListener) updatedInterest = ((CCNInterestListener)handler).handleContent(co, interest); else updatedInterest = ((CCNContentHandler)handler).handleContent(co, interest); // Possibly we should optimize here for the case where the same interest is returned back // (now we would unregister it, then reregister it) but need to be careful that the timing // behavior is right if we do that if (null != updatedInterest) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Interest callback: updated interest to express: {0}", updatedInterest.name()); // if we want to cancel this one before we get any data, we need to remember the // updated interest in the handler expressInterest(this.owner, updatedInterest, handler); } } else { // This is the "get" case content = co; synchronized (this) { if (null != this.sema) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Data consumes pending get: {0}", this.interest.name()); // Waiting thread will pickup data -- wake it up // If this interest came from net or waiting thread timed out, // then no thread will be waiting but no harm is done if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, "releasing {0}", this.sema); this.sema.release(); } } if (null == this.sema) { // this is no longer valid registration if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Interest callback skipped (not valid) for: {0}", this.interest.name()); } } } catch (Exception ex) { _stats.increment(StatsEnum.DeliverContentFailed); Log.warning(Log.FAC_NETMANAGER, "failed to deliver data: {0}", ex); Log.warningStackTrace(ex); } } } /* protected class InterestRegistration extends CallbackHandlerRegistration */ /** * Record of a filter describing portion of namespace for which this * application can respond to interests. Used to deliver incoming interests * to registered interest handlers */ protected class Filter extends CallbackHandlerRegistration { protected Interest interest = null; // interest to be delivered // extra interests to be delivered: separating these allows avoidance of ArrayList obj in many cases protected ContentName prefix = null; public Filter(ContentName n, Object h, Object o) { prefix = n; handler = h; owner = o; } /** * Call the user's interest handler callback * @param interest - the interest that triggered this * @return - whether we handled the interest. If true we won't call any more handlers * matching this interest */ public boolean deliver(Interest interest) { try { // Call into client code without holding any library locks if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Filter callback for: {0}", prefix); if (handler instanceof CCNFilterListener) return ((CCNFilterListener)handler).handleInterest(interest); return ((CCNInterestHandler)handler).handleInterest(interest); } catch (RuntimeException ex) { _stats.increment(StatsEnum.DeliverInterestFailed); Log.warning(Log.FAC_NETMANAGER, "failed to deliver interest: {0}", ex); Log.warningStackTrace(ex); return false; } } @Override public String toString() { return prefix.toString(); } } /* protected class Filter extends CallbackHandlerRegistration */ private class CCNDIdGetter implements Runnable { CCNNetworkManager _networkManager; KeyManager _keyManager; @SuppressWarnings("unused") public CCNDIdGetter(CCNNetworkManager networkManager, KeyManager keyManager) { _networkManager = networkManager; _keyManager = keyManager; } public void run() { boolean isNull = false; PublisherPublicKeyDigest sentID = null; synchronized (_idSyncer) { isNull = (null == _ccndId); } if (isNull) { try { sentID = fetchCCNDId(_networkManager, _keyManager); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (null == sentID) { Log.severe(Log.FAC_NETMANAGER, "CCNDIdGetter: call to fetchCCNDId returned null."); } synchronized(_idSyncer) { _ccndId = sentID; if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, "CCNDIdGetter: ccndId {0}", ContentName.componentPrintURI(sentID.digest())); } } /* null == _ccndId */ } /* run() */ } /* private class CCNDIdGetter implements Runnable */ /** * The constructor. Attempts to connect to a ccnd at the currently specified port number * @throws IOException if the port is invalid */ public CCNNetworkManager(KeyManager keyManager) throws IOException { _managerId = _managerIdCount.incrementAndGet(); _managerIdString = "NetworkManager " + _managerId + ": "; if (null == keyManager) { // Unless someone gives us one later, we won't be able to register filters. Log this. if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, formatMessage("CCNNetworkManager: being created with null KeyManager. Must set KeyManager later to be able to register filters.")); } _keyManager = keyManager; // Determine port at which to contact agent String portval = System.getProperty(PROP_AGENT_PORT); if (null != portval) { try { _port = new Integer(portval); } catch (Exception ex) { throw new IOException(formatMessage("Invalid port '" + portval + "' specified in " + PROP_AGENT_PORT)); } Log.warning(Log.FAC_NETMANAGER, formatMessage("Non-standard CCN agent port " + _port + " per property " + PROP_AGENT_PORT)); } String hostval = System.getProperty(PROP_AGENT_HOST); if (null != hostval && hostval.length() > 0) { _host = hostval; Log.warning(Log.FAC_NETMANAGER, formatMessage("Non-standard CCN agent host " + _host + " per property " + PROP_AGENT_HOST)); } _protocol = SystemConfiguration.AGENT_PROTOCOL; if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, formatMessage("Contacting CCN agent at " + _host + ":" + _port)); String tapname = System.getProperty(PROP_TAP); if (null == tapname) { tapname = System.getenv(ENV_TAP); } if (null != tapname) { long msecs = System.currentTimeMillis(); long secs = msecs/1000; msecs = msecs % 1000; String unique_tapname = tapname + "-T" + Thread.currentThread().getId() + "-" + secs + "-" + msecs; setTap(unique_tapname); } _channel = new CCNNetworkChannel(_host, _port, _protocol, _tapStreamIn); _ccndId = null; _channel.open(); } /** * Shutdown the connection to ccnd and all threads associated with this network manager */ public void shutdown() { Log.info(Log.FAC_NETMANAGER, formatMessage("Shutdown requested")); _run = false; if (_periodicTimer != null) _periodicTimer.cancel(); if (_thread != null) _thread.interrupt(); if (null != _channel) { try { setTap(null); } catch (IOException io) { // Ignore since we're shutting down } try { _channel.close(); } catch (IOException io) { // Ignore since we're shutting down } } // Print the statistics for this network manager if (SystemConfiguration.DUMP_NETMANAGER_STATS) System.out.println(getStats().toString()); } @Override protected void finalize() throws Throwable { try { if (_run) { Log.warning(Log.FAC_NETMANAGER, formatMessage("Shutdown from finalize")); } shutdown(); } finally { super.finalize(); } } /** * Get the protocol this network manager is using * @return the protocol */ public NetworkProtocol getProtocol() { return _protocol; } /** * Turns on writing of all packets to a file for test/debug * Overrides any previous setTap or environment/property setting. * Pass null to turn off tap. * @param pathname name of tap file */ public void setTap(String pathname) throws IOException { // Turn off any active tap if (null != _tapStreamOut) { FileOutputStream closingStream = _tapStreamOut; _tapStreamOut = null; closingStream.close(); } if (null != _tapStreamIn) { FileOutputStream closingStream = _tapStreamIn; _tapStreamIn = null; closingStream.close(); } if (pathname != null && pathname.length() > 0) { _tapStreamOut = new FileOutputStream(new File(pathname + "_out")); _tapStreamIn = new FileOutputStream(new File(pathname + "_in")); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, formatMessage("Tap writing to {0}"), pathname); } } /** * Get the CCN Name of the 'ccnd' we're connected to. * * @return the CCN Name of the 'ccnd' this CCNNetworkManager is connected to. * @throws IOException */ public PublisherPublicKeyDigest getCCNDId() throws IOException { /* * Now arrange to have the ccndId read. We can't do that here because we need * to return back to the create before we know we get the answer back. We can * cause the prefix registration to wait. */ PublisherPublicKeyDigest sentID = null; boolean doFetch = false; synchronized (_idSyncer) { if (null == _ccndId) { doFetch = true; } else { return _ccndId; } } if (doFetch) { sentID = fetchCCNDId(this, _keyManager); if (null == sentID) { Log.severe(Log.FAC_NETMANAGER, formatMessage("getCCNDId: call to fetchCCNDId returned null.")); return null; } } synchronized (_idSyncer) { _ccndId = sentID; return _ccndId; } } public KeyManager getKeyManager() { return _keyManager; } public void setKeyManager(KeyManager manager) { _keyManager = manager; } /** * Write content to ccnd * * @param co the content * @return the same content that was passed into the method * * TODO - code doesn't actually throw either of these exceptions but need to fix upper * level code to compensate when they are removed. * @throws IOException * @throws InterruptedException */ public ContentObject put(ContentObject co) throws IOException, InterruptedException { _stats.increment(StatsEnum.Puts); try { write(co); } catch (ContentEncodingException e) { Log.warning(Log.FAC_NETMANAGER, formatMessage("Exception in lowest-level put for object {0}! {1}"), co.name(), e); } return co; } /** * get content matching an interest from ccnd. Expresses an interest, waits for ccnd to * return matching the data, then removes the interest and returns the data to the caller. * * TODO should probably handle InterruptedException at this level instead of throwing it to * higher levels * * @param interest the interest * @param timeout time to wait for return in ms * @return ContentObject or null on timeout * @throws IOException on incorrect interest data * @throws InterruptedException if process is interrupted during wait */ public ContentObject get(Interest interest, long timeout) throws IOException, InterruptedException { _stats.increment(StatsEnum.Gets); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, formatMessage("get: {0} with timeout: {1}"), interest, timeout); InterestRegistration reg = new InterestRegistration(interest, null, null); expressInterest(reg); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, formatMessage("blocking for {0} on {1}"), interest.name(), reg.sema); // Await data to consume the interest if (timeout == SystemConfiguration.NO_TIMEOUT) reg.sema.acquire(); // currently no timeouts else reg.sema.tryAcquire(timeout, TimeUnit.MILLISECONDS); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, formatMessage("unblocked for {0} on {1}"), interest.name(), reg.sema); // Typically the main processing thread will have registered the interest // which must be undone here, but no harm if never registered unregisterInterest(reg); return reg.content; } /** * We express interests to the ccnd and register them within the network manager * * @param caller must not be null * @param interest the interest * @param handler handler to callback on receipt of data * @throws IOException on incorrect interest */ public void expressInterest( Object caller, Interest interest, Object handler) throws IOException { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. if (null == handler) { throw new NullPointerException(formatMessage("expressInterest: callbackHandler cannot be null")); } if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, formatMessage("expressInterest: {0}"), interest); InterestRegistration reg = new InterestRegistration(interest, handler, caller); expressInterest(reg); } private void expressInterest(InterestRegistration reg) throws IOException { _stats.increment(StatsEnum.ExpressInterest); try { registerInterest(reg); write(reg.interest); } catch (ContentEncodingException e) { unregisterInterest(reg); throw e; } } /** * Cancel this query * * @param caller must not be null * @param interest * @param handler */ public void cancelInterest(Object caller, Interest interest, Object handler) { if (null == handler) { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. throw new NullPointerException(formatMessage("cancelInterest: handler cannot be null")); } _stats.increment(StatsEnum.CancelInterest); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, formatMessage("cancelInterest: {0}"), interest.name()); // Remove interest from repeated presentation to the network. unregisterInterest(caller, interest, handler); } /** * Register a standing interest filter with callback to receive any * matching interests seen. Any interests whose prefix completely matches "filter" will * be delivered to the handler. Also if this filter matches no currently registered * prefixes, register its prefix with ccnd. * * @param caller must not be null * @param filter ContentName containing prefix of interests to match * @param handler a CCNInterestHandler * @throws IOException */ public void setInterestFilter(Object caller, ContentName filter, Object handler) throws IOException { setInterestFilter(caller, filter, handler, null); } /** * Register a standing interest filter with callback to receive any * matching interests seen. Any interests whose prefix completely matches "filter" will * be delivered to the handler. Also if this filter matches no currently registered * prefixes, register its prefix with ccnd. * * Note that this is mismatched with deregistering prefixes. When registering, we wait for the * registration to complete before continuing, but when deregistering we don't. * * @param caller must not be null * @param filter ContentName containing prefix of interests to match * @param callbackHandler a CCNInterestHandler * @param registrationFlags to use for this registration. * @throws IOException */ public void setInterestFilter(Object caller, ContentName filter, Object callbackHandler, Integer registrationFlags) throws IOException { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, formatMessage("setInterestFilter: {0}"), filter); if ((null == _keyManager) || (!_keyManager.initialized() || (null == _keyManager.getDefaultKeyID()))) { Log.warning(Log.FAC_NETMANAGER, formatMessage("Cannot set interest filter -- key manager not ready!")); throw new IOException(formatMessage("Cannot set interest filter -- key manager not ready!")); } // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. setupTimers(); if (_usePrefixReg) { RegisteredPrefix prefix = null; synchronized(_registeredPrefixes) { // Determine whether we need to register our prefix with ccnd // We do if either its not registered now, or the one registered now is being // cancelled but its still in the process of getting deregistered. In the second // case (closing) we need to wait until the prefix has been deregistered before // we go ahead and register it. And of course, someone else could have registered it // before we got to it so check for that also. If its already registered, just bump // its use count. if (_registrationChangeInProgress && Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE)) { Log.fine(Log.FAC_NETMANAGER, formatMessage("SetInterestFilter: Waiting for pending registration activity")); } while (_registrationChangeInProgress) { // Wait for anyone else messing around with prefixes try { _registeredPrefixes.wait(); } catch (InterruptedException e) {} } prefix = getRegisteredPrefix(filter); // Did someone else already register it? if (null == prefix) { _registrationChangeInProgress = true; } } // We don't want to hold the _registeredPrefixes lock here, but we're safe to change things // because we have set _registrationChangeInProgress to true if (null == prefix) { try { if (null == _prefixMgr) { _prefixMgr = new PrefixRegistrationManager(this); } prefix = registerPrefix(filter, registrationFlags); } catch (CCNDaemonException e) { Log.warning(Log.FAC_NETMANAGER, formatMessage("setInterestFilter: unexpected CCNDaemonException: " + e.getMessage())); throw new IOException(e.getMessage()); } synchronized (_registeredPrefixes) { _registrationChangeInProgress = false; _registeredPrefixes.notifyAll(); } } prefix._refCount++; } // Now we've dealt with what ccnd needs to know, register our callback so we can be called on // receipt of a matching interest Filter newOne; newOne = new Filter(filter, callbackHandler, caller); _myFilters.add(filter, newOne); } /** * Get current list of prefixes that are actually registered on the face associated with this * netmanager * * @return the list of prefixes as an ArrayList of ContentNames */ public ArrayList<ContentName> getRegisteredPrefixes() { ArrayList<ContentName> prefixes = new ArrayList<ContentName>(); synchronized (_registeredPrefixes) { for (ContentName name : _registeredPrefixes.keySet()) { prefixes.add(name); } } return prefixes; } /** * Register a prefix with ccnd. * * @param filter * @param registrationFlags * @throws CCNDaemonException */ private RegisteredPrefix registerPrefix(ContentName filter, Integer registrationFlags) throws CCNDaemonException { ForwardingEntry entry; if (null == registrationFlags) { entry = _prefixMgr.selfRegisterPrefix(filter); } else { entry = _prefixMgr.selfRegisterPrefix(filter, null, registrationFlags, Integer.MAX_VALUE); } RegisteredPrefix newPrefix = null; synchronized (_registeredPrefixes) { newPrefix = new RegisteredPrefix(entry); _registeredPrefixes.put(filter, newPrefix); // FIXME: The lifetime of a prefix is returned in seconds, not milliseconds. The refresh code needs // to understand this. This isn't a problem for now because the lifetime we request when we register a // prefix we use Integer.MAX_VALUE as the requested lifetime. if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, "registerPrefix for {0}: entry.lifetime: {1} entry.faceID: {2}", filter, entry.getLifetime(), entry.getFaceID()); _registrationChangeInProgress = false; _registeredPrefixes.notifyAll(); } return newPrefix; } /** * Unregister a standing interest filter. * If we are the last user of a filter registered with ccnd, we request a deregistration with * ccnd but we don't need to wait for it to complete. * * @param caller must not be null * @param filter currently registered filter * @param handler the handler registered to it */ public void cancelInterestFilter(Object caller, ContentName filter, Object handler) { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, formatMessage("cancelInterestFilter: {0}"), filter); Filter newOne; newOne = new Filter(filter, handler, caller); Entry<Filter> found = null; found = _myFilters.remove(filter, newOne); if (null != found) { if (_usePrefixReg) { // Deregister it with ccnd only if the refCount would go to 0 RegisteredPrefix prefix = null; boolean doRemove = false; synchronized (_registeredPrefixes) { prefix = getRegisteredPrefix(filter); if (null != prefix) { // We need to deregister it with ccnd. But first we need to make sure nobody else is messing around // with the ccnd prefix registration. if (prefix._refCount <= 1) { if (_registrationChangeInProgress && Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE)) { Log.fine(Log.FAC_NETMANAGER, formatMessage("CancelInterestFilter: Waiting for pending registration activity")); } while (_registrationChangeInProgress) { try { _registeredPrefixes.wait(); } catch (InterruptedException e) {} } prefix = getRegisteredPrefix(filter); // Did some else already remove this prefix? if (null != prefix) { _registrationChangeInProgress = true; doRemove = true; } } else prefix._refCount } } if (doRemove) { // We are going to deregister the prefix with ccnd. We don't want to hold locks here but // we don't have to worry about others changing the prefix registration underneath us because // _registrationChangeInProgress is true. try { if (null == _prefixMgr) { _prefixMgr = new PrefixRegistrationManager(this); } ForwardingEntry entry = prefix._forwarding; _prefixMgr.unRegisterPrefix(filter, prefix, entry.getFaceID()); } catch (CCNDaemonException e) { Log.warning(Log.FAC_NETMANAGER, formatMessage("cancelInterestFilter failed with CCNDaemonException: " + e.getMessage())); } } } } else { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, formatMessage("cancelInterestFilter: {0} not found"), filter); } } /** * Merge prefixes so we only add a new one when it doesn't have a * common ancestor already registered. * * Must be called with _registeredPrefixes locked * * We decided that if we are registering a prefix that already has another prefix that * is an descendant of it registered, we won't bother to now deregister that prefix because * it would be complicated to do that and doesn't hurt anything. * * Notes on efficiency: First of all I'm not sure how important efficiency is in this routine * because it may not be too common to have many different prefixes registered. Currently we search * all prefixes until we see one that is past the one we want to register before deciding there are * none that encapsulate it. There may be a more efficient way to code this that is still correct but * I haven't come up with it. * * @param prefix * @return prefix that incorporates or matches this one or null if none found */ protected RegisteredPrefix getRegisteredPrefix(ContentName prefix) { for (ContentName name : _registeredPrefixes.keySet()) { if (name.isPrefixOf(prefix)) return _registeredPrefixes.get(name); if (name.compareTo(prefix) > 0) break; } return null; } protected void write(ContentObject data) throws ContentEncodingException { _stats.increment(StatsEnum.WriteObject); WirePacket packet = new WirePacket(data); writeInner(packet); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, formatMessage("Wrote content object: {0}"), data.name()); } /** * Write an interest directly to ccnd * Don't do this unless you know what you are doing! See CCNHandle.expressInterest for the proper * way to output interests to the network. * * @param interest * @throws ContentEncodingException */ public void write(Interest interest) throws ContentEncodingException { _stats.increment(StatsEnum.WriteInterest); WirePacket packet = new WirePacket(interest); writeInner(packet); } // DKS TODO unthrown exception private void writeInner(WirePacket packet) throws ContentEncodingException { try { byte[] bytes = packet.encode(); ByteBuffer datagram = ByteBuffer.wrap(bytes); synchronized (_channel) { int result = _channel.write(datagram); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, formatMessage("Wrote datagram (" + datagram.position() + " bytes, result " + result + ")")); if( result < bytes.length ) { _stats.increment(StatsEnum.WriteUnderflows); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, formatMessage("Wrote datagram {0} bytes to channel, but packet was {1} bytes"), result, bytes.length); } if (null != _tapStreamOut) { try { _tapStreamOut.write(bytes); } catch (IOException io) { Log.warning(Log.FAC_NETMANAGER, formatMessage("Unable to write packet to tap stream for debugging")); } } } } catch (IOException io) { _stats.increment(StatsEnum.WriteErrors); // We do not see errors on send typically even if // agent is gone, so log each but do not track Log.warning(Log.FAC_NETMANAGER, formatMessage("Error sending packet: " + io.toString())); } } /** * Internal registration of interest to callback for matching data relationship. * * @throws IOException */ private InterestRegistration registerInterest(InterestRegistration reg) throws IOException { // Add to standing interests table setupTimers(); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, formatMessage("registerInterest for {0}, and obj is " + _myInterests.hashCode()), reg.interest.name()); _myInterests.add(reg.interest, reg); return reg; } private void unregisterInterest(Object caller, Interest interest, Object handler) { InterestRegistration reg = new InterestRegistration(interest, handler, caller); unregisterInterest(reg); } /** * @param reg - registration to unregister */ private void unregisterInterest(InterestRegistration reg) { _myInterests.remove(reg.interest, reg); } /** * Reader thread: this thread will handle reading datagrams and perform callbacks after reading * complete packets. */ public void run() { if (! _run) { Log.warning(Log.FAC_NETMANAGER, formatMessage("CCNNetworkManager run() called after shutdown")); return; } //WirePacket packet = new WirePacket(); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, formatMessage("CCNNetworkManager processing thread started for port: " + _port)); while (_run) { try { boolean wasConnected = _channel.isConnected(); XMLEncodable packet = _channel.getPacket(); if (null == packet) { // If ccnd went up and down, we have to reregister all prefixes that used to be // registered to restore normal operation if (!wasConnected && _channel.isConnected()) reregisterPrefixes(); continue; } if (packet instanceof ContentObject) { _stats.increment(StatsEnum.ReceiveObject); ContentObject co = (ContentObject)packet; if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, formatMessage("Data from net for port: " + _port + " {0}"), co.name()); // SystemConfiguration.logObject("Data from net:", co); _handlerCallTime = System.currentTimeMillis(); deliverContent(co); } else if (packet instanceof Interest) { _stats.increment(StatsEnum.ReceiveInterest); Interest interest = (Interest) packet; if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, formatMessage("Interest from net for port: " + _port + " {0}"), interest); InterestRegistration oInterest = new InterestRegistration(interest, null, null); _handlerCallTime = System.currentTimeMillis(); deliverInterest(oInterest, interest); } else { // for interests _stats.increment(StatsEnum.ReceiveUnknown); } } catch (Exception ex) { _stats.increment(StatsEnum.ReceiveErrors); Log.severe(Log.FAC_NETMANAGER, formatMessage("Processing thread failure (UNKNOWN): " + ex.getMessage() + " for port: " + _port)); Log.warningStackTrace(ex); } _handlerCallTime = NOT_IN_HANDLER; } Log.info(Log.FAC_NETMANAGER, formatMessage("Shutdown complete for port: " + _port)); } /** * Internal delivery of interests to pending filter handlers * @param ireg */ protected void deliverInterest(InterestRegistration ireg, Interest interest) { _stats.increment(StatsEnum.DeliverInterest); // Call any handlers with matching filters for (Filter filter : _myFilters.getValues(ireg.interest.name())) { if (filter.owner != ireg.owner) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, formatMessage("Schedule delivery for interest: {0}"), interest); _stats.increment(StatsEnum.DeliverInterestMatchingFilters); long startTime = System.nanoTime(); boolean succeeded = filter.deliver(interest); _stats.addSample(StatsEnum.InterestHandlerTime, System.nanoTime() - startTime); if (succeeded) break; // We only run interest handlers until one succeeds } } } /** * Deliver data to all blocked getters and registered interests * @param co */ protected void deliverContent(ContentObject co) { _stats.increment(StatsEnum.DeliverContent); for (InterestRegistration ireg : _myInterests.getValues(co)) { _stats.increment(StatsEnum.DeliverContentMatchingInterests); long startTime = System.nanoTime(); ireg.deliver(co); _stats.addSample(StatsEnum.ContentHandlerTime, System.nanoTime() - startTime); } } protected PublisherPublicKeyDigest fetchCCNDId(CCNNetworkManager mgr, KeyManager keyManager) throws IOException { try { ContentName serviceKeyName = new ContentName(ServiceDiscoveryProfile.localServiceName(ServiceDiscoveryProfile.CCND_SERVICE_NAME), KeyProfile.KEY_NAME_COMPONENT); Interest i = new Interest(serviceKeyName); i.scope(1); ContentObject c = mgr.get(i, SystemConfiguration.CCNDID_DISCOVERY_TIMEOUT); if (null == c) { String msg = formatMessage("fetchCCNDId: ccndID discovery failed due to timeout."); Log.severe(Log.FAC_NETMANAGER, msg); throw new IOException(msg); } PublisherPublicKeyDigest sentID = c.signedInfo().getPublisherKeyID(); // TODO: This needs to be fixed once the KeyRepository is fixed to provide a KeyManager if (null != keyManager) { ContentVerifier v = new ContentObject.SimpleVerifier(sentID, keyManager); if (!v.verify(c)) { String msg = formatMessage("fetchCCNDId: ccndID discovery reply failed to verify."); Log.severe(Log.FAC_NETMANAGER, msg); throw new IOException(msg); } } else { Log.severe(Log.FAC_NETMANAGER, formatMessage("fetchCCNDId: do not have a KeyManager. Cannot verify ccndID.")); return null; } return sentID; } catch (InterruptedException e) { Log.warningStackTrace(e); throw new IOException(e.getMessage()); } catch (IOException e) { String reason = e.getMessage(); Log.warningStackTrace(e); String msg = formatMessage("fetchCCNDId: Unexpected IOException in ccndID discovery Interest reason: " + reason); Log.severe(Log.FAC_NETMANAGER, msg); throw new IOException(msg); } } /* PublisherPublicKeyDigest fetchCCNDId() */ /** * Reregister all current prefixes with ccnd after ccnd goes down and then comes back up * Since this is called internally from the network manager run loop, but it needs to make use of * the network manager to correctly process the reregistration, we run the reregistration in a * separate thread * * @throws IOException */ private void reregisterPrefixes() { new Thread() { public void run() { TreeMap<ContentName, RegisteredPrefix> newPrefixes = new TreeMap<ContentName, RegisteredPrefix>(); try { synchronized (_registeredPrefixes) { for (ContentName prefix : _registeredPrefixes.keySet()) { ForwardingEntry entry = _prefixMgr.selfRegisterPrefix(prefix); RegisteredPrefix newPrefixEntry = new RegisteredPrefix(entry); newPrefixEntry._refCount = _registeredPrefixes.get(prefix)._refCount; newPrefixes.put(prefix, newPrefixEntry); } _registeredPrefixes.clear(); _registeredPrefixes.putAll(newPrefixes); } } catch (CCNDaemonException cde) {} } }.start(); } // Statistics protected CCNEnumStats<StatsEnum> _stats = new CCNEnumStats<StatsEnum>(StatsEnum.Puts); public CCNStats getStats() { return _stats; } public enum StatsEnum implements IStatsEnum { // Just edit this list, dont need to change anything else Puts ("ContentObjects", "The number of put calls"), Gets ("ContentObjects", "The number of get calls"), WriteInterest ("calls", "The number of calls to write(Interest)"), WriteObject ("calls", "The number of calls to write(ContentObject)"), WriteErrors ("count", "Error count for writeInner()"), WriteUnderflows ("count", "The count of times when the bytes written to the channel < buffer size"), ExpressInterest ("calls", "The number of calls to expressInterest"), CancelInterest ("calls", "The number of calls to cancelInterest"), DeliverInterest ("calls", "The number of calls to deliverInterest"), DeliverContent ("calls", "The number of calls to cancelInterest"), DeliverInterestMatchingFilters ("calls", "Count of the number of calls to interest handlers"), DeliverContentMatchingInterests ("calls", "Count of the number of calls to content handlers"), DeliverContentFailed ("calls", "The number of content deliveries that failed"), DeliverInterestFailed ("calls", "The number of interest deliveries that failed"), InterestHandlerTime("nanos", "The average amount of time spent in interest handlers"), ContentHandlerTime("nanos", "The average amount of time spent in content handlers"), ReceiveObject ("objects", "Receive count of ContentObjects from channel"), ReceiveInterest ("interests", "Receive count of Interests from channel"), ReceiveUnknown ("calls", "Receive count of unknown type from channel"), ReceiveErrors ("errors", "Number of errors from the channel in run() loop"), ContentObjectsIgnored ("ContentObjects", "The number of ContentObjects that are never handled"), ; // This is the same for every user of IStatsEnum protected final String _units; protected final String _description; protected final static String [] _names; static { _names = new String[StatsEnum.values().length]; for(StatsEnum stat : StatsEnum.values() ) _names[stat.ordinal()] = stat.toString(); } StatsEnum(String units, String description) { _units = units; _description = description; } public String getDescription(int index) { return StatsEnum.values()[index]._description; } public int getIndex(String name) { StatsEnum x = StatsEnum.valueOf(name); return x.ordinal(); } public String getName(int index) { return StatsEnum.values()[index].toString(); } public String getUnits(int index) { return StatsEnum.values()[index]._units; } public String [] getNames() { return _names; } } protected String formatMessage(String message) { return _managerIdString + message; } }
package jkind.api.xml; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import jkind.JKindException; public class Kind2WebInputStream extends InputStream { private static final int POLL_INTERVAL = 1000; private final URI baseUri; private final List<String> args; private final String lustre; private String jobId; private String buffer; private int index; private volatile boolean done; public Kind2WebInputStream(URI baseUri, List<String> args, String lustre) { this.baseUri = baseUri; this.args = args; this.lustre = lustre; } @Override public int read() throws IOException { if (done) { return -1; } if (jobId == null) { submitJob(); buffer = ""; index = 0; } while (index >= buffer.length()) { try { Thread.sleep(POLL_INTERVAL); } catch (InterruptedException e) { return -1; } buffer = retrieveJob(); if (buffer == null || done) { done = true; return -1; } index = 0; } return buffer.charAt(index++); } private void submitJob() throws IOException { URL url = baseUri.resolve("submitjob").toURL(); URLConnection conn = createRequest(lustre, url); conn.connect(); jobId = getJobId(conn.getInputStream()); conn.getInputStream().close(); } private URLConnection createRequest(String lustre, URL url) throws IOException { // http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests/2793153#2793153 URLConnection conn = url.openConnection(); conn.setUseCaches(false); conn.setDoOutput(true); // Just generate some unique random value. String boundary = Long.toHexString(System.currentTimeMillis()); String CRLF = "\r\n"; // Line separator required by multipart/form-data. conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"), true)) { // kind param writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"kind\"").append(CRLF); writer.append(CRLF).append("kind2").append(CRLF).flush(); // arg param for (String arg : args) { writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"arg\"").append(CRLF); writer.append(CRLF).append(arg).append(CRLF).flush(); } // file param writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"upload.lus\"") .append(CRLF); writer.append("Content-Type: text/plain; charset=UTF-8").append(CRLF); writer.append(CRLF).flush(); writer.append(lustre); writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF); } return conn; } private String retrieveJob() throws IOException { StringBuilder content = new StringBuilder(); URL url = baseUri.resolve("retrievejob/").resolve(jobId).toURL(); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); } conn.getInputStream().close(); String body = content.toString(); if (body.startsWith("<Jobstatus msg=\"completed\">")) { return null; } else { return body; } } private String getJobId(InputStream is) throws IOException { Pattern jobIdPattern = Pattern.compile(".*jobid=\"(.*?)\".*"); Pattern abortPattern = Pattern.compile(".*msg=\"aborted\">(.*?)</.*"); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null) { Matcher match = jobIdPattern.matcher(line); if (match.matches()) { return match.group(1); } match = abortPattern.matcher(line); if (match.matches()) { throw new JKindException("Kind2 server aborted job: " + match.group(1)); } } throw new JKindException("Failed to receive job id from " + baseUri); } @Override public void close() { if (jobId != null && !done) { cancelJob(); done = true; } } private void cancelJob() { try { URL url = baseUri.resolve("canceljob/").resolve(jobId).toURL(); URLConnection conn = url.openConnection(); conn.getInputStream().close(); } catch (IOException e) { throw new JKindException("Error canceling kind2 job", e); } } }
package com.jme3.scene; import com.jme3.scene.Mesh; import com.jme3.scene.VertexBuffer.Type; /** * A static, indexed, Triangles-mode mesh for an axis-aligned rectangle in the * X-Y plane. * * <p>The rectangle extends from (-width/2, -height/2, 0) to * (width/2, height/2, 0) with normals set to (0,0,1). * * <p>This differs from {@link com.jme3.scene.shape.Quad} because it puts * (0,0,0) at the rectangle's center instead of in a corner. * * @author Kirill Vainer */ public class CenterQuad extends Mesh { public static CenterQuad UnitQuad = new CenterQuad(0.5f, 0.5f); public static Mesh CenterSplitQuad; private float width; private float height; /** * Create a quad with the given width and height. The quad * is always created in the XY plane. * * @param width The X extent or width * @param height The Y extent or width */ public CenterQuad(float width, float height){ updateGeometry(width, height); } /** * Create a quad with the given width and height. The quad * is always created in the XY plane. * * @param width The X extent or width * @param height The Y extent or width * @param flipCoords If true, the texture coordinates will be flipped * along the Y axis. */ public CenterQuad(float width, float height, boolean flipCoords){ updateGeometry(width, height, flipCoords); this.setStatic(); } public float getHeight() { return height; } public float getWidth() { return width; } public void updateGeometry(float width, float height){ updateGeometry(width, height, false); } public void updateGeometry(float width, float height, boolean flipCoords) { this.width = width; this.height = height; setBuffer(Type.Position, 3, new float[]{-width/2, -height/2, 0, width/2, -height/2, 0, width/2, height/2, 0, -width/2, height/2, 0 }); if (flipCoords){ setBuffer(Type.TexCoord, 2, new float[]{0, 1, 1, 1, 1, 0, 0, 0}); }else{ setBuffer(Type.TexCoord, 2, new float[]{0, 0, 1, 0, 1, 1, 0, 1}); } setBuffer(Type.Normal, 3, new float[]{0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1}); if (height < 0){ setBuffer(Type.Index, 3, new short[]{0, 2, 1, 0, 3, 2}); }else{ setBuffer(Type.Index, 3, new short[]{0, 1, 2, 0, 2, 3}); } updateBound(); } }
package joliex.db; import java.math.BigDecimal; import java.sql.Clob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import jolie.runtime.CanUseJars; import jolie.runtime.FaultException; import jolie.runtime.JavaService; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.embedding.RequestResponse; /** * @author Fabrizio Montesi * 2008 - Marco Montesi: connection string fix for Microsoft SQL Server * 2009 - Claudio Guidi: added support for SQLite */ @CanUseJars({ "derby.jar", // Java DB - Embedded "derbyclient.jar", // Java DB - Client "jdbc-mysql.jar", // MySQL "jdbc-postgresql.jar", // PostgreSQL "jdbc-sqlserver.jar", // Microsoft SQLServer "jdbc-sqlite.jar" // SQLite }) public class DatabaseService extends JavaService { private Connection connection = null; private String connectionString = null; private String username = null; private String password = null; private boolean mustCheckConnection = false; private final Object transactionMutex = new Object(); @Override protected void finalize() { if ( connection != null ) { try { connection.close(); } catch( SQLException e ) {} } } @RequestResponse public void connect( Value request ) throws FaultException { if ( connection != null ) { try { connectionString = null; username = null; password = null; connection.close(); } catch( SQLException e ) {} } mustCheckConnection = request.getFirstChild( "checkConnection" ).intValue() > 0; String driver = request.getChildren( "driver" ).first().strValue(); String host = request.getChildren( "host" ).first().strValue(); String port = request.getChildren( "port" ).first().strValue(); String databaseName = request.getChildren( "database" ).first().strValue(); username = request.getChildren( "username" ).first().strValue(); password = request.getChildren( "password" ).first().strValue(); String separator = "/"; try { if ( "postgresql".equals( driver ) ) { Class.forName( "org.postgresql.Driver" ); } else if ( "mysql".equals( driver ) ) { Class.forName( "com.mysql.jdbc.Driver" ); } else if ( "derby".equals( driver ) ) { Class.forName( "org.apache.derby.jdbc.ClientDriver" ); } else if ( "sqlite".equals( driver ) ) { Class.forName( "org.sqlite.JDBC" ); } else if ( "sqlserver".equals( driver ) ) { //Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver" ); separator = ";"; databaseName = "databaseName=" + databaseName; } else if ( "as400".equals( driver ) ) { Class.forName( "com.ibm.as400.access.AS400JDBCDriver" ); } else { throw new FaultException( "InvalidDriver", "Uknown driver: " + driver ); } connectionString = "jdbc:"+ driver + "://" + host + ( port.equals( "" ) ? "" : ":" + port ) + separator + databaseName; connection = DriverManager.getConnection( connectionString, username, password ); if ( connection == null ) { throw new FaultException( "ConnectionError" ); } } catch( ClassNotFoundException e ) { throw new FaultException( "InvalidDriver", e ); } catch( SQLException e ) { throw new FaultException( "ConnectionError", e ); } } private void checkConnection() throws FaultException { if ( connection == null ) { throw new FaultException( "ConnectionError" ); } if ( mustCheckConnection ) { try { if ( !connection.isValid( 0 ) ) { connection = DriverManager.getConnection( connectionString, username, password ); } } catch( SQLException e ) { throw new FaultException( e ); } } } public Value update( String query ) throws FaultException { checkConnection(); Value resultValue = Value.create(); Statement stm = null; try { synchronized( transactionMutex ) { stm = connection.createStatement(); resultValue.setValue( stm.executeUpdate( query ) ); } } catch( SQLException e ) { throw new FaultException( e ); } finally { if ( stm != null ) { try { stm.close(); } catch( SQLException e ) {} } } return resultValue; } private static void resultSetToValueVector( ResultSet result, ValueVector vector ) throws SQLException { Value rowValue, fieldValue; ResultSetMetaData metadata = result.getMetaData(); int cols = metadata.getColumnCount(); int i; int rowIndex = 0; while( result.next() ) { rowValue = vector.get( rowIndex ); for( i = 1; i <= cols; i++ ) { fieldValue = rowValue.getFirstChild( metadata.getColumnLabel( i ) ); switch( metadata.getColumnType( i ) ) { case java.sql.Types.INTEGER: case java.sql.Types.SMALLINT: case java.sql.Types.TINYINT: fieldValue.setValue( result.getInt( i ) ); break; case java.sql.Types.BIGINT: // TODO: to be changed when getting support for Long in Jolie. fieldValue.setValue( result.getInt( i ) ); break; case java.sql.Types.DOUBLE: fieldValue.setValue( result.getDouble( i ) ); break; case java.sql.Types.FLOAT: fieldValue.setValue( result.getFloat( i ) ); break; case java.sql.Types.BLOB: //fieldValue.setStrValue( result.getBlob( i ).toString() ); break; case java.sql.Types.CLOB: Clob clob = result.getClob( i ); fieldValue.setValue( clob.getSubString( 0L, (int)clob.length() ) ); break; case java.sql.Types.NVARCHAR: case java.sql.Types.NCHAR: case java.sql.Types.LONGNVARCHAR: String s = result.getNString( i ); if ( s == null ) { s = ""; } fieldValue.setValue( s ); break; case java.sql.Types.NUMERIC: BigDecimal dec = result.getBigDecimal( i ); if ( dec == null ) { fieldValue.setValue( 0 ); } else { if ( dec.scale() <= 0 ) { // May lose information. // Pay some attention to this when Long becomes supported by JOLIE. fieldValue.setValue( dec.intValue() ); } else if ( dec.scale() > 0 ) { fieldValue.setValue( dec.doubleValue() ); } } break; case java.sql.Types.VARCHAR: default: String str = result.getString( i ); if ( str == null ) { str = ""; } fieldValue.setValue( str ); break; } } rowIndex++; } } public Value executeTransaction( Value request ) throws FaultException { checkConnection(); Value resultValue = Value.create(); ValueVector resultVector = resultValue.getChildren( "result" ); synchronized( transactionMutex ) { try { connection.setAutoCommit( false ); } catch( SQLException e ) { throw new FaultException( e ); } Value currResultValue; Statement stm; for( Value statementValue : request.getChildren( "statement" ) ) { currResultValue = Value.create(); stm = null; try { stm = connection.createStatement(); if ( stm.execute( statementValue.strValue() ) == true ) { resultSetToValueVector( stm.getResultSet(), currResultValue.getChildren( "row" ) ); } resultVector.add( currResultValue ); } catch( SQLException e ) { try { connection.rollback(); } catch( SQLException e1 ) { connection = null; } throw new FaultException( e ); } finally { if ( stm != null ) { try { stm.close(); } catch( SQLException e ) { throw new FaultException( e ); } } } } try { connection.commit(); } catch( SQLException e ) { throw new FaultException( e ); } finally { try { connection.setAutoCommit( true ); } catch( SQLException e ) { throw new FaultException( e ); } } } return resultValue; } public Value query( String query ) throws FaultException { checkConnection(); Value resultValue = Value.create(); Statement stm = null; try { synchronized( transactionMutex ) { stm = connection.createStatement(); ResultSet result = stm.executeQuery( query ); resultSetToValueVector( result, resultValue.getChildren( "row" ) ); } } catch( SQLException e ) { throw new FaultException( "SQLException", e ); } finally { if ( stm != null ) { try { stm.close(); } catch( SQLException e ) {} } } return resultValue; } }
package org.strongback; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BooleanSupplier; import org.strongback.annotation.Immutable; import org.strongback.annotation.ThreadSafe; import org.strongback.components.Switch; /** * A threadsafe {@link SwitchReactor} implementation that relies upon being periodically {@link Executable#execute(long) * executed}. This class is carefully written to ensure that all functions are registered atomically even while * {@link #execute(long)} is being called. * * @author Randall Hauch */ @ThreadSafe final class AsyncSwitchReactor implements Executable, SwitchReactor { private final ConcurrentMap<Switch, Container> listeners = new ConcurrentHashMap<>(); @Override public void execute(long time) { listeners.forEach((swtch, container) -> container.notifyListeners(swtch.isTriggered())); } @Override public void onTriggered(Switch swtch, Runnable function) { listeners.computeIfAbsent(swtch,(s)->new Container()).addWhenTriggered(function); } @Override public void onUntriggered(Switch swtch, Runnable function) { listeners.computeIfAbsent(swtch,(s)->new Container()).addWhenUntriggered(function); } @Override public void whileTriggered(Switch swtch, Runnable function) { listeners.computeIfAbsent(swtch,(s)->new Container()).addWhileTriggered(function); } @Override public void whileUntriggered(Switch swtch, Runnable function) { listeners.computeIfAbsent(swtch,(s)->new Container()).addWhileUntriggered(function); } /** * A container class for all listener functions associated with a specific {@link Switch}. The class is threadsafe to allow * for new listener functions to be added while the existing functions are called based upon the switch's current state. * <p> * To achieve efficient and lock-free concurrent operations, each of the functions for a specific Switch state or transition * are maintained in a simple linked-list structure (see {@link Listener}). Each immutable Listener is created to hold one * function and an optional "next" listener. To add a new function, a new Listener object is created with the function and * the current Listener object for that state, and the Container's reference to that state's listeners is updated with the * new Listener object. In essence, new functions are added to the front of the linked list without using any locking. * <p> * It is not currently possible to remove functions that have been registered. * * @author Randall Hauch */ @ThreadSafe private static final class Container { private boolean previouslyTriggered; private final AtomicReference<Listener> whenTriggered = new AtomicReference<>(); private final AtomicReference<Listener> whenUntriggered = new AtomicReference<>(); private final AtomicReference<Listener> whileTriggered = new AtomicReference<>(); private final AtomicReference<Listener> whileUntriggered = new AtomicReference<>(); public void notifyListeners(boolean nowTriggered) { notifyAtomicallyWhen(()->!previouslyTriggered && nowTriggered, whenTriggered); notifyAtomicallyWhen(()->previouslyTriggered && !nowTriggered, whenUntriggered); notifyAtomicallyWhen(()->previouslyTriggered && nowTriggered, whileTriggered); notifyAtomicallyWhen(()->!previouslyTriggered && !nowTriggered, whileUntriggered); previouslyTriggered = nowTriggered; } private void notifyAtomicallyWhen(BooleanSupplier criteria, AtomicReference<Listener> listenerRef ) { Listener listener = listenerRef.get(); if ( listener != null && criteria.getAsBoolean() ) listener.fire(); } public void addWhenTriggered(Runnable function) { whenTriggered.updateAndGet((existing)->new Listener(function,existing)); } public void addWhenUntriggered(Runnable function) { whenUntriggered.updateAndGet((existing)->new Listener(function,existing)); } public void addWhileTriggered(Runnable function) { whileTriggered.updateAndGet((existing)->new Listener(function,existing)); } public void addWhileUntriggered(Runnable function) { whileUntriggered.updateAndGet((existing)->new Listener(function,existing)); } } /** * One node in a linked list of listener functions. * * @author Randall Hauch */ @Immutable private static final class Listener { private final Runnable function; private final Listener next; public Listener(Runnable function, Listener next) { this.function = function; this.next = next; } public void fire() { function.run(); if (next != null) next.fire(); } } }
package cucumber.api.junit; import cucumber.api.CucumberOptions; import cucumber.api.event.TestRunFinished; import cucumber.api.formatter.Formatter; import cucumber.runtime.ClassFinder; import cucumber.runtime.Runtime; import cucumber.runtime.RuntimeOptions; import cucumber.runtime.RuntimeOptionsFactory; import cucumber.runtime.io.MultiLoader; import cucumber.runtime.io.ResourceLoader; import cucumber.runtime.io.ResourceLoaderClassFinder; import cucumber.runtime.junit.Assertions; import cucumber.runtime.junit.FeatureRunner; import cucumber.runtime.junit.JUnitOptions; import cucumber.runtime.junit.JUnitReporter; import cucumber.runtime.model.CucumberFeature; import org.junit.runner.Description; import org.junit.runner.notification.RunNotifier; import org.junit.runners.ParentRunner; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * <p> * Classes annotated with {@code @RunWith(Cucumber.class)} will run a Cucumber Feature. * The class should be empty without any fields or methods. * </p> * <p> * Cucumber will look for a {@code .feature} file on the classpath, using the same resource * path as the annotated class ({@code .class} substituted by {@code .feature}). * </p> * Additional hints can be given to Cucumber by annotating the class with {@link CucumberOptions}. * * @see CucumberOptions */ public class Cucumber extends ParentRunner<FeatureRunner> { private final JUnitReporter jUnitReporter; private final List<FeatureRunner> children = new ArrayList<FeatureRunner>(); private final Runtime runtime; private final Formatter formatter; /** * Constructor called by JUnit. * * @param clazz the class with the @RunWith annotation. * @throws java.io.IOException if there is a problem * @throws org.junit.runners.model.InitializationError if there is another problem */ public Cucumber(Class clazz) throws InitializationError, IOException { super(clazz); ClassLoader classLoader = clazz.getClassLoader(); Assertions.assertNoCucumberAnnotatedMethods(clazz); RuntimeOptionsFactory runtimeOptionsFactory = new RuntimeOptionsFactory(clazz); RuntimeOptions runtimeOptions = runtimeOptionsFactory.create(); ResourceLoader resourceLoader = new MultiLoader(classLoader); runtime = createRuntime(resourceLoader, classLoader, runtimeOptions); formatter = runtimeOptions.formatter(classLoader); final JUnitOptions junitOptions = new JUnitOptions(runtimeOptions.getJunitOptions()); final List<CucumberFeature> cucumberFeatures = runtimeOptions.cucumberFeatures(resourceLoader, runtime.getEventBus()); jUnitReporter = new JUnitReporter(runtime.getEventBus(), runtimeOptions.isStrict(), junitOptions); addChildren(cucumberFeatures); } /** * Create the Runtime. Can be overridden to customize the runtime or backend. * * @param resourceLoader used to load resources * @param classLoader used to load classes * @param runtimeOptions configuration * @return a new runtime * @throws InitializationError if a JUnit error occurred * @throws IOException if a class or resource could not be loaded */ protected Runtime createRuntime(ResourceLoader resourceLoader, ClassLoader classLoader, RuntimeOptions runtimeOptions) throws InitializationError, IOException { ClassFinder classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader); return new Runtime(resourceLoader, classFinder, classLoader, runtimeOptions); } @Override public List<FeatureRunner> getChildren() { return children; } @Override protected Description describeChild(FeatureRunner child) { return child.getDescription(); } @Override protected void runChild(FeatureRunner child, RunNotifier notifier) { child.run(notifier); } @Override protected Statement childrenInvoker(RunNotifier notifier) { final Statement features = super.childrenInvoker(notifier); return new Statement() { @Override public void evaluate() throws Throwable { features.evaluate(); runtime.getEventBus().send(new TestRunFinished(runtime.getEventBus().getTime())); runtime.printSummary(); } }; } private void addChildren(List<CucumberFeature> cucumberFeatures) throws InitializationError { for (CucumberFeature cucumberFeature : cucumberFeatures) { FeatureRunner featureRunner = new FeatureRunner(cucumberFeature, runtime, jUnitReporter); if (!featureRunner.isEmpty()) { children.add(featureRunner); } } } }